//This code toggle led state using interrupt
const int buttonPin = 2; // Interrupt-capable pin on Uno
const int ledPin = 8; // LED pin
volatile bool ledState = false; // LED state
volatile bool interruptFlag = false; // Set in ISR when triggered
unsigned long lastInterruptTime = 0; // For software debounce
const unsigned long debounceDelay = 200; // in milliseconds
// Interrupt Service Routine
void handleInterrupt() {
// Prevent bouncing: record time and ignore if too soon
unsigned long currentTime = millis();
if (currentTime - lastInterruptTime > debounceDelay) {
interruptFlag = true; // mark that a valid press occurred
lastInterruptTime = currentTime;
}
}
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT); // External pull-up
Serial.begin(9600);
Serial.println("System Initialized - Waiting for Button Interrupt...");
attachInterrupt(digitalPinToInterrupt(buttonPin), handleInterrupt, FALLING);
}
void loop() {
if (interruptFlag) {
ledState = !ledState; // Toggle LED state
digitalWrite(ledPin, ledState); // Update LED
Serial.println("Interrupt Triggered: LED Toggled");
interruptFlag = false; // Clear flag
}
// Short delay to prevent Serial flooding
delay(50);
}