【STM32】串口数据帧接收与分析处理算法
- 串口中断函数接收数据到FIFO。
- 根据通信协议GetInterUARTMessage()函数对数据帧进行判断获取。
- 根据通信协议AnalyzeInterUARTMessage()函数对数据帧进行分类处理。
重点分析:
memcmp()函数: 对数据帧类别进行判断,并做后续处理。
变量ucInterHead 和 usInterPos : 对数据帧帧头和帧尾位置进行定位。
串口FIFO中的InterRxBufferRead(): 读取FIFO中一个字节数据。
void GetInterUARTMessage(void) { uint8_t ucData; static uint8_t ucInterHead = 0; static uint8_t ucaInterBuf[512]; static uint16_t usInterPos = 0; //数据帧长度位置标志位 while (1) { if(InterRxBufferRead(&ucData)) //判断串口FIFO数据使用为空 { if (ucInterHead == 0) //判断帧头位置是否找到 { if (ucData == $) { ucInterHead = 1; usInterPos = 0; } } else { if (usInterPos < sizeof(ucaInterBuf)) //判断数据读取是否越界 { ucaInterBuf[usInterPos++] = ucData; //数据赋值 if (ucData == @) //判断是否找到帧尾 { //数据帧接收成功,进入数据帧处理函数 AnalyzeInterUARTMessage(ucaInterBuf, usInterPos-1); ucInterHead = 0; } } else { ucInterHead = 0; } } continue; } break; } } void AnalyzeInterUARTMessage(uint8_t *ucaBuf, uint16_t usLen) { //根据帧头后的数据标识,对数据帧进行分类处理 if(memcmp(ucaBuf, "SetSleepTime", 12) == 0) { #if 1 char string[20]; memcpy(string,ucaBuf,usLen); string[usLen] = ; printf("%s ",string); #endif } if(memcmp(ucaBuf, "SaveData", 6) == 0) { #if 1 char string[20]; memcpy(string,ucaBuf,usLen); string[usLen] = ; printf("%s ",string); #endif } }