0
0
Arduinoprogramming~5 mins

ISR best practices in Arduino

Choose your learning style9 modes available
Introduction

ISRs (Interrupt Service Routines) help your Arduino react quickly to events. Using them well keeps your program fast and reliable.

You want to respond immediately when a button is pressed.
You need to count pulses from a sensor without missing any.
You want to measure time precisely using timers.
You want to handle communication events like receiving data.
You want to avoid slowing down your main program while waiting for events.
Syntax
Arduino
void ISR_name() {
  // code to run when interrupt happens
}

attachInterrupt(digitalPinToInterrupt(pin), ISR_name, mode);

The ISR function must have no parameters and return void.

Use attachInterrupt() to link the ISR to a pin and event type.

Examples
This runs buttonPressed when pin 2 goes from LOW to HIGH.
Arduino
void buttonPressed() {
  // quick action when button pressed
}

attachInterrupt(digitalPinToInterrupt(2), buttonPressed, RISING);
This counts pulses on pin 3 when signal falls from HIGH to LOW.
Arduino
volatile int count = 0;

void countPulse() {
  count++; // count pulses quickly
}

attachInterrupt(digitalPinToInterrupt(3), countPulse, FALLING);
Sample Program

This program counts how many times a button connected to pin 2 is pressed. The ISR countPress runs quickly on each press. The main loop prints the count when it changes.

Arduino
#include <Arduino.h>

volatile int buttonPresses = 0;

void countPress() {
  buttonPresses++;
}

void setup() {
  pinMode(2, INPUT_PULLUP);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), countPress, FALLING);
}

void loop() {
  static int lastCount = 0;
  if (buttonPresses != lastCount) {
    Serial.print("Button pressed: ");
    Serial.println(buttonPresses);
    lastCount = buttonPresses;
  }
}
OutputSuccess
Important Notes

Keep ISR code very short and fast to avoid missing interrupts.

Use volatile for variables shared between ISR and main code.

Avoid using delay(), Serial.print(), or complex logic inside ISRs.

Summary

ISRs let Arduino react quickly to events.

Keep ISR code short and simple.

Use volatile for shared variables and attach interrupts properly.