</pre><pre name="code" class="cpp">/*
* 串口数据包格式
* __________________________________________________________________________________________
* | head(2byte) | type(1byte)| len_total(1byte) | rec_buff[64] | CheckSum (1byte)|
* ------------------------------------------------------------------------------------------
* 同步 类型 数据长度 数据 异或和校验
* (0xAA,0x55)
*/
/*
* 接收时按照状态解析数据
*/
typedef enum{
HEAD1,
HEAD2,
TYPE,
LEN,
DATA,
CHECK,
}State;
/*
* 正确接收数据状态判定
*/
typedef enum
{
FALSE,
TRUE
}Bool;
typedef unsigned char u8;
#if 0
typedef struct _Frame{
u8 type;
u8 len_total;
u8 rec_buff[10];
}Frame;
#endif
u8 rec_buff[64];
Bool Rec_OK = FALSE;
u8 type;
u8 len_total = 0;
void Serial_ISR(void)
{
static State Curr_State = HEAD1;
static u8 count = 0;
static u8 CheckSum = 0;
switch(Curr_State)
{
case HEAD1:
if(Rec == 0xAA)
{
Curr_State = HEAD2;
}
break;
case HEAD2:
if(Rec == 0x55)
{
Curr_State = TYPE;
}
else if(Rec == 0xAA)
{
Curr_State = HEAD2;
}else
{
Curr_State = HEAD1;
}
break;
case TYPE:
type = Rec;
Curr_State = LEN;
len_total = 0;
break;
case LEN:
len_total = Rec;
Curr_State = DATA;
count = 0;
CheckSum = 0;
break;
case DATA:
if(count < len_total)
{
rec_buff[count++] = Rec;
CheckSum ^= Rec;
}
else
{
Curr_State = CHECK;
}
break;
case CHECK:
if(CheckSum == Rec)
{
Rec_OK = TRUE;
}
Curr_State = HEAD1;
break;
default:
Curr_State = HEAD1;
break;
}
}
基于状态机的串口通信解析
最新推荐文章于 2023-12-11 20:23:30 发布