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

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条)

报告相同问题?

悬赏问题

  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导