Communication between Autohotkey / Arduino

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
Albireo
Posts: 1778
Joined: 16 Oct 2013, 13:53

Communication between Autohotkey / Arduino

Post by Albireo » 02 Dec 2019, 10:38

Is it difficult to communicate between an Arduino and AHK?

Have some problems I was going to solve (with an arduino)
for example.:
- Every night, two wires must be broken and two other wires connected for a while, and then back.

Whether arduinon should be standalone or always connected to USB, I haven't decided.
(or the communication between AHK and Arduinin should be done over local-ethernet - but it felt more difficult - maybe ...)

Another wish is that e.g. make a voltmeter and display the voltage in an AHK GUI

SOTE
Posts: 1426
Joined: 15 Jun 2015, 06:21

Re: Communication between Autohotkey / Arduino

Post by SOTE » 02 Dec 2019, 11:44

Some years back on the old forum, a user did some tinkering, and made some scripts for AutoHotkey and Arduino.
https://autohotkey.com/board/topic/64696-some-code-arduinoahk-beta-01/

Looks like it's time for more updates from any AutoHotkey and Arduino users out there.

colt
Posts: 291
Joined: 04 Aug 2014, 23:12
Location: Portland Oregon

Re: Communication between Autohotkey / Arduino

Post by colt » 02 Dec 2019, 12:19

A while back I used some code from this thread https://autohotkey.com/board/topic/26231-serial-com-port-console-script/ to send and receive data over uart.
I used two xbee transmitters to create a wireless link between a laptop and remote control airplane. The xbee connected to the laptop using https://www.sparkfun.com/products/11812 which exposed the data stream to the com port.


Albireo
Posts: 1778
Joined: 16 Oct 2013, 13:53

Re: Communication between Autohotkey / Arduino

Post by Albireo » 03 Dec 2019, 03:41

Has a program in the arduino that detects button presses and can read potentiometers.
Program Arduino - digital / analog
In Arduino's series monitor in windows, the status ​​of these buttons and potentiometers can be read.
The values I got in the monitor is something like this .: 00:58:44.434 -> Buttons A:1 B:1 C:1 D:1 E:1 F:1 -- Position X:334 Y:321
(the program in the Aurdino works)

My whish is to read Com3 - 9600 - n - 8 - 1 and get the same values of some of the buttons in ahk-GUI.
I have tested the program above (serial.ahk / arduino.ahk) but I got nothing to work....
(I don't understand how to get the right values from the serial port)

Albireo
Posts: 1778
Joined: 16 Oct 2013, 13:53

Re: Communication between Autohotkey / Arduino

Post by Albireo » 03 Dec 2019, 08:35

This is my test AHK program. (changed from 9,600 to 19,200 bps)
1) It read Arduinon's serial port.
AHK Read serialdata from Arduino
2) I expected to read a certain number of bytes (10000), but it feels random how many bytes are in the result variable. (97, 136, 123, 154 bytes...)

The next step is to divide the data into "rows". Each row ends with HEX "0D0A" CarrigeReturn / LineFeed.
But first, the reading of the COM port must be more stable.
Right now I don't know how - is Serial.ahk outdated?

Albireo
Posts: 1778
Joined: 16 Oct 2013, 13:53

Re: Communication between Autohotkey / Arduino

Post by Albireo » 08 Dec 2019, 18:40

Right now I'm focusing on being able to communicate with Autohotkey, between a PC and Windows 7 or Windows 10 with an Arduino.
Be able to understand how data is sent / read between these two devices. I have no problem to communicate between the Arduino Serial monitor on the PC and an Arduino Uno.
And want to do "the same" with Autohotkey

I found an example in VisualBasic .: Arduino Computer Control

Code: Select all

Imports System.IO
Imports System.IO.Ports
Imports System.Threading

