Jump to content

Serial Port /COM Port UDF


martin
 Share

Recommended Posts

hello, im having some debugging problems with the com udf, maybe im missing code or didn't use proper parameters.

if someone can please check my script in post 14 here

http://www.autoitscript.com/forum/index.ph...mp;#entry520597

the script runs for about less then 2 min then the com adapter disconnects, (it does that when a program closes connection with it) but the script is still going

and when that happens or when i wanna close the script it like freezes the com port and i have to reinstall the serial emulator, to restart the ports status.

Link to comment
Share on other sites

hello, im having some debugging problems with the com udf, maybe im missing code or didn't use proper parameters.

if someone can please check my script in post 14 here

http://www.autoitscript.com/forum/index.ph...mp;#entry520597

the script runs for about less then 2 min then the com adapter disconnects, (it does that when a program closes connection with it) but the script is still going

and when that happens or when i wanna close the script it like freezes the com port and i have to reinstall the serial emulator, to restart the ports status.

You have put CommSetPort inside the while loop. You only need to initialize the port once so put this line

_CommSetPort($COMn, $result, 4800, 8, 0, 1, 0)

before the while loop.

However, I wouldn't have expected that to cause the problem you report, although resetting the port parameters might make it look like the port is being closed I suppose.

Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

I don't have permision to make a new topic so I write here.

I don't know have to use _CommSendByteArray. Can you give any example?

I trying like this:

#include <GUIConstants.au3>
#include <CommMG.au3>
#include <Array.au3>

$set1 = _CommSetport(4,0,9600,8,0,1,0)
    

Dim $avArray
$avArray = _ArrayCreate(Dec("7B"),Dec("7B"),Dec("7B"),Dec("7B"),Dec("7B"),Dec("7B"))

_CommSendByteArray($avArray[1], 5,1000)

;===============================================================================

; Function Name: _CommSendByteArray($pAddr,$iNum,$iWait)

; Description: Sends the bytes from address $pAddress

; Parameters: $iNum the number of bytes to send.

; $iWaitComplete - integer: if 0 then functions returns without

; waiting for bytes to be sent

; if <> 0 then waits untill all bytes are sent.

; Returns: on success returns 1

; on failure returns -1 and sets @error to 1

;

;;NB could hang if byte cannot be sent and $iWaitComplete <> 0

; could lose data if you send more bytes than the size of the outbuffer.

; the output buffer size is 2048

;===============================================================================

Link to comment
Share on other sites

I don't have permision to make a new topic so I write here.

I don't know have to use _CommSendByteArray. Can you give any example?

I trying like this:

#include <GUIConstants.au3>
#include <CommMG.au3>
#include <Array.au3>

$set1 = _CommSetport(4,0,9600,8,0,1,0)
    

Dim $avArray
$avArray = _ArrayCreate(Dec("7B"),Dec("7B"),Dec("7B"),Dec("7B"),Dec("7B"),Dec("7B"))

_CommSendByteArray($avArray[1], 5,1000)

;===============================================================================

; Function Name: _CommSendByteArray($pAddr,$iNum,$iWait)

; Description: Sends the bytes from address $pAddress

; Parameters: $iNum the number of bytes to send.

; $iWaitComplete - integer: if 0 then functions returns without

; waiting for bytes to be sent

; if <> 0 then waits untill all bytes are sent.

; Returns: on success returns 1

; on failure returns -1 and sets @error to 1

;

;;NB could hang if byte cannot be sent and $iWaitComplete <> 0

; could lose data if you send more bytes than the size of the outbuffer.

; the output buffer size is 2048

;===============================================================================

You need to do this sort of thing. I'm not in a situation where I can test this so if it doesn't work let me know, however it shows how you use the address for the data to be sent and received. I have only used 4 bytes but it could be many more. Somewhere I have an example for recieving chunks of data, say 1K at a time, until you get the required amount. I think I've tested it by sending files which are exe's of a few Mb then running them to prove the transmission worked ok.

