一段奇怪的数字 2019-11-05 19:24 采纳率: 50%
浏览 999
已采纳

STM32怎么判断发送的数据和接收到的数据是一样的

比如我要发送一个1024个字节的数据,我用什么来判断字节数和内容是一致的。
图片说明

  • 写回答

3条回答 默认 最新

  • qmfr 2019-11-06 17:22
    关注
    #define PACK_DATA_LEN (1024)
    typedef struct
    {
        unsigned char head[2]; /*帧头,我这边定义帧头为0xAA 0x55*/
            unsigned char data[PACK_DATA_LEN]; /*存放你想要的数据*/
            unsigned char checksum; /*校验和,从*/
    }T_Pack; /*数据包定义*/
    
    T_Pack rxPack = {0}; 
    T_Pack txPack = {0}; 
    
    /*校验和*/
    unsigned char checkSum(unsigned char *buf, unsigned int bufLen)
    {
        unsigned int i;
        unsigned char ret = 0;
        for(i=0; i< bufLen; i++)
        {
            ret += buf[i];
        }
        return ret;
    }
    
    /*发包*/
    void sendPack(unsigned char *buf, unsigned int bufLen)
    {
        unsigned int i;
        /*设置帧头*/
        txPack[0] = 0xAA;
        txPack[1] = 0x55;
        for(i=0; (i<bufLen)&&(i<PACK_DATA_LEN); i++)
        {
            txPack.data[i] = buf[i];
        }
        txPack.checksum = checkSum((unsigned char *)&txPack, sizeof(txPack)-1);
        uartSend((unsigned char *)&txPack, sizeof(txPack)); /*使用自己定义的串口发送函数*/
    }
    
    /*解包*/
    void findPack(unsigned char byteMsg) /*输入参数为从串口获得的一个数据*/
    {
        static unsigned char caseStu = 0;
        static unsigned int count = 0;
        static unsigned char* p = (unsigned char*)&rxPack;
        switch(caseStu)
        {
            case 0: /*判断hread 1*/
            count = 0;
                if(byteMsg == 0xAA) 
                {
                    p[count++] = byteMsg;
                    caseStu++;
                }
            break;
            case 1: /*处理head 2*/
                if(byteMsg == 0x55) 
                {
                    p[count++] = byteMsg;
                    caseStu++;
                }
                else
                {
                    caseStu = 0;
                }
            break;
            case 2: 
                p[count++] = byteMsg;
                if(count >= PACK_DATA_LEN+3) /*收到一包数据*/
                {
                    if(checkSum(p, count-1) == p[count-1]) /*校验数据正确性*/
                    {
                        rxPack.data ... /*data里面的数据就是接收的正确数据了*/
                    }
                    caseStu = 0; 
                }
            break;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。