0
0
Arduinoprogramming~5 mins

attachInterrupt() function in Arduino

Choose your learning style9 modes available
Introduction

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.

You want to count how many times a button is pressed without missing any presses.
You need to respond quickly when a sensor detects movement or a change.
You want to measure the time between events accurately, like a speed sensor.
You want your program to keep running other tasks but still react fast to an event.
Syntax
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.

Examples
Run blinkLED function when pin 2 signal goes from LOW to HIGH.
Arduino
attachInterrupt(digitalPinToInterrupt(2), blinkLED, RISING);
Run countPresses function when pin 3 signal goes from HIGH to LOW.
Arduino
attachInterrupt(digitalPinToInterrupt(3), countPresses, FALLING);
Sample Program

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.

Arduino
#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++;
}
OutputSuccess
Important Notes

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.

Summary

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.