清除Arduino串行缓冲区

时间:2014-10-12 11:29:08

标签: arduino

我有一个简单的arduino代码:

void loop()
{
  if serial.available
  {
    c = serial.read();
    if (c == 'a')
    {
      blinkled();
    }
    else
      offled();
  }
}
如果我发送一个角色'它应该发光led。 当循环进入下一个循环时,当我不提供任何东西时它就会消失。

但是一旦我给出了'它开始发光,永远不会消失。

是否正在阅读char' a'从缓冲区? 如果是的话那么如何清除呢?

Serial.flush()无效。

请提出任何想法。 我是arduino的新手。 抱歉,如果它很傻。

2 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

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.
        }
    }
}

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

答案 1 :(得分:1)

您已将您的offled函数置于Serial.available()路径中。您只能通过Serial.available()将其关闭为true并且您推送一个不同的字符,以便它读取除' a'

之外的其他内容

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

构造它以使led在if语句

之外关闭
相关问题