首页 > 解决方案 > C#到微控制器的串行通信问题

问题描述

我在 Visual Studio C# 环境中与嵌入式设备进行串行通信时遇到问题,当前的解决方案是使用以下配置与腻子会话进行通信:

每次建立连接时,腻子终端上都​​会显示一个菜单,其中显示控制器的可用命令。

我尝试了从 MS 示例中借用的以下内容:


public class PortChat
{
    static bool _continue;
    static SerialPort _serialPort;

    public static void Main()
    {

        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();

        _serialPort.PortName = "COM4";
        _serialPort.BaudRate = 9600;
        _serialPort.Parity = Parity.None;
        _serialPort.DataBits = 8;
        _serialPort.StopBits = StopBits.One;
        _serialPort.Handshake = Handshake.RequestToSend;


        // Set the read/write timeouts
        _serialPort.ReadTimeout = 5000;
        _serialPort.WriteTimeout = 5000;

        _serialPort.Open();
        Thread.Sleep(1000);
    }

}

在“Port.Open”之后从端口读取会导致异常,请参见第一个屏幕截图。写入端口也会导致异常,请参见第二个屏幕截图。我在这里想念什么?

谢谢

读取错误

写入错误

标签: c#serial-portmicrocontroller

解决方案


ReadLine 一直等到它看到 SerialPort.NewLine 字符串。如果这没有在 SerialPort.ReadTimeout 内到达,则会引发 TimeoutException。要么增加你的超时时间,要么使用ReadExisting().

参见:串口通信抛出 TimeoutException

根据 MSDN:[SerialPort.ReadTimeout] Gets or sets the number of milliseconds before a time-out occurs when a read operation does not finish.

请参阅:https ://docs.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.readtimeout?view=netframework-4.8

By default, the ReadLine method will block until a line is received. If this behavior is undesirable, set the ReadTimeout property to any non-zero value to force the ReadLine method to throw a TimeoutException if a line is not available on the port.

请参阅:https ://docs.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.readline?view=netframework-4.8


推荐阅读