如何计算 Modbus RTU 消息 CRC?为了确保消息数据的完整性,除了验证消息 CRC 之外,建议实现检查串行端口 (UART) 帧错误的代码。如果接收到的消息中的 CRC 与接收设备计算的 CRC 不匹配,则应忽略该消息。下面的 C 语言代码片段显示了如何使用按位移位和异或运算来计算 Modbus 消息 CRC。CRC 是使用消息帧中的每个字节计算的,除了最后两个字节组成 CRC 本身。
// Compute the MODBUS RTU CRC
UInt16 ModRTU_CRC(byte[] buf,
int
len)
{
UInt16 crc = 0xFFFF;
for
(
int
pos = 0; pos < len; pos++) {
crc ^= (UInt16)buf[pos];
// XOR byte into least sig. byte of crc
for
(
int
i = 8; i != 0; i--) {
// Loop over each bit
if
((crc & 0x0001) != 0) {
// If the LSB is set
crc >>= 1;
// Shift right and XOR 0xA001
crc ^= 0xA001;
}
else
// Else LSB is not set
crc >>= 1;
// Just shift right
}
}
// Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes)
return
crc;
}