0
0
Arduinoprogramming~5 mins

Timer interrupts with TimerOne library in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Timer interrupts with TimerOne library
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

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
1010
100100
10001000

Pattern observation: The number of ISR calls grows linearly with the running time.

Final Time Complexity

Time Complexity: O(n)

This means the total number of interrupt calls grows directly in proportion to the running time.

Common Mistake

[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.

Interview Connect

Understanding how timer interrupts scale with time helps you reason about real-time systems and how often tasks run in embedded programming.

Self-Check

What if we changed the timer interval from 1 second to 0.1 seconds? How would the time complexity change?