#include <CommMG3.au3>;or if you save the commMg.dll in the @scripdir use #include @SciptDir & '\commmg.dll'
Local $sportSetError, $result, $totRead
$sendbuf = DllStructCreate("byte[4]")
$pSendBuf = DllStructGetPtr($sendbuf)
$result = _CommSetPort("1",$sportSetError,115200);channel 1 is COM1
_commswitch(2)
_CommSetPort("11",$sportSetError,115200);channel 2 is COM11
_commswitch(1);go back to COM1

$in = binary("0x01995566")
msgbox(0,"Info $in, (to be sent)",$in)
DllStructSetData($sendbuf,1,$in)
$result = _CommSendByteArray($pSendBuf,4,0);send the 4 bytes
msgbox(0,"Info sendbytearray",$result)


$pruebas = DllStructGetData($sendbuf,1)
msgbox(0,"Info DllStructGetData",$pruebas)

;now replace data with 0
DllStructSetData($sendbuf,1,0x00000000)
msgbox(0,"Info DllStructGetData is now",$pruebas)

_Commswitch(2);now start using COM11
$result = _CommReadByteArray($pSendBuf,4,0);read the bytes sent out on COM1
msgbox(0,"Info readbytearray",$result)

$pruebas = DllStructGetData($sendbuf,1)
msgbox(0,"Info DllStructGetData after ReadByteArray",$pruebas);is the data back to what it was?

msgbox(0,"Info Close Port result",_CommClosePort())
Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

im trying to make a status box to check if the script connected to the com port or not

at first its a label that has a red background, and a button next to it that says connect and will connect to the com when pressed,

then when it connects i want the red label to change to green and say connected, and the button to say disconnect, and of course disconnect from the com

i can't figure out how to do this though?

Link to comment
Share on other sites

im trying to make a status box to check if the script connected to the com port or not

at first its a label that has a red background, and a button next to it that says connect and will connect to the com when pressed,

then when it connects i want the red label to change to green and say connected, and the button to say disconnect, and of course disconnect from the com

i can't figure out how to do this though?

This is more of a general support question than anything to do with the UDF.

Try this

#include <GUIConstantsEx.au3>
#include <staticconstants.au3>


GUICreate("My GUI"); will create a dialog box that when displayed is centered

$lab1 = GUICtrlCreateLabel("Not Connect", 10, 30, 90, 14, $SS_CENTER)
GUICtrlSetBkColor(-1, 0xff0000)
GUICtrlSetColor(-1, 0xffffff)

GUISetState(); will display an empty dialog box

; Run the GUI until the dialog is closed
$connected = False
Do
    $msg = GUIGetMsg()
    If $msg = $lab1 Then
        If Not $connected Then
    ;do the connect thing and check it returns true
    ;if connected ok now
            GUICtrlSetBkColor($lab1, 0x00ff00)
            $connected = True
            GUICtrlSetData($lab1, "Connected")
    ;endif connected ok
        Else
    ;do the disconnect thing and check it returns true
    ;if not connected now
            GUICtrlSetBkColor($lab1, 0xff0000)
            $connected = False
            GUICtrlSetData($lab1, "Not Connected")
    ;endif not connected
        EndIf
    EndIf
    
Until $msg = $GUI_EVENT_CLOSE
Edited by martin
Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

It's all I need.

Thank you verry much form POLAND.

Glad you're so easily pleased :)
Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

well ya no this is why i posted it here, im trying to have a colored label and next to it is the button, and the label only changes with the status of the com being connected or not, i think i found it, i can use if _CommPortConnection()

just now sure how i sould apply it to this code (i changed yours to how im looking for it to work)

