gpt4 book ai didi

c# - 如何使用 SerialPort.Write(String) 将字符串写入串口

转载 作者:行者123 更新时间:2023-11-30 16:10:32 26 4
gpt4 key购买 nike

我正在尝试使用 SerialPort.Write(String) 将字符串写入串行端口。到目前为止,我已经尝试过了

我在构造函数中实例化串行端口对象。编辑:设置端口参数解决了问题。

public CSerialPort()
{
this._serialPort = new SerialPort("COM6",1200,Parity.None,8,StopBits.One);
this._serialPort.DataReceived += OnSerialPortDataReceived;
}

我打开端口:

public void OpenSerialPort()
{
try
{
_logger.DebugFormat("Trying to open Serial Port: {0}", this._serialPort.PortName);
this._serialPort.Open();
this.PortIsOpen = true;
}
catch (UnauthorizedAccessException ex)
{
_logger.DebugFormat("Trying to open Serial Port: {0}", ex);
}
catch (ArgumentOutOfRangeException ex)
{
_logger.DebugFormat("Trying to open Serial Port: {0}", ex);
}
catch (ArgumentException ex)
{
_logger.DebugFormat("Trying to open Serial Port: {0}", ex);
}
catch (InvalidOperationException ex)
{
_logger.DebugFormat("Trying to open Serial Port: {0}", ex);
}
}

然后我尝试通过串口发送一个字符串的内容:

public void WriteToSerialPort(string writeBuffer)
{
this._serialPort.Write(writeBuffer);
}

String的内容在哪里:

this._serialPort.WriteToSerialPort("ABC");

我的问题是在接收方(另一台带有串行端口监控软件的 PC)我没有收到“ABC”。我收到的是“þ”,它是 ASCII 字符代码 254。

我尝试将 Encoding 属性更改为所有可用的编码,但这没有帮助。

谁能告诉我如何使用串行端口类将任何字符串发送到串行端口?我错过或误解了什么吗?

最佳答案

尝试使用:

byte[] MyMessage = System.Text.Encoding.UTF8.getBytes(yourString);

MySerialPort.Write(MyMessage,0,MyMessage.Length);

您可能还想检查连接两端的波特率(这些值必须相同)。

关于c# - 如何使用 SerialPort.Write(String) 将字符串写入串口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25637820/

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