Hi!
I just started to use an Arduino Leonardo (embedded on a littleBit) a few weeks ago, and from the get-go I wished I could use coroutines to "script" event sequences in time... I did find an old thread on these forums that proposed a simple implementation, but it had 0 replies and it was a bit too straightforward, I wanted something more akin to coroutines the Unity game engine for example.
So I set out to make my own library to do C coroutines with more usable constructs like waiting, suspending and looping, as well as supporting some manner of stack preservation by saving local variables.
They're definitely macro-heavy, but I think they're pretty easy to use. Here's a coroutine that flashes a light once for 100 milliseconds :
// flashes a LED attached to analog pin 5 for 100ms
void flashOnce(COROUTINE_CONTEXT(coroutine))
{
BEGIN_COROUTINE;
analogWrite(5, 255);
coroutine.wait(100);
COROUTINE_YIELD;
analogWrite(5, 0);
END_COROUTINE;
}
And then you can start it at various points in your program without worrying about timers or interrupting other running code :
coroutines.start(flashOnce);
There's a couple more things involved to make them work though, (an update() callback and the instantiation of a manager object).
Take a look at the documentation on GitHub and give it a shot!
Renaud (@renaudbedard)