📄 crc16.c
字号:
#include "typedef.h"
#include "global.h"
extern uchar deviceAddr;
extern uchar pcdata[Len];
#define POLYNOMIAL 0x8408 /*x^16+x^12+x^5+1*/
#define PRESET_VALUE 0xFFFF
#define CHECK_VALUE 0xF0B8
#define CALC_CRC 1
#define CHECK_CRC 0
uchar crc16Calculate(uchar *pBuf, uchar byLen);
uchar verifyType();
uchar chkCRC_re(uchar * cBuf,uchar cLen);
/*
计算字符数组的CRC校验,pBuf 为字符数组首地址,byLen为长度
*/
uchar crc16Calculate(uchar *pBuf, uchar byLen)
{
unsigned int current_crc_value;
uchar i,j;
current_crc_value = PRESET_VALUE;
for(i=0;i<byLen;i++)
{
current_crc_value = current_crc_value^pBuf[i];
for(j=0;j<8;j++)
{
if(current_crc_value & 0x0001)
current_crc_value = (current_crc_value>>1)^POLYNOMIAL;
else
current_crc_value = (current_crc_value>>1);
}
}
current_crc_value = ~current_crc_value;
return(current_crc_value);
}
uchar verifyType()
{
uchar type;
if( deviceAddr == pcdata[1] ){ type = 1;} /*地址合法*/
else if(pcdata[1] == 0xfe) { type = 2;} /*广播地址*/
else if(pcdata[1] == 0xff) { type = 3;} /**/
else { type = 0;}
if(type)
if(!chkCRC_re(pcdata,pcdata[0]))type = 0; /*CRC校验正确*/
return(type);
}
uchar chkCRC_re(uchar * cBuf,uchar cLen)
{
uchar flag=1 ;
uchar j;
j = ~ crc16Calculate(cBuf,cLen-2);
flag = (cBuf[cLen-2] == (j&0x00ff) ); //crc MSByte
flag &= (cBuf[cLen-1] == (j>>8) ); //crc LSByte
return(flag);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -