2

我正在做一个 Arduino 项目,并希望从Serial portarduino 串行事件中接收一些命令。但是它总是不满足条件,使代码不知道串行事件已经完成。这是我的代码。

void serialEvent() {
    while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read(); 
    if (inChar == '`')
    {
        // 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 == '|') {
            settingsReceived = true; // <----- This will never be called
            Serial.println("true"); // <------ Nor this will too
        }  
    }
  }
}

我试过`Hello|从串行监视器传递字符串,但它不会响应。另外,我尝试了Line endingwith No Line EndingNewline但它不起作用,有人可以帮忙吗?谢谢!

4

2 回答 2

2

我已经想通了问题,Serial.read()每次只会读取一个字节,例如`Hello|会被拆分成

` H e l l o |  

所以第一次,if (inChar == '`')是真的,所以进入里面的动作,但是从第二个字符开始,(H,e,l,l,o,|)不是字符“`”,意思是if (inChar == '`')不正确,之后不让它进入状态。

这应该是这样做的正确方法:

void serialEvent() {
    if (Serial.available())
    {
       char inChar = (char)Serial.read();
       if (inChar != '`')
       {
         return;    // <----- Rejecting the char if not starting with `
       } 
    }

    while (Serial.available()) {
    // get the new byte:
      char inChar = (char)Serial.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 == '|') {
        settingsReceived = true;
        Serial.println("true");
      }

    }
}
于 2013-08-10T06:16:55.507 回答
1

inputstring在草图中定义的吗?还有,loop()还有setup()一些任务要完成。请参阅:http ://arduino.cc/en/Tutorial/SerialEvent这个页面有一个很好的起始示例,首先让它工作,然后针对您的特定代码进行修改。

当你输入“你好|” 然后按回车,什么是'|' 为了?您是否有理由不测试 '\n' 作为行终止字符?

此外,您正在测试 inChar == '`' 然后将其添加到字符串中,但您输入的是“Hello”?串行 I/O 一次传递一个字符,因此您需要允许输入的 inChars。

于 2013-08-10T05:45:12.833 回答