// 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; // LED state to toggle
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 both LED states
ledState = !ledState;
digitalWrite(ledPin1, ledState); // LED1 follows ledState
digitalWrite(ledPin2, !ledState); // LED2 is the inverse of ledState
}
}
}
// Save the last button state
lastButtonState = reading;
}