[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.
|Get updates||Follow @aron-bordin|
How to use Timer on Arduino
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.
In your seput(), add it:
now declare the function PrintHello:
And, to keep your timer running, on loop() add:
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():
Example2 - Replacing delay() with Arduino Timer:
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.