// Pin definitions
const int led1 = 8;
const int led2 = 9;
const int button1 = 2; // Interrupt pin 1
const int button2 = 3; // Interrupt pin 2
// Flags for interrupt events
volatile bool led1State = false;
volatile bool led2State = false;
unsigned long lastDebounceTime1 = 0; // Last debounce time for button 1
unsigned long lastDebounceTime2 = 0; // Last debounce time for button 2
unsigned long debounceDelay = 150; // debounce time in milliseconds
void setup() {
// Set LED pins as OUTPUT
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
// Set button pins as INPUT_PULLUP (internal pull-up resistors)
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
// Attach interrupts to the button pins
attachInterrupt(digitalPinToInterrupt(button1), toggleLed1, FALLING); // Trigger on falling edge
attachInterrupt(digitalPinToInterrupt(button2), toggleLed2, FALLING); // Trigger on falling edge
// Start serial communication
Serial.begin(9600);
}
void loop() {
// Main loop with a long delay
Serial.println("Waiting for interrupt...");
Serial.println("Executing Delay...");
delay(5000); // Simulate a long delay
// Main loop does not handle LED logic anymore
}
// Interrupt service routines
void toggleLed1() {
// Debounce logic for button1 (button1 interrupt)
if ((millis() - lastDebounceTime1) > debounceDelay) {
led1State = !led1State; // Toggle the state of LED1
digitalWrite(led1, led1State); // Control LED1 directly in ISR
Serial.print("Interrupt on pin ");
Serial.print(button1);
Serial.println(" triggered LED1 toggle");
lastDebounceTime1 = millis(); // Update debounce timer
}
}
void toggleLed2() {
// Debounce logic for button2 (button2 interrupt)
if ((millis() - lastDebounceTime2) > debounceDelay) {
led2State = !led2State; // Toggle the state of LED2
digitalWrite(led2, led2State); // Control LED2 directly in ISR
Serial.print("Interrupt on pin ");
Serial.print(button2);
Serial.println(" triggered LED2 toggle");
lastDebounceTime2 = millis(); // Update debounce timer
}
}