狀態機在嵌入式編程中絕對是個不可多得的好東西,用順手了,程序可以簡短不少,可以少用好多標誌位,這是我目前瞭解到的。
通信中的應用:
串口通信在嵌入式開發中,絕對是必須的一個環節。大多數採用中斷接收,主動發送的方式,進行通信。
通信接收部分,可以直接簡單的只是接收;當然也可以在接收過程中就進行判斷,當接收到包頭(幀頭)時,纔開始接收,否則放棄,等待包頭部分。這個判斷的過程中就用到了狀態機。
例如一個幀數據結構爲: ##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 ----- */