【问题标题】:Arduino reading from serial gives unwanted inputArduino从串行读取给出了不需要的输入
【发布时间】:2019-07-05 22:38:09
【问题描述】:

我正在尝试构建一个小程序来控制 3 个 LED。 LED 连接在引脚 11(红色)、12(黄色)和 13(绿色)上。

对于某些我不知道的原因,以下代码似乎不起作用。如果我在串行输入中输入 1,黄色 LED 会亮起。但大约 1 秒后,它再次关闭,红色 LED 亮起。在我看来,串行输入上总是有一个 0,但这不可能吧?

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available() > 0) {
    changeLed(Serial.parseInt());
  }
}

void changeLed(int color) {
  turnAllLedsOff();
  turnOnLed(color);
}

void turnOnLed(int ledPin) {
  enum ledControl {RED, YELLOW, GREEN};
  if(ledPin == RED) {
    digitalWrite(11, HIGH);
  }
  if(ledPin == YELLOW) {
    digitalWrite(12, HIGH);
  }
  if(ledPin == GREEN) {
    digitalWrite(13, HIGH);
  }
}

void turnAllLedsOff() {
  digitalWrite(11, LOW);
  digitalWrite(12, LOW);
  digitalWrite(13, LOW);
}

【问题讨论】:

    标签: arduino arduino-uno


    【解决方案1】:

    我相信您的串行监视器的行尾设置设置为Both NL & CR。一个触发Serial.parseInt(),另一个触发另一个Serial.parseInt()。因此,每个串行输入,您调用该函数两次。第二个总是返回0,因为仅换行符(或仅回车符)不是有效数字。这就是为什么您的红色 LED 会亮起的原因。尝试其他行尾设置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-18
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      • 2022-11-10
      • 2014-06-26
      相关资源
      最近更新 更多