AutoHotkey Homepage AutoHotkey Community
Let's help each other out
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Serial ( COM ) Port Console Script
Goto page Previous  1, 2, 3, 4, 5, 6, 7, 8, 9  Next
 
Reply to topic    AutoHotkey Community Forum Index -> Scripts & Functions
View previous topic :: View next topic  
Author Message
Lesley



Joined: 17 Dec 2009
Posts: 1
Location: UK

PostPosted: Thu Dec 17, 2009 5:16 am    Post subject: HELP! pc to nxt bluetooth Reply with quote

hello everyone, I am just a mere student compared to all the geniuses on this forum like aobrein & trenton_xavier. I have a project and I need to be able to send strings to the lego NXT. The nxt bluetooth protocol involves hexadecimal values, and frankly i dont understand it. The protocol can be seen after downloading the bluetooth developer kit in the link below

http://mindstorms.lego.com/en-us/support/files/default.aspx


I have been able to use aobrein code, the code NOT involving the PORT.dll to establish a connection between my pc and the lego NXT. Now, I just need to be able to send string or integer( just a code to be able to send "a" for example).

Please please I need your help as this is my final year project.
Thank you!
Back to top
View user's profile Send private message
aobrien



Joined: 14 Feb 2008
Posts: 70
Location: Santa Clara, CA

PostPosted: Thu Dec 24, 2009 6:11 am    Post subject: Reply with quote

Hi Golericas,

I don't think that it will be possible to do what you want (serial port snooping) with this script - not very easily at any rate. I think Trenton's idea is best use some other software to do the sniffing.

aobrien
Back to top
View user's profile Send private message
aobrien



Joined: 14 Feb 2008
Posts: 70
Location: Santa Clara, CA

PostPosted: Thu Dec 24, 2009 6:23 am    Post subject: Reply with quote

Hi Lesley,

This Serial Port (COM) Script can send/receive any 8 bit combination on any serial port. If you wanted to send the string 'a' you would have to look up the ASCII equivalent. http://www.asciitable.com/

0x61 is the equivalent to 'a'. Whenever someone sends the string 'a' they are actually sending the hex code 0x61 or the binary code 01100001.

So, if you wanted to send 'a' you would use the following command... Write_to_COM(0x61)

This is all documented at the beginning of the script. If you are still having problems then post your script and what you are trying to do and we can go from there.

aobrien
Back to top
View user's profile Send private message
GerryT
Guest





PostPosted: Tue Jan 05, 2010 11:03 am    Post subject: Reply with quote

Hello all, I would like to hopefully add this to my init string,

3 standard port <Flow Control Options>,

-NONE
-HARDWARE
-XON/XOFF


Can someone please show how these options work into COM_Settings string? Smile
Back to top
Franz
Guest





PostPosted: Wed Jan 06, 2010 2:19 pm    Post subject: Reply with quote

Greets > what does the DTR=OFF optoin stand for.. and this value otherwise may contain? Cool
Back to top
trenton_xavier



Joined: 16 Jun 2008
Posts: 82
Location: Pittsburgh, Pennsylvania, USA

PostPosted: Wed Jan 06, 2010 5:27 pm    Post subject: Reply with quote

@GerryT

Here's the commplete BuildCommDCB function as described on MSDN (converted into AHK-ish):

Code:
COM_Settings = %COM_Port%:baud=%COM_Baud% parity=%COM_Parity% data=%COM_Data% stop=%COM_Stop% to=%COM_to% xon=%COM_xon% odsr=%COM_odsr% octs=%COM_octs% dtr=%COM_dtr% rts=%COM_rts% idsr=%COM_idsr%


Fill in or delete what you don't use, but they must be kept in this order!

From MSDN:
Quote:
By default, BuildCommDCB disables XON/XOFF and hardware flow control. To enable flow control, you must explicitly set the appropriate members of the DCB structure.



@Franz

DTR : http://en.wikipedia.org/wiki/Data_Terminal_Ready

It's for hardware control and can either be on, off, or hs (handshake).


References:
For BuildCommDCB syntax: http://msdn.microsoft.com/en-us/library/aa363143%28VS.85%29.aspx
For MODE syntax: http://technet.microsoft.com/en-us/library/bb490932.aspx
Back to top
View user's profile Send private message AIM Address
Guppy
Guest





PostPosted: Thu Jan 07, 2010 12:34 pm    Post subject: Reply with quote

Thank you for this console script, it is quite excellent and versatile.

I have a quick question - how do I retrieve the Device Description Value property from a selected COM? Smile
Back to top
aobrien



