您的位置:首页 > 编程语言 > C#

C#上位机

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

a) 波特率:115200

b) 数据位:8

c) 校验位:None

d) 停止位:1

接收数据: int len = serialPort1.BytesToRead;

byte[] data = new byte[len];

serialPort1.Read(data, 0, len);

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

for (int i = 0; i < len; i += 23)

{

byte[] newByte = ByteConvertToFloat.SubByte(data, i, 23);//下面定义的一个截取定长字节数组的方法

if (newByte[0] == 0x24)//帧头

{

if (newByte[1] == 0x02)//Paket_Quat

{

if (newByte[2] == 0x00)//四元数标志位

{

//对收到的数据进行处理的代码,字节转整型浮点型等

}

}

}

截取定长数组:

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

别人博客上的方法 :http://blog.sina.com.cn/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)

{

System.IO.MemoryStream bufferStream = new System.IO.MemoryStream();

byte[] returnByte = new byte[] { };

if (srcBytes == null) { return returnByte; }

if (startIndex < 0) { startIndex = 0; }

if (startIndex < srcBytes.Length)

{

if (length < 1 || length > srcBytes.Length - startIndex)

{

length = srcBytes.Length - startIndex;

}

bufferStream.Write(srcBytes, startIndex, length);

returnByte = bufferStream.ToArray();

bufferStream.SetLength(0);

bufferStream.Position = 0;

}

bufferStream.Close();

bufferStream.Dispose();

return returnByte;

}

}

有误之处请指正,谢谢,多多交流,共同进步。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: