1.预期实现效果
上图中是一些mavlink数据,最后2位是校验位,收到mavlink信息后,需要对buf生成crc校验位,然后得到buf_crc。
2.程序代码
c语言环境下,直接运行。
static unsigned int CRC_value = 0xffff;
static void update_checksum(unsigned char data)
{
unsigned int tmp;
data= data & 0xff;
tmp = data ^ (CRC_value & 0xff);
tmp ^= (tmp << 4) & 0xff;
CRC_value = ((CRC_value >> 8) & 0xff) ^ (tmp << 8) ^ (tmp << 3)^ ((tmp >> 4) & 0xf);
}
void Generate_CRC(unsigned char *Check_Data,unsigned int leg)
{
unsigned char MAVLINK_MESSAGE_CRCS[256] = {
50, 124, 137, 0, 237, 217, 104, 119, 0, 0, 0, 89, 0, 0, 0, 0, 0, 0, 0, 0,//20
214, 159, 220, 168, 24, 23, 170, 144, 67, 115, 39, 246, 185, 104, 237, 244, 222, 212, 9, 254,//40
230, 28, 28, 132, 221, 232, 11, 153, 41, 39, 0, 0, 0, 0, 15, 3, 0, 0, 0, 0,//60
0, 153, 183, 51, 82, 118, 148, 21, 0, 243, 124, 0, 0, 38, 20, 158, 152, 143, 0, 0,//80
0, 106, 49, 22, 29, 12, 241, 233, 0, 231, 183, 63, 54, 0, 0, 0, 0, 0, 0, 0,//100
175, 102, 158, 208, 56, 93, 211, 108, 32, 185, 84, 0, 0, 124, 119, 4, 76, 128, 56, 116,//120
134, 237, 203, 250, 87, 203, 220, 25, 226, 0, 29, 223, 85, 6, 229, 203, 1, 0, 0, 0,//140
0, 0, 0, 0, 0, 0, 0, 42, 49, 0, 134, 219, 208, 188, 84, 22, 19, 21,134, 0,//160
78, 68, 189, 127, 154, 21, 21, 144, 1, 234, 73, 181, 22, 83, 167, 138, 234, 240, 47, 189,//180
52, 174, 0, 0, 0, 0, 0, 0, 0, 0, 0, 92, 36, 0, 0, 0, 0, 0, 0, 0,//200
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 8, 204, 49, 170, 44, 83, 46, 0};
unsigned char j,k;
unsigned int i;
CRC_value = 0xffff;
update_checksum(Check_Data[1]);//len
update_checksum(Check_Data[2]);//seq
update_checksum(Check_Data[3]);//sysid
update_checksum(Check_Data[4]);//compid
update_checksum(Check_Data[5]);//msgid
for(i=0;i<(leg-8);i++)
{
update_checksum(Check_Data[6+i]);//payload
}
j=Check_Data[5];
k=MAVLINK_MESSAGE_CRCS[j];
update_checksum(MAVLINK_MESSAGE_CRCS[j]);
Check_Data[leg-2]=CRC_value&0xff;
Check_Data[leg-1]=(CRC_value&0xff00)>>8;
}
int main()
{
unsigned char buff[17] = {0xFE,0x09,0x68,0xFF,0xBE,0x00,0x00,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x00};
Generate_CRC(buff,sizeof(buff));
int i;
for(i=0;i<17;i++)
{
printf("%02x ", buff[i]);
}
return 0;
}
3.最终实现效果
完成了预期效果复现,最后两位校验位补齐。
方便各位所需移植。
所以,本地将crc校验demo程序跑起来之后,移植到我们所需的位置就水到渠成了。