关于那个7位的CRC校验,我在网上找了一个查表程序,改了一下,
发现四组数据,有两个是对的,第一个和第四个,0x57,0x26.
第二个和第三个不对:
单片机程序里是0x6e,0x4b,我计算的是0x26,0x2f.
代码:
# include <stdio.h>
# include <string.h>
#define uint8_t unsigned char
#define uint16_t unsigned int
#define uint32_t unsigned long int
#define TAB_LEN 256
#define ALPHA 0x65
#define BUFFER_SIZE_5 5 /* CRC7_DATA8_TEST5[] is 5-byte long */
#define BUFFER_SIZE_17 17 /* CRC7_DATA8_TEST17[] is 17-byte long */
#define BUFFER_SIZE_1 1 /* CRC7_DATA8_TEST1[] is 1-byte long */
#define BUFFER_SIZE_2 2 /* CRC7_DATA8_TEST2[] is 2-byte long */
const uint8_t CRC7_DATA8_TEST5[5] = {0x12,0x34,0xBA,0x71,0xAD};
const uint8_t CRC7_DATA8_TEST17[17] = {0x12,0x34,0xBA,0x71,0xAD,
0x11,0x56,0xDC,0x88,0x1B,
0xEE,0x4D,0x82, 0x93,0xA6,
0x7F,0xC3};
const uint8_t CRC7_DATA8_TEST1[1] = {0x19};
const uint8_t CRC7_DATA8_TEST2[2] = {0xAB,0xCD};
const unsigned char testdat[10] = "0123456789";
/* Expected CRC Values */
/* The 7 LSB bits are the 7-bit long CRC */
uint32_t uwExpectedCRCValue_1 = 0x00000057; /* First byte stream CRC */
uint32_t uwExpectedCRCValue_2 = 0x0000006E; /* Second byte stream CRC */
uint32_t uwExpectedCRCValue_3 = 0x0000004B; /* Third byte stream CRC */
uint32_t uwExpectedCRCValue_4 = 0x00000026; /* Fourth byte stream CRC */
unsigned char result;
int table_gen8(unsigned char *buf){
unsigned int alpha = ALPHA; //x^7+x^3+1
int i,j;
unsigned char tmp;
for(i=0;i<TAB_LEN;i++){
tmp = i;
for(j=0;j<8;j++){
if(tmp & 0x80)
tmp ^= alpha;
tmp <<= 1;
}
buf[i] = tmp>>1; /*余数为7bit,计算中用了8bit,结尾多一位0要去掉*/
}
return 0;
}
unsigned char get_crc7(unsigned char start, const unsigned char *buff, int len, unsigned char *table){
unsigned char accu = start;
//unsigned char accu = (start<<1);
unsigned int i= 0;
for (i=0; i < len; i++) {
accu = table[(accu << 1) ^ buff[i]];
//accu = table[accu^ buff[i]];
}
return (accu);
}
int main(void){
unsigned char data[TAB_LEN] = {0};
int i,j;
printf("CRC7 table:\n");
table_gen8(data);
for(i=0;i<TAB_LEN/8;i++){
for(j=0;j<8;j++)
printf("0x%02x ",data[i*8+j]);
printf("\n");
}
printf("\n");
/*Test*/
//result = get_crc7(0, testdat, 10, data);
//result = get_crc7(0x7f, CRC7_DATA8_TEST5, 5, data);
//result = get_crc7(0x7f, CRC7_DATA8_TEST17, 17, data);
//result = get_crc7(0x7f, CRC7_DATA8_TEST1, 1, data);
result = get_crc7(0x7f, CRC7_DATA8_TEST2, 2, data);
printf("get_crc7:0x%02x\n",result);
return 0;
}