Arduino finite state machine library

Introducing arduino-fsm, a library that makes it easy to use a finite state machine in an Arduino project.


This library is composed of two classes: Fsm and State:

State Represents a state in the state machine. A state has two callback functions associated with it: on_enter and on_exit, which are called when the state is entered into and exited from, respectively.
Fsm Represents the state machine. Transitions are added using the add_transition function. This function takes pointers to two states, an event id, and a callback to a function that's called when the transition takes place. Calling trigger with the event id invokes the transition, but only if the Fsm is in the start state, otherwise nothing happens.


First create the Fsm and State instances at the top of your source file.

#include <Fsm.h>

Fsm fsm;  
State state_light_on(on_light_on_enter, &on_light_on_exit);  
State state_light_off(on_light_off_enter, &on_light_off_exit);  

In your Setup() function, add the state transitions.

void setup()  
    fsm.add_transition(&state_light_on, &state_light_off,
    fsm.add_transition(&state_light_off, &state_light_on,

In this case, two transitions are added:

  1. From the light on state to the light off state when the event FLIP_LIGHT_SWITCH is triggered;
  2. From the light off state to the light on state when the event FLIP_LIGHT_SWITCH is triggered.

Define your callback functions. If a callback isn't required, just pass NULL to the function instead.

void on_light_on_enter()  
  // Entering LIGHT_ON state

void on_light_on_exit()  
  // Exiting LIGHT_ON state

void on_light_off_enter()  
  // Entering LIGHT_OFF state

void on_light_off_exit()  
  // Exiting LIGHT_OFF state

void on_trans_light_on_light_off()  
  // Transitioned from LIGHT_ON to LIGHT_OFF

void on_trans_light_off_light_on()  
  // Transitioned from LIGHT_OFF to LIGHT_ON

And finally, trigger a state transition.

fsm.trigger(FLIP_LIGHT_SWITCH); // Trigger the event FLIP_LIGHT_SWITCH  

The full source code for this example can be found in the Github repository.

Author image
Creator of Humble Coder and serial hobbyist