附加字符串时出现C#SerialPort DataReceived问题 [英] C# SerialPort DataReceived problem when when attached strings
问题描述
我有一个DataReceived方法,该方法正在触发从RS232设备发送数据.使用以下代码,一切运行顺利
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";
仍然可以接收数据,但偶尔会显示不正确.例如.如果我正在连接磅秤,并且应该读取"10.45kg asdf",则它将在计算机上显示为"10. asdf45kg".这是什么问题?
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". What is the problem here?
推荐答案
当串行端口感觉像要触发它时,将触发 DataReceived
方法,而当您从接收到完整的字符串时并不一定要触发该方法.装置.请参见此答案进行详细的讨论.如果您知道终结符,则可以通过设置SerialPort的 NewLine
属性,然后使用 ReadLine()
.来解决此问题.
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()
.
这篇关于附加字符串时出现C#SerialPort DataReceived问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!