|     Inicio    |   |         |  |   FOROS      |  |      |      
   Elastix - VoIP B4A (Basic4Android) App inventor 2 PHP - MySQL
  Estación meteorológica B4J (Basic4Java) ADB Shell - Android Arduino
  Raspberry Pi Visual Basic Script (VBS) FireBase (BD autoactualizable) NodeMCU como Arduino
  AutoIt (Programación) Visual Basic Cosas de Windows Webs interesantes
Translate:
Búsqueda en este sitio:


.

Autoit en español
Aplicaciones con Autoit - Juan Antonio Villalpando

-- Tutorial de iniciación a Autoit --

Volver al índice del tutorial

____________________________

62.- Bluetooth y Arduino mediante AutoIt.

- Vamos a ejecutar una aplicación en AutoIt que se conectará a un módulo Bluetootd de Arduino, de manera que desde el ordenador podamos encender y apagar un LED de Arduino enviando la información por Bluetooth.

- Suponemos que el ordenador tiene conexión Bluetooth interna, como en el caso de los portátiles o mediante un "dongle" bluetooth, como mencioné en el tutorial anterior.

- También suponemos que ese dispositivo bluetooth del ordenador tiene sus controladores instalados correctamente.

___________________________________________
1.- Conexión del Arduino y el módulo Bluetooth HC-06.

- Esto ya lo hemos visto en varios tutoriales: 9bluetootharduino.htm


- Forma de conectarlo.

Módulo Bluetooh Arduino
VCC 5 V
GND GND
TXD RX (es la conexión 0 del Arduino)
RXD TX (es la conexión 1 del Arduino)

- Fíjate que el TXD va con el RX y que el RXD va con el TX

- En el momento de alimentarlo con los 5V, el LED del módulo bluetooth parpadeará.

- Podemos poner un LED en el terminal 12 y otro en el 13, pero para facilitar el montaje, vamos a utilizarlo solamente con el LED13 que tiene el Arduino en su placa, así que no es necesario ponerle LED externos.

 

___________________________________________
2.- Controlador del Bluetooth en el ordenador.

- En el ordenador vamos al Administrador de dispositivos, debemos observar algo así:

- El "dongle" bluetooth USB está actuando como un puerto COM, más bien como varios puertos COM según observas en la figura superior.

___________________________________________
3.- Código del Arduino.

- Este código prepara el puerto Serie (terminales 0 y 1, donde está conectado el módulo bluetooth) para trasmitir/recibir información a 9600 baudios.

- Si no quieres poner un LED en el terminal 12 y otro en el terminal 13, haz las pruebas solamente con el LED13 que tiene el Arduino en su placa.

- Cuando recibe un 0 o un 1, apaga/enciende un LED conectado al pin12 del Arduino.

- Cuando recibe un 2 o un 3, apaga/enciende el LED13 del Arduino.

- Podemos hacer pruebas visualizando solamente el LED13 del Arduino que está integrado en su placa, por lo cual no sería necesario poner más LED.

- NOTA: cuando vayas a cargar el programa en el Arduino, desconecta la alimentación del módulo bluetooth.

bluetooth_autoit.ino
				   
// Juan Antonio Villalpando
// juana1991@yahoo.com
// kio4.com

char val;
int ledPin12 = 12;
int ledPin13 = 13;

void setup() { 
Serial.begin(9600); // Aqui establecemos la velocidad
pinMode(ledPin12, OUTPUT); 
pinMode(ledPin13, OUTPUT); 
}

void loop() { 
if( Serial.available() )
val = Serial.read();

if( val == '0' )
{ 
digitalWrite(ledPin12, LOW);
}

if( val == '1' )
{ 
digitalWrite(ledPin12, HIGH);
} 
if( val == '2' )
{ 
digitalWrite(ledPin13, LOW);
}

if( val == '3' )
{ 
digitalWrite(ledPin13, HIGH);
} 
}

___________________________________________
4.- Código de AutoIt.

- Lo obtenemos de:

https://www.autoitscript.com/forum/topic/183106-question-regarding-serial-coms/#comment-1314735

- Son necesarias las librerías:

CommMG.au3

commg.dll

- Que las puedes obtener de aquí:

https://www.autoitscript.com/forum/topic/177095-windows-10-problem-with-commmgau3-serial-send-to-arduino/

- El archivo CommMG.au3 lo copias en la carpeta Include de donde tengas instalado el AutoIt, por ejemplo: C:\Program Files (x86)\AutoIt3\Include

- El archivo commg.dll lo copias en la misma carpeta en la que vas a guardar el siguiente Script:

bluetooth_autoit_arduino.au3

;Example program showing how to use some of the commMg3.au3 UDF functions
;this example is a very simple terminal
;Version 2 26th July 2006
;changes-
;change flow control checkbox to combo and add NONE
;correct error in call to _CommSetPort - stop bits were missing which meant th eflow control was used for stop bits
;Dec 2013 - correct setting of Parity and flow, thanks to MichaelXMike

