C# SerialPort DataReceived problem when when attached strings(附加字符串时的C#SerialPort DataReceived问题)
问题描述
我有一个 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
";
数据仍然被接收,但偶尔会显示不正确.例如.如果我连接到秤并且应该读取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
方法会在串口感觉触发的时候触发,不一定是收到完整的字符串装置.请参阅 此 SO 答案详细讨论.如果您有一个已知的终止符,您可以通过设置 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问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:附加字符串时的C#SerialPort DataReceived问题
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01