c++ - Arduino清除缓冲区

标签 c++ c arduino microprocessors

#include <stdio.h>

#define LED 13

void setup() {
  pinMode(LED, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() == 4) {
    char command[5];

    for (int i = 0; i < 4; i++) command[i] = Serial.read();
    command[4] = '\0';

    Serial.println(command);

    if (strcmp(command, "AAAA") == 0) {
      digitalWrite(LED, HIGH);
      Serial.println("LED13 is ON");
    } else if (strcmp(command, "BBBB") == 0) {
      digitalWrite(LED, LOW);
      Serial.println("LED13 is OFF");
    }
  }
}

我有这段代码,可以读取 4 个字符长的字符串。但是,我需要它忽略任何长度不超过 4 个字符的字符串。

所以,想象一下这个输入:

AAAA
BBBB
BBB
AAAA

现在,它显示为 {"AAAA", "BBBB", "BBBA"}。

我需要它来读取 {"AAAA", "BBBB", "AAAA"}。

有什么想法吗?谢谢。

最佳答案

您可以检查字符间延迟的持续时间。设置超时时间,例如100ms。当指定的超时时间后没有收到更多数据时,表示整个字符串已传输完毕。然后您可以检查字符串的长度并执行您的应用程序逻辑。

关于c++ - Arduino清除缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10456931/

相关文章:

c++ - 如何让我的系统支持纳秒精度

c++ - 在 Arduino 中将字节 * 转换为字符串

c# - 如何从 C++ 调用托管 (C#) 函数?

c++ - 为什么 CoCreateInstance 可以在完全相同的上下文中返回两个不同的 HRESULT?

c - fseek 和 fwrite 过去的 EOF

c - 管道设置终端到 gnuplot 管道在屏幕上产生垃圾

c - subq $40 %rsp 与 AS 崩溃但 GCC 没有

android - 与其他字符相比,c++/Arduino 是否以不同方式处理 '?'

c++ - 将字符串对象附加到 Arduino 中的字符数组

c++ - 将 void 函数转换为 char* C++