Sometimes, your Arduino needs to save power by sleeping. It can wake up when something important happens, like pressing a button. This is done using interrupts.
0
0
Wake-up from sleep with interrupt in Arduino
Introduction
You want your Arduino to sleep to save battery and wake up when a button is pressed.
You want to pause your program until a sensor detects movement.
You want to reduce power use but still respond quickly to an event.
You want to wake your Arduino from sleep when a signal arrives on a pin.
Syntax
Arduino
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode); // pin: the pin number to watch // ISR: the function to run when interrupt happens // mode: when to trigger (LOW, CHANGE, RISING, FALLING)
The ISR function must be very short and fast.
Use digitalPinToInterrupt(pin) to get the correct interrupt number for the pin.
Examples
Wake up when pin 2 goes from LOW to HIGH.
Arduino
attachInterrupt(digitalPinToInterrupt(2), wakeUp, RISING);Wake up when pin 3 goes from HIGH to LOW.
Arduino
attachInterrupt(digitalPinToInterrupt(3), wakeUp, FALLING);Sample Program
This program puts the Arduino to sleep to save power. When you press the button on pin 2, it triggers an interrupt that wakes the Arduino. The program then prints "Woke up!" and goes back to sleep.
Arduino
#include <avr/sleep.h> volatile bool wokeUp = false; void wakeUp() { wokeUp = true; // This runs when interrupt happens } void setup() { pinMode(2, INPUT_PULLUP); // Button on pin 2 Serial.begin(9600); attachInterrupt(digitalPinToInterrupt(2), wakeUp, FALLING); Serial.println("Going to sleep. Press button on pin 2 to wake up."); } void loop() { if (!wokeUp) { set_sleep_mode(SLEEP_MODE_PWR_DOWN); sleep_enable(); sleep_cpu(); // Arduino sleeps here sleep_disable(); } if (wokeUp) { Serial.println("Woke up!"); wokeUp = false; // Reset flag delay(1000); // Wait a bit before sleeping again } }
OutputSuccess
Important Notes
Interrupts can wake the Arduino from deep sleep modes.
Keep the interrupt service routine (ISR) very short to avoid problems.
Use INPUT_PULLUP for buttons to avoid floating pins.
Summary
Use interrupts to wake Arduino from sleep when an event happens.
Attach interrupt to a pin with attachInterrupt() and define a short ISR.
Put Arduino to sleep with sleep_mode() and it wakes on interrupt.