// Define pins
const int buttonPin = 5; // Push button attached to PB5 (with ground connection)
const int ledPin1 = 0; // LED1 attached to PB0
const int ledPin2 = 1; // LED2 attached to PB1
// Variables to store button state and debouncing
bool buttonState = HIGH;
bool lastButtonState = HIGH;
bool ledState = LOW; // To keep track of which LED should turn on
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50; // Debounce time in milliseconds
void setup() {
// Set pin modes
pinMode(buttonPin, INPUT_PULLUP); // Use internal pull-up resistor
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
// Start with both LEDs off
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
}
void loop() {
// Read the button state
bool reading = digitalRead(buttonPin);
// Check for button press with debounce
if (reading != lastButtonState) {
lastDebounceTime = millis(); // Reset the debouncing timer
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// Only act if the button state has changed
if (reading != buttonState) {
buttonState = reading;
// If the button is pressed (LOW)
if (buttonState == LOW) {
// Toggle LED state
ledState = !ledState;
// Turn on the LEDs based on the current state
if (ledState) {
digitalWrite(ledPin1, HIGH); // Turn on LED1
digitalWrite(ledPin2, LOW); // Turn off LED2
} else {
digitalWrite(ledPin1, LOW); // Turn off LED1
digitalWrite(ledPin2, HIGH); // Turn on LED2
}
} else {
// If button is released, turn off both LEDs
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
}
}
}
// Save the last button state
lastButtonState = reading;
}