Arduino Serial接收错误数据

时间:2016-08-05 20:49:04

标签: bluetooth arduino serial-port arduino-uno

我正在开展一个项目,我使用我建立的手机应用程序来使用Google的语音识别器,通过蓝牙将我的手机与我的Arduino连接,然后当我说出一个单词时,它会发送单词以便在液晶显示屏上显示。

手机应用程序运行良好,没有任何问题。问题出在Arduino代码中。当我说单词 hello 时,Arduino会收到 ello 。我知道它接收它是因为我还使用串行监视器在我的计算机屏幕上显示除LCD之外的数据。然后在Arduino收到第一个数据块后,如果我发送第二个字,如 world ,Arduino会收到 elloorld 。所以它不仅再次错过了单词的第一个字母,而且在循环结束时串行端口也不是空的。

我尝试使用data += c;代替data.concat(c);,区别在于第二个单词不是 elloorld 而且它只是的 年世界

这是我的代码:

#include <LiquidCrystal.h> 

LiquidCrystal lcd(12, 11, 9, 8, 7, 6, 5, 4, 3, 2);

char c;
String data = "";

void setup() {
  lcd.begin(16, 2);

  Serial.begin(9600);
}

void loop() {
  lcd.clear();  //clean the lcd
  lcd.home();   // set the cursor in the up left corner

  while(Serial.available() > 0){
    c = Serial.read();
    data.concat(c);
  }

  if(data.length() > 0){
    Serial.println(data);
  }

  lcd.print(data);

  delay(3000);

  data = "";
}

如果在循环结束时我尝试使用以下代码清理串行端口:

while(Serial.available() > 0){
  Serial.read();
}

然后arduino根本没有收到数据。

1 个答案:

答案 0 :(得分:1)

您的代码每3000毫秒唤醒一次,然后处理串行输入缓冲区中待处理的所有内容并再次入睡。

如果删除那些丑陋的String数据和丑陋的延迟(3000)以及不必要的延迟,你可以尝试这个简单的循环:

unsigned long lastreceived;
void loop() {
  if (Serial.available()) {
     lcd.write(Serial.read());
     lastreceived=millis();
  }
  if (millis() - lastreceived > 1000) {
    // after one second of silence, prepare for a new message
    lcd.clear();
    lcd.home();
    lastreceived=millis(); // don't clear too often
  }
}