状态机在嵌入式编程中绝对是个不可多得的好东西,用顺手了,程序可以简短不少,可以少用好多标志位,这是我目前了解到的。
通信中的应用:
串口通信在嵌入式开发中,绝对是必须的一个环节。大多数采用中断接收,主动发送的方式,进行通信。
通信接收部分,可以直接简单的只是接收;当然也可以在接收过程中就进行判断,当接收到包头(帧头)时,才开始接收,否则放弃,等待包头部分。这个判断的过程中就用到了状态机。
例如一个帧数据结构为: ##0123456&&
可以使用一个statemachine, 根据当前接收状态判断,决定是否写入接受缓存。
代码示例如下,未添加容错,仅作示例,自行修改:
#include <inttypes.h>
<span style="white-space:pre"> </span>
// ===================================================================================
// Name: USART_Interrupt
// Description:
// Input:
// Return:
// ===================================================================================
void USART_Interrupt ( )
{
static uint8_t Statemachine = 0;
uint8_t tData = 0;
tData = USART_ReceiveData(USART1);
if( Statemachine == 0 )
{
if( tData == '#')
{
gRxBuf[0] = tData;
Statemachine = 1;
}
}
else if( Statemachine == 1 )
{
if( tData == '#' )
{
gRxBuf[1] = tData;
Statemachine = 2;
}
else
{
Statemachine = 0;
}
}
else if( Statemachine == 2 )
{
gRxBuf[2] = tData;
......
if( tData == '&' )
{
Statemachine = 3;
}
}
else if( Statemachine == 3 )
{
gRxBuf[i] = tData;
RecvEndProcess();
......
}
} /* ----- end of function USART_Interrupt ----- */