Code organization with functions in Arduino - Time & Space Complexity
When we organize Arduino code using functions, it helps keep things neat and clear.
We want to see how the time to run the program changes as we call these functions more or less.
Analyze the time complexity of the following code snippet.
void blinkLED(int times) {
for (int i = 0; i < times; i++) {
digitalWrite(LED_BUILTIN, HIGH);
delay(100);
digitalWrite(LED_BUILTIN, LOW);
delay(100);
}
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
blinkLED(5);
delay(1000);
}
This code defines a function to blink an LED a number of times, then calls it repeatedly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside the blinkLED function that runs 'times' times.
- How many times: The loop runs exactly as many times as the 'times' argument given (5 in this example).
Explain the growth pattern intuitively.
| Input Size (times) | Approx. Operations |
|---|---|
| 10 | About 10 LED blinks |
| 100 | About 100 LED blinks |
| 1000 | About 1000 LED blinks |
Pattern observation: The time to run grows directly with the number of blinks requested.
Time Complexity: O(n)
This means the time grows in a straight line as you increase the number of times the LED blinks.
[X] Wrong: "Using functions always makes the program run faster."
[OK] Correct: Functions help organize code but do not change how many times loops run or how long delays last.
Understanding how functions affect time helps you write clear code and explain your choices confidently.
"What if we changed the blinkLED function to call itself recursively instead of using a loop? How would the time complexity change?"