woot, 2nd version, now with multiple triggers for the same timer!
// up to 5 "virtual" overflows with the same timer
#define _TIMERS 5
static unsigned int _msecs[_TIMERS];
static unsigned int _counters[_TIMERS];
static void (*_funcs[_TIMERS])();
void _overFlow();
void Timer2Init();
void Timer2Func(byte num, void (*f)());
void Timer2Ms(byte num, unsigned int msecs); // msecs = 0 for disabling
void _overFlow() {
byte tmp;
for(tmp = 0; tmp < _TIMERS; tmp++) {
if (_msecs[tmp] > 0) {
_counters[tmp] += 1;
if ((_counters[tmp] % (_msecs[tmp]*2)) == 0) {
_counters[tmp] = 0;
(*(_funcs[tmp]))();
}
}
}
}
void Timer2Init() {
byte tmp;
for(tmp = 0; tmp < _TIMERS; tmp++) {
_msecs[tmp] = 0;
_funcs[tmp] = 0;
_counters[tmp] = 0;
}
FrequencyTimer2::setPeriod(1000);
FrequencyTimer2::setOnOverflow(_overFlow);
}
void Timer2Func(byte num, void (*f)()) {
_funcs[num] = f;
}
void Timer2Ms(byte num, unsigned int msecs) {
_msecs[num] = msecs;
}
And a simple example:
void flash() {
static boolean output = HIGH;
digitalWrite(13, output);
output = !output;
}
void flash2() {
static boolean output = HIGH;
digitalWrite(12, output);
output = !output;
}
void setup() {
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
Timer2Init();
Timer2Ms(0, 1000); // flash a led each second
Timer2Func(0, flash);
Timer2Ms(1, 3000);
Timer2Func(1, flash2); // flash a led each 3 seconds
}
void loop() {
}