Tutorial 2: Modbus RTU - CRC check sum (16-bit check sum consists of 2 8-b

  • 7 năm trước
CYCLICAL REDUNDANCY CHECK CALCULATION
CRC checksum: Starting from Address and ending at Data Content.
Step 1: Make the 16-bit register (CRC register) = FFFFH
Step 2: Exclusive OR the first 8-bit message and the low 16-bit CRC register. Store the result in the CRC
register.
Step 3: Right shift CRC register for a bit and fill “0” into the high bit.
Step 4: Check the value shifted to the right. If it is 0, fill in the new value obtained in step 3 and store the value in
CRC register; otherwise, Exclusive OR A001H and CRC register and store the result in the CRC register.
Step 5: Repeat step 3 – 4 and finish operations of all the 8 bits.
Step 6: Repeat step 2 – 5 for obtaining the next 8-bit message until the operation of all the messages are
completed. The final value obtained in the CRC register is the CRC checksum. The CRC checksum has to be
placed interchangeably in the checksum of the message.

Example C#

private byte[] CRC(byte[] data)
{
// Set the 16-bit register (CRC register) = FFFFH.
ushort CRCFull = 0xFFFF;
byte CRCHigh = 0xFF, CRCLow = 0xFF;
char CRCLSB;
byte[] CRC = new byte[2];
for (int i = 0; i > 1) & 0x7FFF);

if (CRCLSB == 1)
CRCFull = (ushort)(CRCFull ^ 0xA001);
}
}
CRC[1] = CRCHigh = (byte)((CRCFull >> 8) & 0xFF);
CRC[0] = CRCLow = (byte)(CRCFull & 0xFF);
return CRC;
}

Được khuyến cáo