#include <GUIConstantsEx.au3>
#include <staticconstants.au3>
GUICreate("testing status", 200, 50, 282, 399)
$lab1 = GUICtrlCreateLabel("Not Connected", 0, 0, 125, 50, BitOR($SS_CENTER,$SS_CENTERIMAGE))
GUICtrlSetBkColor(-1, 0xff0000)
GUICtrlSetColor(-1, 0xffffff)
$button = GUICtrlCreateButton("Connect", 125, 0, 75, 50, 0)
GUISetState(); will display an empty dialog box
$connected = False
Do
    $msg = GUIGetMsg()
    If $msg = $button Then
        If Not $connected Then
            GUICtrlSetBkColor($lab1, 0x00ff00)
            $connected = True
            GUICtrlSetData($button, "Disconnect")
            GUICtrlSetData($lab1, "Connected")
        Else
            GUICtrlSetBkColor($lab1, 0xff0000)
            $connected = False
            GUICtrlSetData($button, "Connect")
            GUICtrlSetData($lab1, "Not Connected")
        EndIf
    EndIf
Until $msg = $GUI_EVENT_CLOSE

This is more of a general support question than anything to do with the UDF.

Edited by seesoe
Link to comment
Share on other sites

well ya no this is why i posted it here, im trying to have a colored label and next to it is the button, and the label only changes with the status of the com being connected or not, i think i found it, i can use if _CommPortConnection()

Yes you could use that, but it might not return a Com port which is connected because it only returns the current channel connected. If you haven't used the CommSwitch function then this doesn't matter. Otherwise it does. If you want to know if COM17 is connected for example, but don't know which channel it might be used on then

$chan = IsConnected("COM17")
if $chan <> 0 then MsgBox(0,'COM17', "Is connected on channel " & $chan)

Func IsComConnected($someCOM)
    Local $n
    For $n = 1 To 4
        _CommSwitch ($n)
        If _CommPortConnection () = $someCOM Then Return $n
    Next
    Return 0;not connected
EndFunc  ;==>IsComConnected

(This makes me realize there is no method provided to find the current channel used. I will add that to my TODO list.)

Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

hmmm im not sure i fully understand, but i still used it and i got it working the way i want it now, when you press the button it only changes colors and says connected only when the connection is established and not once the button is pressed, thanks for the help:D

$msg = GUIGetMsg()
    If $msg = $button Then
        If Not $connected Then
            _CommSetPort(10,$errorHolder, 4800, 8, 0, 1, 0)
            If _CommPortConnection() Then
                GUICtrlSetBkColor($lab1, 0x00ff00)
                $connected = True
                GUICtrlSetData($button, "Disconnect")
                GUICtrlSetData($lab1, "Connected")
            Else
                GUICtrlSetBkColor($lab1, 0xff0000)
                $connected = False
                GUICtrlSetData($button, "Connect")
                GUICtrlSetData($lab1, "Not Connected")
            EndIf
        Else
            GUICtrlSetBkColor($lab1, 0xff0000)
            $connected = False
            GUICtrlSetData($button, "Connect")
            GUICtrlSetData($lab1, "Not Connected")
            _Commcloseport()
        EndIf
    EndIf
Link to comment
Share on other sites

hmmm im not sure i fully understand, but i still used it and i got it working the way i want it now, when you press the button it only changes colors and says connected only when the connection is established and not once the button is pressed, thanks for the help:D

$msg = GUIGetMsg()
    If $msg = $button Then
        If Not $connected Then
            _CommSetPort(10,$errorHolder, 4800, 8, 0, 1, 0)
            If _CommPortConnection() Then
                GUICtrlSetBkColor($lab1, 0x00ff00)
                $connected = True
                GUICtrlSetData($button, "Disconnect")
                GUICtrlSetData($lab1, "Connected")
            Else
                GUICtrlSetBkColor($lab1, 0xff0000)
                $connected = False
                GUICtrlSetData($button, "Connect")
                GUICtrlSetData($lab1, "Not Connected")
            EndIf
        Else
            GUICtrlSetBkColor($lab1, 0xff0000)
            $connected = False
            GUICtrlSetData($button, "Connect")
            GUICtrlSetData($lab1, "Not Connected")
            _Commcloseport()
        EndIf
    EndIf
I don't quite agree with what you've done. _CommPortConnection returns the port connected; it might not be the one you tried to connect to if it failed. So I think it would be more reliable to do this

