Arduino-Timer Library & Examples

In this tutorial, we’ll discuss Arduino-Timer Library how it works, and how to use it to handle periodic tasks (functions). The Arduino-Timer library can be easily installed within Arduino IDE itself and it’s based on the millis() & micros() functions which are also based on Arduino internal hardware timers.

We’ll create a couple of Arduino-Timer Library Example Projects in this tutorial to practice what we’ll learn all the way through. We’ll test both milliseconds & microseconds periodicity resolution for the timer library.

Table of Contents

  1. Arduino Timers
  2. Arduino-Timer Library
  3. Arduino-Timer Library Installation
  4. Arduino-Timer Library Example (ms Task)
  5. Arduino-Timer Library Example (μs Task)
  6. Arduino-Timer Library Wrap Up

Arduino Timers

Timer modules in Arduino provide precise timing functionality. They allow us to perform various tasks, such as generating accurate delays, creating periodic events, measuring time intervals, and meeting the time requirements of the target application.

Each Arduino board has its target microcontroller that has its own set of hardware timers. Therefore, we always need to refer to the respective datasheet of the target microcontroller to know more about its hardware capabilities and how to make the best use of it.

1. Arduino Hardware Timers

Arduino UNO (Atemga328p) has 3 hardware timers which are:

  • Timer0: 8-Bit timer
  • Timer1: 16-Bit timer
  • Timer2: 8-Bit timer

Those timer modules are used to generate PWM output signals and provide timing & delay functionalities to the Arduino core, and we can also use them to run in any mode to achieve the desired functionality as we’ll see later on in this tutorial.

Each hardware timer has a digital counter register at its core that counts up based on an input clock signal. If the clock signal is coming from a fixed-frequency internal source, then it’s said to be working in timer mode. But if the clock input is externally fed from an IO or any async source, it’s said to be working as a counter that counts incoming pulses.

2. Arduino Timers Comparison

This is a summarized table for Arduino UNO (Atmega328p) timers, differences between them, capabilities, operating modes, interrupts, and use cases.

Timer0Timer1Timer2
Resolution8 Bits16 Bits8 Bits
Used For PWM Output Pins#5, 69, 1011, 3
Used For Arduino Functions delay()
millis()
micros()
Servo Functions tone()
Timer Mode
Counter Mode
Output Compare (PWM) Mode
Input Capture Unit Mode
Interrupts Vectors TIMER0_OVF_vect
TIMER0_COMPA_vect
TIMER0_COMPB_vect
TIMER1_OVF_vect
TIMER2_COMPA_vect
TIMER1_COMPB_vect
TIMER1_CAPT_vect
TIMER2_OVF_vect
TIMER2_COMPA_vect
TIMER2_COMPB_vect
Prescaler Options1:1, 1:8, 1:64, 1:256, 1:10241:1, 1:8, 1:64, 1:256, 1:10241:1, 1:8, 1:32, 1:64, 1:128, 1:256, 1:1024
❕ Note

Playing with any timer configurations can and will disrupt the PWM output channels associated with that module. Moreover, changing the configurations of timer0 will disrupt the Arduino’s built-in timing functions ( delay, millis, and micros). So keep this in mind to make better design decisions in case you’ll be using a hardware timer module for your project. Timer1 can be the best candidate so to speak.

3. Arduino Timers Control

You can configure & program the Arduino timer modules in two different ways. The first of which is bare-metal register access programming using the Timer control registers & the information provided in the datasheet. And this is exactly what we’ve discussed in the Arduino Timers & Timer Interrupts Tutorial.

The other method to control timer modules is to use Timer Libraries like the Arduino-Timer Library. This is the topic of this tutorial, as we’ll discuss how to install and use arduino-timer library. Which can be a lot easier to use than what we’ve done in the Arduino timer interrupts tutorial previously.

For more information about Arduino Timers, fundamental concepts, different timer operating modes, and code examples, it’s highly recommended to check out the tutorial linked below. It’s the ultimate guide for Arduino Timers.

???? Also Read
Arduino Timers Tutorial [Ultimate Guide]

This article will give more in-depth information about Arduino Timers, how timers work, different timer operating modes, practical use cases and code examples, and everything you’d ever need to know about Arduino Timers.


Arduino-Timer Library

The Arduino-Timer library is a community-contributed library that enables users to configure timer-based events (tasks) without the need to do register-level programming for the timer modules. It uses the built-in timer-based millis() and micros() functions, so it’s like a wrapper layer of useful APIs on top of the built-in timer-based functions.

1- Using Arduino-Timer Library

To use the Arduino-Timer library, you need to include its header file and create a Timer instance.

Include the library like this.

Create a default timer instance with default configurations.

Alternatively, you can specify the configurations you want for the timer instance as shown below.

As you might have noticed there are 3 different templates for creating a Timer instance. This enables you to specify the maximum number of tasks that you’ll need to use with the timer instance, the resolution of task periodicity (in ms or μs), and the argument data type for the task handler functions (if needed).

2- Arduino-Timer MainFunction

The main function in the Arduino-Timer library is called .tick() and you must call it in the main super loop() while the microcontroller is IDLE to advance the tick count and dispatch the tasks when their periodicity time is due.

❕ Note

If the microcontroller is busy-waiting or doing other logic that takes too long so it doesn’t call the tick() function frequently, you’ll risk missing the deadlines of the periodic tasks assigned to the timer instance.

3- Arduino-Timer Task Handler Function Creation

To create a task handler function, use the following function definition template.

The task handler function can take an optional argument while assigning it to the timer instance using any of the functions .in(), .at(), or .every() which we’ll discuss hereafter. You can just remove it if not needed and declare your task handler function like this.

4- Arduino-Timer Tasks Assignation

After creating an instance of the timer class, you can assign to it the tasks (functions) that you’d like to run periodically. And this can be done in 3 different ways depending on what you’re trying to achieve.

Let’s say you’d like to attach the function Task1_Handler() to the timer instance ( MyTimer), you can use any of the following three methods.

.every()

.at()

.in()

5- Arduino-Timer Tasks Cancellation

To cancel a task, make sure to get a handle for that task while assigning it to the timer instance. Here is an example of how to do it.

To cancel all running tasks, use the following function.


Arduino-Timer Library Installation

You can download and install the Arduino-Timer library manually from GitHub, or alternatively, install it within the Arduino IDE itself. Just open the library manager. Tools > Manage Libraries > Search for arduino-timer. Then, click Install and let it finish the installation.

Arduino-Timer-Library-Installation

Now, you can easily use the Arduino-Timer library and check the built-in examples for the library to help you get started.

We’ll move now to the practical code examples to test this Arduino-Timer library for generating periodic events in both resolutions (ms and μs).


Arduino-Timer Library Example (ms Task)

In this example project, we’ll test the Arduino-Timer library. We’ll create two tasks with 80ms and 35ms periodicities. Each of which will toggle an LED output pin. And we’ll measure the output timing using an oscilloscope to make sure that the timer library is working as expected.

Arduino-Timer Library Example Code

Here is the full code listing for this Arduino-Timer Example (ms Tasks).

Code Explanation

We should first include the library and create a timer instance.

Task1_Handler() And Task2_Handler()

This is the Task1 handler function that we’d like to execute periodically every 80ms. In which we’ll toggle the output LED1 pin.

This is the Task2 handler function that we’d like to execute periodically every 35ms. In which we’ll toggle the output LED2 pin.

setup()

in the setup() function, we’ll set the LED pins’ mode to output and attach the Task1_Handler & Task2_Handler functions to the timer instance we’ve created and set them to be called every (80ms & 35ms) time intervals respectively.

loop()

in the loop() function, we need to continuously call the .tick() function which is the main function of the Arduino-Timer library.

Proteus Simulation

Here is the simulation result for this project on the Proteus (ISIS) simulator. The TinkerCAD simulation for this example will not produce a reliable behavior maybe due to inaccuracies in the microcontroller model in the simulation environment. The proteus simulation is way more accurate and behaves exactly like the real Arduino UNO board.

Moreover, we’ve got a better and much more powerful set of virtual measurement tools (oscilloscope, function generator, multimeters, virtual serial terminal, etc).

Check out the tutorial below to help you get started with simulating your Arduino projects in the Proteus simulation environment.

???? Also Read
Arduino Proteus Library Simulation Guide

This article will provide you with more in-depth information about using proteus ISIS for Arduino projects simulation.

