c# 串口协议解析

c# 串口协议解析


串口每次读上来数据长度不确定,接收到数据是不固定的长度,协议是起始是57 AB ,标准协议包是11位 ,中间偶尔会有4位的短包。
57 AB 88 07 21 00 04 F6 00 30 2A
57 AB 88 07 21 00 04 F7 00 31 2C
57 AB 88 07 21 00 03 F9 00 32 2E
57 AB 88 07 21 00 02 FA 00 33 2F
57 AB 88 07 21 00 04 F8 00 34 30
57 AB 82 A3
57 AB 88 07 21 00 02 FB 00 35 32
57 AB 88 07 21 00 02 FB 00 36 33
57 AB 88 07 21 00 02 FA 00 37 33
57 AB 88 07 21 00 02 FB 00 38 35
57 AB 88 07 21 00 02 FB 00 39 36
57 AB 88 07 21 00 02 FC 00 3A 38
57 AB 88 07 21 00 03 FA 00 3B 38
57 AB 88 07 21 00 01 FC 00 3C 39
57 AB 88 07 21 00 02 FC 00 3D 3B
57 AB 82 A3

接收到的数据有可能是57 AB 88 07 21 00 04 F6 00 30 2A
也可能是57 AB 88 07 21 00 04 F7 00 31 2C 57 AB 88 07 21 00 03 F9 00 32

要做的是将接到的数据先拼接成完整数据包。
然后 按照模板比对 是 11 字的包 还是 4字的同步包
在协议中会把4字协议包去除。只解析11字的包

        {
            // This method will be called when there is data waiting in the port's buffer
            int i;
            // Obtain the number of bytes waiting in the port's buffer
            int bytes = ballcomport.BytesToRead;

            // Create a byte array buffer to hold the incoming data
            byte[] buffer = new byte[bytes];

            // Read the data from the port and store it in our buffer
            ballcomport.Read(buffer, 0, bytes);

            for (i = 0; i < bytes; i++)//用来将buf的数据拼接到list数组,以保证把完整的一帧数据加到一个数组里面
            {
                list.Insert(b, buffer[i]);
            }
            while (list.Count >= 11)
            {
                if (list[0] == 0x57 && list[1] == 0xab)//判断数据
                {
                    if (list[2] == 0x82)
                    {
                        list.RemoveRange(0, 4);
                        continue;
                    }
                    else if (list[2] == 0x88 && list[3] == 0x07 && list[4] == 0x21)
                    {
                        if (list[6] >= 128)
                            xialx += (int)(list[6]-256);
                        else
                            xialx += (int)list[6];
                        if (list[7] >= 128)
                            xialy += (int)(list[7] -256);
                        else
                            xialy += (int)list[7];

                        list.RemoveRange(0, 11);                     
                        continue;
                    }                 
                }
                else
                {
                    list.RemoveRange(0,1);
                }

            }
          
        }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值