Joined: 14 Feb 2008
Posts: 70
Location: Santa Clara, CA

PostPosted: Tue Jan 12, 2010 1:36 am    Post subject: Reply with quote

Hi Guppy,

I'm not even sure what the Device Description Value is... I'm guessing that it is describing the device settings.

Anyway, this script isn't capable of retrieving the COM port settings. To do that would most likely require a separate DLL call.

Sorry,
aobrien
Back to top
View user's profile Send private message
wiseley



Joined: 22 Apr 2009
Posts: 29

PostPosted: Tue Jan 12, 2010 11:52 am    Post subject: Reply with quote

Guppy wrote:
Thank you for this console script, it is quite excellent and versatile.

I have a quick question - how do I retrieve the Device Description Value property from a selected COM? Smile


see http://www.autohotkey.com/forum/topic10030.html
Back to top
View user's profile Send private message
HelpAHK
Guest





PostPosted: Tue Jan 12, 2010 3:01 pm    Post subject: Reply with quote

Thank you everyone, ... all folks making this easier to understand and better. Very Happy

I am hoping someone can take some time to understand why problem described below is making my life miserable.

I am connecting this to a laptop, which hooks into an automobile engine performance monitor. It generates data on engine speed, battery life, etc.

Basically, I am trying to read data with Read_From_Com(Num_Bytes).

It works perfectly with this script. EXCEPT - if I unplug the device, and restart the script, I get garbage out of it. Even if I reboot I still get garbage out... somehow the script crashes the hardware.

HOWEVER, if I run something like Hyperterminal, ... and connect to it, the device works again, produces clean data. Everytime! So if I re-run the script, it works there again! Un-plug / re-plug hardware and run hyperterminal does not produce this result. It works & never a problem... This script works, only on first run.

What could this script not be doing to set things up?

I am really confused and open to any suggestions on what I can try. Thank you all for any ideas.

Cool
Back to top
aobrien



Joined: 14 Feb 2008
Posts: 70
Location: Santa Clara, CA

PostPosted: Tue Jan 19, 2010 5:24 pm    Post subject: Reply with quote

Hi HelpAHK,

I think that the problem might be in the Serial Port buffers in the PC. Read_from_COM() simply retrieves data from the buffers. If you don't close the COM port and/or flush out the buffer then you could get out of sync and everything would look like garbage. Sounds like HyperTerminal is taking care of the housekeeping. Did you try CTRL-F1 (close COM port) before you removed the cable?

I have an application that reads temperature from a multimeter. The multimeter constantly streams data regardless of what is connected. In this case I take a snapshot of the data and figure out where the starting point is then I take decode everything from that point.

Are you using the script exactly as posted or did you take the functions and make your own script? Can you post your code? If not then you could send it to me in a PM and I will look at it and help you debug.

Regards,
aobrien
Back to top
View user's profile Send private message
HelpAHK
Guest





PostPosted: Tue Jan 19, 2010 6:38 pm    Post subject: Reply with quote

Aobrien, thank you for the analysis which seems spot on to what might be happening here. I am utilizing the functions here just as they are with no further modifications. The garbage appears, even if I properly shut down (Close Com Port), then un-plug. Strangely, even if I re-boot, the garbage is still there. So the Windows buffer must keep it in state somewhere, and... yep, running Hyperterminal seems to do the trick to 're-set' things.

So I imagine, maybe there is something I can do up-front in my script to clean house, so things can get going right. Any ideas?
Back to top
aobrien



Joined: 14 Feb 2008
Posts: 70
Location: Santa Clara, CA

PostPosted: Tue Jan 26, 2010 5:42 pm    Post subject: Reply with quote

Hi HelpAHK,

Can you give me 3 things to look at?
1) The ASCII output in passing mode
2) Data in the passing mode
3) Data the failure mode

Then we will be able to compare the information to see if it is some sort of buffer/synchronization problem.

To enable data output make the change to the script shown below. You need to change the IF (1) to IF (0).

