luni
Well-known member
I often need to pass state to callbacks attached to an IntervalTimer. Since the IntervalTimer only accepts void(*)() callbacks, it is a bit tedious to work around. I therefore did a shallow wrapper around the IntervalTimer which accepts callbacks of type std::function. I.e., you can attach more or less anything callable to it. Since IntervalTimerEx objects use normal IntervalTimers as workhorses they do not interfere with standard IntervalTimers and can be used in parallel.
IntervalTimerEx.h
IntervalTimerEx.cpp
https://github.com/luni64/IntervalTimerEx
Here a few examples:
// Output
Since the IntervalTimerEx accepts std::function callbacks it is easy to embed it in a class and use non static member functions as callbacks. Here a simple blinker class showing how to achieve that:
IntervalTimerEx.h
IntervalTimerEx.cpp
https://github.com/luni64/IntervalTimerEx
Here a few examples:
Code:
#include "IntervalTimerEx.h"
// plain vanilla void(*)() callback
void myCallback_0(){
Serial.print("myCallback_0 ");
Serial.println(millis());
}
// need to manipulate the calling timer in the callback?
void myCallback_1(IntervalTimer* caller){
Serial.print("--> myCallback_1 ");
Serial.println(millis());
caller->end(); // e.g. do a one shot timer
}
IntervalTimerEx t1, t2;
void setup(){
t1.begin(myCallback_0, 150'000);
t2.begin([] { myCallback_1(&t2); }, 1'000'000); // attach callback using a lambda
}
void loop(){
}
// Output
Code:
...
myCallback_0 900
myCallback_0 1050
myCallback_0 1200
--> myCallback_1 1300
myCallback_0 1350
myCallback_0 1500
myCallback_0 1650
myCallback_0 1800
...
Since the IntervalTimerEx accepts std::function callbacks it is easy to embed it in a class and use non static member functions as callbacks. Here a simple blinker class showing how to achieve that:
Code:
#include "IntervalTimerEx.h"
class Blinker
{
public:
void begin(float seconds)
{
pinMode(LED_BUILTIN, OUTPUT);
timer.begin([this] { this->blink(); }, seconds * 1E6); // attach member function
}
protected:
IntervalTimerEx timer;
void blink()
{
digitalToggleFast(LED_BUILTIN);
}
};
//----------------------------
Blinker blinker;
void setup(){
blinker.begin(0.1); // start the blinker
}
void loop(){
}
Last edited: