I want to write a C++ wrapper class which can be used to handle multiple timer interrupts in parallel.
For one interrupt at a time i have a working solution similar to this one: Use lambda function as microcontroller interrupts handler
My wrapper class looks like this:
class Rp2040RepeatingTimer {
private:
struct repeating_timer _repeating_timer; /* Config for repeating timer*/
std::function<void()> _callback;
static Rp2040RepeatingTimer* _instance;
static bool timerHandler(struct repeating_timer *t){
if (_instance){
_instance->_callback();
}
return true;
}
public:
Rp2040RepeatingTimer(std::function<void()> _callback) : _callback(_callback) {
_instance = this;
}
bool start(const int32_t intervall);
bool stop();
};
My test program looks like this:
Rp2040RepeatingTimer* Rp2040RepeatingTimer::_instance = nullptr;
int main(){
stdio_init_all();
// Handle interrupt
// This lambda function is never called when timer1 occurs
Rp2040RepeatingTimer timer1([]() {
printf("GOTCHA 1");
});
Rp2040RepeatingTimer timer2([]() {
printf("GOTCHA 2");
});
timer1.start(500);
timer2.start(1000);
while(1){}
}
Nevertheless, in this case all class instances share the same static value for the instance, which makes it impossible to use this solution for handling multiple timers. Any ideas how to adopt it for multiple interrupt handlers in parallel?
Thanks to @TerenceSimpson I was able to figure out a working solution for my problem. The idea was to use the user_data-pointer of the interrupt handler to pass the corresponding timer obejct (which in return stores the function pointer to the user-callback).
My timer.hpp file for class declaration:
My timer.cpp file for function defintion:
My main.cpp for testing: