【问题标题】:Clearing Arduino's serial buffer清除 Arduino 的串行缓冲区
【发布时间】:2014-10-12 11:29:07
【问题描述】:

我有一个简单的 arduino 代码:

void loop()
{
  if serial.available
  {
    c = serial.read();
    if (c == 'a')
    {
      blinkled();
    }
    else
      offled();
  }
}

如果我发送一个字符'a',它应该会发光。 当循环进入下一次迭代时,当我不提供任何东西时,它就会熄灭。

但是一旦我给出'a'。它开始发光,永不熄灭。

它是从缓冲区中读取字符“a”吗? 如果是的话怎么清除呢?

Serial.flush() 不工作。

请有任何想法。 我是阿杜伊诺的新手。 对不起,如果它很傻。

【问题讨论】:

    标签: arduino


    【解决方案1】:

    您已将 offled 函数放在 Serial.available() 路径中。您只能通过 Serial.available() 为真并按下不同的字符来关闭它,以便它读取除 'a' 以外的其他内容

    不幸的是,上面的例子也犯了同样的错误。

    构造它以使 LED 在 if 语句之外关闭

    【讨论】:

      【解决方案2】:

      你可以这样使用:

      void loop() {
          while (Serial.available() > 0)
          {
              char received = Serial.read();
              inData += received; 
      
              // Process message when new line character is received
              if (received == '\n')
              {
                  Serial.print("Arduino Received: ");
                  Serial.print(inData);
      
                  // You can put some if and else here to process the message juste like that:
      
                  if(inData == "a\n"){ // DON'T forget to add "\n" at the end of the string.
                    Serial.println("OK, I'll blink now.");
                    blinkled();
                  }
                  else if (inData == "b\n") {
                    offled();
                  }   
      
                  inData = ""; // to flush the value.
              }
          }
      }
      

      编辑:我已根据正确答案修改了我的答案。

      【讨论】:

      • 等待循环是个坏主意,您可以执行if(Serial.available() > 0) 然后没有inData += received mumbo jumbo,您可以执行inData = Serial.readBytesUntil('\n') 阅读直到\n
      • 是的,两者都有效。关于readBytesUntil,我不确定它在撰写本文时是否可用。
      猜你喜欢
      • 1970-01-01
      • 2022-08-11
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多