【问题标题】:C# - SerialPort.ReadLine() freezes my programC# - SerialPort.ReadLine() 冻结我的程序
【发布时间】:2018-09-01 20:53:13
【问题描述】:

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

我的 Arduino 代码被编程为每当我按下按钮时发送一个“1”,当我松开手指时发送一个“0”。

所以它不是不断发送数据。

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

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();
    }
}

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

【问题讨论】:

  • ReadLine 读取直到流中有行终止符 (\n)。根据您的描述,您的设备似乎从不输出此类终止符,因此 ReadLine 会永远阻塞。
  • 在流设备(如串口)中使用ReadLine 不是一个好主意,因为它会冻结程序(当没有完成的'行',或者在全部)。使用DataReceived 事件确保有数据,使用ReadExisting 代替。

标签: c# arduino serial-port readline


【解决方案1】:

改用这样的方法。它至少不会挂起,然后您可以通过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

表示已经通过一个端口接收到数据 SerialPort 对象。

SerialPort.ReadExisting Method ()

根据编码读取所有立即可用的字节 SerialPort 对象的流和输入缓冲区。

【讨论】:

  • 谢谢!!这真的很有帮助!
【解决方案2】:

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

例如,假设arduino发送的数据是“1”,用port.ReadLine();它应该是 "1\n"

另外,别担心,port.ReadLine(); 不读取“\n”。当它看到“\n”时就停在那里。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多