0
0
Embedded Cprogramming~5 mins

Reading digital input pin state in Embedded C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Reading digital input pin state
O(n)
Understanding Time Complexity

When reading a digital input pin, we want to know how the time to get the pin state changes as we do it more times.

We ask: How does the time grow if we read the pin many times?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


// Read digital input pin state multiple times
int readPinState(int pin, int times) {
    int state = 0;
    for (int i = 0; i < times; i++) {
        state = digitalRead(pin);
    }
    return state;
}
    

This code reads the state of a digital input pin repeatedly for a given number of times.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling digitalRead(pin) inside a loop.
  • How many times: Exactly times times, controlled by the loop.
How Execution Grows With Input

Each time we increase the number of reads, the total work grows directly with it.

Input Size (times)Approx. Operations
1010 calls to digitalRead
100100 calls to digitalRead
10001000 calls to digitalRead

Pattern observation: The number of operations grows in a straight line as the input size increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to read the pin grows directly in proportion to how many times we read it.

Common Mistake

[X] Wrong: "Reading the pin multiple times takes the same time as reading it once."

[OK] Correct: Each read is a separate action, so doing it more times adds more work and takes more time.

Interview Connect

Understanding how repeated hardware reads affect time helps you reason about performance in embedded systems clearly and confidently.

Self-Check

"What if we added a delay inside the loop after each read? How would the time complexity change?"