Arduino sleep modes - Time & Space Complexity
When using Arduino sleep modes, we want to know how the time the program spends sleeping or waking changes as we add more tasks or checks.
We ask: How does the program's running time grow when we use sleep modes with different input sizes?
Analyze the time complexity of the following code snippet.
#include <avr/sleep.h>
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
set_sleep_mode(SLEEP_MODE_IDLE);
sleep_enable();
sleep_cpu();
sleep_disable();
}
This code blinks an LED and then puts the Arduino into idle sleep mode once every loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop() function runs repeatedly, blinking the LED and then sleeping.
- How many times: It runs forever, repeating the blink and sleep cycle each time.
Here, the "input size" can be thought of as how many times the loop runs or how many tasks are added inside the loop.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 blink and sleep cycles |
| 100 | About 100 blink and sleep cycles |
| 1000 | About 1000 blink and sleep cycles |
Pattern observation: The total time grows linearly with the number of cycles because each cycle takes roughly the same time.
Time Complexity: O(n)
This means the total running time grows directly in proportion to how many times the loop runs.
[X] Wrong: "Using sleep mode makes the program run instantly or faster regardless of loop size."
[OK] Correct: Sleep mode saves power but the loop still runs each cycle, so total time grows with the number of cycles.
Understanding how sleep modes affect program timing helps you write efficient embedded programs and shows you can think about how code scales in real devices.
"What if we added more tasks inside the loop before sleeping? How would the time complexity change?"