开发者

C# SerialPort DataReceived problem when when attached strings

开发者 https://www.devze.com 2023-01-28 21:34 出处:网络
I have a DataReceived method being trigger a data is send from a RS232 device. Things run smoothly with the following code

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. E.g. if I'm connecting to a scale and should be reading "10.45kg asdf" it would show on my computer as "10. asdf45kg"开发者_JS百科. 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().

0

精彩评论

暂无评论...
验证码 换一张
取 消