Arduino 逻辑错误?

Faulty Arduino Logic?

我正在制作一个简单的 Led 程序,它将变成我项目的库。我已经创建了四种方法,可以让您 A) 设置任意数量的 Led 引脚并将它们作为输出。 B) 在自定义时间闪烁 LED 灯。 C) 打开 LED。 D) 关闭 LED。如果我只是 运行 void loop() 中的方法,一切正常。例如:

Void loop(){

flashLed(pinNum, 2000);
turnOf(pinNum);
turnOn(pinNum);
}

如果我运行上面的代码它工作正常,但是它一直在循环,因为它显然在循环中。所以我决定通过在 setup() 中使用 Serial.begin(9600) 来启动串行 com,然后测试串行 com 并使用 switch case 语句以适当地实现这些方法。我在这里做错了什么?我完全没有错误。当我输入串行监视器时没有任何反应,我相信我的逻辑很好,但这就是我在这里的原因。当在串行监视器中键入任何内容时,代码 运行 是 switch case 语句中的默认值,仅此而已。我试过使用 while,如果无济于事。还测试了 serial 的逆函数 !serial.available() 这是我的代码:

//Define the pin numbers
byte pinNum[] = {4, 3, 2};


void setup() {
  //Setup the ledPins
  ledSetup(pinNum);
  Serial.begin(9600);  
}

void loop() {

  while(Serial.available() > 0){
    //Read the incoming byte
    byte ledStatus = Serial.read();
    switch (ledStatus){
      case 0: 
      turnOff(pinNum);
      Serial.println("The Leds Have Been Turned Off");
      break;
      case 1:
      turnOn(pinNum);
      Serial.println("The Leds Have Been Turned On");
      break;
      case 2:
      flashLed(pinNum, 1000); //This will make the Led blink for half a second
      Serial.println("The Leds Will Begin Flashing");
      break;
      default:
      flashLed(pinNum, 1000); //This will make the Led blink for half a second
      break;
    }
  }
}

//Method to declare the pins as output
void ledSetup(byte ledPins[]){
  for (int i = 0; i <= sizeof(ledPins); i++){
    pinMode(ledPins[i], OUTPUT);
  }
}

//Method to blink the Led light/lights
void flashLed(byte ledBlink[], int duration){
  //Time is divided by two because it takes 2 seconds 
  //to run the sketch 
for (int i = 0; i <= sizeof(ledBlink); i++){
  digitalWrite(ledBlink[i], HIGH);
  delay(duration/2);
  digitalWrite(ledBlink[i], LOW);
  delay(duration/2);
}
}

//Method to turn Leds off
void turnOff(byte ledOff[]){
  for(int i = 0; i <= sizeof(ledOff); i++){
    digitalWrite(ledOff[i], LOW);
}
}

//Method to turn Leds On
void turnOn(byte turnOn[]){
for (int i = 0; i <= sizeof(turnOn); i ++){
  digitalWrite(turnOn[i], HIGH);

}
}

串行监视器发送以ASCII格式编码的符号。

例如当你输入0,Serial.read()returns 48,就是数字 0 的 ASCII 代码。由于在以下情况下未列出值 48,因此采用 default 分支:

      case 0: ...
      case 1: ...
      case 2: ...
      default: ...

您的问题有 多种 种解决方案。

1. 更改 case 条件以匹配您发送的内容:

      case '0': ...
      case '1': ...
      case '2': ...

2.Serial.read() 替换为 Serial.parseInt():

    int ledStatus = Serial.parseInt();

这实际上适用于更通用的输入,例如123,但如果输入缓冲区中的 数字 有任何不同,它将 return 0

3.Serial.read() 包裹在 atoi():

    byte ledStatus = atoi(Serial.read());

这比之前的两个选项都有更多限制,因为现在您的开关中只能有 10 个案例。