Declare
PortID
,
Data
Declare
MyCmd
=
"0x1,0x3,0x0,0x14,0x0,0x3C"
; command to be sent
GoSub
"Sub.CalcModBusCRC"
,
MyCmd
; Calculate Modbus CRC
NumToList
_RetVal
,
_RetVal
,
2
,
1
; Convert CS to list of bytes (F! to see Help)
; Print command and CRC to the ETS terminal (Blue window)
HBClear
PrintMessage
"Sent: Command | "
$
MyCmd
PrintMessage
" CRC | "
$
_RetVal
; Use RC_TelnetPortSet to communicate over Telnet
RC_SerialPortSet
PortID
,
"COM1"
,
9600
; Init Serial port on COM1
MyCmd
$=
","
$
_RetVal
RC_Send
MyCmd
,
PortID
,
-
1
,
1
; Send as a binary data (the last argument set to 1)
Delay
100
; It takes time until the target responces.
RC_Read
Data
,
PortID
,
1
; Read the response data in binary format
; Convert the Data to HEX format
StrConvertValueRadix
Data
,
16
,
10
,
1
Print
"Received | "
$
Data
$
"^M^J"
; Analyze recevied Data
Declare
Num
,
CRC
,
Cmd
StrGetFieldElements
Num
,
Data
,
","
; Get number of bytes in message
StrField
Cmd
,
Data
,
0
,
","
,
Num
-
2
StrField
CRC
,
Data
,
Num
-
2
,
","
,
2
GoSub
"Sub.CalcModBusCRC"
,
Cmd
; Calculate Modbus CRC
ListToNum
CRC
,
CRC
,
2
; Convert to U16 number
If
_RetVal
!=
CRC
Then
TMMessage
GT_ErrorID
,
"Wrong CRC..."
; Close the port
RC_Close
PortID
End
;-------------------------------------------
<Sub.CalcModBusCRC>
i_Cmd
Declare
Byte
,
Cnt
,
Carry
,
CS
CS
=
0xffff
ForEach
Byte
in
i_Cmd
CS
^=
Byte
For
Cnt
=
1
To
8
; Loop over each bit
Carry
=
CS
&
1
; Extract LSB
CS
>>=
1
; Shift right
If
Carry
==
1
Then
CS
^=
0xA001
; XOR 0xA001 if LSB is set
Next
EndEach
Return
CS