I have written a simple state machine. Comments and feedback are welcome.
#include <stdio.h>
#include <stdlib.h>
typedef enum Event
{
eEVENT_X,
eEVENT_Y,
eEVENT_Z,
}Event;
typedef enum States
{
eSTATE_X,
eSTATE_Y,
eSTATE_Z
}States;
int e = eEVENT_X;
int s = eSTATE_X;
struct state_transition
{
Event EventId;
States StateId;
void (*function)(void); //call back utility
};
#define NSTATES 3
#define NEVENTS 3
#define STATE_END 3
#define EVENT_END 3
void function_eXsX(void)
{
printf("\n xx \n");
e = eEVENT_X;
s = eSTATE_Y;
}
void function_eXsY(void)
{
printf("\n xy \n");
e = eEVENT_X;
s = eSTATE_Z;
}
void function_eXsZ(void)
{
printf("\n xz \n");
e = eEVENT_Y;
s = eSTATE_X;
}
void function_eYsX(void)
{
printf("\n yx \n");
e = eEVENT_Y;
s = eSTATE_Y;
}
void function_eYsY(void)
{
printf("\n yy \n");
e = eEVENT_Y;
s = eSTATE_Z;
}
void function_eYsZ(void)
{
printf("\n yz \n");
e = eEVENT_Z;
s = eSTATE_X;
}
void function_eZsX(void)
{
printf("\n zx \n");
e = eEVENT_Z;
s = eSTATE_Y;
}
void function_eZsY(void)
{
printf("\n zy \n");
e = eEVENT_Z;
s = eSTATE_Z;
}
void function_eZsZ(void)
{
printf("\n zz \n");
e = EVENT_END;
s = STATE_END;
}
struct state_transition stateTrans[NEVENTS][NSTATES] =
{
{{eEVENT_X,eSTATE_X,function_eXsX},{eEVENT_X,eSTATE_Y,function_eXsY},{eEVENT_X,eSTATE_Z,function_eXsZ}},
{{eEVENT_Y,eSTATE_X,function_eYsX},{eEVENT_Y,eSTATE_Y,function_eYsY},{eEVENT_Y,eSTATE_Z,function_eYsZ}},
{{eEVENT_Z,eSTATE_X,function_eZsX},{eEVENT_Z,eSTATE_Y,function_eZsY},{eEVENT_Z,eSTATE_Z,function_eZsZ}},
};
int main(int argc,char *argv[])
{
while(1)
{
stateTrans[e][s].function();
if(e == STATE_END && s == EVENT_END)
break;
}
return 0;
}