0
0
Arduinoprogramming~5 mins

Why interrupts improve responsiveness in Arduino

Choose your learning style9 modes available
Introduction

Interrupts let your Arduino stop what it is doing to quickly respond to important events. This makes your program faster and more responsive.

When you need to react immediately to a button press without waiting.
When you want to measure the exact time between signals, like from a sensor.
When you want to handle multiple tasks at once without missing any event.
When you want to save power by letting the Arduino sleep until something happens.
Syntax
Arduino
attachInterrupt(digitalPinToInterrupt(pin), ISR_function, mode);

pin is the Arduino pin number that supports interrupts.

ISR_function is the function called when the interrupt happens. It must be short and fast.

mode defines when the interrupt triggers: LOW, CHANGE, RISING, or FALLING.

Examples
Call buttonPressed function when pin 2 changes from LOW to HIGH.
Arduino
attachInterrupt(digitalPinToInterrupt(2), buttonPressed, RISING);
Call sensorTriggered function when pin 3 changes from HIGH to LOW.
Arduino
attachInterrupt(digitalPinToInterrupt(3), sensorTriggered, FALLING);
Sample Program

This program uses an interrupt to detect when a button is pressed on pin 2. The interrupt sets a flag quickly. The main loop checks the flag and toggles the LED on pin 13 and prints a message. This way, the button press is detected immediately without waiting.

Arduino
#include <Arduino.h>

volatile bool buttonPressedFlag = false;

void setup() {
  pinMode(2, INPUT_PULLUP); // Button connected to pin 2
  pinMode(13, OUTPUT);       // Built-in LED
  attachInterrupt(digitalPinToInterrupt(2), onButtonPress, FALLING);
  Serial.begin(9600);
}

void loop() {
  if (buttonPressedFlag) {
    buttonPressedFlag = false;
    digitalWrite(13, !digitalRead(13)); // Toggle LED
    Serial.println("Button pressed! LED toggled.");
  }
}

void onButtonPress() {
  buttonPressedFlag = true;
}
OutputSuccess
Important Notes

Keep interrupt service routines (ISR) very short and fast to avoid delays.

Use volatile keyword for variables shared between ISR and main code.

Do not use delay() or Serial prints inside ISR.

Summary

Interrupts let your Arduino react immediately to events.

They improve responsiveness by stopping normal code to handle important signals.

Use interrupts for buttons, sensors, and time-critical tasks.