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

发布于 2024-10-06 00:41:33 字数 446 浏览 0 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

聊慰 2024-10-13 00:41:33

当串行端口想要触发它时,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 the NewLine property of the SerialPort, and then using ReadLine().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文