Pass parameters to one-shot software timer's callback function

When starting a one-shot software timer, I would like the callback function to perform different tasks depending on where the timer was started. For example read from a different sensor. How can this be achieved? Is there a way to pass parameters to the callback function?

Have it use a global variable which you can change?

1 Like

It could also just advance a FSM and each step then calls a separate function?


Two possible solutions have been given - if you have been able to try these out could you now mark this thread as Solved by ticking Solution?

As an illustration of the above ideas:

int sensorState;  //global variable
// pre-declare timer function
void time_to_read_sensors()
    switch (sensorState)
        case 1:
        //read sensor1 in case of state 1
        case 2:
       //read sensor2 in case of state 2
//declare timer object one shot
Timer readmysensors(1000, time_to_read_sensors, true);

in your loop()

sensorState = 1;

One word of warning - timer handler functions only get a small amount of stack assigned so you need to keep the code short and not call functions which might require a lot of memory. In that case, you would need to employ a FSM approach to throw calling the functions back to the loop() by setting another state for the loop to handle.