#include <GUIConstants.au3>
#include <CommMG.au3>;or if you save the commMg.dll in the @scripdir use #include @SciptDir & '\commmg.dll'
#include <GuiEdit.au3>
#include <GuiComboBox.au3>
#include <windowsconstants.au3>
#include <buttonconstants.au3>
#include <Array.au3>


Opt("WINTITLEMATCHMODE", 3)
;Opt("OnExitFunc","alldone")
HotKeySet("{ESC}", "alldone")

$result = '';used for any returned error message setting port
Const $settitle = "COMMG listExample - set Port", $maintitle = "COMMG Example"
$setflow = 2;default to no flow control
Dim $FlowType[3] = ["Hardware (RTS, CTS)", "XOnXoff", "NONE"]
Dim $ParityType[5] = ["odd", "even", "none", "Mark", "Space"]
#region main program

#Region ### START Koda GUI section ### Form=d:\my documents\miscdelphi\commg\ExampleComm.kxf
$Form2 = GUICreate("COMMG Example", 473, 349, 339, 333, BitOR($WS_MAXIMIZEBOX, $WS_MINIMIZEBOX, $WS_SIZEBOX, $WS_THICKFRAME, $WS_SYSMENU, $WS_CAPTION, _
$WS_OVERLAPPEDWINDOW, $WS_TILEDWINDOW, $WS_POPUP, $WS_POPUPWINDOW, $WS_GROUP, $WS_TABSTOP, $WS_BORDER, $WS_CLIPSIBLINGS))

$Edit1 = GUICtrlCreateEdit("", 10, 25, 449, 223, BitOR($ES_AUTOVSCROLL, $ES_AUTOHSCROLL, $ES_READONLY, $ES_WANTRETURN, $WS_HSCROLL, $WS_VSCROLL))
$BtnSend = GUICtrlCreateButton("Send", 380, 273, 53, 30, $BS_FLAT)
$Input1 = GUICtrlCreateInput("", 18, 279, 361, 21)
$Checkbox1 = GUICtrlCreateCheckbox("Add LF to incomming CR", 273, 4, 145, 17)
GUICtrlSetState(-1, $GUI_CHECKED)
GUICtrlSetResizing(-1, $GUI_DOCKAUTO)
$Label11 = GUICtrlCreateLabel("Text to send", 24, 261, 63, 17)
$BtnSetPort = GUICtrlCreateButton("Set Port", 16, 312, 73, 30, $BS_FLAT)
$Label21 = GUICtrlCreateLabel("Received text", 34, 6, 70, 17)
$Label31 = GUICtrlCreateLabel("commg.dll version unknown", 272, 328, 135, 17)
GUICtrlSetColor(-1, 0x008080)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

WinSetTitle($Form2, "", $maintitle & "  UDF = " & _CommGetVersion(1))

While setport(0) = -1
    If MsgBox(4, 'Port not set', 'Do you want to quite the program?') = 6 Then Exit
WEnd


ConsoleWrite("stage 1" & @CRLF)
GUICtrlSetData($Label31, 'using ' & _CommGetVersion(1))
ConsoleWrite("stage 2" & @CRLF)
Events()
ConsoleWrite("at 64" & @CRLF)
_CommSetXonXoffProperties(11, 13, 100, 100)
;consolewrite("return from set timeouts = " & _CommSetTimeouts(5,5,5,5,5) & @CR)
GUICtrlSetState($Edit1, $GUI_FOCUS)
ConsoleWrite("at 67" & @CRLF)

While 1
    ;sleep(40)
    ;gets characters received returning when one of these conditions is met:
    ;receive @CR, received 20 characters or 200ms has elapsed
    $instr = _commGetLine(@CR, 20, 200);_CommGetString()

    If $instr <> '' Then;if we got something
        If GUICtrlRead($Checkbox1) = $GUI_CHECKED Then $instr = StringReplace($instr, @CR, @CRLF)
        FileWrite(@ScriptDIr & "/Data.txt", $instr)
        GUICtrlSetData($Edit1, $instr, 1)
    Else
        Sleep(20) ;MichaelXMike
    EndIf

WEnd

Alldone()


Func port11()
    ;MsgBox(0,'now set to channel',_CommSwitch(2))
    _commSwitch(2)
    $s2 = "1 2 3 4";_CommGetString()
    ConsoleWrite("comm1 gets " & $s2 & @CRLF)
    _CommSendString($s2)
    _CommSwitch(1)

EndFunc   ;==>port11

