串口循环Buffer接收
//串口
#define UART0_RX_BUFF_LEN (56 * 16)
#define UART0_FRAME_MAX_LEN (56) //单帧最长长度
/****************************************** 全局变量 *********************************************/
/*串口缓存全局变量初始化*/
volatile unsigned charg_u8Uart0RxDataMem = {0}; //串口0缓存
volatile unsigned short gUart0RxByteNum = 0; //已经接收到的字节数量
volatile unsigned short gUart0RxIndex = 0; //接收循环写入
volatile unsigned short gUart0RxStartIndex = 0; //处理起始位
//串口一个字节一个字节的收
LONG CAudioProcessorDlg::OnCommunication(WPARAM ch, LPARAM port)
{
unsigned char *pUart0RxDataMem = (unsigned char * )g_u8Uart0RxDataMem;
unsigned char u8DataLen = 0; //解析桢字节长度
CString str;
str.Format(L"%02X", ch);
unsigned char u8Temp = { 0 };
int nRet = 0;
int i = 0;
int nRealLen = 0;
int nRealBeginIndex = 0;
unsigned char u8UartParaBuf = {0}; //临时变量,每次处理一帧数据
Unicode_Cstring2char(str, (char*)u8Temp);
//转换一下
for (i = 0; i < 4; i++ )
{
if (u8Temp >= 'A')
{
u8Temp = u8Temp - 55;
}
else
{
u8Temp = u8Temp - 0x30;
}
}
//按字节接收数据,保证此buf是循环buf
g_u8Uart0RxDataMem = (u8Temp << 4) | u8Temp;
gUart0RxIndex = (gUart0RxIndex + 1) % UART0_RX_BUFF_LEN;
gUart0RxByteNum++;
//开始解析数据
while(gUart0RxByteNum) //接收的长度如果大于0
{
if(pUart0RxDataMem == 0x55)//第一个帧头字节正确
{
break;
}
pUart0RxDataMem = 0;
gUart0RxStartIndex = (gUart0RxStartIndex + 1) % UART0_RX_BUFF_LEN;
gUart0RxByteNum--;
}
if(gUart0RxByteNum >= UART_RX_PROTOCOL_SIZE) //接收到字节数大于14字节
{
if (0xAA == pUart0RxDataMem[((gUart0RxStartIndex + 1) % UART0_RX_BUFF_LEN)])
{
//取桢长度
u8DataLen = pUart0RxDataMem[((gUart0RxStartIndex + 2) % UART0_RX_BUFF_LEN)];
if((UART_RX_PROTOCOL_SIZE == u8DataLen) || (UART_RX_ExPROTOCOL_SIZE == u8DataLen))
{
if(CheckReciveDataCRC(pUart0RxDataMem, u8DataLen))
{
//拷贝一帧数据出来
for(i = 0; i < u8DataLen; i++)
{
//校验通过将数据取出存放到u8UartParaBuf
u8UartParaBuf = pUart0RxDataMem;
pUart0RxDataMem = 0;
gUart0RxStartIndex = (gUart0RxStartIndex + 1) % UART0_RX_BUFF_LEN;
gUart0RxByteNum--;
}
u8DataLen = ProcessingProtocolData(u8UartParaBuf, u8DataLen);
CommunicationSend((char *)u8UartParaBuf, u8DataLen);
}
else
{
pUart0RxDataMem = 0;
gUart0RxStartIndex = (gUart0RxStartIndex + 1) % UART0_RX_BUFF_LEN;
gUart0RxByteNum--;
}
}
else
{
pUart0RxDataMem = 0;
gUart0RxStartIndex = (gUart0RxStartIndex + 1) % UART0_RX_BUFF_LEN;
gUart0RxByteNum--;
}
}
else
{
//桢头异常,清除此桢
pUart0RxDataMem = 0;
gUart0RxStartIndex = (gUart0RxStartIndex + 1) % UART0_RX_BUFF_LEN;
gUart0RxByteNum--;
}
}
return 0;
}
环形接收么这个是?
页:
[1]