Close

A simple task manager

A project log for Backcountry Beacon

USB Powered Offline Map Server

brett-smithBrett Smith 08/26/2024 at 09:230 Comments

This project brings in FunctionTimer—maybe the simplest task manager ever use for Arduino. It's designed to schedule repetitive tasks effortlessly, and honestly I find myself copying it into most Arduino projects.


Essentially, all this library does is check how much time has elapsed since the last time it ran. If the correct amount of time has run, it runs the function again. We're basically just

if ( millis() - last > schedulePeriod){
    last = mills();
    runFunction();
}

Only now I have a built up class for it! This is the whole class:

class FunctionTimer{
public:
    void (* func_ptr)();
    int update_time;
    int last;
    FunctionTimer(void (* _func_ptr)(), int _update_time){
        func_ptr = _func_ptr;
        update_time = _update_time;
        last = 0;
    }

    void service() {
        if ((millis() - last) > update_time) {
            func_ptr();
            last = millis();
        }
    }
};

In our project, FunctionTimer helps us keep track of various tasks that need to run at different intervals. Here’s what we’re doing with it:

Here’s how simple it is to implement:

FunctionTimer screenMonitor(checkIfScreenInactive, 10000);
FunctionTimer buttonMonitor(buttonHandler, 100);
FunctionTimer heapMonitor(logHeap, 10000);
FunctionTimer connectionMonitor(&checkForStaleConnections, 1000);
FunctionTimer gpsReader(readGPS, 1000); 

void loop() {
    connectionMonitor.service();
    heapMonitor.service();
    gpsReader.service();
    buttonMonitor.service();
    screenMonitor.service();
    vTaskDelay(1); // Yield to the scheduler
}

One key point: functions triggered by the timer can block others, potentially delaying critical tasks, especially in Arduino's single-threaded environment. To avoid this, it's essential to ensure that functions are quick and non-blocking.

You can dig deeper into this little helper here: https://github.com/diyaquanauts/BackcountryBeacon/tree/main/firmware/include

Discussions