0
0
Embedded Cprogramming~5 mins

Button debouncing in software in Embedded C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Button debouncing in software
O(n)
Understanding Time Complexity

When we write code to handle button presses, we want to know how long it takes as the input changes.

Here, we ask: how does the time to check and debounce a button grow with the number of checks?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#define DEBOUNCE_TIME 5

int debounceButton(int *buttonState, int (*readPin)(void)) {
    int count = 0;
    while (count < DEBOUNCE_TIME) {
        if (readPin() == *buttonState) {
            count++;
        } else {
            count = 0;
            *buttonState = readPin();
        }
    }
    return *buttonState;
}
    

This code checks a button state repeatedly until it reads the same value several times in a row to confirm the press.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop that reads the button state repeatedly.
  • How many times: Up to DEBOUNCE_TIME times in a row with the same reading.
How Execution Grows With Input

Each time the button state changes, the code resets the count and starts over.

Input Size (n)Approx. Operations
5 (DEBOUNCE_TIME)5 reads if stable
10 (twice stable)10 reads if stable twice
100 (many changes)Up to 100 reads if bouncing

Pattern observation: The time grows linearly with the number of reads needed to confirm stability.

Final Time Complexity

Time Complexity: O(n)

This means the time to debounce grows directly with the number of button state checks performed.

Common Mistake

[X] Wrong: "Debouncing always takes constant time regardless of input changes."

[OK] Correct: If the button bounces, the code resets counting and takes longer, so time depends on input stability.

Interview Connect

Understanding how input affects code timing shows you can think about real hardware behavior and write reliable software.

Self-Check

"What if we changed the debounce count to depend on a variable input instead of a fixed constant? How would the time complexity change?"