Public Class Form1
Shared _continue As Boolean
Shared _serialPort As SerialPort

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With SerialPort1
.Close()
.PortName = "COM4"
.BaudRate = 19200
.Parity = Parity.None
.DataBits = 8
.StopBits = StopBits.One
.DtrEnable = True
.RtsEnable = True
.ReceivedBytesThreshold = 1
.Open()
End With
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SerialPort1.Write("A")
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SerialPort1.Write("B")
End Sub

End Class
Is it possible to do the same with Autohotkey?



Have asked the same questions on the Arduino forum, (but there seems to be few who know Autohotkey or can handle Autohotkey ...)

I think to communicate between Autohotkey and Arduino should work, but it's probably something I don't understand or the wrong DLL is used or..
(I have no Idea - right now...)

I have tested this files (for windows XP) but I don't get it to work (https://www.autohotkey.com/boards/viewtopic.php?p=78939)
Does Windows 7/10 handle serial ports differently?

I found another file for AHK-Studio Arduino.ahk (not tested)
Maybe this work?

Any idea how to resolve the communication with an Arduino?

Albireo
Posts: 1778
Joined: 16 Oct 2013, 13:53

Re: Communication between Autohotkey / Arduino

Post by Albireo » 12 Dec 2019, 15:06

The ideas on how AHK can communicate with an Arduino come to an end. Everything I've tested has not worked.
Have I missed any AHK instruction to send/receive data to/from an USB-port?
Do not think that Baudrate can play any role.

colt
Posts: 291
Joined: 04 Aug 2014, 23:12
Location: Portland Oregon

Re: Communication between Autohotkey / Arduino

Post by colt » 12 Dec 2019, 20:02

I created this sample script from code from my gps logger. On your micro you need to create a program that echos the uart buffer. This program will send whatever you type in the input terminal to the serial port that you specify in RS232_Port. Your micro will send it back and the data will go onto the serial buffer. When the timer "readData" goes off the script will read the serial buffer and place the contents in the termial output.

Code: Select all

;simpleTerm 12-12-2019
#singleinstance force
setbatchlines -1

inputHistory := ""
header := "- - - - - - TERMINAL OUTPUT - - - - - -" . chr(10) . chr(10) . ">>"

gui main:add,text,w200 x10 center,Terminal Input
gui main:add,text,wp x+10 center,Terminal Output
gui main:add,edit,wp h100 y+5 x10 vgSendField gSend,
gui main:add,edit,wp h100 yp x+10 vgRecieveField readonly,
gui main:show,,SimpleTerm

;attempt to connect to serial port
	
RS232_Port		:= "COM4"
RS232_Baud     	:= 9600
RS232_Parity   	:= "N"
RS232_Data     	:= 8
RS232_Stop     	:= 1
RS232_Delay    	:= 100 ;decrease this value for lower latency 


RS232_Settings   = %RS232_Port%:baud=%RS232_Baud% parity=%RS232_Parity% data=%RS232_Data% stop=%RS232_Stop% dtr=Off	
RS232_FileHandle:= RS232_Initialize(RS232_Settings)
send_serial(header)
setTimer, readData, -%RS232_Delay%
return

~Backspace::
	;clear the terminals
	inputHistory :=""
	guiControl,Main:,gRecieveField,
	guiControl,Main:,gSendField,
	send_serial(header)
return

Send:
	; launched when you type in the terminal input
	; finds what new text you have entered and sends it to the serial connection
	gui,Main:Submit,Nohide
	changes := ""
	changes := strReplace(gSendField,inputHistory) ;allows for copy paste events
	inputHistory := gSendField	
	changes := strReplace(changes,"`n","`n>>") ;modify for output formatting	
	send_serial(changes)
return

