Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 9 of 9

Thread: IntervalTimerEx - Callbacks with state

Threaded View

  1. #1
    Senior Member
    Join Date
    Apr 2014
    Location
    Germany
    Posts
    1,210

    IntervalTimerEx - Callbacks with state

    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:

    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 by luni; 09-12-2020 at 08:18 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •