// Define the button pin
#define buttonPin 2
// State variables for managing LED states and button debouncing
volatile int ledState = 0; // Keeps track of the current LED pattern (0 = all off, 1 = LED1 on, etc.)
void setup() {
// Set pins for LEDs (Pin 13, 12, and 11) as outputs
DDRB |= (1 << PB5) | (1 << PB4) | (1 << PB3); // Configure PB5, PB4, PB3 as outputs for LEDs
// Attach an interrupt to the button pin to trigger the interrupt on a FALLING edge (button press)
attachInterrupt(digitalPinToInterrupt(buttonPin), IntCallback, FALLING);
// Set the button pin (pin 2) as an input
DDRD &= ~(1 << PD2); // Pin 2 (PD2) set as input
}
void loop() {
// The main loop is empty because the button press is handled via interrupts
// No need for continuous polling of the button in the loop
}
// Interrupt callback function that handles button press
void IntCallback() {
// Cycle through LED patterns on each button press
if (ledState < 3) {
ledState++; // Move to the next LED state (1 -> 2 -> 3)
} else {
ledState = 0; // Reset to the first LED state (0 = all off)
}
// Update the LEDs based on the current ledState
updateLEDs();
}
// Function to update LEDs based on the current state
void updateLEDs() {
// Control LEDs based on the value of ledState
if (ledState == 1) {
// Turn on only LED 1 (Pin 13), keep the others off
PORTB |= (1 << PB5); // Set PB5 high (LED 1 ON)
} else if (ledState == 2) {
// Turn on LED 2 (Pin 12), keep the others off
PORTB &= ~(1 << PB5); // Set PB5 low (LED 1 OFF)
PORTB |= (1 << PB4); // Set PB4 high (LED 2 ON)
} else if (ledState == 3) {
// Turn on LED 3 (Pin 11), keep the others off
PORTB &= ~(1 << PB4); // Set PB4 low (LED 2 OFF)
PORTB |= (1 << PB3); // Set PB3 high (LED 3 ON)
} else {
// Turn off all LEDs
PORTB &= ~(1 << PB3); // Set PB3 low (LED 3 OFF)
}
}