New library: TimedAction

TimedAction:
This is a utility class for providing a way to do protothreading on arduino. It is a bit like (MsTimer2 - timer2 usage) + Metro.

TimedAction abstracts the mechanics of how to use millis in order to simulate multitasking.

Files:
TimedAction.h
TimedAction.cpp
keywords.txt
examples/BlinkAction/BlinkAction.pde

All files:
TimedAction.rar

Blink example using TimedAction class:

/*
||
|| Description:
|| This sketch blinks an LED as Examples->Digital->Blink
||
|| @author Alexander Brevig
|| @version 1.1
||
*/

#include <TimedAction.h>

//this initializes a TimedAction class that will change the state of an LED every second.
TimedAction ta = TimedAction(NO_PREDELAY,1000,blink);

//pin / state variables
#define ledPin 13
boolean ledState = false;

void setup(){
pinMode(ledPin,OUTPUT);
digitalWrite(ledPin,ledState);
}

void loop(){
ta.check();
}

void blink(){
ledState ? ledState=false : ledState=true;
digitalWrite(ledPin,ledState);
}

Nice concept. However...

void TimedAction::check(){ if (millis() - previous > interval) { previous = millis(); execute(); }

When millls() rolls over to 0, every 49 days, the timed action may fail for a very long time because there is a good chance that 'previous' is very large before rollover of millis(). Rollover os millis() an issue we all code for and deal with eventually. You should add some code to check for the rollover boundary.

Oh. Actually, that is me being lazy. It's just copypaste from the examples blink without delay.

a simple:

if ( millis()-previous >= interval ) {

would do the trick

I think the blink without delay should be updated?

[edit]And it's changed. Current version: 1.2 Thank you for noticing![/edit]

the timed action may fail for a very long time because there is a good chance that 'previous' is very large before rollover of millis().

George, this is not correct. Because of the nature of unsigned arithmetic, AlphaBeta's code handles the overflow boundary condition just fine.

Let's assume "previous" is very large, nearing the "overflow" point at, say, 0xFFFFFFF0. 17 milliseconds have elapsed since previous was last calculated, so millis() has just overflowed and is now 1. In unsigned long C arithmetic,

1 - 0xFFFFFFF0 = 17

Exactly the value you expect.

Mikal