数据在通过串行端口传输期间损坏

Data gets corrupted during transmission over the serial port(数据在通过串行端口传输期间损坏)
本文介绍了数据在通过串行端口传输期间损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个程序来与旧系统进行通信.我为此使用 System.IO.Ports.SerialPort.问题是当我发送更长的消息时,消息会损坏.我使用线路监听器并得到以下结果

I am developing a program to communicate with an old system. I use System.IO.Ports.SerialPort for this. The problem is when I send a longer message, the message bevome corrupt. I use a line listener and get the following results

我发送的内容

aa 01 00 00 12 03 06 18 02 c1 94 02 c1 94 00 00 00 00 00 00 00 00 00 00 00 00 1e fd 

我得到了什么

c2 aa 01 00 00 12 03 06 18 02 c3 81 c2 94 02 c3 81 c2 94 00 00 00 00 00 00 00 00 00 00 00 00 1e c3 bd

我使用的代码是

_comPort.Encoding = new UTF8Encoding();
_comPort.PortName = PortName;  //Com1
_comPort.BaudRate = BaudRate;  //9600
_comPort.StopBits = StopBits;  //1
_comPort.DataBits = DataBits;  //8
_comPort.Parity   = Parity;    //None
_comPort.Open();

_comPort.Write(messageStr);

为什么数据会损坏,我该如何解决?

Why is data corrupted and how do I fix this?

推荐答案

我的猜测是 messageStr 是一个字符串,而您看到的是编码问题.您已经明确指定了 UTF-8 编码,所以这就是您得到的 - 但我怀疑这不是您真正想要的.

My guess is that messageStr is a string, and you're seeing encoding issues. You've explicitly specified the UTF-8 encoding, so that's what you're getting - but I suspect it's not what you really want.

您已经显示了 二进制 数据,因此我假设您实际上想要发送该二进制数据 - 在这种情况下,您应该使用 Write(byte[], int, int) 过载.

You've shown binary data, so I assume you actually want to send exactly that binary data - in which case you should use the Write(byte[], int, int) overload.

如果您真的想要编写文本数据,您可能只需要选择正确的编码 - 但您需要向我们提供更多信息,以便我们帮助您做出正确的选择.

If you really want to write text data, you probably just need to pick the right encoding - but you'll need to give us more information for us to help you make the right choice.

这篇关于数据在通过串行端口传输期间损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

相关文档推荐

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子句?)