0
0
Embedded Cprogramming~5 mins

Writing HIGH and LOW to output pins in Embedded C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Writing HIGH and LOW to output pins
O(n)
Understanding Time 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.

Scenario Under Consideration

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

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

Each time we increase n, the number of writes grows directly with n.

Input Size (n)Approx. Operations
1020 writes
100200 writes
10002000 writes

Pattern observation: The total operations grow in a straight line as n increases.

Final Time Complexity

Time Complexity: O(n)

This means the time taken grows directly in proportion to the number of writes we do.

Common Mistake

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

Interview Connect

Understanding how repeated pin writes affect time helps you write efficient embedded code and explain your reasoning clearly in interviews.

Self-Check

"What if we only wrote HIGH once before the loop and LOW once after? How would the time complexity change?"