[Tutorial] Arduino Timer- Scheduling callbacks


In this post, I’ll present you the Arduino Timer module from .PNG Arduino Framework. This module allows you to schedule a function call in the future; once or repeatedly at specified intervals. This make your code more fluid, avoiding delay(), and consuming less power. Let’s take a look!!

About .PNG Arduino Framework

The .PNG Arduino Framework was developed by students of Unesp – São Paulo State University, Brazil, with the goal to turn Arduino project development easier. The framework has a chain of modular classes, compatible with some Arduino components.

Source code

Get updates Follow @aron-bordin
Star it: Star
Contribute: Fork
Download: Download

How to use Timer on Arduino

Read the docs for more information about it: http://png-arduino-framework.readthedocs.org/timer.html

From now, you can open your Arduino IDE , File -> Examples -> Arduino Timer. Take a look in the example and test if everything is working.

The first thing is to include the lib to your sketch and create a pointer of type Timer. With this timer, Arduino will be able to schedule a callback function in the configured interval.

#include "Timer.h"
Timer *timer1 = new Timer(500); //will call the callback in the interval of 500 ms

In your seput(), add it:

void setup(){
	timer1->setOnTimer(&PrintHello); //callback function
	timer1->Start(); //start the thread.

now declare the function PrintHello:

void PrintHello(){
	Serial.println("Hello timer!!");

And, to keep your timer running, on loop() add:

void loop(){

With this code, Arduino will run and check if the Timer Object is ready to call the function callback. If so, the function will be called and it will print on Serial.

[Important] You must not use delay() command, or Timer will not work!! Take a look in the next topic, and see how to replace delay() with this lib.

Replace Arduino delay() with Timer

The timer works as a delay(), you can “wait” until call something.

Example1 - Using delay():

void loop(){
	Serial.println("Using delay()

Example2 - Replacing delay() with Arduino Timer:

Timer *timer = new Timer(500);

void Hello(){
	Serial.println("Using Timer!! :)");

void loop(){

The both codes work in the same way, will wait 500ms and show a message. But when you use the Timer, your program will be always running, so if you need to call a sensor in an interval, you can use it easily. You can create as many Timers as necessary, and check each sensor, or call each function when you need it.

That’s it, if you have some problem, need help, suggestion, or this kind of stuff, just comment here!!

Thanks for reading, see you in the next post.

Aron Bordin

Aron Bordin
Computer Science Student and AI researcher. Always coding something fun :)

[Tutorial] Android Material Icon Library

### Welcome!In this post, I'll show you how to use [Material Icon Library](https://github.com/code-mc/material-icon-lib).This is a really...… Continue reading