ModbusRTU CRC 校验参考代码
uint16_t ModbusRTU_SendFrameSum(uint8_t *temp_TxBuf,uint16_t nLength);
uint8_t ModbusRTU_ReceiveFrameSum(uint8_t *temp_RxBuf, uint16_t nLength);
uint16_t ModbusRTU_SendFrameSum(uint8_t *temp_TxBuf,uint16_t nLength)
{
uint16_t i, j;
uint16_t crc = 0xFFFF;
for(i=0;i<nLength;i++){
crc ^= *(temp_TxBuf + i);
for(j = 0; j < 8; j++){
if((crc & 0x01) == 0x01){
crc >>= 1;
crc ^= 0xA001;
}
else{
crc >>= 1;
}
}
}
*(temp_TxBuf + nLength) = crc % 256;
*(temp_TxBuf + nLength + 1) = crc / 256;
return(crc);
}
uint8_t ModbusRTU_ReceiveFrameSum(uint8_t *temp_RxBuf, uint16_t nLength)
{
uint16_t i, j;
uint16_t sum_receive;
uint16_t crc = 0xFFFF; // init data
sum_receive = (*(temp_RxBuf + nLength)) + ((*(temp_RxBuf + nLength + 1))
* 256);
for(i = 0;i < nLength; i++){
crc ^= *(temp_RxBuf + i);
for(j = 0; j < 8; j++){
if((crc & 0x01) == 0x01){
crc >>= 1;
crc ^= 0xA001;
}
else{
crc >>= 1;
}
}
}
if(sum_receive == crc){return (1);}
else{return(0);}
}
void main(void)
{
uint8_t UartTxBuff[10] = {0x01, 0x06, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00};
SysInit();
While(1){
//now UartTxBuff[10] = {0x01, 0x06, 0x00, 0x00, 0x00, 0x02, 0x08, 0x0B};
ModbusRTU_SendFrameSum(UartTxBuff, 6);
if((ModbusRTU_ReceiveFrameSum(UartTxBuff, 6) == 1){
//a valid rtu frame
while(1);
}
}
}