Arduino,来自 BT-Module 的输入正在堆叠并添加

Arduino, input from BT-Module is stacking and added

我写了一个 Android 应用程序,它通过蓝牙向 Arduino 发送数据。连接工作正常并且非常稳定。唯一困扰我的是串行连接的输入不是我想要的。这对我来说很难解释,但每次我发送新命令时,ols 命令仍在串行输入中,因此我编写的代码无法识别新输入。也许这只是一个非常愚蠢的问题,但我只是不知道我能做些什么来解决它。我将 post 代码和输出放在这里,以便问题可见。

我正在使用 SoftwareSerial(此处为 BTserial),感觉我必须清除连接的 HC-05 模块或串行缓冲区的缓冲区,我尝试了很多其他解决方案,但 none 成功了,也许我只是不明白这里的问题是什么。

我的代码:

void loop() {

  //Serial.println(BTserial.available());
  if (BTserial.available() > 0) {
    delay(100);
    serialEvent();

    if (stringComplete) {
      Serial.println(inputString);

      int colorValues[3] = {0, 0, 0};

      sscanf(inputString.c_str(), "%d,%d,%d", &colorValues[0], &colorValues[1], &colorValues[2]);

      analogWrite(red, colorValues[0]);
      analogWrite(green, colorValues[1]);
      analogWrite(blue, colorValues[2]);
    }
  }
}


void serialEvent() {
  while (BTserial.available()) {
    // get the new byte:
    char inChar = (char)BTserial.read();
    // add it to the inputString:
    inputString += inChar;

    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}
Serial output

1,2,3

1,2,3
1,2,3

1,2,3
1,2,3
1,2,3

1,2,3
1,2,3
1,2,3
1,2,3

1,2,3
1,2,3
1,2,3
1,2,3
1,2,3

1,2,3
1,2,3
1,2,3
1,2,3
1,2,3
1,2,3

1,2,3
1,2,3
1,2,3
1,2,3
1,2,3
1,2,3
1,2,3

这不是您需要清除的串行缓冲区。这是保存您阅读的命令的字符串。你必须清除它。当您从中读取字符时,串行缓冲区会被清除。

if (stringComplete) {
          Serial.println(inputString);

          int colorValues[3] = {0, 0, 0};

          sscanf(inputString.c_str(), "%d,%d,%d", &colorValues[0], &colorValues[1], &colorValues[2]);

          inputString = "";     // Remove old command from inputString

          analogWrite(red, colorValues[0]);
          analogWrite(green, colorValues[1]);
          analogWrite(blue, colorValues[2]);
        }