_CommSetPort(10,$errorHolder, 4800, 8, 0, 1, 0)
 If _CommPortConnection() = "COM10" Then

But it would be easier to do this

if _CommSetPort(10,$errorHolder, 4800, 8, 0, 1, 0) then
Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

i have a drop down menu, and even if i pick one of the other ones it still goes to connected, but no biggy, i picked to use ur second method it worked like how i did but i guess just better coding.

Link to comment
Share on other sites

  • 3 weeks later...

For beginner.

#include <GuiConstantsEx.au3>
#include <CommMG.au3>
#include <file.au3>
#include <Date.au3>
#include <WindowsConstants.au3>

;You can see what send to port com. You must download PortMon from Microsoft.

GuiCreate("ConnectToPort by SZYJA"&Chr(153), 400, 220)
GUISetFont (10, 400, 0)
$Edit = GUICtrlCreateEdit("",0,120,400,100,$WS_VSCROLL)
GUISetFont (8.5, 400, 0)
;----------------------------------------------------------------------
$list_ports = _CommlistPorts()
GUICtrlCreateLabel("Choose port: ", 10, 30, 70, 20)
$available_port = GuiCtrlCreatecombo("",80, 26, 60,20)
GUICtrlSetData(-1,""&$list_ports)
$connect = GUICtrlCreateButton("Connect", 155,17,110,40)
$disconnect = GUICtrlCreateButton("Disconnect", 280,17,110,40)
GUICtrlSetState ($disconnect, $gui_disable)
$send_string = GUICtrlCreateButton("Send String", 155,70,110,40)
$clear_edit = GUICtrlCreateButton("Clear edit", 280,70,110,40)
;----------------------------------------------------------------------
$HW = "Hello World";string to send
guisetstate ()
while 1;start main loop
;----------------------------------------------------------------------
;----------------------------------------------------------------------
$open_port = 0
$status_port = 0
while $open_port <= 0 ;start connect loop
   
    $msg_1 = GUIGetMsg()
   
Select
    case $msg_1 = $connect ;connect to port
            $file = Fileopen("Log.txt", 1);Create a log file
            ;----------------------------------------------------------------------
            local $result
            $baud = 115200
            $bits = 8
            $par = 0
            $stop = 1
            $flow = 0
            sleep(100)
            ;----------------------------------------------------------------------     
            $_available_port = GUICtrlRead($available_port)
            $nr_port = StringReplace(""&$_available_port, "COM", "")
            $status_port = _CommSetPort($nr_port,$result,$baud,$bits,$par,$stop,$flow)
                if $status_port = 1 Then
                    FileWriteLine($file, "" &_NowTime() &" Connect to port: " &$_available_port)
                    sleep(400)
                Else
                    MsgBox(0,"Error","Port "&$nr_port &" " &$result)
                EndIf
            $open_port =  $status_port
       
    case $msg_1 = $gui_event_close
        exit   

EndSelect
wend;end connect loop. We connected.
;----------------------------------------------------------------------
;---------------------------------------------------------------------- 
if $open_port = 1 Then
    GUICtrlSetState ($connect, $gui_disable)
    GUICtrlSetState ($disconnect, $gui_enable)
    GUICtrlSetState ($available_port, $gui_disable)
EndIf


while 1;start program loop
    $msg = GUIGetMsg()
   
Select
    case $msg = $send_string
        _CommSendString($HW,10)
        FileWriteLine($file, "" &_NowTime() &" " &$HW)
        ;sometimes need sleep before use _Commgetstring()
        ;sleep(1500)
        $rec = _Commgetstring()
        GUICtrlSetData($Edit, $rec)
       
    Case $msg = $clear_edit
        GUICtrlSetData($Edit, "")
   
    case $msg = $disconnect
        _CommClosePort()
        sleep(400)
        GUICtrlSetState ($connect, $gui_enable)
        GUICtrlSetState ($disconnect, $gui_disable)
        GUICtrlSetState ($available_port, $gui_hide)
        $list_ports = _CommlistPorts()
        $available_port = GuiCtrlCreatecombo("",80, 26, 60,20)
        GUICtrlSetData(-1,""&$list_ports)
        FileWriteLine($file, "" &_NowTime() &" Disconnected")
        FileClose($file)
        exitloop;escape to start main  loop
       
    case $msg = $gui_event_close
        _CommClosePort()
        exit   
