我正在尝试编写一个带有注释的草图,以按照以下说明控制 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;
}
我觉得是这样的
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 将一直亮起,直到您第一次按下按钮