Arduino library to use timer 2 with a configurable resolution. Based on MsTimer2 by Javier Valencia. It's called FlexiTimer2 because it's based on MsTimer2, but offers more flexibility, since it has a configurable timer resolution.
It works on:
Originally written by Wim Leers for the project associated with the "Mobile & Pervasive Computing" course at Hasselt University in Belgium.
units
time the resolution
for the overflow. Each overflow, "f" will be called. "f" has to be declared void with no parameters. E.g. units=1
, resolution = 1.0/3000
will call f
3000 times per second, whereas it would be called only 1500 times per second when units=2
.
resolution = 0.001
.
License: LGPL (like MsTimer2)
Download:
A fork is available here:
After downloading the zip file, rename the zip file something simple like "FlexiTimer2.zip". (The Arduino IDE sometimes chokes on zip files with dashes or other symbols in the file name).
Install it like any other Arduino library. (See http://arduino.cc/en/Guide/Libraries ). It should end up in the {arduino-path}/hardware/libraries/ folder.
This example is *identical* to the one for MsTimer2, but "Ms" has been replaced with "Flexi". Really, that's all you have to do to port your code, if you want to be prepared for more granular control, but don't need it yet.
// Toggle LED on pin 13 each second #include <FlexiTimer2.h> void flash() { static boolean output = HIGH; digitalWrite(13, output); output = !output; } void setup() { pinMode(13, OUTPUT); FlexiTimer2::set(500, flash); // 500ms period FlexiTimer2::start(); } void loop() { }
The line
FlexiTimer2::set(500, flash);
is equivalent with
FlexiTimer2::set(500, 1.0/1000, flash);
The latter configures a resolution of 1/1000th of a second, i.e.: 1 millisecond.
In this example, we show how to use FlexiTimer2 to achieve sub-millisecond resolution for your interrupts.
The original author of FlexiTimer2 needed to simulate PWM over a 8x8 multiplexed grid of LEDs. Without going into detail on that, he needed 2880 interrupts per second to update the LEDs to be able to generate a decent range of colors.
#include <FlexiTimer2.h> void simulatePWM() { // Add your code to simulate PWM here. } void setup() { FlexiTimer2::set(1, 1.0/2880, simulatePWM); FlexiTimer2::start(); } void loop() { }
Note that the PWM signals created by Timer 2 will become unusable while Flexitimer2 is using Timer 2.
On Arduino Uno, those are pins 3 and 11.
On Arduino Mega, those are pins 9 and 10.
Report bugs in the issue queue.