Arduino Timed Events

#015 Arduino Timed Events

I love Arduinos. They are on almost all of my projects. However, running code anything but sequentially takes careful manipulation of program flow. Arduino Timed Events essentially replicates the JS event loop by allowing users to schedule code that should be run at a certain time. I had a blast making it, so I am putting it here.

The code keeps a list of scheduled Tasks, which can either be scheduled to run once, at an interval, or anytime a boolean condition is true. It doesn't utilize timer interrupts, so if you schedule code that includes a delay and that code is called, the program will hang until the code is completed. Missed events will run after that event, however.

Check out the github for an usage guide. Here is some sample code. Note the use of function pointers, lambdas and capturing lambdas. Memory de-allocation is handled for you in the case of the capturing lambda.

        #include <MemoryFree.h>
        #define pl(x) Serial.println(F(x));
        #define pt(x) Serial.print(F(x));
        #define pSize(x) {Serial.print(F("sizeof(" #x)); Serial.print(F(") = "));Serial.println(sizeof(x));}

        #include <Tasks.h>
        #define PIN 2

        void fm() {
            pt("Free Memory = ");
            Serial.println(freeMemory());
        }

        void setup ()
        {
            //Required setup
            pinMode(PIN, INPUT_PULLUP);
            Serial.begin(115200);

            //Setup something that prints the free memory every second
            setInterval(fm, 0, 1000);
            pt("Starting free memory: ");
            fm();

            // Add an event listener that should run 
            byte x = addEventListener([]() {
                Serial.println("Pin is high!");
                delay(100);
            } , []() -> boolean {return digitalRead(PIN);});

            // Cancel the event listener using the ID of the old event listener after 20 seconds
            setTimeout(new auto ([ = ]() {
                pl("Stopping event listener");
                deleteTask(x);
            }), 20000);

            pt("After setup: ");
            fm();
        }

        void loop () {
            runTasks();
        }
        
Go To Top Guess what? I made this website! Check it and many of my other projects on my github.