const int redLEDPin = 13; // Red LED pin
const int greenLEDPin = 7; // Green LED pin
const int pushbuttonPin = 4; // Pushbutton pin
int previousState = LOW; // Previous state of pushbutton
int currentState = LOW; // Current state of pushbutton
bool isBlinkingRed = true; // Flag to determine which LED is blinking (Red or Green)
unsigned long lastDebounceTime = 0; // Last time the pushbutton was debounced
const long debounceTime = 50; // Debounce time in milliseconds
void setup() {
pinMode(redLEDPin, OUTPUT); // Set red LED pin as output
pinMode(greenLEDPin, OUTPUT); // Set green LED pin as output
pinMode(pushbuttonPin, INPUT_PULLUP); // Set pushbutton pin as input with pull-up resistor
}
void loop() {
currentState = digitalRead(pushbuttonPin); // Read current state of pushbutton
// Debounce pushbutton to eliminate bouncing effect
if (currentState != previousState) {
unsigned long currentTime = millis();
if (currentTime - lastDebounceTime >= debounceTime) {
lastDebounceTime = currentTime;
if (currentState == HIGH) { // If pushbutton is pressed
if (isBlinkingRed) { // If red LED is blinking, switch to blinking green
isBlinkingRed = false;
} else { // If green LED is blinking, switch to blinking red
isBlinkingRed = true;
}
}
}
}
previousState = currentState; // Update previous state
// Update LEDs based on blinking state
if (isBlinkingRed) {
digitalWrite(redLEDPin, HIGH); // Turn on red LED
digitalWrite(greenLEDPin, LOW); // Turn off green LED
} else {
digitalWrite(redLEDPin, LOW); // Turn off red LED
digitalWrite(greenLEDPin, HIGH); // Turn on green LED
}
// Blink the active LED
if (isBlinkingRed) {
delay(500); // Blink red LED at 0.5 Hz
digitalWrite(redLEDPin, LOW);
} else {
delay(500); // Blink green LED at 0.5 Hz
digitalWrite(greenLEDPin, LOW);
}
}