switch 块在 arduino C++ 上无法正确执行

switch block not executing correctly on 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() {
  
}