EndSelect

wend;end start program loop
;----------------------------------------------------------------------
wend;end main loop
;----------------------------------------------------------------------
Edited by kmeleon

Feed Polish children: pajacyk - just go to this page and close it. Thanks. World website: free rice.

Link to comment
Share on other sites

Nice script!

Read first pages...

Is possible to pilote a self build circuit capable to turn on my desk lamp ?

If yes, anyone can help me to find information to build a simple serial com interface ?

thank you!

m.

Link to comment
Share on other sites

Nice script!

Read first pages...

Is possible to pilote a self build circuit capable to turn on my desk lamp ?

If yes, anyone can help me to find information to build a simple serial com interface ?

thank you!

m.

Such a circuit can be made using the serial port or using the parallel port. (There are other threads in Example Scripts for parallel ports.) You can buy serial port driven Input/output interfaces for a reasonable price.

Trying to switch mains is VERY dangerous (death can easily result) and there is no need to do that directly at all.

If you want to switch your lamp on and off, and you want to make your own circuit then please do it this way.

Buy a remote controlled mains socket. These are very cheap and come with a remote controller (like a remote TV controller). Then connect your relays across buttons on the remote controller and plug your lamp into the remotely controlled socket. It means messing with the controller but that won't harm you no matter what you do (apart from trying to swallow it) It also means no need for wires from the PC to the lamp, and no danger, and often one controller can control up to 5 different sockets so you could have some fun with it.

Edited by martin
Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

Would this dll work in WinPE 2 ?

I would expect so but I haven't tried. If you try let me know what happens.
Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

  • 3 weeks later...

Hi Martin,

Looks like you've made a pretty awesome script! I'm a newbie to autoit and COM communication am desperately trying to communicate with some hardware of mine. I have a laser micrometer that is set to measure diameters of different objects and then puts their profiles into AutoCAD. I've been able to automate the importation into AutoCAD and everything but have failed in communicating with my micrometer using autocad. The original owner of the micrometer had it set up to hyperterminal but that software is not useful for my application. Right now I am trying to just sucessfully communicate but in theory I want to store the data read from the com port into an array. I can do that but gettting data into a variable from the comm port is my problem.

Right now when reading the lasermicrometer manual it reads this for serial port communication:

Data must be sent using the ?J0/ command followed by a linefeed and/or carriage return. i.e : ?J0/<#><CR><LF>

The number I want to send it is 68 (which is to read the average diamater) and at this moment I have a code that creates a gui and when I press a button it should return the measurement but it is not working. I don't understand what I should put as a linefeed or carriage return and maybe that is the problem. But here is my script right now.

#include <GUIConstantsEx.au3>

#include "CommMG.au3"

Opt('MustDeclareVars', 1)

Example()

_CommSetPort(4,"error",9600,7,0,2,0)

Func Example()

Local $Button_1, $Text1, $msg,$Data1

GUICreate("Filament Micrometer v1.0", 320, 40)

GUISetState(@SW_SHOW)

Opt("GUICoordMode", 2)

$Button_1 = GUICtrlCreateButton("Get LaserMike Position", 10, 10, 150,20)

$Text1 = GUICtrlCreateInput("", 0, -1)

GUISetState()

While 1

$msg = GUIGetMsg()

Select

Case $msg = $GUI_EVENT_CLOSE

ExitLoop

Case $msg = $Button_1

_CommSendString("?J0/<A>",0)

$Data1=_CommGetstring()

GUICtrlSetData ( $Text1, $Data1)

Case $msg = $Text1

EndSelect

WEnd

EndFunc

If anyone could help me understand why my data is not being returned correctly their help would be greatly appreciated.

Thanks,

J

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...