关于 Arduino 初学者项目代码的问题

问题描述 投票:0回答:1

Picture of the circuit

我正在尝试编写一个带有注释的草图,以按照以下说明控制 3 个 LED 和按钮:

  • 草图应以红灯亮起开始。
  • 按下按钮后,只要按住按钮,绿灯就会亮。
  • 松开按钮后,绿灯熄灭, 黄灯亮一秒然后熄灭。
  • 随后红灯亮起,直到下次按下按钮。

现在我的代码可以运行了;但是,它从黄色开始,然后每次运行代码时切换为红色。我不知道如何让它默认从红色开始,只有发布后才开始从黄色变成红色。

这是到目前为止的代码:

// Pin variables
int red = 9;        // Red LED connected to pin 9
int yellow = 10;    // Yellow LED connected to pin 10
int green = 11;     // Green LED connected to pin 11
int button = 2;     // Button connected to pin 2

// Variables for button state tracking
int buttonState = 0;                   // Current state of the button (LOW or HIGH)
int previousButtonState = HIGH;        // Variable to store the previous state of the button

void setup() {
  // Set pin modes for LEDs (OUTPUT) and button (INPUT)
  pinMode(red, OUTPUT);
  pinMode(yellow, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(button, INPUT);
}

void loop() {
  // Read the current state of the button
  buttonState = digitalRead(button);

  // Check if the button is pressed for the first time
  if (buttonState == HIGH && previousButtonState == LOW) {
    // Turn off red light, turn on green light
    digitalWrite(red, LOW);
    digitalWrite(green, HIGH);
  } 
  // Check if the button is continuously pressed
  else if (buttonState == HIGH && previousButtonState == HIGH) {
    // Keep the green light (do nothing)
  } 
  // Check if the button is released after being pressed
  else if (buttonState == LOW && previousButtonState == HIGH) {
    // Turn off green light, turn on yellow light, delay, turn off yellow light, turn on red light
    digitalWrite(green, LOW);
    digitalWrite(yellow, HIGH);
    delay(1000);  // Delay for 1000 milliseconds (1 second)
    digitalWrite(yellow, LOW);
    digitalWrite(red, HIGH);
  }

  // Save the current button state for the next time through
  previousButtonState = buttonState;
}
c++ arduino
1个回答
0
投票

我觉得是这样的

int previousButtonState = LOW; //<= start with LOW

void setup(){
   ..... //initiate the pins as you do
   
   digitalWrite(red, HIGH); //turn the red ON on program start

}

您在设置中打开红色 LED,并且由于 IF 语句中没有 LOW/LOW 情况,红色 LED 将一直亮起,直到您第一次按下按钮

© www.soinside.com 2019 - 2024. All rights reserved.