C#上位机

时间:2025-04-17 20:32:29

今天分配的任务是做出上位机接收单片机发送的四元数,里程数,角度值数据,协议都已经给出,采用串口通信。

a) 波特率:115200

b) 数据位:8

c)  校验位:None

d) 停止位:1

接收数据:  int len = ;
                      byte[] data = new byte[len];
                      (data, 0, len);

            23是协议中一个包的长,根据实际需要进行更改

             for (int i = 0; i < len; i += 23)
            {
                byte[] newByte = (data, i, 23);//下面定义的一个截取定长字节数组的方法
                if (newByte[0] == 0x24)//帧头
                {
                    if (newByte[1] == 0x02)//Paket_Quat
                    {
                        if (newByte[2] == 0x00)//四元数标志位
                        {
                                 //对收到的数据进行处理的代码,字节转整型浮点型等

                       }
                    }     
            }

截取定长数组:

接收到的数据不一定是完整的,要进行验证,而且可以一帧一帧进行处理,方法是照搬的

别人博客上的方法 :/s/blog_903d6d5d0101i7rk.html

 public static class ByteConvertToFloat
        {

            /// <summary>
            /// 截取定长的数组字节
            /// </summary>
            /// <param name="srcBytes">要被截取的源数组</param>
            /// <param name="startIndex">开始截取的索引值</param>
            /// <param name="length">要截取的字节长度</param>
            /// <returns></returns>


            public static byte[] SubByte(byte[] srcBytes, int startIndex, int length)
            {
                bufferStream = new ();
                byte[] returnByte = new byte[] { };
                if (srcBytes == null) { return returnByte; }
                if (startIndex < 0) { startIndex = 0; }
                if (startIndex < )
                {
                    if (length < 1 || length > - startIndex)
                    {
                        length = - startIndex;
                    }
                    (srcBytes, startIndex, length);
                    returnByte = ();
                    (0);
                    = 0;
                }
                ();
                ();
                return returnByte;
            }
        }

有误之处请指正,谢谢,多多交流,共同进步。