单片机通信中的CRC算法原理及程序设计
0x41,0x2a,0 x51,0xb1,0x60,0x38,0x70,0xcf,0x87,0x46,0x97,0xdd,0xa6,0x54,0xb6,0xeb, 0xc5,0x62,0xd5,0xf9,0xe4,0x70,0xf4,0x08,0x04,0x81,0x14,0x1a,0x25,0 x93,0x35,0x2c,0x46,0xa5,0x56,0x3e,0x67,0xb7,0x77,0x40,0x80,0xc9,0x90, 0x52,0xa1,0xdb,0xb1,0x64,0xc2,0xed,0xd2,0x76,0xe3,0xff,0xf3,0x89,0x04, 0x00,0x14,0x9b,0x25,0x12,0x35,0xad,0x46,0x24,0x56,0xbf,0x67,0x36,0x77, 0xc1,0x80,0x48,0x90,0xd3,0xa1,0x5a,0xb1,0xe5,0xc2,0x6c,0xd2,0xf7,0xe3, 0x7e,0xf3,0x0a,0x05,0x83,0x15,0x18,0x24,0x91,0x34,0x2e,0x47,0 xa7,0x57,0x3c,0x66,0xb5,0x76,0x42,0x81,0xcb,0x91,0x50,0xa0,0 xd9,0xb0,0x66,0xc3,0xef,0xd3,0x74,0xe2,0xfd,0xf2,0x8b,0x05,0x02,0x15, 0x99,0x24,0x10,0 x34,0xaf,0x47,0x26,0x57,0xbd,0x66,0x34,0x76,0xc3,0x81,0x4a,0x91,0xd1, 0xa0,0x58,0xb0,0xe7,0xc3,0x6e,0xd3,0xf5,0xe2,0x7c,0xf2,0x0c,0x06,0x85, 0x16,0x1e,0x27,0 x97,0x37,0x28,0 x44,0xa1,0x54,0x3a,0x65,0xb3,0x75,0x44,0x82,0xcd,0x92,0x56,0xa3,0xdf, 0xb3,0 x60,0 xc0,0xe9,0xd0,0x72,0xe1,0xfb,0xf1,0x8d,0x06,0x04,0x16,0x9f,0x27,0x16, 0x37,0xa9,0x44,0 x20,0x54,0xbb,0x65,0x32,0x75,0xc5,0x82,0x4c,0x92,0xd7,0xa3,0x5e,0xb3, 0xe1,0xc0,0x68,0xd0,0 xf3,0xe1,0x7a,0xf1,0x0e,0x07,0x87,0x17,0x1c,0x26,0x95,0x36,0x2a,0x45, 0xa3,0x55,0x38,0x64,0xb1,0x74,0x46,0x83,0xcf,0x93,0x54,0xa2,0xdd,0xb2, 0x62,0xc1,0xeb,0xd1,0x70,0xe0,0xf9,0xf0,0x8f,0x07,0x06,0x17,0x9d,0x26, 0x14,0x36,0xab,0 x45,0x22,0x55,0xb9,0x64,0x30,0x74,0xc7,0x83,0x4e,0x93,0xd5,0xa2,0x5c, 0xb2,0xe3,0xc1,0x6a,0xd1,0xf1,0xe0,0x78,0xf0}; #define BUFLEN 512 /*--缓冲区大小———*/ #define ETB (byte)0x20 /*——报文结束符——*/ byte crc0=0,crc1=0; /*———字节变量———*/ void main(void) { /*———根据要求编写主程序,调用crcvalue()子程序———*/ } word crcvalue(byte*crcbuf) /*计算报文的CRC值,crcbuf是缓冲区*/ { word count; for(crc0=crc1=0,count=1;crcbuf[count]!=ETB&&count <BUFLEN;count++) crccount(crcbuf[count]); if(count+4>=BUFLEN)return 0; crccount(crcbuf[count]); crcbuf(++count)=crc0;crcbuf(++count)=crc1;crcbuf(++ count)=crc0; crcbuf(++count)=crc1;crcbuf(++count)=crc0;crcbuf(++ count)=crc1; return ++count; } viod crccount(byte crc100) /*计算一个字节的CRC值*/ { byte crc10,crc11,crc20,crc21; word crclen; crclen=(word)crc100; crclen=(crclen&0xff)<<1; crc10=crcclar [crclen++]; crc11=crcclar[crclen++]; crc11=crc100^crc0^crc11; crc10=crc1 ^crc10; crclen=(word)crc0; crclen=(crclen&0xff)<<1; crc20= crcclar[crclen++]; crc21=crcclar[crclen++]; crc0=drd^crc20; crc1=crc11^ crc21; } 4 CRC算法的优缺点 用软件实现的CRC算法,其主要优点是突出了一个“快”字,为了提高校验速度,把参数表和应用程序一起写入单片机的EPROM内,当进行CRC校验时,对需要发送的每一字节,按上述的方法进行计算,就可得到该字节的校验值。从而提高了速度,较好地克服了异步传输中校验和发送时间很不匹配的矛盾。 CRC算法的缺点是由于要存储512字节的参数表,需要更多的存储空间,但是在单片机的应用中,这种以空间换取时间的方法是值得提倡的。 5 结束语 CRC算法能很好地解决传输报文过程中的校验问题,在8031,80C196,80188等CPU控制的单片机中,进行了大量的有/无线传输报文实验,在300BPS,600BPS,1200BPS,2400BPS,4800BPS的波特率下,CRC算法都能很好地进行校验,提高了传输速度。 [参考文献] [1]白驹珩,等.单片机及其应用[M].电子科技大学出版社,1994.5
- 嵌入式编程需注意的Cache机制及其原理(05-25)
- 通信系统原理技术与DSP实验平台的研制(06-06)
- Linux 环境下USB 的原理、驱动和配置(06-06)
- 基于FPGA的原型板原理图的验证(06-05)
- CAN总线原理介绍(12-16)
- 直流无刷电动机原理与控制(12-15)