sm001 A state machine in C

Transporting a struct from state to state.

You can move info around betwen the states

All include in the C source below is just for printing and sleep

raw sm001.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define NRPARM 4

typedef struct stateTp {
  int parm[NRPARM];
  void (*ptr2state)(struct stateTp * stateInfo);
} stateTp;

void init(stateTp * stateInfo);
void ledOn(stateTp * stateInfo);
void ledOff(stateTp * stateInfo);



void init(stateTp * stateInfo)
{
  printf("\ninit\n");
  stateInfo->parm[0]++;

  sleep(1);

  stateInfo->ptr2state = ledOn;
  return;
}

void ledOn(stateTp * stateInfo)
{
  printf("\nledOn\n");
  stateInfo->parm[1]++;

  sleep(1);

  stateInfo->ptr2state = ledOff;
  return;
}

void ledOff(stateTp * stateInfo)
{
  printf("\nledOff\n");
  stateInfo->parm[2]++;

  sleep(1);

  stateInfo->ptr2state = 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.ptr2state = 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 :-)
    (*curState.ptr2state)(&curState);
  }
}