attachInterrupt() function in Arduino - Time & Space Complexity
When using the attachInterrupt() function, it's important to understand how often the interrupt code runs as input changes.
We want to know how the time spent in the interrupt grows as events happen.
Analyze the time complexity of the following code snippet.
volatile int count = 0;
void setup() {
attachInterrupt(digitalPinToInterrupt(2), countPulse, RISING);
}
void countPulse() {
count++;
}
void loop() {
// main code runs here
}
This code counts how many times a signal rises on pin 2 using an interrupt.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The interrupt service routine
countPulse()runs each time the signal rises. - How many times: It runs once per rising signal event, which depends on external input frequency.
The time spent in countPulse() grows directly with the number of rising signals detected.
| Input Size (number of rising signals) | Approx. Operations (interrupt calls) |
|---|---|
| 10 | 10 calls to countPulse() |
| 100 | 100 calls to countPulse() |
| 1000 | 1000 calls to countPulse() |
Pattern observation: The number of interrupt calls grows linearly with the number of signal events.
Time Complexity: O(n)
This means the total time spent in the interrupt grows directly with the number of signal events.
[X] Wrong: "The interrupt runs constantly and uses the same time no matter how many signals come."
[OK] Correct: The interrupt only runs when a signal event happens, so more events mean more interrupt calls and more time spent.
Understanding how interrupts affect program timing helps you write responsive and efficient code in real projects.
What if the interrupt routine did more work inside? How would that affect the time complexity?