// from http://c-faq.com/decl/recurfuncp.html
// Mod by JDN for Arduino
//
// Simple efficent way to model state machines in C
typedef void *(*pFunc)(); // for typecast for calling function
#define NEXT(x,y,z) return ((void *)x)
// States -- you need this forward dcl for the compiler and calling
// led-off --> led-on ---|
// ^-------------------|
// all driven from main (or here setup fct)
void *led_on(); // as name indicates ...
void *led_off();
pFunc statefunc = led_on, oldfunc = led_on;
void *led_on() {
digitalWrite(13,HIGH);
delay(1000); // sleep for a second
NEXT(led_off, led_on,arctext2);
}
void *led_off() {
digitalWrite(13,LOW);
delay(1000); // sleep for a second
NEXT(led_on, led_off,arctext);
}
void setup() {
pinMode(13,OUTPUT);
}
/*
* The idea
* Variable named statefunc(aka state) holds address of next function to be called
* when you leave a function you simply return reference to enxt function or state to be called
* This address is stored in variable statefunc.
* The code loops and call again and now we call next state
* Instead of having code in loop you could have it every where like
*
* while (1) {
* oldfunc = statefunc; // just if you want to see the previous state - debugging !!!
* statefunc = (pFunc)(*statefunc)();
* }
*
*/
void loop() {
oldfunc = statefunc; // just if you want to see the previous state - debugging !!!
statefunc = (pFunc)(*statefunc)();
}