Software timers + multi threaded mode

I believe the timers are executed outside the main loop and I need to perform a callback. I’ve tried working with the examples in the docs but I can’t get them to compile.

Could someone write me an example that works or show me where I’m going wrong…

class CallbackClass
     void getStatus();

CallbackClass callback;
Timer tmrStatus(1000, &CallbackClass::getStatus, callback);

void setup(){ 

void loop(){


void getStatus() {
    //do stuff

Since getStatus is a member of CallbackClass, you need to define it either directly inside the class, or outside in the following format:

void CallbackClass::getStatus() {
//do stuff


1 Like

Thanks for the link, I’ve been having a play around and it all makes sense now.

I have a further question about SWtimers…

I have a class called musicPlayer, one of the methods is called playNote . playNote, plays a single note then set up a timer to fire playNote again in X milliseconds. From a different thread, @ScruffR noted that rather than spawning timers you would just change the delay and reuse the same timer. this all works fine but I have one problem.

Where do I declare my timer? I need to pass a pointer to the function, but also the class instance. I can’t declare it in my class because I dont know the class instance here. Is there a C++ equivalent of “this” ? If I declare my timer in the main .ino I’ll need to pass a pointer to the timer in the constructor of the musicPlayer class, but I need to construct the class first to pass the instance to the timer!

A long winded solution would be to crate and instance of the class, declare the timer, then call a method musicPlayer.setTimer(&myTimer) but this seems messy.

Any better ideas?

So I tried both ways, I can’t seem to be able to declare a Timer as a property of a class. If I try to create a method setTimer(Timer *tmr) then call it with &myTimer that works, but in my class if I then do *tmr.start() it throws an error.

this is a valid keyword in C++.
But if you want to pass an instance via the this pointer, you’d write *this
I’m not sure this would work as expected, but the syntax that should build would be

Timer _t(1000, &ThisClass::theCallback, *this);
// if above doesn't work for some reason try
Timer _t = Timer(1000, &ThisClass::theCallback, *this);

Brilliant, solved my problem and I now have a none blocking RTTTL music player :smiley:

1 Like