gpt4 book ai didi

c# - 从串口接收到的数据有错误的换行符

转载 作者:太空狗 更新时间:2023-10-30 00:42:43 28 4
gpt4 key购买 nike

我编写了一个应用程序,可以将数据发送到 COM 端口并接收返回的数据。

发送效果很好,但接收效果不好。多行和只读文本框中的换行符不正确。

截图:

enter image description here

我的接收代码是:

void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[_serialPort.BytesToRead];
_serialPort.Read(data, 0, data.Length);

string str = System.Text.Encoding.UTF8.GetString(data);

textBox3.Text = textBox3.Text + str;

textBox3.SelectionStart = textBox3.TextLength;
textBox3.ScrollToCaret();
}

在打开端口之前,我将 New Line 属性设置为\r\n:

_serialPort.NewLine = "\r\n";

如何解决这个问题?

最佳答案

来自 the documentation :

Gets or sets the value used to interpret the end of a call to theReadLine and WriteLine methods.

关键是它使用解释调用的结束,而不是设置 .

NewLine 属性处理 SerialPort 对象如何尝试解释传入数据。它不会操纵传入的数据。

换句话说,通过将 NewLine 属性设置为“\r\n”,您告诉它查找“\r\n”并使用它作为换行符。

进入串口的数据就是这样。您无法更改其他人发送数据的方式。 (除非您也编写了该应用程序。)您只能告诉 SerialPort 如何尝试正确读取数据。

您需要做的是找出程序发送给您的内容并将 .NewLine 属性设置为那个。它很可能只是发送“\n”或“\r”,因此如果您将 NewLIne 属性设置为匹配,您的程序将开始正确识别发送给它的换行符。

SerialPort.ReadLine Property Usage 上有更多信息可能会有所帮助

关于c# - 从串口接收到的数据有错误的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13992477/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com