附加字符串时的C#SerialPort DataReceived问题

C# SerialPort DataReceived problem when when attached strings(附加字符串时的C#SerialPort DataReceived问题)
本文介绍了附加字符串时的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问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)