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问题
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01