0
0
Arduinoprogramming~5 mins

Interrupt-driven button handling in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Interrupt-driven button handling
O(n)
Understanding Time Complexity

When using interrupts to handle button presses, we want to know how the program's work changes as more button events happen.

We ask: how does the time spent reacting to button presses grow as the number of presses increases?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


volatile int buttonPressCount = 0;

void setup() {
  pinMode(2, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(2), countPress, FALLING);
}

void loop() {
  // Main code runs here
}

void countPress() {
  buttonPressCount++;
}
    

This code counts how many times a button connected to pin 2 is pressed using an interrupt.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The interrupt service routine (ISR) increments a counter each time the button is pressed.
  • How many times: Once per button press event, which can happen many times independently of the main program.
How Execution Grows With Input

Each button press triggers a quick increment operation. The total work grows directly with the number of presses.

Input Size (n)Approx. Operations
1010 increments
100100 increments
10001000 increments

Pattern observation: The work grows in a straight line as button presses increase.

Final Time Complexity

Time Complexity: O(n)

This means the time spent handling button presses grows directly with how many times the button is pressed.

Common Mistake

[X] Wrong: "The interrupt runs constantly and slows down the program regardless of button presses."

[OK] Correct: The interrupt code only runs when the button is pressed, so the time spent depends on the number of presses, not on time passing.

Interview Connect

Understanding how interrupts affect program time helps you write responsive and efficient embedded programs, a useful skill in many real projects.

Self-Check

What if we added a delay inside the interrupt routine? How would the time complexity change?