Code:
 
    ;7/23/08 Modified this IF statement because Read_from_COM() now returns data instead of ASCII
    ;Set to 0 if you want to see the hex data as received by the serial port.
    IF (0) ; <= Change the 1 to a 0
    {
      ;Begin Data to ASCII conversion
      ASCII =
      .
      .
      .


aobrien
Back to top
View user's profile Send private message
HelpAHK
Guest





PostPosted: Thu Jan 28, 2010 6:29 pm    Post subject: Reply with quote

Thank you! Smile I am working on this and will report some clear results soon. Thank you!
Back to top
haichen



Joined: 05 Feb 2007
Posts: 189
Location: Osnabrück, Germany

PostPosted: Tue Mar 16, 2010 2:26 pm    Post subject: standardlib compatibility Reply with quote

Dear aobrien,
thank you for your script! I used it to read data from a cheap weathersensor. It works very fine.

I made your functions stdlib compatible. Therfore i changed the names to PORT_ because there is already Seans COM_ bib.
But of course if you like to have it renamed i will change this. I got rid of the globals and everything work like expected. Hopefully ( I tested the readcapability only).
The only thing i changed was mentioning of the COM-number in the errormessages.

Maybe this is useful for you and others.

PORT.ahk (standardlib compatible)

Code:
;################### 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.
;     PORT_FileHandle:= PORT_Initialize(PORT_Settings) -- Get the filehandle
;     PORT_Close(PORT_FileHandle)
;     PORT_Read(PORT_FileHandle,"0xFF",PORT_Bytes_Received) -- 0xFF Size of receive buffer. This returns ASCII
;                                representation of the received HEX data.
;     Example: Read_Data := PORT_Read(PORT_FileHandle,"0xFF",PORT_Bytes_Received) ;if the RX buffer contained
;              0x11, 0x22, 0x00, 0x33, 0x44 then Read_Data will contain 1122003344
;     PORT_Write(PORT_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
;     PORT_Write(PORT_FileHandle,Hex_Data)
;
; Instructions:
; 1) Modify the COM port settings (under the User Variables heading)
;    to your needs and save the file.
;
; 2) Launch this script to connect to the COM Port.
;
; 3) CTRL-F1 to close the COM port and exit the receive loop.

