Finite State Machine Basics

Status
Not open for further replies.

misterT

Well-Known Member
Most Helpful Member
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:


your code will not compile for sure ...
void hello(void) {
//...
{
//wrong closing bracket !

beside that here my 2 cents on FSM ...

using function pointer is fine and elegant,
but I prefer to used switch and a local state variable,

why ...
- all states of the FSM are enclose into a function or a block of code, more easy to trace while reading the code and more easy to debug too

- compilers are pretty go at optimizing jump table in a switch, so basicly no a slow thing.



Code:
static u8 state = 0;
//....

for(;;){
    switch( state ) {
    case 0:
       //
       state = 1;
       break;
    case 1:
        //
        state = 0;
        break;
     }
  }
 


your code will not compile for sure ...
void hello(void) {
//...
{
//wrong closing bracket !

Thanks for pointing that out.. silly mistake.

switch-case is the most awful structure in C language. It is so error prone. I prefer "if-else if" over "switch-case". I think it is safer, easier and elegant.. and the compiler does equally good job with it.

Also I prefer to write human readable code.
Compare:

state = 1;

vs.

next_state = write_hello;
 
Last edited:
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…