0
0
Arduinoprogramming~5 mins

Rising, falling, and change triggers in Arduino

Choose your learning style9 modes available
Introduction

These triggers help your Arduino notice when a button or sensor changes from off to on, on to off, or just changes state. This way, your program can react right away.

When you want to detect when a button is pressed down (going from off to on).
When you want to detect when a button is released (going from on to off).
When you want to detect any change in a sensor or switch, whether it turns on or off.
When you want to save power by only reacting when something changes, not all the time.
When you want to trigger an action exactly once when a signal changes.
Syntax
Arduino
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);

// pin: the pin number
// ISR: the function to run when triggered
// mode: RISING, FALLING, or CHANGE

RISING triggers when the signal goes from LOW to HIGH.

FALLING triggers when the signal goes from HIGH to LOW.

CHANGE triggers on any change, either LOW to HIGH or HIGH to LOW.

Examples
This runs the buttonPressed function when pin 2 changes from LOW to HIGH.
Arduino
attachInterrupt(digitalPinToInterrupt(2), buttonPressed, RISING);
This runs the buttonReleased function when pin 3 changes from HIGH to LOW.
Arduino
attachInterrupt(digitalPinToInterrupt(3), buttonReleased, FALLING);
This runs the sensorChanged function whenever pin 4 changes state.
Arduino
attachInterrupt(digitalPinToInterrupt(4), sensorChanged, CHANGE);
Sample Program

This program counts how many times a button connected to pin 2 is pressed. It uses a FALLING trigger because the button connects the pin to ground when pressed (going from HIGH to LOW). The count increases each time the button is pressed, and the number is printed every second.

Arduino
#define buttonPin 2
volatile int count = 0;

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

void loop() {
  // Just print the count every second
  Serial.print("Button pressed: ");
  Serial.print(count);
  Serial.println(" times");
  delay(1000);
}

void countPresses() {
  count++;
}
OutputSuccess
Important Notes

Interrupt functions (ISR) should be short and fast. Avoid using delay() or Serial.print() inside them.

Use volatile for variables shared between the ISR and main code to keep values correct.

Not all pins support interrupts on every Arduino board. Check your board's documentation.

Summary

RISING triggers when a signal goes from LOW to HIGH.

FALLING triggers when a signal goes from HIGH to LOW.

CHANGE triggers on any change in the signal.