readData:
	;read data that is on the serial port buffer
	;post it to the terminal output
	Read_Data := RS232_Read(RS232_FileHandle,"0xFF",RS232_Bytes_Received)
	if(RS232_Bytes_Received>0)
	{
		critical on
		ASCII =
		Read_Data_Num_Bytes := StrLen(Read_Data) / 2 ;RS232_Read() returns 2 characters for each byte
		textRecieved := ""
		Loop %Read_Data_Num_Bytes%
		{
			StringLeft, Byte, Read_Data, 2
			StringTrimLeft, Read_Data, Read_Data, 2
			Byte = 0x%Byte%
			;msgbox %Byte%
			Byte := Byte + 0 ;Convert to Decimal       


			ASCII_Chr := Chr(Byte)
			textRecieved .= ASCII_Chr
			
		}
		critical off
		gui,Main:Submit,Nohide
		textRecieved := gRecieveField . textRecieved
		guiControl,Main:,gRecieveField,%textRecieved%
	}
	setTimer, readData, -%RS232_Delay%
return

^+r::
	reload
return

send_serial(data)
{
	global
	;msgbox %data%
	SetFormat, INTEGER, H
	var := ""
	loop parse,data
	{		
		var .= Asc(SubStr(A_LoopField,0)) . "`," ;Get the key that was pressed and convert it to its ASCII code
	}	
	SetFormat, INTEGER, D
	RS232_Write(RS232_FileHandle,var)	
}

#Include console.ahk

console.ahk modified from some version from this thread https://autohotkey.com/board/topic/26231-serial-com-port-console-script/

Code: Select all

;################### Serial_Port_Console_ReadFile.ahk ###################
; 8/11/09
; Assembled, tested (on WinXP), and debugged by aobrien with help from
;   other AHK forum members (especially Lexikos) and threads.
;
; This script is based upon dll structures that are built into the
; Microsoft Windows environment. This script is ugly (not very readable),
; because, it was written for demonstration purposes and I didn't want
; to complicate things by using #Include files.
;
; The most useful subroutines are listed below. Take them and write your
; application around them.
;     RS232_FileHandle:= RS232_Initialize(RS232_Settings) -- Get the filehandle
;     RS232_Close(RS232_FileHandle)
;     RS232_Read(RS232_FileHandle,"0xFF",RS232_Bytes_Received) -- 0xFF Size of receive buffer. This 
;                                returns HEX data (in ASCII form) received from the serial port.
;     Example: Read_Data := RS232_Read(RS232_FileHandle,"0xFF",RS232_Bytes_Received) ;if the RX buffer 
;              contained 0x11, 0x22, 0x00, 0x33, 0x44 then Read_Data will contain 1122003344
;
;     RS232_Write(RS232_FileHandle,Hex_Data) -- Comma delimited hex data. If I wanted to
;                               send "Hello World" I would do the following:
;     ;ASCII DATA=  H    e    l    l    o   SP    W    o    r    l    d
;     Hex_Data = 0x48,0x65,0x6C,0x6C,0x6F,0x20,0x57,0x6F,0x72,0x6C,0x64
;     RS232_Write(RS232_FileHandle,Hex_Data)
;
; Instructions:
; 1) Modify the RS232 port settings (under the User Variables heading)
;    to your needs and save the file.
;
; 2) Launch this script to connect to the RS232 COM Port.
;
; 3) CTRL-F1 to close the RS232 COM port and exit the receive loop.
;
; Script Behavior/Notes:
; * The script is designed to use a text editor (Notepad) to place the
;     received RS232 COM port characters.
; * When you attempt to type into the designated text editor the script
;     will capture the character and send it out the RS232 COM port. This is
;     accomplished with the Hotkey Assignments section.
; * Currently the script is written to only send/receive ASCII characters,
;     however, it would be REALLY EASY to modify the script so that it
;     will output/input data - something that HyperTerminal can't do.
; * When you first launch the script it will open Notepad and save it
;     using the Console_Path variable and a predetermined file name.
;
; !!!The Notepad text file MUST be saved so that the words
;      "COM1_Console.txt - Notepad" appear as the window
;      title, because the script will want to change to the window with
;      that name when it receives a character on the RS232 COM port.
;
;########################################################################
MsgBox, Begin RS232 COM Test

