串口多字节接收
2014-08-15 15:22 Danhuise 阅读(715) 评论(0) 编辑 收藏 举报1 /* 数据发送格式: 2 * 0 1 2 3 4 ... DataLenth-1 DataLenth 3 * HEAD1 - HEAD2 - DataLenth(n+1) - data_1 - data_2 - ... - data_n - CheckSum 4 * CheckSum = HEAD1 + HEAD2 + DataLenth + data_1 + data_2 + ... + data_n 5 */ 6 7 #define FRAME_HEADER1 0xFA // 定义帧头 1 8 #define FRAME_HEADER2 0xFA // 定义帧头 2 9 unsigned char ReceiveDataBuffer[16] = {FRAME_HEADER1, FRAME_HEADER2, 0x00}; 10 unsigned char DataBufferCnt = 0x02; 11 unsigned char CheckSum = FRAME_HEADER1 + FRAME_HEADER2; 12 // 串口接收中断程序 13 void USART_IRQHandler(void) 14 { 15 static unsigned char headBufCnt = 0x00; 16 unsigned char buf; 17 18 buf = ReadRegisterReceiveBuffer(); // 读接收寄存器数据到缓冲区 19 20 #if (FRAME_HEADER1 != FRAME_HEADER2) // 检测帧头,两字节帧头不同 21 if(FRAME_HEADER1 == buf) { headBufCnt = 0x01;} 22 else if(0x00 != headBufCnt) 23 { 24 headBufCnt = 0x00; 25 if(FRAME_HEADER2 == buf) 26 { 27 DataBufferCnt = 0x02; 28 CheckSum = FRAME_HEADER1 + FRAME_HEADER2; 29 return; 30 } 31 } 32 #else // 检测帧头,两字节帧头相同 33 if(FRAME_HEADER1 == buf) { headBufCnt ++;} 34 else if(headBufCnt >= 2) 35 { 36 headBufCnt = 0x00; 37 DataBufferCnt = 0x02; 38 CheckSum = FRAME_HEADER1 + FRAME_HEADER2; 39 } 40 else { headBufCnt = 0x00;} 41 #endif /* FRAME_HEADER1 != FRAME_HEADER2 */ 42 43 ReceiveDataBuffer[DataBufferCnt] = buf; 44 if((DataBufferCnt-2) < ReceiveDataBuffer[2]) 45 { 46 CheckSum += ReceiveDataBuffer[DataBufferCnt]; // 计算校验和 47 DataBufferCnt ++; 48 } 49 else // 数据接收完毕 50 { 51 if(CheckSum == ReceiveDataBuffer[DataBufferCnt]) // 数据校验成功 52 { 53 // 数据校验完毕且正确 54 } 55 DataBufferCnt = 0x02; 56 } 57 }