0
0
Arduinoprogramming~5 mins

Timer interrupts with TimerOne library in Arduino

Choose your learning style9 modes available
Introduction

Timer interrupts let your Arduino do tasks automatically at set times without stopping other work.

You want to blink an LED exactly every second without delay.
You need to measure time intervals precisely while running other code.
You want to run a function repeatedly at fixed time intervals.
You want to avoid using delay() so your program stays responsive.
Syntax
Arduino
Timer1.initialize(period_in_microseconds);
Timer1.attachInterrupt(yourFunction);

initialize() sets how often the interrupt happens in microseconds.

attachInterrupt() links your function to run each time the timer fires.

Examples
This sets the timer to call blinkLED() every 1 second.
Arduino
Timer1.initialize(1000000); // 1 second
Timer1.attachInterrupt(blinkLED);
This calls updateSensor() every half second.
Arduino
Timer1.initialize(500000); // 0.5 seconds
Timer1.attachInterrupt(updateSensor);
Sample Program

This program uses TimerOne to toggle the built-in LED every second without blocking the main loop.

Arduino
#include <TimerOne.h>

const int ledPin = 13;
volatile bool ledState = false;

void setup() {
  pinMode(ledPin, OUTPUT);
  Timer1.initialize(1000000); // 1 second
  Timer1.attachInterrupt(toggleLED);
}

void loop() {
  // Main code can run here without delay
}

void toggleLED() {
  ledState = !ledState;
  digitalWrite(ledPin, ledState);
}
OutputSuccess
Important Notes

Functions called by interrupts should be short and fast to avoid problems.

Use volatile for variables shared between interrupt and main code.

TimerOne library works on Arduino boards with 16-bit timers like Uno and Mega.

Summary

TimerOne library helps run code at exact time intervals using interrupts.

Use initialize() to set the timer period and attachInterrupt() to set the function.

Interrupt functions should be quick and use volatile for shared variables.