Reducing power consumption tips in Arduino - Time & Space Complexity
When we write code to save power on an Arduino, we want to know how much work the code does as it runs.
We ask: how does the time the code takes change when we add more steps or checks?
Analyze the time complexity of the following code snippet.
void loop() {
delay(1000); // wait 1 second
digitalWrite(LED_BUILTIN, HIGH); // turn LED on
delay(100); // short on time
digitalWrite(LED_BUILTIN, LOW); // turn LED off
delay(1000); // wait 1 second
}
This code blinks an LED with delays to save power by turning the LED off most of the time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop function repeats forever.
- How many times: Each loop cycle runs once, but inside it, delay pauses the program.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 cycles of loop, each with fixed delays |
| 100 | 100 cycles, same fixed delays each time |
| 1000 | 1000 cycles, delays do not change |
Pattern observation: The time spent grows linearly with the number of cycles, but each cycle takes the same fixed time.
Time Complexity: O(n)
This means the total time grows directly with how many times the loop runs, but each loop takes a fixed amount of time.
[X] Wrong: "Adding more delay calls makes the program faster."
[OK] Correct: Delay pauses the program, so more delays actually make it slower, not faster.
Understanding how your code's timing grows helps you write better programs that save power and run efficiently on small devices like Arduino.
"What if we replaced delay() with a non-blocking timer? How would the time complexity change?"