C# - SerialPort.ReadLine() 冻结了我的程序

C# - SerialPort.ReadLine() freezes my program

我正在尝试使用波特率 9600 通过串行端口读取从我的 Arduino 发送的消息。

我的 Arduino 代码被编程为在我按下按钮时发送“1”,在我松开按钮时发送“0”。

所以不是一直在发送数据。

我的 C# 程序将读取该消息并将其添加到列表框。但是每当我启动它时,程序就会挂起。

private void button1_Click(object sender, EventArgs e)
{
    SerialPort port = new SerialPort();
    port.BaudRate = 9600;
    port.PortName = "COM4";
    port.ReadTimeout = 1000;
    port.Open();


    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    try
    {
        ee = port.ReadLine();
        listBox1.Items.Add(ee);
    }
    catch (Exception)
    {
        timer1.Stop();
    }
}

我猜,可能是因为我的程序在接收之前应该检查是否有数据可以接收?

为避免此问题,您需要将 "\n" 添加到您的 arduino 数据中,因为 port.ReadLine();搜索结束行 ("\n")

比如arduino发送的数据是"1",用port.ReadLine()读取这个数据;应该是 "1\n"

还有,别着急,port.ReadLine(); 不读“\n”。当它看到 "\n".

时就停在那里

希望对您有所帮助。

试试这样的方法。它至少不会挂起,然后你可以通过 DataReceived

来整理你得到的数据类型

从那里您可以确定如何更好地编写您的应用程序

private void button1_Click(object sender, EventArgs e)
{
    SerialPort port = new SerialPort();
    port.BaudRate = 9600;
    port.PortName = "COM4";
    port.ReadTimeout = 1000;

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

   // Begin communications
   port.Open();
}

private void port_DataReceived(object sender,
                                 SerialDataReceivedEventArgs e)
{
   // Show all the incoming data in the port's buffer in the output window
   Debug.WriteLine("data : " + port.ReadExisting());
}

SerialPort.DataReceived Event

Indicates that data has been received through a port represented by the SerialPort object.

SerialPort.ReadExisting Method ()

Reads all immediately available bytes, based on the encoding, in both the stream and the input buffer of the SerialPort object.