简体   繁体   中英

C# SerialPort DataReceived problem when when attached strings

I have a DataReceived method being trigger a data is send from a RS232 device. Things run smoothly with the following code

byte[] data = new Byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
string read = System.Text.Encoding.ASCII.GetString(data);

but if I add a string after a data

string read = System.Text.Encoding.ASCII.GetString(data) + "asdf \n";

The data is still received but occasionally would be displayed incorrectly. Eg if I'm connecting to a scale and should be reading "10.45kg asdf" it would show on my computer as "10. asdf45kg". What is the problem here?

The DataReceived method will be triggered when the serial port feels like triggering it, which is NOT necessarily when you receive a full string from the device. See this SO answer for a great discussion of the details. If you have a known terminator character, you can work around this problem by setting the NewLine property of the SerialPort, and then using ReadLine() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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