#define PACK_DATA_LEN (1024)
typedef struct
{
unsigned char head[2]; /*帧头,我这边定义帧头为0xAA 0x55*/
unsigned char data[PACK_DATA_LEN]; /*存放你想要的数据*/
unsigned char checksum; /*校验和,从*/
}T_Pack; /*数据包定义*/
T_Pack rxPack = {0};
T_Pack txPack = {0};
/*校验和*/
unsigned char checkSum(unsigned char *buf, unsigned int bufLen)
{
unsigned int i;
unsigned char ret = 0;
for(i=0; i< bufLen; i++)
{
ret += buf[i];
}
return ret;
}
/*发包*/
void sendPack(unsigned char *buf, unsigned int bufLen)
{
unsigned int i;
/*设置帧头*/
txPack[0] = 0xAA;
txPack[1] = 0x55;
for(i=0; (i<bufLen)&&(i<PACK_DATA_LEN); i++)
{
txPack.data[i] = buf[i];
}
txPack.checksum = checkSum((unsigned char *)&txPack, sizeof(txPack)-1);
uartSend((unsigned char *)&txPack, sizeof(txPack)); /*使用自己定义的串口发送函数*/
}
/*解包*/
void findPack(unsigned char byteMsg) /*输入参数为从串口获得的一个数据*/
{
static unsigned char caseStu = 0;
static unsigned int count = 0;
static unsigned char* p = (unsigned char*)&rxPack;
switch(caseStu)
{
case 0: /*判断hread 1*/
count = 0;
if(byteMsg == 0xAA)
{
p[count++] = byteMsg;
caseStu++;
}
break;
case 1: /*处理head 2*/
if(byteMsg == 0x55)
{
p[count++] = byteMsg;
caseStu++;
}
else
{
caseStu = 0;
}
break;
case 2:
p[count++] = byteMsg;
if(count >= PACK_DATA_LEN+3) /*收到一包数据*/
{
if(checkSum(p, count-1) == p[count-1]) /*校验数据正确性*/
{
rxPack.data ... /*data里面的数据就是接收的正确数据了*/
}
caseStu = 0;
}
break;
}
}