简体   繁体   English

从C#的串行端口读取字节流

[英]Reading stream of bytes from serial port in C#

I am new to c#. 我是C#的新手。 I have a serial (COM port) device which is streaming an array of bytes continuously. 我有一个串行(COM端口)设备,该设备连续不断地传输字节数组。 The array contains values of different sensors which are read by micro-controller. 该数组包含微控制器读取的不同传感器的值。 Basically the value of each sensor is shown by 8 bytes such that each byte represents an ascii character.There is no delimiter between these bytes. 基本上每个传感器的值都由8个字节显示,因此每个字节代表一个ascii字符。这些字节之间没有定界符。 After 32 bytes, we have two bytes of a carriage (D) and a new line (A). 在32个字节之后,我们有两个字节的回车(D)和换行(A)。

I use serialPort1.ReadExisting() to read data from serial port and then display readings in a textbox. 我使用serialPort1.ReadExisting()从串行端口读取数据,然后在文本框中显示读数。 However, I need the numeric values of these sensors for plotting and calculations. 但是,我需要这些传感器的数值进行绘图和计算。 How can I convert these values to float numbers? 如何将这些值转换为浮点数? Or how should I change the way I am reading serial port. 或者我应该如何更改读取串行端口的方式。

I really appreciate your help! 非常感谢您的帮助!

To convert bytes to floating point numbers you could use the BitConverter object. 要将字节转换为浮点数,可以使用BitConverter对象。 Then call the ToSingle method. 然后调用ToSingle方法。

see HERE for reference. 请参阅此处以供参考。

It sounds like you need to read the datasheet of the device sending in the bytes to know big endian or little endian. 听起来您需要阅读发送字节的设备的数据表,才能知道大字节序或小字节序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM