Arduino finite state machine library

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

Design

This library is composed of two classes:

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 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.

Tutorial

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

1#include <Fsm.h>
2
3#define FLIP_LIGHT_SWITCH 1
4Fsm fsm;
5State state_light_on(on_light_on_enter, &on_light_on_exit);
6State state_light_off(on_light_off_enter, &on_light_off_exit);

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

1void setup()
2{
3    fsm.add_transition(&state_light_on, &state_light_off,
4                       FLIP_LIGHT_SWITCH,
5                       &on_trans_light_on_light_off);
6    fsm.add_transition(&state_light_off, &state_light_on,
7                       FLIP_LIGHT_SWITCH,
8                       &on_trans_light_off_light_on);
9}

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.

 1void on_light_on_enter()
 2{
 3  // Entering LIGHT_ON state
 4}
 5
 6void on_light_on_exit()
 7{
 8  // Exiting LIGHT_ON state
 9}
10
11void on_light_off_enter()
12{
13  // Entering LIGHT_OFF state
14}
15
16void on_light_off_exit()
17{
18  // Exiting LIGHT_OFF state
19}
20
21void on_trans_light_on_light_off()
22{
23  // Transitioned from LIGHT_ON to LIGHT_OFF
24}
25
26void on_trans_light_off_light_on()
27{
28  // Transitioned from LIGHT_OFF to LIGHT_ON
29}

And finally, trigger a state transition.

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

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