The attachInterrupt() function lets your Arduino react immediately when something important happens, like a button press or a sensor signal, without waiting for the main program to check.
attachInterrupt() function in Arduino
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);
pin is the Arduino pin number where the interrupt signal comes from.
ISR is the name of the function that runs when the interrupt happens.
mode tells when to trigger the interrupt: LOW, CHANGE, RISING, or FALLING.
blinkLED function when pin 2 signal goes from LOW to HIGH.attachInterrupt(digitalPinToInterrupt(2), blinkLED, RISING);countPresses function when pin 3 signal goes from HIGH to LOW.attachInterrupt(digitalPinToInterrupt(3), countPresses, FALLING);This program uses attachInterrupt() to detect when a button connected to pin 2 is pressed (signal goes LOW). Each press increases buttonPresses. The main loop lights the LED and prints a message when a press is detected.
#define buttonPin 2 #define ledPin 13 volatile int buttonPresses = 0; void setup() { pinMode(ledPin, OUTPUT); pinMode(buttonPin, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(buttonPin), countPresses, FALLING); Serial.begin(9600); } void loop() { if (buttonPresses > 0) { digitalWrite(ledPin, HIGH); delay(200); digitalWrite(ledPin, LOW); buttonPresses = 0; Serial.println("Button pressed!"); } } void countPresses() { buttonPresses++; }
The function called by attachInterrupt() (ISR) should be short and fast.
Use volatile for variables shared between the ISR and main code to avoid errors.
Not all pins support interrupts; check your Arduino model's documentation.
attachInterrupt() lets Arduino react instantly to events on specific pins.
Use it to handle buttons, sensors, or signals without missing any changes.
Keep interrupt functions short and use volatile for shared variables.