16位的CRC校验码生成,可使用以下函数:
//16位CRC校验码生成//返回值:CRC校验码unsigned int CRC_check(unsigned char *addr,int num){unsigned int crc=0xffff;unsigned char i, p;for(p=0;p<num;p++){crc = crc^(*addr++);for(i = 0;i<8;i++){if(crc & 0x0001) crc = (crc>>1)^0xa001;else crc >>= 1;}}return(crc); }
示例:
//对数组modbus_data_tx[ ]生成校验码modbus_data_tx[8]={0X01, 0X03, 0X00, 0X00, 0X00, 0X07};unsigned int CRC_code;CRC_code = CRC_check(modbus_data_tx,6);//生成CRC校验码