const int buttonPin = 2; // Button connected to pin 2
const int ledPin = 13; // LED connected to pin 13
volatile bool interruptOccurred = false;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 10; // Adjust as needed
bool ledState = LOW;
bool lastButtonState = HIGH; // Assuming INPUT_PULLUP
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
// Attach an interrupt to the button pin
attachInterrupt(digitalPinToInterrupt(buttonPin), buttonInterrupt, FALLING);
}
void loop() {
if (interruptOccurred) {
interruptOccurred = false;
if ((millis() - lastDebounceTime) > debounceDelay) {
bool reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
if (reading == LOW) { // Button is pressed (LOW due to INPUT_PULLUP)
ledState = !ledState;
digitalWrite(ledPin, ledState);
}
lastButtonState = reading;
}
}
}
}
// Interrupt Service Routine
void buttonInterrupt() {
interruptOccurred = true;
}