【问题标题】:C# Serial Communications issues with ArduinoArduino 的 C# 串行通信问题
【发布时间】:2016-09-11 17:32:57
【问题描述】:

我一直在为一些代码的通信速度而苦苦挣扎。

所以我想提高代码和 Arduino 的波特率。但如果我离开 9600 波特率,数据将停止正确发送和接收。 所以我设置了一个简单的测试程序。

Arduino 代码:

void setup()
{
    Serial.begin(9600);
    Serial.setTimeout(10);
}

void loop()
{
    if (Serial.available())
    {
        String Data = Serial.readStringUntil('#');
        if (Data == "Test")
        {
            Serial.println("Recived");
        }
    }
    delay(1);
}

c#代码:

SerialPort Port = new SerialPort("COM4", 9600);
Port.Open();
if (Port.IsOpen)
{
     Port.Write("Test#");
     System.Threading.Thread.Sleep(1000);
     String Read = Port.ReadExisting();
     Port.Close();
}

因此,运行 String Read 会返回“Recived\r\n”。 将波特率更改为 19200 后返回 ""。

任何想法为什么会发生这种情况?

编辑:如果我使用 Arduino IDE 的串行监视器程序,无论使用的波特率如何,它都可以正常工作。一旦我使用c#,就会出现这个问题。我认为这排除了硬件问题。

【问题讨论】:

  • 您必须设置 Handshake 属性。如果您不这样做,那么您将获得上次用于该端口的任何程序的握手模式。或者,如果您没有使用此类程序,或者程序在关闭端口时将其恢复,则为系统默认值。这对于 Arduino 来说往往很麻烦,因为它没有实现握手信号。您必须明确地将其设置为 Handshake.None。

标签: c# arduino serial-port .net-4.5 baud-rate


【解决方案1】:

尝试从 PC 一次发送一个字符并使用 Serial.read() 将一个字符读入 arduino 的缓冲区。有时,以高波特率从 PC 发送整个文本对于 arduino 来说太多了。

【讨论】:

    【解决方案2】:

    感谢您的意见。

    我想我已经找到了解决方案,虽然不清楚原因。

    我认为这是由于Serial.Avalible() 命令。看来我需要先发送一些数据以使其注册端口已打开。

    因此将我的 C# 代码修改为:有效

    SerialPort Port = new SerialPort("COM4", 9600);
    Port.Open();
    if (Port.IsOpen)
    {
         Port.Write("#");
         Port.Write("Test#");
         System.Threading.Thread.Sleep(1000);
         String Read = Port.ReadExisting();
         Port.Close();
    }
    

    非常感谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多