首页 文章

错误的Arduino逻辑?

提问于
浏览
0

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

Void loop(){

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

如果我运行上面的代码它工作正常,但它保持循环显然在循环中 . 所以我决定在setup()中使用Serial.begin(9600)启动串口com,然后测试串口com并使用switch case语句来正确实现这些方法 . 我在这做错了什么?我没有任何错误 . 当我输入串行监视器时没有任何反应,我相信我的逻辑很好,但这就是我在这里的原因 . 当在串行监视器中输入任何内容时,代码将在switch case语句中运行默认值,即可 . 我尝试过使用,如果无济于事 . 还测试了串口的逆,这将是!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);

}
}

1 回答

  • 1

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

    e.g. 当您输入 0 时, Serial.read() 返回 48 ,这是数字 0 的ASCII代码 . 由于在以下情况中未列出值 48 ,因此采用默认分支:

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

    您的问题有 many 解决方案 .

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

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

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

    int ledStatus = Serial.parseInt();
    

    这实际上适用于更一般的输入,例如: 123 ,但如果输入缓冲区中的数字有任何不同,它将返回 0 .

    atoi()3. wrap Serial.read()

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

    这比以前的两个选项都要有限,因为现在你的交换机只能有 10 个案例 .

相关问题