#endregion main program
Func Events()
    Opt("GUIOnEventMode", 1)
    GUISetOnEvent($GUI_EVENT_CLOSE, "justgo")
    GUICtrlSetOnEvent($BtnSend, "SendEvent")
    GUICtrlSetOnEvent($BtnSetPort, "SetPortEvent")
EndFunc   ;==>Events

Func SetPortEvent()
    setport();needed because a parameter is optional for setport so we can't use "setport" for the event
    GUICtrlSetState($Edit1, $GUI_FOCUS)
EndFunc   ;==>SetPortEvent

Func justgo()
    Exit
EndFunc   ;==>justgo

Func SendEvent();send the text in the inputand append CR
    _CommSendstring(GUICtrlRead($Input1) & @CR)
    GUICtrlSetData($Input1, '');clear the input
    ;GUICtrlSetState($edit1,$GUI_FOCUS);sets the caret back in the terminal screen
EndFunc   ;==>SendEvent


Func AllDone()
    ;MsgBox(0,'will close ports','')
    _Commcloseport(true)
    ;MsgBox(0,'port closed','')
    Exit
EndFunc   ;==>AllDone


; Function SetPort($mode=1)
; Creates a form for the port settings
;Parameter $mode sets the return value depending on whether the port was set
;Returns  0 if $mode <> 1
;          -1 If` the port not set and $mode is 1
Func SetPort($mode = 1);if $mode = 1 then returns -1 if settings not made
    Local $sportSetError
    Opt("GUIOnEventMode", 0);keep events for $Form2, use GuiGetMsg for $Form3

    #Region ### START Koda GUI section ### Form=d:\my documents\miscdelphi\commg\examplecommsetport.kxf
    $Form3 = GUICreate("COMMG Example - set Port", 422, 279, 329, 268, BitOR($WS_MINIMIZEBOX, $WS_CAPTION, $WS_POPUP, $WS_GROUP, $WS_BORDER, $WS_CLIPSIBLINGS, _
	$DS_MODALFRAME), BitOR($WS_EX_TOPMOST, $WS_EX_WINDOWEDGE))

    $Group1 = GUICtrlCreateGroup("Set COM Port", 18, 8, 288, 252)
    $CmboPortsAvailable = GUICtrlCreateCombo("", 127, 28, 145, 25, BitOR($GUI_SS_DEFAULT_COMBO, $CBS_SORT))
    $CmBoBaud = GUICtrlCreateCombo("9600", 127, 66, 145, 25, BitOR($CBS_DROPDOWN, $CBS_AUTOHSCROLL, $CBS_SORT, $WS_VSCROLL))
    GUICtrlSetData(-1, "10400|110|115200|1200|128000|14400|150|15625|1800|19200|2000|2400|256000|28800|38400|3600|38400|4800|50|56000|57600|600|7200|75")
    $CmBoStop = GUICtrlCreateCombo("1", 127, 141, 145, 25)
    GUICtrlSetData(-1, "1|2|1.5")
    $CmBoParity = GUICtrlCreateCombo("", 127, 178, 145, 25)
    GUICtrlSetData(-1, "odd|even|none|Mark|Space")
    GUICtrlSetData(-1, "none")
    $Label2 = GUICtrlCreateLabel("Port", 94, 32, 23, 17)
    $Label3 = GUICtrlCreateLabel("baud", 89, 70, 28, 17)
    $Label4 = GUICtrlCreateLabel("No. Stop bits", 52, 145, 65, 17)
    $Label5 = GUICtrlCreateLabel("parity", 88, 182, 29, 17)
    $CmboDataBits = GUICtrlCreateCombo("8", 127, 103, 145, 25)
    GUICtrlSetData(-1, "7|8")
    $Label7 = GUICtrlCreateLabel("No. of Data Bits", 38, 107, 79, 17)
    $ComboFlow = GUICtrlCreateCombo("NONE", 127, 216, 145, 25)
    GUICtrlSetData(-1, "NONE|XOnXOff|Hardware (RTS, CTS)")
    $Label1 = GUICtrlCreateLabel("flow control", 59, 220, 58, 17)
    GUICtrlCreateGroup("", -99, -99, 1, 1)
    $BtnApply = GUICtrlCreateButton("Apply", 315, 95, 75, 35, $BS_FLAT)
    GUICtrlSetFont(-1, 12, 400, 0, "MS Sans Serif")
    $BtnCancel = GUICtrlCreateButton("Cancel", 316, 147, 76, 35, $BS_FLAT)
    GUICtrlSetFont(-1, 12, 400, 0, "MS Sans Serif")
    GUISetState(@SW_SHOW)
    #EndRegion ### END Koda GUI section ###


    WinSetTitle($Form3, "", $settitle);ensure a change to Koda design doesn't stop script working
    $mainxy = WinGetPos($Form2)
    WinMove($Form3, "", $mainxy[0] + 20, $mainxy[1] + 20)

    $portlist = _CommListPorts(0);find the available COM ports and write them into the ports combo
    If @error = 1 Then
        MsgBox(0, 'trouble getting portlist', 'Program will terminate!')
        Exit
    EndIf

    For $pl = 1 To $portlist[0]
        $portnum = StringReplace($portlist[$pl], "COM", '')
        if StringLen($portnum) = 1 then $portnum = ' ' & $portnum
        $portlist[$pl] = 'COM' & $portnum
        GUICtrlSetData($CmboPortsAvailable, $portlist[$pl]);_CommListPorts())
    Next
    GUICtrlSetData($CmboPortsAvailable, $portlist[1]);show the first port found
    GUICtrlSetData($ComboFlow, $FlowType[$setflow])

    _GUICtrlComboBox_SetMinVisible($CmBoBaud, 10);restrict the length of the drop-down list


    $retval = 0

    While 1
        $msg = GUIGetMsg()
        If $msg = $BtnCancel Then
            If Not $mode Then $retval = -1
            ExitLoop
        EndIf


        If $msg = $BtnApply Then

            $comboflowsel = GUICtrlRead($ComboFlow)
            For $n = 0 To 2
                If $comboflowsel = $FlowType[$n] Then
                    $setflow = $n
                    ConsoleWrite("flow = " & $setflow & @CRLF)
                    ExitLoop
                EndIf

            Next
            $setport = StringReplace(GUICtrlRead($CmboPortsAvailable), 'COM', '')

            $ParitySel = GUICtrlRead($CmBoParity)
            For $n = 0 To 4
                If $ParitySel = $ParityType[$n] Then
                    $SetParity = $n
                    ExitLoop
                EndIf
            Next

            $setStop = StringReplace(GUICtrlRead($CmBoStop), '.', '');replace 1.5 with 15 if needed

	$resOpen = _CommSetPort($setport, $sportSetError, GUICtrlRead($CmBoBaud), GUICtrlRead($CmboDataBits), $SetParity, $setStop, $setflow)
	;$resOpen = _CommSetPort($setPort,$sportSetError,GUICtrlRead($CmBoBaud),GUICtrlRead($CmboDataBits),GUICtrlRead($CmBoParity),GUICtrlRead($CmBoStop),$setFlow)

            if $resOpen = 0 then
                ConsoleWrite($sportSetError & @LF)
                Exit
            EndIf

            Sleep(1000)
            ConsoleWrite('ok' & @CRLF)
            ;next
            $mode = 1;
            ExitLoop
        EndIf

        ;stop user switching back to $form2
        If WinActive($maintitle) Then
            ConsoleWrite('main is active' & @CRLF)
            If WinActivate($settitle) = 0 Then MsgBox(0, 'not found', $settitle)
        EndIf


    WEnd
    ConsoleWrite(244 & @CRLF)
    GUIDelete($Form3)
    ConsoleWrite(247 & @CRLF)
    WinActivate($maintitle)
    ConsoleWrite(248 & @CRLF)
    Events()
    Return $retval


EndFunc   ;==>SetPort

___________________________________________
5.- Ejecución del Script de AutoIt.

- Nos saldrá la siguente ventana. Pulsamos en Set Port. Debemos elegir el puerto en donde está el "dongle" bluetooth del ordenador. [No confundir con el puerto del IDE de Arduino]

- Será uno de los puertos que vimos en el Administrador de dispositivos. Vamos probando puertos hasta lograr que el LED del módulo bluetooth no parpadee.

- En mi caso el LED del módulo bluetooth dejó de parpadear cuando conectó con el puerto COM29.

- La velocidad 9600

- Según introduzcamos en el casillero un 2 o un 3 se apagará/encenderá el LED13 del Arduino.

_________________
- Propuesta.

- Funciones disponibles del commmg.au3

 Functions available:
    _CommGetVersion
    _CommListPorts
    _CommSetPort
    _CommPortConnection
    _CommClearOutputBuffer
    _CommClearInputBuffer
    _CommGetInputcount
    _CommGetOutputcount
    _CommSendString
    _CommGetString
    _CommGetLine
    _CommReadByte
    _CommReadChar
    _CommSendByte
    _CommSendBreak; not tested!!!!!!!!!!
    _CommCloseport
    _CommSwitch
    _CommSendByteArray
    _CommReadByteArray

https://www.autoitscript.com/forum/topic/74461-newbi-question-commmgau3/

_________________

- Mi correo:
juana1991@yahoo.com
- KIO4.COM - Política de cookies. Textos e imágenes propiedad del autor:
© Juan A. Villalpando
No se permite la copia de información ni imágenes.
Usamos cookies propias y de terceros que entre otras cosas recogen datos sobre sus hábitos de navegación y realizan análisis de uso de nuestro sitio.
Si continúa navegando consideramos que acepta su uso. Acepto    Más información