Testing Results

Here is the result of running this example project on my Arduino UNO board and capturing the output signal on my DSO (digital storage oscilloscope).

It shows a perfect 80ms pin toggle event & another 35ms pin toggle event, exactly as we have expected and seen in the simulation.

Arduino-Timer-Library-Example-Result


Arduino-Timer Library Example (μs Task)

In this example project, we’ll test the Arduino-Timer library microseconds resolution. We’ll create a periodic task that executes every 100μs, in which we’ll toggle an output LED pin. Then, we’ll measure the resulting waveform timing to make sure the timer library is working as expected.

Arduino-Timer Library Example Code

Here is the full code listing for this Arduino-Timer Example (μs Task).

Code Explanation

We should first include the library and create a timer instance. Note that here I’m setting the configuration for MyTimer instance to use micros() function as a resolution instead of millis() that we’ve used in the previous example.

Task1_Handler()

This is the Task1 handler function that we’d like to execute periodically every 100μs. In which we’ll toggle the output LED pin.

setup()

in the setup() function, we’ll set the LED1 pin mode to output and attach the Task1_Handler function to the timer instance we’ve created and set it to be called every (100μs) time interval.

loop()

in the loop() function, we need to continuously call the .tick() function which is the main function of the Arduino-Timer library.

Proteus Simulation

Here is the simulation result for this project on the Proteus (ISIS) simulator. The TinkerCAD simulation for this example will not produce a reliable behavior maybe due to inaccuracies in the microcontroller model in the simulation environment. The proteus simulation is way more accurate and behaves exactly like the real Arduino UNO board.

Moreover, we’ve got a better and much more powerful set of virtual measurement tools (oscilloscope, function generator, multimeters, virtual serial terminal, etc).

Arduino-Timer-Library-Example-Simulation

Testing Results

Here is the result of running this example project on my Arduino UNO board and capturing the output signal on my DSO (digital storage oscilloscope).

It shows a perfect 100μs pin toggle event exactly as we have expected and seen in the simulation.

Arduino Timer Library Example Code Test Result


Parts List

Here is the full components list for all parts that you’d need in order to perform the practical LABs mentioned here in this article and for the whole Arduino Programming series of tutorials found here on DeepBlueMbedded. Please, note that those are affiliate links and we’ll receive a small commission on your purchase at no additional cost to you, and it’d definitely support our work.

Download Attachments

You can download all attachment files for this Article/Tutorial (project files, schematics, code, etc..) using the link below. Please consider supporting my work through the various support options listed in the link down below. Every small donation helps to keep this website up and running and ultimately supports our community.


Arduino-Timer Library Wrap Up

To conclude this tutorial, we’d like to highlight the fact that the Arduino-Timer library is very easy to install and use. It acts like a wrapper for the timer-based Arduino millis() & micros() functions and provides us with very easy-to-use APIs as we’ve seen in the example projects in this tutorial.

This tutorial is a fundamental part of our Arduino Series of Tutorials because we’ll build on top of it to interface various sensors and modules with Arduino in other tutorials & projects. So make sure you get the hang of it and try all provided code examples & simulations (if you don’t have your Arduino Kit already).

If you’re just getting started with Arduino, you need to check out the Arduino Getting Started [Ultimate Guide] here.

???? Also Read
Getting Started With Arduino Programming For Beginners

This is the ultimate guide for getting started with Arduino for beginners. It’ll help you learn the Arduino fundamentals for Hardware & Software and understand the basics required to accelerate your learning journey with Arduino Programming.

Share This Page With Your Network!
Join Our +25,000 Newsletter Subscribers!

Stay Updated With All New Content Releases. You Also Get Occasional FREE Coupon Codes For Courses & Other Stuff!

Photo of author
Author
Khaled Magdy
Embedded systems engineer with several years of experience in embedded software and hardware design. I work as an embedded SW engineer in the Automotive & e-Mobility industry. However, I still do Hardware design and SW development for DSP, Control Systems, Robotics, AI/ML, and other fields I'm passionate about.
I love reading, writing, creating projects, and teaching. A reader by day and a writer by night, it's my lifestyle. I believe that the combination of brilliant minds, bold ideas, and a complete disregard for what is possible, can and will change the world! I will be there when it happens, will you?

Leave a Comment