附加字符串时 C# SerialPort DataReceived 问题
我有一个 DataReceived 方法,用于触发从 RS232 设备发送数据。使用以下代码,事情运行顺利,
byte[] data = new Byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
string read = System.Text.Encoding.ASCII.GetString(data);
但如果我在数据后添加一个字符串,
string read = System.Text.Encoding.ASCII.GetString(data) + "asdf \n";
数据仍然会收到,但有时会显示不正确。例如,如果我连接到秤并且应该读取“10.45kg asdf”,它将在我的计算机上显示为“10.asdf45kg”。这里有什么问题呢?
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". What is the problem here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当串行端口想要触发它时,
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 theNewLine
property of the SerialPort, and then usingReadLine()
.