sm002 - A state machine in Cwith lookup table(array) etc all include in the C source below is just for printing and sleep #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define NRPARM 4 // identify state by nr (0,1,2,3) typedef struct stateTp { int parm[NRPARM]; int state; } stateTp; void init(stateTp * stateInfo); void ledOn(stateTp * stateInfo); void ledOff(stateTp * stateInfo); const int INIT = 0; const int LEDON = 1; const int LEDOFF = 2; void (*stateFunc[])(struct stateTp *ss) = {init, ledOn, ledOff}; // state 0 1 2 ... void init(stateTp * stateInfo) { printf("\ninit\n"); stateInfo->parm[0]++; sleep(1); stateInfo->state = LEDON; return; } void ledOn(stateTp * stateInfo) { printf("\nledOn\n"); stateInfo->parm[1]++; sleep(1); stateInfo->state = LEDOFF; return; } void ledOff(stateTp * stateInfo) { printf("\nledOff\n"); stateInfo->parm[2]++; sleep(1); stateInfo->state = LEDON; return; } int enVar; int *ptr2enVar; void dumpVars(stateTp * stateInfo) { printf("\ndumpVars in state variable"); for (int i = 0; i < NRPARM; i++) { printf("%i ", stateInfo->parm[i]); } } int main() { stateTp curState; curState.state = INIT; for (int i = 0 ; i < NRPARM; i++) { curState.parm[i] = 0; } printf("\nstarting state machine\n"); while (1) { printf("\nback in scheduler"); dumpVars(&curState); // debug :-) (*stateFunc[curState.state])(&curState); } } |