Timer interrupts with TimerOne library in Arduino - Time & Space Complexity
When using timer interrupts with the TimerOne library, it's important to understand how often the interrupt code runs as input changes.
We want to know how the number of operations grows as the timer interval or workload changes.
Analyze the time complexity of the following code snippet.
#include <TimerOne.h>
volatile int count = 0;
void setup() {
Timer1.initialize(1000000); // 1 second
Timer1.attachInterrupt(timerIsr);
}
void loop() {
// main code runs here
}
void timerIsr() {
count++;
}
This code sets a timer interrupt to run every 1 second and increments a counter each time the interrupt triggers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The interrupt service routine (ISR) runs repeatedly.
- How many times: It runs once every timer interval (e.g., every 1 second).
The number of times the ISR runs depends on the total time the program runs and the timer interval.
| Input Size (seconds running) | Approx. ISR Calls |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of ISR calls grows linearly with the running time.
Time Complexity: O(n)
This means the total number of interrupt calls grows directly in proportion to the running time.
[X] Wrong: "The interrupt runs only once or a fixed number of times regardless of time."
[OK] Correct: The interrupt triggers repeatedly at each timer interval, so the total calls increase as time passes.
Understanding how timer interrupts scale with time helps you reason about real-time systems and how often tasks run in embedded programming.
What if we changed the timer interval from 1 second to 0.1 seconds? How would the time complexity change?