【HAL库】串口数据帧接收与分析处理算法

基于对串口FIFO的通信数据帧进行接收和分析处理
(关于串口FIFO使用可以参见作者另一篇博文)
算法流程:

  1. 串口中断函数接收数据到FIFO。
  2. 根据通信协议GetInterUARTMessage()函数对数据帧进行判断获取。
  3. 根据通信协议AnalyzeInterUARTMessage()函数对数据帧进行分类处理。

重点分析:

memcmp()函数:
对数据帧类别进行判断,并做后续处理。

变量ucInterHead 和 usInterPos :
对数据帧帧头和帧尾位置进行定位。

串口FIFO中的InterRxBufferRead():
读取FIFO中一个字节数据。

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] = '\0';			
			printf("%s\r\n",string);
		#endif
	}	
	if(memcmp(ucaBuf, "SaveData", 6) == 0)
	{		
		#if 1	
			char string[20];
			memcpy(string,ucaBuf,usLen);
			string[usLen] = '\0';			
			printf("%s\r\n",string);
		#endif
	}
}
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))
		{
			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;	
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_44064233/article/details/108535226
今日推荐