Wake-up from sleep with interrupt in Arduino - Time & Space Complexity
When using sleep mode with interrupts on Arduino, we want to know how the program's running time changes as input or events happen.
We ask: How often does the code run and how does that affect time?
Analyze the time complexity of the following code snippet.
#include <avr/sleep.h>
volatile bool wokeUp = false;
void wakeUp() {
wokeUp = true; // interrupt sets flag
}
void setup() {
pinMode(2, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(2), wakeUp, FALLING);
}
void loop() {
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_cpu(); // sleeps until interrupt
sleep_disable();
if (wokeUp) {
// do something after wake-up
wokeUp = false;
}
}
This code puts the Arduino to sleep and wakes it up when a button press triggers an interrupt.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
loop()function runs repeatedly, but most time is spent sleeping. - How many times: It runs once per wake-up event, which depends on external interrupts (button presses).
The program mostly sleeps, so execution time depends on how often the interrupt happens.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 interrupts | Runs loop 10 times |
| 100 interrupts | Runs loop 100 times |
| 1000 interrupts | Runs loop 1000 times |
Pattern observation: The number of operations grows linearly with the number of interrupts (events).
Time Complexity: O(n)
This means the program runs once for each interrupt event, so time grows directly with the number of wake-ups.
[X] Wrong: "The loop runs continuously and uses a lot of CPU time even when sleeping."
[OK] Correct: The CPU actually sleeps and does almost no work until an interrupt wakes it, so time spent running code depends on interrupts, not continuous looping.
Understanding how interrupts affect program flow and timing shows you can write efficient code that waits for events without wasting time.
"What if we replaced the interrupt with a polling check inside the loop? How would the time complexity change?"