Reading digital input pin state in Embedded C - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Calling
digitalRead(pin)inside a loop. - How many times: Exactly
timestimes, controlled by the loop.
Each time we increase the number of reads, the total work grows directly with it.
| Input Size (times) | Approx. Operations |
|---|---|
| 10 | 10 calls to digitalRead |
| 100 | 100 calls to digitalRead |
| 1000 | 1000 calls to digitalRead |
Pattern observation: The number of operations grows in a straight line as the input size increases.
Time Complexity: O(n)
This means the time to read the pin grows directly in proportion to how many times we read it.
[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.
Understanding how repeated hardware reads affect time helps you reason about performance in embedded systems clearly and confidently.
"What if we added a delay inside the loop after each read? How would the time complexity change?"