A simple serial receive (with protocol)
Data header information (5)
the data length information (a)
data (<1024)
data check (1)
Data Tail
I. receiving serial data buf
typedef struct _UartCommadType
{
uint8_t Buffer[1024];
uint16_t Index; // buffer index
uint16_t u8Len;
}UartCommadType;
Two serial port received state, if the reception is not completed within the time limit, the received error
uint16_t g_Uart2CheckTick;//时间限制
uint8_t g_bUart2Detected;//检测标志
void Uart2_1ms_ISR(void)
{
if (g_Uart2CheckTick)
{
--g_Uart2CheckTick;
if ( g_Uart2CheckTick == 0 )
{
g_bUart2Detected = 0;
g_Uart2Command.Index = 0;
}
}
}
III. Detecting receiver, the data has been put into buf, if the length of data bits is detected, then the received data length in the data length bits End
#define UART_RX_HEADER ( 0x00 )
#define UART_RX_ID ( 0x01 )
#define UART_RX_CATEGORY ( 0x02 )
#define UART_RX_PAGE ( 0x03 )
#define UART_RX_FUNC ( 0x04 )
#define UART_RX_DATA_LENGTH ( 0x05 )
#define UART_RX_CONTROL ( 0x06 )
void Uart2_RecvHandler(int c)
{
g_Uart2CheckTick = 50;// time-out control ms
if((g_Uart2Command.u8CmdLen != 0)&&( g_Uart2Command.Index < g_Uart2Command.u8CmdLen))
{
g_Uart2Command.u8CmdLen = 0;
}
g_Uart2Command.Buffer[g_Uart2Command.Index] = c;
g_Uart2Command.Index++;
g_Uart2Command.Index &= 0x3FF;//max is 1024
if(g_Uart2Command.Index > UART_RX_DATA_LENGTH)
{
if((g_Uart2Command.Index - UART_RX_DATA_LENGTH) > g_Uart2Command.Buffer[UART_RX_DATA_LENGTH])
{
g_bUart2Detected = 1; // command buffer recieve ok
g_Uart2CheckTick = 0;
g_Uart2Command.Index = 0; // reset index of command buffer
g_Uart2Command.u8Len = g_Uart2Command.Buffer[UART_RX_DATA_LENGTH];
}
}
}
IV. Verification data header
uint8_t Uart2_Verify(void)
{
if((g_Uart2Command.Buffer[UART_RX_HEADER] == UART_VALUE_HEADER)
&&(g_Uart2Command.Buffer[UART_RX_ID] == UART_VALUE_ID)
&&(g_Uart2Command.Buffer[UART_RX_CATEGORY] == UART_VALUE_CATEGORY)
&&(g_Uart2Command.Buffer[UART_RX_PAGE] == UART_VALUE_PAGE)
&&(g_Uart2Command.Buffer[UART_RX_FUNC] == UART_VALUE_FUNC)
&&(g_Uart2Command.Buffer[UART_RX_CONTROL] == UART_VALUE_CONTROL)
){
return 1;
}
return 0;
}
Parity bit can define your own