A Finite State Machine (FSM) consist of number of states. For example "waiting for character". When the character comes in, the machine changes to another state. This is called a state transition. There are many ways to implement FSM. Some are complex and some are very straight forward. Using function pointer may sound complex at first, but it is actually quite simple, but powerful way to implement FSM. Below is a very minimalistic state machine that writes "Hello World!" repeatedly using some function write().
C:
/* Declare the function pointer. Variable 'state_machine' is a pointer to a function that takes no parameters and doesn't return anything. */
void (*state_machine)(void);
/* State functions */
void hello(void) {
write("Hello ");
state_machine = world; // State transition
}
void world(void) {
write("World!");
state_machine = newline; // State transition
}
void newline(void) {
write("\n");
state_machine = hello; // State transition
}
/* Main function */
void main(void){
state_machine = hello; // Initialize function pointer to the first state
while(1){
state_machine(); // This is all that is needed to keep FSM running
}
}
Last edited: