Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用SerialPort.write(字符串)将字符串写入串行端口_C#_String_Serial Port_Ascii - Fatal编程技术网

C# 如何使用SerialPort.write(字符串)将字符串写入串行端口

C# 如何使用SerialPort.write(字符串)将字符串写入串行端口,c#,string,serial-port,ascii,C#,String,Serial Port,Ascii,我正在尝试使用SerialPort.write(字符串)将字符串写入串行端口。 到目前为止,我一直在尝试 我在构造函数中实例化串行端口对象。 编辑:设置端口参数解决了问题 public CSerialPort() { this._serialPort = new SerialPort("COM6",1200,Parity.None,8,StopBits.One); this._serialPort.DataReceived += OnSerialPortDataReceived;

我正在尝试使用SerialPort.write(字符串)将字符串写入串行端口。 到目前为止,我一直在尝试

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

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);
}
其中,字符串的内容为:

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

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

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

尝试使用:

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

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

您可能还需要检查连接两侧的波特率(它们必须相同)。

您需要定义另一侧所需的字符串类型-ASCII字符串或其他类型,结尾是否为空。您的代码不包含端口设置,如波特率。如果另一方使用不同的端口参数,则结果未定义。Alex,另一方需要/等待ASCII字符串。我将设置参数并尝试。THXIt最好使用
SerialPort.Write(字节[],Ini32,Int32)
重载,它不依赖于任何字符串编码设置。根据另一面的要求准备字节数组。就这么简单,但你救了我一天。我设置了参数,它就工作了。我忘了我把另一边的波特率设置为1200。因此,它无法使用默认波特率。我还将尝试实现您对SerialPort.Write(字节[],Ini32,Int32)的提示。太多了!