0
0
Arduinoprogramming~5 mins

Interrupt-driven button handling in Arduino

Choose your learning style9 modes available
Introduction

Interrupt-driven button handling lets your Arduino react immediately when a button is pressed, without waiting or checking all the time.

You want your Arduino to respond quickly to a button press.
You want to save power by not constantly checking the button.
You have other tasks running and don't want to miss button presses.
You want to avoid delays caused by checking buttons in the main loop.
Syntax
Arduino
attachInterrupt(digitalPinToInterrupt(pin), ISR_function, mode);

pin is the Arduino pin number connected to the button.

ISR_function is the name of the function to run when the button is pressed.

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

Examples
Run buttonPressed function when pin 2 goes from HIGH to LOW (button press).
Arduino
attachInterrupt(digitalPinToInterrupt(2), buttonPressed, FALLING);
Run buttonPressed function when pin 3 goes from LOW to HIGH (button release).
Arduino
attachInterrupt(digitalPinToInterrupt(3), buttonPressed, RISING);
Sample Program

This program uses an interrupt to detect when the button connected to pin 2 is pressed (goes from HIGH to LOW). The interrupt sets a flag. The main loop checks the flag and prints a message when the button is pressed.

Arduino
#define BUTTON_PIN 2
volatile bool buttonPressedFlag = false;

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP); // Button connected to pin 2 with internal pull-up
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), handleButtonPress, FALLING);
}

void loop() {
  if (buttonPressedFlag) {
    Serial.println("Button was pressed!");
    buttonPressedFlag = false; // Reset flag
  }
}

void handleButtonPress() {
  buttonPressedFlag = true; // Set flag to indicate button press
}
OutputSuccess
Important Notes

Use volatile for variables shared between interrupt and main code to avoid errors.

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

Use INPUT_PULLUP mode for buttons to avoid needing extra resistors.

Summary

Interrupts let your Arduino react instantly to button presses.

Use attachInterrupt() with a pin, function, and trigger mode.

Keep ISR code short and use flags to communicate with the main program.