0
0
Arduinoprogramming~5 mins

Wake-up from sleep with interrupt in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Wake-up from sleep with interrupt
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

The program mostly sleeps, so execution time depends on how often the interrupt happens.

Input Size (n)Approx. Operations
10 interruptsRuns loop 10 times
100 interruptsRuns loop 100 times
1000 interruptsRuns loop 1000 times

Pattern observation: The number of operations grows linearly with the number of interrupts (events).

Final Time Complexity

Time Complexity: O(n)

This means the program runs once for each interrupt event, so time grows directly with the number of wake-ups.

Common Mistake

[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.

Interview Connect

Understanding how interrupts affect program flow and timing shows you can write efficient code that waits for events without wasting time.

Self-Check

"What if we replaced the interrupt with a polling check inside the loop? How would the time complexity change?"