Modbus is a very common protocol but using Modbus ASCII can be tricky, especially when it comes to calculating the LRC that you should use at the end of the message.
Firstly, if you don't know Modbus ASCII is a serial protocol used by several industrial devices. (More details on Modbus on serial lines
here) Unfortunately Modbus ASCII is not as simple to work with as it's sister protocol Modbus RTU because it is difficult to remember when to use the HEX values and when to use the ASCII representations of the HEX values!
Every message in Modbus ASCII starts with a colon ":". Following the colon is a string of ASCII characters representing the HEX values that should be sent for the required Modbus message. Error checking of this string is carried out with a Longitudinal Redundancy Check (LRC) and finally the message is terminated with a Carriage Return (0x13) and a Line Feed (0x10) character.
In ASCII the standard modbus command to read 10 holding registers stating at 40003 from device address 1 would be:
":01030002000EE10D0A"
The LRC “EE” above is calculated from the values shown above rather than the binary data actually transmitted.
Step 1:
SUM values all bytes after the “:”
1 + 3 + 0 + 2 + 0 + 14 + 225 + 13 + 10 = 268
Step 2:
Take the modulus* of the Step 1’s result with 255.
268 Mod 255 = 13
*modulus = divide by 255 and keep the remainder.
Step 3:
Take the two’s compliment by subtracting step 2’s result from 254.
254 – 13 = 241
Step 4:
Convert to hexadecimal and send this result as two ASCII characters.
241 = F1h
Easy as that!
For further information on Modbus consult
www.modbus.org