zoukankan      html  css  js  c++  java
  • 串口多字节接收

     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 }
  • 相关阅读:
    Python程序员用文字加密的方式,给女程序员写情书,一周后牵手回家
    小学生在网吧用python抓取LOL英雄皮肤,步骤简单
    vuex中module的命名空间概念
    动态设置html的font-size值
    JavaScript判断各种数据类型
    vuex脑图
    作用域链和函数内部this指向问题以及bind、call、apply方法
    BOM
    jQuery_base
    js_base_note
  • 原文地址:https://www.cnblogs.com/Danhuise/p/3914966.html
Copyright © 2011-2022 走看看