Interrupt-driven button handling in Arduino - Time & Space 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?
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 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.
Each button press triggers a quick increment operation. The total work grows directly with the number of presses.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The work grows in a straight line as button presses increase.
Time Complexity: O(n)
This means the time spent handling button presses grows directly with how many times the button is pressed.
[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.
Understanding how interrupts affect program time helps you write responsive and efficient embedded programs, a useful skill in many real projects.
What if we added a delay inside the interrupt routine? How would the time complexity change?