简体   繁体   English

从串口C#读取的数据不完整

[英]Incomplete data reading from serial port c#

I'm having a problem in reading the data transmitted from serial port (incomplete data in every first time running the project). 我在读取从串行端口传输的数据时遇到问题(每次运行该项目时,数据都不完整)。

I've tried two methods to read: 我尝试了两种方法来读取:

byte[] data = new byte[_serialPort.BytesToRead];
_serialPort.Read(data, 0, data.Length);
txtGateway.Text = System.Text.Encoding.UTF8.GetString(data);

And

txtGateway.Text = _serialPort.ReadExisting();

However, it only reads 14 bytes in every first time when I start the program. 但是,每次启动程序时,它仅在每次第一次读取14个字节。 When I trace the program, _serialPort.BytesToRead gives only 14 in every first time. 当我跟踪程序时, _serialPort.BytesToRead每次第一次仅给出14。 If I send the data for the second time, the data is read correctly. 如果我第二次发送数据,则可以正确读取数据。

The above two methods have the same result. 以上两种方法具有相同的结果。 I'm sure that writing data from serial port gives the complete data. 我确信从串行端口写入数据可以提供完整的数据。

Serial ports don't have any message boundaries. 串行端口没有任何消息边界。 If you want framing, you have to add it yourself. 如果要构图,则必须自己添加。

As for only the most recent 14 bytes being in the serial port when your program starts, 14 bytes is a typical FIFO size for serial ports. 至于程序启动时只有最近的14个字节在串行端口中,14个字节是串行端口的典型FIFO大小。 See also How do you programmatically configure the Serial FIFO Receive and Transmit Buffers in Windows? 另请参见如何在Windows中以编程方式配置串行FIFO接收和发送缓冲区?

Or just flush the receive buffer when the program starts. 或者在程序启动时仅刷新接收缓冲区。

在此处输入图片说明

Hi you can use array with carriage return \\r and ascii code \\x02 for STX 嗨,您可以将带有回车符\\ r和ASCII代码\\ x02的数组用于STX

string data = _serialPort.ReadExisting();
string[] arr1 = data.Split('\r');
checkFinal = checkFinal.Replace("\x02", "").ToString().Trim();

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

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