// Define pins
const byte ButtonPin = 4; // Push button attached to PB4 (with ground connection)
const byte LedPin1 = 0; // LED1 attached to PB0
const byte 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;
}