0
votes

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. When I trace the program, _serialPort.BytesToRead gives only 14 in every first time. 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.

2
BytesToRead and ReadExisting are both unreliable.Ben Voigt

2 Answers

0
votes

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. See also How do you programmatically configure the Serial FIFO Receive and Transmit Buffers in Windows?

Or just flush the receive buffer when the program starts.

enter image description here

0
votes

Hi you can use array with carriage return \r and ascii code \x02 for STX

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