【问题标题】:How to write character string to serial port using SerialPort.Write(String)如何使用 SerialPort.Write(String) 将字符串写入串口
【发布时间】:2014-09-03 06:40:54
【问题描述】:

我正在尝试使用 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 属性更改为所有可用的编码,但这没有帮助。

谁能告诉我如何使用串口类将任何字符串发送到串口? 我是否遗漏或误解了什么?

【问题讨论】:

  • 您需要定义在另一端期望什么样的字符串 - ASCII 字符串或其他东西,最后是否为 null。您的代码不包含端口设置,例如波特率。如果另一端使用不同的端口参数,则结果未定义。
  • Alex,对方需要/等待一个 ASCII 字符串。我将设置参数并尝试。 THX
  • 最好使用不依赖于任何字符串编码设置的SerialPort.Write(Byte[], Ini32, Int32) 重载。根据另一方要求准备字节数组。
  • 就这么简单,但你拯救了我的一天。我设置了参数并且它起作用了。我忘了我将另一边的波特率设置为 1200。所以它不适用于默认波特率。我还将尝试实现您对 SerialPort.Write(Byte[], Ini32, Int32) 的提示。非常感谢!

标签: c# string serial-port ascii


【解决方案1】:

尝试使用:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多