#SingleInstance Force
SetTitleMatchMode, 2

;########################################################################
;###### User Variables ##################################################
;########################################################################
RS232_Port     := "COM11"
RS232_Baud     := "57600"
RS232_Parity   = N
RS232_Data     = 8
RS232_Stop     = 1
Console_Path = C:\Users\Colt\Desktop

;########################################################################
;###### Script Variables ################################################
;########################################################################
RS232_Settings   = %RS232_Port%:baud=%RS232_Baud% parity=%RS232_Parity% data=%RS232_Data% stop=%RS232_Stop% dtr=Off
Console_File_Name= %RS232_Port%_Console.txt
Console_Title    = %Console_File_Name% - Notepad
RS232_FileHandle := RS232_Initialize(RS232_Settings)


;########################################################################
;###### Notepad Console Check ###########################################
;########################################################################
;Check for console, if there isn't already one, then open it.


;########################################################################
;###### Hotkey Assignments - Used for Serial Port Transmit ##############
;########################################################################
;If the Console window is the focus then typing any character on the
;  keyboard will cause the script to send the character out the RS232 COM port.


;########################################################################
;###### Serial Port Receive #############################################
;########################################################################
;Quit_var is used to exit the RS232 COM port receive loop
;  0=Don't Exit; 1=Exit; CTRL-F1 to set to 1 and exit script.
;Quit_var = 0
;RS232_FileHandle:=RS232_Initialize(RS232_Settings)

;RS232 COM port receive loop
/*
Loop
{
  sleep 200
  ;0xFF in the line below sets the size of the read buffer.
  Read_Data := RS232_Read(RS232_FileHandle,"0xFF",RS232_Bytes_Received)
  ;MsgBox,RS232_FileHandle=%RS232_FileHandle% `n RS232_Bytes_Received=%RS232_Bytes_Received% `n Read_Data=%Read_Data% ; Variable that is set by RS232_Read()

  ;Process the data, if there is any.
  If (RS232_Bytes_Received > 0)
  {
    ;MsgBox, Read_Data=%Read_Data%

    ;Prevent interruption during execution of this loop.
    Critical, On

    ;If care is taken, you can comment out these WinActive lines for performance gains.
    ;IfWinNotActive, %Console_Title%, , WinActivate, %Console_Title%,
    ;  WinWaitActive, %Console_Title%,   

    ;7/23/08 Modified this IF statement because RS232_Read() now returns data instead of ASCII
    ;Set to 0 if you want to see the hex data as received by the serial port.
    IF (1)
    {
      ;Begin Data to ASCII conversion
      ASCII =
      Read_Data_Num_Bytes := StrLen(Read_Data) / 2 ;RS232_Read() returns 2 characters for each byte

      Loop %Read_Data_Num_Bytes%
      {
        StringLeft, Byte, Read_Data, 2
        StringTrimLeft, Read_Data, Read_Data, 2
        Byte = 0x%Byte%
		;msgbox %Byte%
        Byte := Byte + 0 ;Convert to Decimal       
        if(Byte == 32)
		{
			;msgbox hi
			ASCII_Chr := "{SPACE}"
		}
		else
		{
			ASCII_Chr := Chr(Byte)
		}
        ASCII = %ASCII%%ASCII_Chr%
      }
      Send, ^{END}
      Send, %ASCII%
      ;End Data to ASCII conversion
    }
    Else ;Send the data that was received by the RS232 COM port-ASCII format
      Send, ^{END}%Read_Data%

    Critical, Off
  }

  ;CTRL-F1 sets Quit_var=1
  if Quit_var = 1
    Break
}

RS232_Close(RS232_FileHandle)

MsgBox, AHK is now disconnected from %RS232_Port%
;ExitApp ;Exit Script
Return
*/

;########################################################################
;###### Serial Port Transmit ############################################
;########################################################################

