crc16 modbus c语言代码,modbus-crc16——c语言

为确保消息数据的完整性,除了验证消息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;

}

标签:语言,crc16,crc,int,pos,modbus,CRC,UInt16,byte

来源: https://www.cnblogs.com/CodeWorkerLiMing/p/11336107.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值