Modbus Instruction manual 05/0832
32
Modbus Instruction manual 05/08
Example : program sequence (C#)
private int Modbus_CRC(string frame)
{
int poly = 0xA001; // polynomal
int CRC = 0xFFFF; // start CRC
for (int i = 0; i < (int)(frame.Length); i++) // for each sign
{
CRC ^= Convert.ToInt16(frame[i]); // ExOR
for (int j = 0; j < 8; j++) // eight times
{
if ((CRC & 0x01) == 0x01) // lsb == 1 ?
{
CRC >>= 1; // shift left
CRC ^= poly; // ExOR
}
else
{
CRC >>= 1; // shift left
}
}
}
return CRC;
}
Call the function for the frame : “0x02 0x07”
string temp_s = Convert.ToString((char)(0x2))+ Convert.ToString((char)(0x7));
Console.WriteLine(Modbus_CRC(temp_s));
Result : 4673 = 0x1241
CRC Low Byte = 0x41
CRC High Byte = 0x12
The Modbus CRC sequence is :
⇒
CRC Low Byte / High Byte 0x41 0x12