如何从串行端口接收更多消息#

How to receive more messages from Serial Port c#

我正在使用 System.IO.Ports。 我向设备发送消息并希望等待来自它的所有消息。

我正在尝试这样做:

message = Console.ReadLine();
_serialPort.Write(message);
Console.WriteLine(_serialPort.ReadExisting());

但它 return 只是第一行。 我试过使用 port.BytesToRead,但我得到了相同的结果。 当我使用 ReadLine() 它没有 return 任何东西。

编辑:

要查看所有行,请使用事件处理程序。

我的问题的解决方案是在末行使用 \r(输入)。

ReadExisting return 在准确时间可用的可用字节,在读取缓冲区之前延迟,解决方法是

message = Console.ReadLine();
_serialPort.Write(message);
Thread.Sleep(200);
Console.WriteLine(_serialPort.ReadExisting());

编辑 2: 这是我在项目中的做法

private SerialPort port;
string DataReceived  = string.Empty;

public string OpenPort(string PortName, int BaudRate)
    {
        // if the port is already used by other window then return the same instance
        if (port != null)
            if(port.IsOpen)
                return "True";


        port = new SerialPort(PortName, BaudRate, Parity.None, 8, StopBits.One);

        // Attach a method to be called when there
        // is data waiting in the port's buffer
        port.DataReceived += new
            SerialDataReceivedEventHandler(port_DataReceived);

        // Begin communications
        try
        {
            port.Open();
        }
        catch(Exception ex)
        {
            return ex.Message;
        }
        return "True";
    }


private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
Thread.sleep(200);
            DataReceived =  port.ReadExisting();
        }

在你的主要

message = Console.ReadLine();
_serialPort.Write(message);
//use Stopwatch to calculate time befor you can exit from the loop
while(true)
{
if(!string.IsNullOrWhiteSpace(DataReceived))
break;
// Todo : Check stopwatch for timeout
}

也许您的串口设备出现换行问题请尝试:

message = Console.ReadLine();
_serialPort.WriteLine(message);
Console.WriteLine(_serialPort.ReadExisting()); # try debug here replace with string test = _serialPort.ReadLine();