This topic is used for feedback on the "Task Scheduler for Arduino" tutorial:
Hey, the Loop Counter versions are all free to use and modify, if you have a count and make a code change, the new count will show the speed results, that’s what I wrote it for.
The LT in the LT version is for Less Tech.
what is the advantage of this approach over a simpler list of timed function calls?
output
thirdSec
thirdSec
thirdSec
oneSec:
thirdSec
thirdSec
thirdSec
oneSec:
thirdSec
thirdSec
thirdSec
oneSec:
thirdSec
thirdSec
thirdSec
thirdSec
oneSec:
thirdSec
thirdSec
thirdSec
oneSec:
thirdSec
thirdSec
thirdSec
oneSec:
thirdSec
thirdSec
longSec
thirdSec
thirdSec
oneSec:
void oneSec () { Serial.println (" oneSec:"); }
void thirdSec () { Serial.println (" thirdSec"); }
void longSec () { Serial.println (" longSec"); }
// -----------------------------------------------------------------------------
struct TimedTask {
unsigned long msecPeriod;
void (*func) (void);
const char *desc;
unsigned long msecLst;
}
tTasks [] = {
{ 1000, oneSec, "onesec" },
{ 300, thirdSec, "thirdsec" },
{ 6500, longSec, "longsec" },
};
const int NtTask = sizeof(tTasks)/sizeof(TimedTask);
// -----------------------------------------------------------------------------
void loop ()
{
unsigned long msec = millis ();
TimedTask *t = & tTasks [0];
for (int n = 0; n < NtTask; n++, t++) {
if (msec - t->msecLst >= t->msecPeriod) {
t->msecLst = msec;
t->func ();
}
}
}
// -----------------------------------------------------------------------------
void setup ()
{
Serial.begin (9600);
}
Enthusiastic followers of this tutorial will be on the fast track to landing a tireless mentor's help if they need it, no matter at what level.
Or is it the other way around? A talented mentor may land an enthusiastic amateur to help tirelessly.
a7
- Just a hardware person’s feeble/babbling attempt at making a scheduler tutorial.
My main fear was the scheduling part but it appears that you have split non-blocking tasking as I know it into a timer and a function that the timer calls so not what I feared at all!
i'm an EE, not a CS. worked on embedded apps most of my career and a decade on DSPs.
was surpised when someone asked which operating system i was going to use on a DSP monitoring optical power levels. Just ran code in a loop
The code IS the OS!
there are obviously different types of programs, not all programs have features of an operating system (see Definition and purpose), not the code i referred to
I was a computer cowboy, logic slinger, not a robed priest.
That came from “The code IS the comments.” from the early 80’s when I fixed code (my learning path) that had code from a few different writers ALL doing rush work and not maintaining comments that were worse than none overall.
In the mid-90’s I had a few piled higher’s that could not understand my single-pass data compiler decided to damn my code as “you don’t write [edit; word change] programs, you write systems”. Yah? NO DUH!
MY collector owned the machine, to me the running code is the only OS those machines had. Not General Purpose, just a system that ran the box. It’s kind of like how I define “Task” in terms not defined in terms of code… for me when intervals overlap, they are concurrent regardless of how it’s done.
- Added a second action to the heartbeat LED.
Long flash (normal) short flash (blocking code)
//
//================================================^================================================
// Cooperative Non-Blocking Task Scheduler for Arduino (One-Shot & Passive Timer Support)
//================================================^================================================
//
// URL
//
// LarryD
//
// Version YY/MM/DD Comments
// ======= ======== ========================================================================
// 1.00 26/02/21 Running code.
// 1.01 26/02/25 Edited some comments.
// 1.02 26/02/26 Heartbeat LED changed to, long flash (normal) short flash (blocking code).
//
//
//
// The example herein, uses a struct. This struct is one step away for creating a CLASS/library.
// The struct fully exposes all the TIMER code, as opposed to including a library.
//
// This is an "Intermediate tutorial".
// Not for "Absolute beginners" or "First-week Arduino learners".
//
// What Is a Cooperative Scheduler?
// ----------------------------------------------------------------------------------------------
// A cooperative scheduler repeatedly checks small tasks and runs them
// only when their timer expires. Each task must execute quickly and
// return control to loop().
// This differs from:
// - delay() based timing (blocking)
// - interrupt driven scheduling
// - preemptive RTOS scheduling
//
// Description:
// ----------------------------------------------------------------------------------------------
// This sketch implements a lightweight, fully modular cooperative task scheduler for Arduino.
// It helps users understand that a "Task" isn't just a single action, but can be a mini-program
// with its own memory (using static variables).
//
// Multiple independent tasks are executed without using delay(). Each task maintains its own:
// • Optional callback function (nullptr supported)
// • Execution interval
// • Timing base (millis() or micros())
// • ENABLED / DISABLED state
// • Optional one-shot execution mode
// • Expired flag (for passive, non-callback timers)
//
// The scheduler engine runs continuously inside loop() and executes tasks when their
// individual timers expire. All timing is non-blocking and rollover safe.
//
// loop()
// |-----runScheduler()
// | |----- timer[0].checkTimer()
// | |----- timer[1].checkTimer()
// | |----- timer[2].checkTimer()
// | +----- ...
// |
// +-----Other non-blocking code
//
// Features:
// ----------------------------------------------------------------------------------------------
// • Fully non-blocking (no delay())
// • Independent modular timer objects
// • Optional callback (nullptr enables passive mode)
// • Per-timer interval control
// • Selectable time base (millis() or micros())
// • ENABLED / DISABLED runtime control
// • Optional one-shot mode
// • Periodic tasks (heartbeat and LED blink examples)
// • Self-disabling task (5ToggleLED stops after 5 flashes)
// • Edge-triggered event handling (pushbutton input)
// • Built-in expired flag for polling timers
// • Passive, non-callback TIMER polling (watchdogLED turns OFF after 5 seconds)
// • Runtime task control and reconfiguration
//
// One-Shot Demonstration:
// ----------------------------------------------------------------------------------------------
// Pressing the watchdogSwitch:
// 1. Immediately turns oneShotLED ON
// 2. Arms the ONESHOT TIMER as one-shot
// 3. After the configured delay, oneShotLED goes OFF
// 4. The task automatically disables itself
//
// The one-shot behavior is implemented inside the scheduler engine,
// keeping callback functions clean and application-focused.
//
// Watchdog Demonstration:
// ----------------------------------------------------------------------------------------------
// Pressing the watchdogSwitch:
// 1. The watchdogLED is turned ON
// 2. The WATCHDOG TIMER enabled and restarted
// 3. When the WATCHDOG TIMER expires, the TIMER is disabled
// 4. The watchdogLED is turned OFF
//
// Timer expire Demonstration:
// ----------------------------------------------------------------------------------------------
// Pressing the expireSwitch:
// 1. The WATCHDOG TIMER set set to expire
// 2. When the next checkTime() is run, the TIMES expires
// 3. The watchdogLED is turned OFF
//
// Task Control API (Encapsulated in struct):
// ----------------------------------------------------------------------------------------------
// enableRestart() - Enables the TIMER and restart the TIMER
// disable() - Disables the TIMER
// restart() - Restarts the TIMER
// expire() - Forces the TIMER to immediately expire
// setInterval(value) - Changes the TIMER interval
// setOneShot(mode) - Enable or disable one-shot behavior
// isExpired() - Returns the expiredFlag
// clearExpired() - Clears the expiredFlag
// checkTimer() - Checks the TIMER, Callback function runs when the TIMER expires
//
// Design Philosophy:
// ----------------------------------------------------------------------------------------------
// This scheduler is cooperative. Tasks must execute quickly and return control
// to loop(). It is intended for small to medium embedded applications where a full RTOS is
// unnecessary.
//
// This example serves as a reusable foundation for building:
//
// • State machines
// • Event-driven systems
// • Soft real-time control loops
// • Modular embedded frameworks
// • Timed automation sequences
//
// No delay() is used anywhere in this sketch.
//
// Adding a new TIMER:
// ----------------------------------------------------------------------------------------------
// 1. Write a new "callback function".
// • Must return void
// • Must not have parameters
// • Must execute quickly
// • Never use delay()
// ex:
// void myNewTask()
// {
// //Your task code here
// digitalWrite(slowToggleLED, !digitalRead(slowToggleLED));
// }
//
// 2. In the "Callback area for Function Prototype", add your new function prototype.
// ex: void myNewTask();
// Note: non-callback TIMERs use "nullptr" as its callback element, a Function Prototype is not need.
//
// 3. In the "timer Table", define the new TIMER.
// ex:{callback, interval, timeBase, enabled, oneShot}
// {myNewTask, 1000, TIME_MILLIS, ENABLED, DISABLED} //callback TIMER
// OR
// {nullptr, 5000, TIME_MILLIS, DISABLED, DISABLED} //non-callback TIMER
//
// 4. Note: In the timer[] array, the order must match the TimerIndex enum.
// In the "TIMER index names area", define a new TIMER name.
// For standardization, this name should be the same as the callback functions name,
// only in capital letters.
// Non-callback TIMERs can be given the name you desire.
// Add this TIMER name into enumeration, "enum TimerIndex {...}".
// Use this name in accessing a TIMERs functions and variables.
// ex:
// ...
// {checkSwitches, 50, TIME_MILLIS, ENABLED, DISABLED}, // 4
// {nullptr, 5000, TIME_MILLIS, DISABLED, DISABLED} // 5
// ...
// enum TimerIndex
// {
// ...
// CHECKSWITCHES,
// WATCHDOG
// //Next TIMER name goes here.
// };
//
//================================================^================================================
//
#define ENABLED true
#define DISABLED false
#define LEDon HIGH
#define LEDoff LOW
#define PUSHED LOW
#define RELEASED HIGH
// M A K E t i m e r
//================================================^================================================
//
enum TimeBase
{
TIME_MILLIS,
TIME_MICROS
};
//============================================================ Maketimer structure definition.
struct MAKEtimer
{
//========================
void (*callback)();
unsigned long interval;
TimeBase timeBase;
bool enabled;
bool oneShot;
bool expiredFlag;
unsigned long lastRun;
//======================== Constructor
MAKEtimer(void (*_callback)(), unsigned long _interval, TimeBase _timeBase, bool _enabled, bool _oneShot)
{
callback = _callback;
interval = _interval;
timeBase = _timeBase;
enabled = _enabled;
oneShot = _oneShot;
expiredFlag = false;
lastRun = 0;
}
//========================
unsigned long now()
{
return (timeBase == TIME_MICROS) ? micros() : millis();
}
//========================
void enableRestart()
{
enabled = true;
expiredFlag = false;
lastRun = now();
}
//========================
void disable()
{
enabled = false;
}
//========================
void restart()
{
expiredFlag = false;
lastRun = now();
//We could use:
//lastRun += interval;
}
//========================
void expire()
{
//Force TIMER to expire on next scheduler pass.
lastRun = now() + interval;
}
//========================
void setInterval(unsigned long value)
{
interval = value;
}
//========================
void setOneShot(bool mode)
{
oneShot = mode;
}
//========================
bool isExpired()
{
return expiredFlag;
}
//========================
void clearExpired()
{
expiredFlag = false;
}
//========================
void checkTimer()
{
if (enabled == false)
{
return;
}
unsigned long currentTime = now();
if (now() - lastRun >= interval)
{
lastRun = currentTime;
if (callback != nullptr)
{
callback();
}
else
{
expiredFlag = true;
}
if (oneShot == true)
{
disable();
}
}
}
}; //END of struct MAKEtimer
//============================================================ Callback area for Function Prototype.
//
void heartbeat();
void fiveToggle();
void slowToggle();
void oneShot();
void checkSwitches();
void shortHeartbeat();
//Next prototype goes here.
//============================================================ TIMER index names area.
//
//Give a name to each index in tasks table.
//Use the same names as callback but add a under score in the front.
//Non-callback TIMERs can have whatever name you desire.
// â–şâ–ş Ensure the order of "this enum" matches the "timer table". â—„â—„
//
enum TimerIndex
{
_heartbeat,
_fiveToggle,
_slowToggle,
_oneShot,
_checkSwitches,
_watchdog,
_shortHeartbeat,
TIMER_COUNT //Leave this as the last entry.
};
//============================================================ timer Table
//Define all our scheduled TIMERs.
//
//Interval constants.
const unsigned long hbInterval = 500UL;
MAKEtimer timer[] =
{
//{callback, interval, timeBase, enabled, oneShot} Indexes
{heartbeat, hbInterval, TIME_MILLIS, ENABLED, DISABLED}, //_heartbeat
{fiveToggle, 400, TIME_MILLIS, ENABLED, DISABLED}, //_fiveToggle
{slowToggle, 800000, TIME_MICROS, ENABLED, DISABLED}, //_slowToggle
{oneShot, 1600000, TIME_MICROS, DISABLED, DISABLED}, //_oneShot
{checkSwitches, 50, TIME_MILLIS, ENABLED, DISABLED}, //_checkSwitches
{nullptr, 5000, TIME_MILLIS, DISABLED, DISABLED}, //_watchdog
{shortHeartbeat, 1000, TIME_MICROS, DISABLED, DISABLED} //_shortHeartbeat
//
//Next TIMER element goes above. Add a comma at the end of the previous element.
};
//========================
//Single TIMER definition.
//Passive/no_callback TIMER.
//
//Make a TIMER called "shortHeartbeat".
//MAKEtimer shortHeartbeat =
//{
// //{callback, interval, timeBase, enabled, oneShot}
// nullptr, 1000, TIME_MICROS, DISABLED, DISABLED
//};
//============================================================ GPIOs and Variables
//
const byte oneShotSwitch = 2;
const byte watchdogSwitch = 3;
const byte expireSwitch = 4;
const byte fiveToggleLED = 5;
const byte slowToggleLED = 6;
const byte oneShotLED = 7;
const byte watchdogLED = 8;
const byte heartbeatLED = 13;
//Heartbeat blocking control.
const unsigned long triggerPoint = 1000UL; //1000us, 1ms
bool blockingFlag = false;
//============================================================ Scheduler Engine
//
//========================
void runScheduler()
{
for (byte i = 0; i < TIMER_COUNT; i++)
{
timer[i].checkTimer();
}
}
//============================================================ TIMER Tasks
//
//========================
void heartbeat()
{
//Gives a rough indication if the sketch has blocking code.
//Did we observe code blocking ?
if (blockingFlag)
{
blockingFlag = false;
//There was blocking code.
//Set TIMER _shortHeartbeat to run once only.
timer[_shortHeartbeat].setOneShot(ENABLED);
//Enable an restart TIMER _shortHeartbeat.
timer[_shortHeartbeat].enableRestart();
digitalWrite(heartbeatLED, HIGH);
}
else
{
//Normal heartbeat toggle.
digitalWrite(heartbeatLED, !digitalRead(heartbeatLED));
}
}
//========================
void fiveToggle()
{
static bool state = LOW;
static byte toggleCount = 0;
static byte flashCount = 0;
state = !state;
digitalWrite(fiveToggleLED, state);
toggleCount++;
if (toggleCount >= 2)
{
toggleCount = 0;
flashCount++;
if (flashCount >= 5)
{
timer[_fiveToggle].disable();
digitalWrite(fiveToggleLED, LOW);
}
}
}
//========================
void slowToggle()
{
static bool state = LOW;
state = !state;
digitalWrite(slowToggleLED, state);
}
//========================
//This is a classic example of a "Watchdog" or "Timed Pulse" pattern.
//It’s a great way to handle things like solenoid valves or backlight timeouts!
void oneShot()
{
//Turn OFF the LED.
digitalWrite(oneShotLED, LEDoff);
}
//========================
//
void shortHeartbeat()
{
digitalWrite(heartbeatLED, LOW);
}
// s e t u p ( )
//================================================^================================================
//
void setup()
{
Serial.begin(115200);
pinMode(oneShotSwitch, INPUT_PULLUP);
pinMode(watchdogSwitch, INPUT_PULLUP);
pinMode(expireSwitch, INPUT_PULLUP);
pinMode(heartbeatLED, OUTPUT);
pinMode(fiveToggleLED, OUTPUT);
pinMode(slowToggleLED, OUTPUT);
pinMode(oneShotLED, OUTPUT);
pinMode(watchdogLED, OUTPUT);
} //END of setup()
// l o o p ( )
//================================================^================================================
//
void loop()
{
//============================================================ Measure loop execution time
//Note: the way this sketch is now, loop() executes in about 70 microseconds.
static unsigned long loopStartMicros = micros();
unsigned long nowMicros = micros();
unsigned long loopTime = nowMicros - loopStartMicros;
loopStartMicros = nowMicros;
static byte blockCount = 0;
//Avoids false positives due to Serial prints etc.
//Does loop() execution time exceed the triggerPoint for multiple consecutive cycles.
if (loopTime >= triggerPoint)
{
if (++blockCount >= 100)
blockingFlag = true;
}
//Not enough blocking events detected.
else
{
blockCount = 0;
}
//============================================================ Blocking test switch.
// A momentary switch connected to pin 2 (INPUT_PULLUP) is used to intentionally
// introduce a delay into the main loop. When the switch is pressed, a
// delayMicroseconds() call increases loop execution time beyond the blocking threshold,
// allowing verification of the blocking-detection logic.
if (digitalRead(oneShotSwitch) == LOW)
{
//Intentionally block this code.
delayMicroseconds(triggerPoint);
}
//============================================================ Service all TIMERs.
//
runScheduler();
//============================================================ _watchdog
//This is an example of a "Passive/no_callback" TIMER.
//When the expired flag is set, the TIMER has expired.
//It is time to turn OFF the watchdogLED ?
//
if (timer[_watchdog].isExpired())
{
//Get ready for the next use of this Flag.
timer[_watchdog].clearExpired();
//Remove this TIMER from being checked by the scheduler. i.e. disable the TIMER "_watchdog".
timer[_watchdog].disable();
//Do other things here.
digitalWrite(watchdogLED, LEDoff);
}
//========================================
//Other non blocking code goes here
//========================================
} //END of loop()
// c h e c k S w i t c h e s ( )
//================================================^================================================
//
void checkSwitches()
{
static bool lastOneShotSwitch = RELEASED;
static bool lastWatchdogSwitch = RELEASED;
static bool lastExpireSwitch = RELEASED;
bool currentState;
//============================================================ oneShotSwitch
//Example of using a one shot control.
//
currentState = digitalRead(oneShotSwitch);
//Was there a change in the switches state ?
if (lastOneShotSwitch != currentState)
{
//Update to the new state
lastOneShotSwitch = currentState;
//Is the switch pushed ?
if (currentState == PUSHED)
{
digitalWrite(oneShotLED, LEDon);
//Set TIMER _oneShot run once only.
timer[_oneShot].setOneShot(ENABLED);
//Enable an restart TIMER ONESHOT.
timer[_oneShot].enableRestart();
}
} //END of oneShotSwitch
//============================================================ watchdogSwitch
//This is a classic example of a "Watchdog" or "Timed Pulse" pattern.
//
currentState = digitalRead(watchdogSwitch);
//Was there a change in the switches state ?
if (lastWatchdogSwitch != currentState)
{
//Update to the new state
lastWatchdogSwitch = currentState;
//Is the switch pushed ?
if (currentState == PUSHED)
{
digitalWrite(watchdogLED, LEDon);
//Clear the expired Flag.
timer[_watchdog].clearExpired();
//Enable and restart the TIMER "_watchdog".
timer[_watchdog].enableRestart();
}
} //END of watchdogSwitch
//============================================================ expireSwitch
//Example of making a TIMER expire prematurely.
//
currentState = digitalRead(expireSwitch);
//Was there a change in the switches state ?
if (lastExpireSwitch != currentState)
{
//Update to the new state
lastExpireSwitch = currentState;
//Is the switch pushed ?
if (currentState == PUSHED)
{
//Make this TIMER expire.
timer[_watchdog].expire();
}
} //END of expireSwitch
} //END of checkSwitches()
// E N D
//================================================^================================================
//
an operating system manages shared resources between independent application without imposing any restrictions on those applications or requiring the applications know about each other.
the shared resources include
- processing time
- memory
- i/o
- disk and network storage, and
- when needed inter-process communication
batch processing, programs loaded and run to completion existed prior to operating systems and essentailly what most simple embedded applications are (of course many embedded applications use Linux)
operating systems made multi-user access possible
and some will say multi-tasking is a social management tool allowing separate sandboxes for each process written by separate individuals
An Operaing System provides the infrastructure to run multiple programs. An OS is not the program
RCA nearly went bankrupt trying to create an operating system like IBM. then Thompson came along a wrote Unix
Yes! OS is not a user application program, but it is a (complex) program. The very basic task of an OS is to help user running his application pogram and then doing other big things like sharing resources among the processes in a multi-user and multi-tasking environment.
An EE student while woked with an 8085/8086 Trainer at university life had learnt very well how the Monitor program (ROM resident OS) helped user to execute his application stored in RAM. The OS cleverly passed the beginning addres of the application to the Program Counter of the MPU.
Modern Win10 OS does the same thing!
I read Tannebaum's text book "Operating systems" against a course work.
seems you're arguing that any program that runs on a processor without a recognized Operating System is an operating system.
obviously programs do different things. they are all code. that typically sequences thru a # stages of processing. Clearly a navigation program is not a database management, or airline reservation system or a terminal or disk controller or radar.
an operating system is code that has a pretty well defined purpose, managing shared resources, scheduling other independent programs that use those resources.
you seem to be saying that any embedded program is an operating sytem + whatever it's purpose is. Not every embedded system has the features of an Operating system, a key one pre-emptive scheduling.
the first emedded project i worked on, a data terminal, had a pre-emptive scheduler written by an english major we called the operating system that supported priority based multi-tasking
i've found it very helpful to have a good understanding of operating system features on embeeded systems when separate tasks need to cooperate and share information
Thank you for the clear and insightful elaboration on the theory of operating systems in embedded systems. There is little value in arguing with those who speak or write from their experience; instead, it is more productive to enrich our understanding by asking relevant questions.
Sure, the program may may be a system that operates hardware on data but the Name Operating System belongs to a bigger concept.
It may handle real world asynch events through many many different independent functions that run concurrently but since those functions are not separate programs But Could Be and Don’t Have To Exist before the program is written, none of that matters unless it is Totally General says The Concept.
Program = code + data.
The IBM/Gates/CPM Disk Operating System I wrote programs to run on was not Multiuser nor Multitasking EXCEPT when the program running on it interleaved multiple tasks written to literally do their things at the same time, what’s in a name… oops.
I guess I’ll have to write “concurrent function” instead of “task” from now on unless that has Only One Specific Rigid Definition.
not multi-tasking except to interleave multiple task? wasn't until it was?
Thompson began working on what became Unix to run iteractive games.
multi-user is one application of multi-tasking. Many embedded applications are easier to develop as multiple tasks. Let the OOS schedule tasks by priority when events make them runnable
If the program does several things at a time but isn’t an Operating System (TM) with ALL THAT ENTAILS then it’s Not Tasking either. A task must be a program that runs on an MT Operating System.
Time for carefully chosen new names, the old words no longer mean what they used to. Flexibility be damned.