;###### Normal Key Presses ######
f4::
data := "m.f6000"
loop parse,data
{
	
	var := Asc(SubStr(A_LoopField,0)) ;Get the key that was pressed and convert it to its ASCII code
	msgbox %var%
	RS232_Write(RS232_FileHandle,var) ;Send it out the RS232 COM port
}
RS232_Write(RS232_FileHandle,13) ;Send it out the RS232 COM port
return

;###### Shift Key Presses ######
HotkeySub_Char_Shift:
var := SubStr(A_ThisHotkey,0) ;Get the key that was pressed.
StringUpper, var, var         ;Convert it to uppercase
var := Asc(var)               ;Get the ASCII equivalent
RS232_Write(RS232_FileHandle,var)  ;Send it out the RS232 COM port
return



;########################################################################
;###### Initialize RS232 COM Subroutine #################################
;########################################################################
RS232_Initialize(RS232_Settings)
{
  ;###### Extract/Format the RS232 COM Port Number ######
  ;7/23/08 Thanks krisky68 for finding/solving the bug in which RS232 COM Ports greater than 9 didn't work.
  StringSplit, RS232_Temp, RS232_Settings, `:
  RS232_Temp1_Len := StrLen(RS232_Temp1)  ;For COM Ports > 9 \\.\ needs to prepended to the COM Port name.
  If (RS232_Temp1_Len > 4)                   ;So the valid names are
    RS232_COM = \\.\%RS232_Temp1%             ; ... COM8  COM9   \\.\COM10  \\.\COM11  \\.\COM12 and so on...
  Else                                          ;
    RS232_COM = \\.\%RS232_Temp1%
	


  ;8/10/09 A BIG Thanks to trenton_xavier for figuring out how to make COM Ports greater than 9 work for USB-Serial Dongles.
  StringTrimLeft, RS232_Settings, RS232_Settings, RS232_Temp1_Len+1 ;Remove the COM number (+1 for the semicolon) for BuildCommDCB.
  ;MsgBox, RS232_COM=%RS232_COM% `nRS232_Settings=%RS232_Settings%

  ;###### Build RS232 COM DCB ######
  ;Creates the structure that contains the RS232 COM Port number, baud rate,...
  VarSetCapacity(DCB, 28)
  BCD_Result := DllCall("BuildCommDCB"
       ,"str" , RS232_Settings ;lpDef
       ,"UInt", &DCB)        ;lpDCB
  If (BCD_Result <> 1)
  {
   ; MsgBox, There is a problem with Serial Port communication. `nFailed Dll BuildCommDCB, BCD_Result=%BCD_Result%.
    ;Exit
	RS232_FileHandle:=0
	Return %RS232_FileHandle%
  }


	  ;###### Create RS232 COM File ######
	  ;Creates the RS232 COM Port File Handle
	  RS232_FileHandle := DllCall("CreateFile"
		   ,"Str" , RS232_COM     ;File Name         
		   ,"UInt", 0xC0000000   ;Desired Access
		   ,"UInt", 3            ;Safe Mode
		   ,"UInt", 0            ;Security Attributes
		   ,"UInt", 3            ;Creation Disposition
		   ,"UInt", 0            ;Flags And Attributes
		   ,"UInt", 0            ;Template File
		   ,"Cdecl Int")

	  If (RS232_FileHandle < 1)
	  {
		;MsgBox, There is a problem with Serial Port communication. `nFailed Dll CreateFile, RS232_FileHandle=%RS232_FileHandle% `nThe Script Will Now Exit.
		RS232_FileHandle:=0
		Return %RS232_FileHandle%
	  }

	  ;###### Set COM State ######
	  ;Sets the RS232 COM Port number, baud rate,...
	  SCS_Result := DllCall("SetCommState"
		   ,"UInt", RS232_FileHandle ;File Handle
		   ,"UInt", &DCB)          ;Pointer to DCB structure
	  If (SCS_Result <> 1)
	  {
		;MsgBox, There is a problem with Serial Port communication. `nFailed Dll SetCommState, SCS_Result=%SCS_Result% `nThe Script Will Now Exit.
		RS232_Close(RS232_FileHandle)
		;Exit
	  }

	  ;###### Create the SetCommTimeouts Structure ######
	  ReadIntervalTimeout        = 0xffffffff
	  ReadTotalTimeoutMultiplier = 0x00000000
	  ReadTotalTimeoutConstant   = 0x00000000
	  WriteTotalTimeoutMultiplier= 0x00000000
	  WriteTotalTimeoutConstant  = 0x00000000

	  VarSetCapacity(Data, 20, 0) ; 5 * sizeof(DWORD)
	  NumPut(ReadIntervalTimeout,         Data,  0, "UInt")
	  NumPut(ReadTotalTimeoutMultiplier,  Data,  4, "UInt")
	  NumPut(ReadTotalTimeoutConstant,    Data,  8, "UInt")
	  NumPut(WriteTotalTimeoutMultiplier, Data, 12, "UInt")
	  NumPut(WriteTotalTimeoutConstant,   Data, 16, "UInt")

	  ;###### Set the RS232 COM Timeouts ######
	  SCT_result := DllCall("SetCommTimeouts"
		 ,"UInt", RS232_FileHandle ;File Handle
		 ,"UInt", &Data)         ;Pointer to the data structure
	  If (SCT_result <> 1)
	  {
		;MsgBox, There is a problem with Serial Port communication. `nFailed Dll SetCommState, SCT_result=%SCT_result% `nThe Script Will Now Exit.
		RS232_Close(RS232_FileHandle)
		;Exit
	  } 
	;Msgbox %RS232_FileHandle%
	Return %RS232_FileHandle%
	
}

;########################################################################
;###### Close RS23 COM Subroutine #######################################
;########################################################################
RS232_Close(RS232_FileHandle)
{
  ;###### Close the COM File ######
  CH_result := DllCall("CloseHandle", "UInt", RS232_FileHandle)
  If (CH_result <> 1)
    ;MsgBox, Failed Dll CloseHandle CH_result=%CH_result%
  Return
}

;########################################################################
;###### Write to RS232 COM Subroutines ##################################
;########################################################################
RS232_Write(RS232_FileHandle,Message)
{
  SetFormat, Integer, DEC

  ;Parse the Message. Byte0 is the number of bytes in the array.
  StringSplit, Byte, Message, `,
  Data_Length := Byte0
  ;MsgBox, Data_Length=%Data_Length% b1=%Byte1% b2=%Byte2% b3=%Byte3% b4=%Byte4%

  ;Set the Data buffer size, prefill with 0xFF.
  VarSetCapacity(Data, Byte0, 0xFF)

  ;Write the Message into the Data buffer
  i=1
  Loop %Byte0%
  {
    NumPut(Byte%i%, Data, (i-1) , "UChar")
    ;MsgBox, %i%
    i++
  }
  ;MsgBox, Data string=%Data%

  ;###### Write the data to the RS232 COM Port ######
  WF_Result := DllCall("WriteFile"
       ,"UInt" , RS232_FileHandle ;File Handle
       ,"UInt" , &Data          ;Pointer to string to send
       ,"UInt" , Data_Length    ;Data Length
       ,"UInt*", Bytes_Sent     ;Returns pointer to num bytes sent
       ,"Int"  , "NULL")
  If (WF_Result <> 1 or Bytes_Sent <> Data_Length)
    MsgBox, Failed Dll WriteFile to RS232 COM, result=%WF_Result% `nData Length=%Data_Length% `nBytes_Sent=%Bytes_Sent%
}

;########################################################################
;###### Read from RS232 COM Subroutines #################################
;########################################################################
RS232_Read(RS232_FileHandle,Num_Bytes,ByRef RS232_Bytes_Received)
{
  SetFormat, Integer, HEX

  ;Set the Data buffer size, prefill with 0x55 = ASCII character "U"
  ;VarSetCapacity won't assign anything less than 3 bytes. Meaning: If you
  ;  tell it you want 1 or 2 byte size variable it will give you 3.
  Data_Length  := VarSetCapacity(Data, Num_Bytes, 0x55)
  ;MsgBox, Data_Length=%Data_Length%

  ;###### Read the data from the RS232 COM Port ######
  ;MsgBox, RS232_FileHandle=%RS232_FileHandle% `nNum_Bytes=%Num_Bytes%
  Read_Result := DllCall("ReadFile"
       ,"UInt" , RS232_FileHandle   ; hFile
       ,"Str"  , Data             ; lpBuffer
       ,"Int"  , Num_Bytes        ; nNumberOfBytesToRead
       ,"UInt*", RS232_Bytes_Received   ; lpNumberOfBytesReceived
       ,"Int"  , 0)               ; lpOverlapped

  ;MsgBox, RS232_FileHandle=%RS232_FileHandle% `nRead_Result=%Read_Result% `nBR=%RS232_Bytes_Received% ,`nData=%Data%
  If (Read_Result <> 1)
  {
   ; MsgBox, There is a problem with Serial Port communication. `nFailed Dll ReadFile on RS232 COM, result=%Read_Result% - The Script Will Now Exit.
    RS232_Close(RS232_FileHandle)
    Exit
  }

  ;###### Format the received data ######
  ;This loop is necessary because AHK doesn't handle NULL (0x00) characters very nicely.
  ;Quote from AHK documentation under DllCall:
  ;     "Any binary zero stored in a variable by a function will hide all data to the right
  ;     of the zero; that is, such data cannot be accessed or changed by most commands and
  ;     functions. However, such data can be manipulated by the address and dereference operators
  ;     (& and *), as well as DllCall itself."
  i = 0
  Data_HEX =
  Loop %RS232_Bytes_Received%
  {
    ;First byte into the Rx FIFO ends up at position 0

    Data_HEX_Temp := NumGet(Data, i, "UChar") ;Convert to HEX byte-by-byte
    StringTrimLeft, Data_HEX_Temp, Data_HEX_Temp, 2 ;Remove the 0x (added by the above line) from the front

    ;If there is only 1 character then add the leading "0'
    Length := StrLen(Data_HEX_Temp)
    If (Length =1)
      Data_HEX_Temp = 0%Data_HEX_Temp%

    i++

    ;Put it all together
    Data_HEX := Data_HEX . Data_HEX_Temp
  }
  ;MsgBox, Read_Result=%Read_Result% `nRS232_Bytes_Received=%RS232_Bytes_Received% ,`nData_HEX=%Data_HEX%

  SetFormat, Integer, DEC
  Data := Data_HEX

  Return Data
}

;########################################################################
;###### Exit Console Receive Loop #######################################
;########################################################################
^F1::
Quit_var = 1
return

^r::
	reload
	return

Albireo
Posts: 1778
Joined: 16 Oct 2013, 13:53

Re: Communication between Autohotkey / Arduino

Post by Albireo » 13 Dec 2019, 13:49

Great solution!
I tested the communication, with this program
in the Arduino .:
If Baud Rate is 9600 bps I can't see any error in the result (on the GUI - Terminal Output) :D

But if the Baud Rate is 19200 - 128000 bps, the desired header - - - - - - TERMINAL OUTPUT - - - - - -
will always / most often get incorrect characters at the beginning of the heading when the AHK-program above is started.
(for example) Ý - - - - - TERMINAL OUTPUT - - - - - - - - or ¶¶- - - - - - - TERMINAL OUTPUT - - - - - - - -
(not sure which characters are created in the beginning of the header)

colt
Posts: 291
Joined: 04 Aug 2014, 23:12
Location: Portland Oregon

Re: Communication between Autohotkey / Arduino

Post by colt » 13 Dec 2019, 14:06

Glad it worked for you. The reason you are getting garbage could be due to existing characters on the serial buffer. You should try clearing the buffer by doing a dummy RS232_Read before sending the header.

Code: Select all

garbage := RS232_Read(RS232_FileHandle,"0xFF",RS232_Bytes_Received)
send_serial(header)

Albireo
Posts: 1778
Joined: 16 Oct 2013, 13:53

Re: Communication between Autohotkey / Arduino

Post by Albireo » 27 Dec 2019, 05:44

Now I have tried to clear the buffer.
I have tested different delays (But nothing seems to help)
It has something to do with the initiation of the USB port - I think.
Console.ahk
is written (and tested) by Windows XP.
One of the thing I don't understand with the Console.ahk (above) code is the if-statemant.: If (RS232_Temp1_Len > 4) ; So the valid names are
RS232_COM = \\.\%RS232_Temp1% ; ... COM8 COM9 \\.\COM10 \\.\COM11 \\.\COM12 and so on...
else
RS232_COM = \\.\%RS232_Temp1%
(what's the difference.)

It seems that USB applications should be developed around winusb.sys (from Win 8.1) Overview of developing Windows applications for USB devices
winusb.sys Appears to be backwards compatible with previous Operating Systems WinUSB (Winusb.sys)

or is it USB serial driver (usbser.sys) to be used for communication with USB devices with Windows 10?

colt
Posts: 291
Joined: 04 Aug 2014, 23:12
Location: Portland Oregon

Re: Communication between Autohotkey / Arduino

Post by colt » 06 Jan 2020, 10:14

No doubt the code is very outdated and is a miracle it is still working.

You should create direct loopback with the micro to take the arduino out of the equation. Do this by putting a jumper between your tx and rx on your arduino and remove the ic from the socket.

It is weird that it only happens at higher baud. Does it happen at 57600?

Do you still see garbage if you comment out all the send(header) commands and just manually type? This will put the program into pure listening mode.

A quick workaround would to put your arduino into a loop sending an initialization character. When you see the full uncorrupted character in the data stream in autohotkey reply with the same initialization character. When the arduino sees this character it will know it has established a clean connection and can break the loop to proceed with the rest of the program.

FancieFink
Posts: 1
Joined: 04 Mar 2020, 11:36

Re: Communication between Autohotkey / Arduino

Post by FancieFink » 04 Mar 2020, 11:47

Hi... I've found another issue to be a USB cord that was too long (9ft). I've replaced the cable with a shorter one.
I'm still having issues with the serial connection, it randomly stops working after a few hours.I've also switched from AutoHotKey to C++.. No luck, the connection randomly crashes.
Last edited by gregster on 26 Mar 2020, 14:24, edited 5 times in total.
Reason: Spam removed.

Albireo
Posts: 1778
Joined: 16 Oct 2013, 13:53

Re: Communication between Autohotkey / Arduino

Post by Albireo » 04 Mar 2020, 13:55

FancieFink wrote:
04 Mar 2020, 11:47
Hi... I've found another issue to be a USB cord that was too long (9ft). I've replaced the cable with a shorter one.
I'm still having issues with the serial connection, it randomly stops working after a few hours.I've also switched from AutoHotKey to C++.. No luck, the connection randomly crashes.
What baud rate did you test against?

I only had problems right at the beginning when the communication was to be initiated, since the serial flow started, I experienced no problems. (didn't have a long USB cable - maybe 1m)

KiddoV
Posts: 13
Joined: 11 May 2020, 20:29

Re: Communication between Autohotkey / Arduino

Post by KiddoV » 22 Dec 2020, 14:13

Anyone know how to send a break signal to a serial port. Just like Teraterm send break with command "sendbreak" or short cut alt+B?. I need to do that on an embed port.
Thanks!

Post Reply

Return to “Ask for Help (v1)”