const int greenLedPin = 12; // Green LED connected to pin 12
const int redLedPin = 10; // Red LED connected to pin 10
const int buttonPin = 2; // Momentary button connected to pin 2
bool isGreenOn = true; // Tracks which LED is currently on
bool buttonState = false; // Current state of the button
bool lastButtonState = false; // Last recorded state of the button
void setup() {
pinMode(greenLedPin, OUTPUT); // Set green LED pin as output
pinMode(redLedPin, OUTPUT); // Set red LED pin as output
pinMode(buttonPin, INPUT); // Set button pin as input
// Start with green LED on
digitalWrite(greenLedPin, HIGH);
digitalWrite(redLedPin, LOW);
}
void loop() {
buttonState = digitalRead(buttonPin); // Read the button state
// Check for a button press (change from LOW to HIGH)
if (buttonState == HIGH && lastButtonState == LOW) {
isGreenOn = !isGreenOn; // Toggle the LED state
// Update LED states
digitalWrite(greenLedPin, isGreenOn ? HIGH : LOW);
digitalWrite(redLedPin, isGreenOn ? LOW : HIGH);
// Debounce delay
delay(50);
}
lastButtonState = buttonState; // Update the last button state
}