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

本文标题为:附加字符串时的C#SerialPort DataReceived问题

基础教程推荐