C# - 如何无限期地从 SerialPort 读取数据

C# - How to read from a SerialPort for an infinite amount of time

我有一个 arduino 连接到我的串行端口,它一直生成从 0 到 64 的数字。

我想在 C# 中读取这些信号并设法将它们附加到富文本框。 不幸的是,在某些时候它们不再写在框中,我必须再次打开端口以再次将文本附加到框中。

这是代码示例:

private void btnOpenPort_Click(object sender, EventArgs e)

    {
        if (Arduino.IsOpen == false)
        {   
            Arduino.BaudRate = 115200;
            Arduino.PortName = cBPortWaehlen.SelectedItem.ToString();
            Arduino.Open();

        }
        while (Arduino.BytesToRead != 0) 
        {
           richTextBox1.AppendText(Arduino.ReadExisting());
        }
    }

我假设语句 Arduino.BytesToRead 永远不会变成假,只要我的 arduino 发送信号,但事实似乎并非如此。我怎样才能做到这一点?

首先,关于在 C# 中建立的任何串行连接都有一个默认事件处理程序,称为 DataReceived。我相信您可以使用它,并删除那里的 while 代码块。

其次,我认为 while 块的操作密集度太高,所以如果你不接受我的第一个建议,请尝试在你的 while 中放置一个 Thread.Sleep(1000),这样它就不会执行那么多次。如果您想每隔几毫秒刷新一次数据,请将 Thread.Sleep(1000) 替换为您喜欢的毫秒数。

希望这能回答您的问题。

稍后编辑:

您可以拥有的代码如下所示:

public void OpenArduinoConnection()
 {
     if(!arduinoBoard.IsOpen)
     {
         arduinoBoard.DataReceived += arduinoBoard_DataReceived;
         arduinoBoard.PortName = "yourportname";
         arduinoBoard.Open();
      }
      else
      {
         throw new InvalidOperationException("The Serial Port is already open!");
      }
 } 

void arduinoBoard_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
   // your code here
}