开关块在arduino C++上未正确执行



我有一个函数,它针对一些常量对单个变量执行switch。然而,它没有正确执行。

使用该代码,actionType4(LED_ACTION(,因此落入";LED动作";块

const int ledPin = LED_BUILTIN;
// Actions
const int NULL_ACTION = 0;
const int SERVO_ACTION = 1;
const int SERVOOP_ACTION = 2;
const int BUZZER_ACTION = 3;
const int LED_ACTION = 4;
void setup() {
Serial.begin(9600);
int actionType = 4;
Serial.print("Action type: ");
Serial.println(actionType);
switch (actionType) {
case BUZZER_ACTION:
Serial.println("Buzzer action");
//      int buzzerPitch = 123;
// int buzzerDuration = 1000;
// tone(buzzerPin, buzzerPitch, buzzerDuration);
break;
case LED_ACTION:
Serial.println("LED action");
int ledState = HIGH;
digitalWrite(ledPin, ledState);
break;
default:
Serial.println("Unknown action");
// Do Nothing
break;
}
int actionSleep = 1000;
Serial.print("Action sleeping for: ");
Serial.println(actionSleep);
delay(actionSleep);
}
void loop() {

}

这可以在日志输出中看到(LED闪烁(:

Action type: 4
LED action
Action sleeping for: 1000

当我在其他语句中添加任何其他内容时,问题就出现了。取消对BUZZER_ACTION块中单个赋值的注释会导致它……它似乎只是跳过了整个过程,没有记录其中的任何一个,也没有记录默认操作,也没有闪烁LED。

Action type: 4
Action sleeping for: 1000

我在这里做什么傻事吗?怎么回事?

这是在Arduino Uno r3上运行的,草图从Arduino IDE和VSCode上传。

谢谢!

Arduino C++不喜欢switch块中的声明,即使它们没有冲突。

把它们移到外面是没有问题的。

const int ledPin = LED_BUILTIN;
// Actions
const int NULL_ACTION = 0;
const int SERVO_ACTION = 1;
const int SERVOOP_ACTION = 2;
const int BUZZER_ACTION = 3;
const int LED_ACTION = 4;
void setup() {
Serial.begin(9600);
int actionType = 4;
Serial.print("Action type: ");
Serial.println(actionType);
int buzzerPitch;
int buzzerDuration;
int ledState;
switch (actionType) {
case BUZZER_ACTION:
Serial.println("Buzzer action");
buzzerPitch = 123;
buzzerDuration = 1000;
tone(buzzerPin, buzzerPitch, buzzerDuration);
break;
case LED_ACTION:
Serial.println("LED action");
ledState = HIGH;
digitalWrite(ledPin, ledState);
break;
default:
Serial.println("Unknown action");
// Do Nothing
break;
}
int actionSleep = 1000;
Serial.print("Action sleeping for: ");
Serial.println(actionSleep);
delay(actionSleep);
}
void loop() {

}

最新更新