Writing HIGH and LOW to output pins in Embedded C - Time & Space Complexity
When writing HIGH or LOW to output pins, it's important to know how the time taken changes as we do more writes.
We want to see how the number of pin writes affects the total time the program takes.
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
digitalWrite(pin, HIGH);
digitalWrite(pin, LOW);
}
This code writes HIGH then LOW to the same output pin repeatedly n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing HIGH and LOW to the output pin.
- How many times: Each write happens inside a loop that runs n times, so 2 writes per loop, total 2*n writes.
Each time we increase n, the number of writes grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 writes |
| 100 | 200 writes |
| 1000 | 2000 writes |
Pattern observation: The total operations grow in a straight line as n increases.
Time Complexity: O(n)
This means the time taken grows directly in proportion to the number of writes we do.
[X] Wrong: "Writing HIGH and LOW inside the loop takes constant time no matter how many times we run it."
[OK] Correct: Each write takes some time, so doing it many times adds up and the total time grows with n.
Understanding how repeated pin writes affect time helps you write efficient embedded code and explain your reasoning clearly in interviews.
"What if we only wrote HIGH once before the loop and LOW once after? How would the time complexity change?"