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



我正在尝试使用波特率 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();
    }
}

我想,也许原因是我的程序应该在接收之前检查是否有可用的数据?

试试这样的事情。它至少不会挂起,然后你可以整理出你通过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 事件

指示已通过 表示的端口接收数据 串行端口对象。

SerialPort.ReadExisting Method ((

根据编码读取所有立即可用的字节,在两者中 串行端口对象的流和输入缓冲区。

为了避免这个问题,你需要在arduino中的数据中添加"">,因为港口。ReadLine((;搜索结束行 (""(

例如,假设arduino发送的数据是"1">,以使用端口读取此数据。ReadLine((;它应该是"1">

另外,别担心,端口。ReadLine((;不读""。当它看到""时就停在那里。

我希望它有所帮助。

最新更新