14 Jun 12 5:05
Coding for Serial COM's can be difficult. I've done a lot of serial COM programming, talking to weighbridge scales, overhead projectors etc.
In my opinion (and there's probably way better coders than I) the best way to READ data from the serial port is to create a procedure for reading the serial port buffer and call the procedure in the 'Timer' embed of the window. Set the Window's timer value to 50.
Read the entire contents of the buffer on each timer event, and append the data read (if any) into a separate STRING Variable (ex. loc:DataBuffer) - leave the Winevent buffer alone, just concatenate the variable contents to your own buffer variable. You then check your buffer(loc:DataBuffer) for the beginning and end character(s) of a 'valid/complete' 'Data packet'... Since you know what the data 'packet' looks like (how many bates, where each piece of data begins and ends etc. inside your packet.)
Once you have valid packet, extract the data using INSTRING etc. and clear your buffer.
Simple example code:
! Some local Variables
loc:BytesRead Byte ! Just a byte type variable to catch the returnvalue of Winevent's 'ReadPort'
loc:RXBuffer STRING(1000) ! WinEvent's buffer which Readport will fill with whatever it gets from the serial port
loc:DataBuffer STRING(1000) ! My own data buffer
! Code to run on timer event
loc:BytesRead = ReadPort(PortId,loc:RXBuffer,0) ! Read EVERYTHING from serial port (returns QTY bytes read in loc:BytesRead variable)
IF loc:BytesRead THEN ! If P:bytesRead has a value then concatenate read data to my own buffer
loc:DataBuffer = CLIP(loc:DataBuffer) & CLIP(loc:RXBuffer) ! just add whatever is read from port to whatever I have in my buffer
! Inspect 'My Buffer' loc:Databuffer and see if you have a valid and complete packet.
! For example, say my packet start is '~x' and the packet end is '~y' : my packet ~x12345678,123,12345678,abc,123~y
IF LEN(CLIP(loc:DataBuffer)) THEN ! If there's data in 'my' buffer
P#=INSTRING('~x',CLIP(loc:DataBuffer),1,1) ! Search for beginning of packet.
IF P# THEN ! great, found beginning
IF Q# THEN ! great, found end
! Now you have the start position and end position of a packet.
! You can now slice out whatever data you want from the 'packet'
! For example: to cut the serialnumber out of the example packet:
S# = INSTRING(',',loc:DataBuffer,1,P#+2) ! look for comma, starting at character just after '~x'
IF S# THEN
loc:SerialNumber = loc:DataBuffer[P#+2:S#-1] ! get all values in buffer between ~x and , (will get 12345678)
P# = INSTRING(',',loc:DataBuffer,1,S#+1) ! look for next comma starting at character just after previous comma
IF P# THEN
loc:SerialNumber = loc:DataBuffer[S#+1:P#-1] ! get all values in buffer between , and , ( will get 123 )
! Once you have 'sliced' all the data from the packet, clear your buffer (loc:DataBuffer)
Easy .... hope it helps.