;########################################################################
PORT_Initialize(PORT_Settings)
{
  ;###### Extract/Format the COM Port Number ######
  ;7/23/08 Thanks krisky68 for finding/solving the bug in which COM Ports greater than 9 didn't work.
  ;8/10/09 Moved this section to the beginning of the sub routine as part of trenton_xavier's fix.
  StringSplit, PORT_COM_Temp, PORT_Settings, `:
  PORT_COM_Temp1_Len := StrLen(PORT_COM_Temp1)  ;For COM Ports > 9 \\.\ needs to prepended to the COM Port name.
  If (PORT_COM_Temp1_Len > 4)                   ;So the valid names are
    PORT_COM = \\.\%PORT_COM_Temp1%             ; ... COM8  COM9   \\.\COM10  \\.\COM11  \\.\COM12 and so on...
  Else                                          ;
    PORT_COM = %PORT_COM_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, PORT_Settings, PORT_Settings, PORT_COM_Temp1_Len+1 ;Remove the COM number (+1 for the semicolon) for BuildCommDCB.
  ;MsgBox, PORT_COM=%PORT_COM% `nPORT_Settings=%PORT_Settings%

  ;###### Build COM DCB ######
  ;Creates the structure that contains the COM Port number, baud rate,...
  VarSetCapacity(DCB, 28)
  BCD_Result := DllCall("BuildCommDCB"
       ,"str" , PORT_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% `nThe Script Will Now Exit.
    Exit
  }

  ;###### Create COM File ######
  ;Creates the COM Port File Handle
  ;StringLeft, PORT_COM, PORT_Settings, 4  ; 7/23/08 This line is replaced by the "Extract/Format the COM Port Number" section above.
  PORT_FileHandle := DllCall("CreateFile"
       ,"Str" , PORT_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 (PORT_FileHandle < 1)
  {
    MsgBox, There is a problem with Serial Port communication. `nFailed Dll CreateFile, PORT_FileHandle=%PORT_FileHandle% `nThe Script Will Now Exit.
    Exit
  }
  ;msgbox, PORT_COM=%PORT_COM%`nPORT_FileHandle=%PORT_FileHandle%
  ;###### Set COM State ######
  ;Sets the COM Port number, baud rate,...
  SCS_Result := DllCall("SetCommState"
       ,"UInt", PORT_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.
    PORT_Close(PORT_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 COM Timeouts ######
  SCT_result := DllCall("SetCommTimeouts"
     ,"UInt", PORT_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.
    PORT_Close(PORT_FileHandle)
    Exit
  }
  ;msgbox, PORT_FileHandle=%PORT_FileHandle%
  Return %PORT_FileHandle%
}


;########################################################################
;###### Close COM Subroutine ############################################
;######################################################################## 
PORT_Close(PORT_FileHandle)
{
  ;###### Close the COM File ######
  CH_result := DllCall("CloseHandle", "UInt", PORT_FileHandle)
  If (CH_result <> 1)
    MsgBox, Failed Dll CloseHandle CH_result=%CH_result%

  Return
}

;########################################################################
;###### Write to COM Subroutines ########################################
;########################################################################
PORT_Write(PORT_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 COM Port ######
  WF_Result := DllCall("WriteFile"
       ,"UInt" , PORT_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 COM, result=%WF_Result% `nData Length=%Data_Length% `nBytes_Sent=%Bytes_Sent%
}

;########################################################################
;###### Read from COM Subroutines #######################################
;########################################################################
PORT_Read(PORT_FileHandle,Num_Bytes,ByRef PORT_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 COM Port ######
  ;msgbox, PORT_FileHandle=%PORT_FileHandle% `nNum_Bytes=%Num_Bytes%
  Read_Result := DllCall("ReadFile"
       ,"UInt" , PORT_FileHandle   ; hFile
       ,"Str"  , Data             ; lpBuffer
       ,"Int"  , Num_Bytes        ; nNumberOfBytesToRead
       ,"UInt*", PORT_Bytes_Received   ; lpNumberOfBytesReceived
       ,"Int"  , 0)               ; lpOverlapped
  ;MsgBox, PORT_FileHandle=%PORT_FileHandle% `nRead_Result=%Read_Result% `nBR=%PORT_Bytes_Received% ,`nData=%Data%
  If (Read_Result <> 1)
  {
    MsgBox, There is a problem with Serial Port communication. `nFailed Dll ReadFile on COM, result=%Read_Result% - The Script Will Now Exit.
    PORT_Close(PORT_FileHandle)
    Exit
  }

;;;;;;;; 7/23/08 This section is replaced by the code below ;;;;;;;;;;;;;
;  SetFormat, Integer, DEC
;
;  ;###### Format the received data ######
;  ;Return only the bytes that were received.
;  If (PORT_Bytes_Received = 0)
;    Return ""
;  Else
;    ;StringTrimRight, Data, Data, %PORT_Bytes_Received% ;5/22/08 This line is essentially useless and could potentially show up as a bug.
;    StringLeft, Data, Data, PORT_Bytes_Received ;5/22/08 This is what the above line should have been
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

  ;###### 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 %PORT_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% `nBR=%PORT_Bytes_Received% ,`nData_HEX=%Data_HEX%

  SetFormat, Integer, DEC
  Data := Data_HEX

  Return Data

}


example.ahk

Code:
  ; Instructions:
; 1) Modify the COM port settings (under the User Variables heading)
;    to your needs and save the file.
;
; 2) Launch this script to connect to the COM Port.
;
; 3) CTRL-F1 to close the COM port and exit the receive loop.
;
; Script Behavior/Notes:
; * The script is designed to use a text editor (Notepad) to place the
;     received COM port characters.
; * When you attempt to type into the designated text editor the script
;     will capture the character and send it out the 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 COM port.
;
;########################################################################
MsgBox, Begin COM Test

#SingleInstance Force
SetTitleMatchMode, 2

;########################################################################
;###### User Variables ##################################################
;########################################################################
COM_Port     = COM1
COM_Baud     = 115200
COM_Parity   = N
COM_Data     = 8
COM_Stop     = 1
Console_Path =


;########################################################################
;###### Script Variables ################################################
;########################################################################
COM_Settings = %COM_Port%:baud=%COM_Baud% parity=%COM_Parity% data=%COM_Data% stop=%COM_Stop% dtr=Off
Console_File_Name= %COM_Port%_Console.txt
Console_Title    = %Console_File_Name% - notepad


;########################################################################
;###### Notepad Console Check ###########################################
;########################################################################
;Check for console, if there isn't already one, then open it.
IfWinNotExist, %Console_Title%
{
  Run, Notepad
  WinWait, Untitled - Notepad
  Send, !fa  ;file save as
  WinWait, Save As
  Clipboard = %Console_Path%\%Console_File_Name%
  Send, ^v{ENTER}
}

;########################################################################
;###### 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 COM port.
Hotkey, IfWinActive, %Console_Title%,

;###### Direct Key Presses for a-z ######
Loop, 26
  HotKey, % "$" chr(96+A_Index), HotkeySub

;###### Direct Key Presses for 0-9 ######
Loop, 10
  HotKey, % "$" chr(47+A_Index), HotkeySub

;###### Direct Key Presses for Other Keys ######
HotKey, -, HotkeySub
HotKey, =, HotkeySub
HotKey, [, HotkeySub
HotKey, ], HotkeySub
HotKey, `;, HotkeySub
HotKey, `', HotkeySub
HotKey, `,, HotkeySub
HotKey, `., HotkeySub
HotKey, `/, HotkeySub
HotKey, `\, HotkeySub
Hotkey, Space, HotkeySub
Hotkey, ENTER, HotkeySub
Hotkey, BS, HotkeySub

;###### Shift Modified Character Key Presses for a-z. ######
Loop, 26
  HotKey, % "$+" chr(96+A_Index), HotkeySub_Char_Shift

;###### Shift Modified Character Key Presses for 0-9 ######
Loop, 10
  HotKey, % "$+" chr(47+A_Index), HotkeySub_Other_Shift

;###### Shift Modified Character Key Presses for Other Keys ######
HotKey, +-, HotkeySub_Other_Shift
HotKey, +=, HotkeySub_Other_Shift
HotKey, +[, HotkeySub_Other_Shift
HotKey, +], HotkeySub_Other_Shift
HotKey, +`;, HotkeySub_Other_Shift
HotKey, +`', HotkeySub_Other_Shift
HotKey, +`,, HotkeySub_Other_Shift
HotKey, +`., HotkeySub_Other_Shift
HotKey, +`/, HotkeySub_Other_Shift
HotKey, +`\, HotkeySub_Other_Shift

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

;COM port receive loop
Loop
{
  Read_Data := PORT_Read(PORT_FileHandle,"0xFF",PORT_Bytes_Received)
  ;msgbox,PORT_FileHandle=%PORT_FileHandle% `n PORT_Bytes_Received=%PORT_Bytes_Received% `n Read_Data=%Read_Data% ; Variable that is set by PORT_Read()

  ;0xFF in the above line basically sets the size of the read buffer.
  ;  Use StringLeft to collect only the data received by the COM port.
  ;  Bytes_Received is a global variable that is set during the PORT_Read() routine.
  ;StringLeft, Read_Data, Read_Data, Bytes_Received ;5/22/08 This line was moved to PORT_Read() subroutine.

  ;Process the data, if there is any.
  If (PORT_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 PORT_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 ;PORT_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%
        Byte := Byte + 0 ;Convert to Decimal       
        ASCII_Chr := Chr(Byte)
        ASCII = %ASCII%%ASCII_Chr%
      }
      Send, ^{END}%ASCII%
      ;End Data to ASCII conversion
    }
    Else ;Send the data that was received by the COM port-ASCII format
      Send, ^{END}%Read_Data%

    Critical, Off
  }

  ;CTRL-F1 sets Quit_var=1
  if Quit_var = 1
    Break
}
PORT_Close(PORT_FileHandle)

MsgBox, AHK is now disconnected from %COM_Port%
;ExitApp ;Exit Script
Return

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

;###### Normal Key Presses ######
HotkeySub:
var := Asc(SubStr(A_ThisHotkey,0)) ;Get the key that was pressed and convert it to its ASCII code
If A_ThisHotkey = Space
  var=0x20
If A_ThisHotkey = BS
  var=0x08
If A_ThisHotkey = ENTER
    var=0x0D,0x0A ;New Line, Carriage Return ; 7/23/08 Changed 0x0A,0x0D to 0x0D,0x0A

PORT_Write(PORT_FileHandle,var) ;Send it out the 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
PORT_Write(PORT_FileHandle,var)             ;Send it out the COM port
return

;###### Other Shift Key Presses ######
HotkeySub_Other_Shift:
var := SubStr(A_ThisHotkey,0) ; Get the key that was pressed.
;Convert it to the shift version
;  StringUpper won't work on the following.
If var = 1
  var = !
If var = 2
  var = @
If var = 3
  var = #
If var = 4
  var = $
If var = 5
  var = `%
If var = 6
  var = ^
If var = 7
  var = &
If var = 8
  var = *
If var = 9
  var = (
If var = 0
  var = )
If var = -
  var = _
If var = =
  var = +
If var = [
  var = {
If var = ]
  var = }
If var = \
  var = |
If var = `;
  var = :
If var = `'
  var = "
If var = `,
  var = <
If var = `.
  var = >
If var = `/
  var = ?

var := Asc(var)   ;Get the ASCII equivalent
PORT_Write(PORT_FileHandle,var) ;Send it out the COM port
return

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


#include port.ahk    ;if you use it as standardlib you can delete this
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic    AutoHotkey Community Forum Index -> Scripts & Functions All times are GMT
Goto page Previous  1, 2, 3, 4, 5, 6, 7, 8, 9  Next
Page 6 of 9

 
Jump to:  
You can post new topics in this forum
You can reply to topics in this forum


Powered by phpBB © 2001, 2005 phpBB Group