Running the program

When I started programming my Arduino Uno I put my program in the loop-function. This worked for a while, but when I wanted to run things in parallel it started to get difficult to have the whole program in a single loop.

Specifically when I was working on my countdown timer with a pulsating addressable RGB-LED strip I started to have some timing problems.

In this post I will show you how to use the TimerOne library to create a timer and a function to be called when the timer fires.

Download the TimerOne lib

  1. Go to https://github.com/PaulStoffregen/TimerOne
  2. Download the lib by clicking the Download ZIP button.
  3. Put the downloaded folder in your Arduino/libraries folder.
  4. Rename the folder from TimerOne-Master to TimerOne.

Now you can open your Arduino programming environment and use the library by including it with: #include <TimerOne.h>.

Using the TimerOne lib

This short program counts down for 30 seconds and prints the current count value to the serial monitor.

#include <TimerOne.h>

long timeLeft = 30;

void setup() {
  Timer1.initialize(1000000); // 1 second
  Timer1.attachInterrupt(countDownOneSecond);

  Serial.begin(9600);
}

void loop() {

}

void countDownOneSecond() {
  timeLeft--;
  Serial.println(timeLeft);

  if(timeLeft == 0) {
    Timer1.stop();
  }
}

As you may have noted there is no code at all in the loop() function. All the logic is done by interupts from the timer.

The timer will fire every second and run the countDownOneSecond() function. When the counter reaches 0 the timer will stop.