Arduino/ESP library to simplify setting up and running a state machine.
- Author: Lennart Hennigs (https://www.lennarthennigs.de)
- Copyright (C) 2023 Lennart Hennigs.
- Released under the MIT license.
This library allows you to quickly setup a State Machine. Read here what a state machine is and why a state machine is neat for hardware projects.
It has been tested with Arduino, ESP8266 and ESP32 devices.
To see the latest changes to the library please take a look at the Changelog.
If you find this library helpful please consider giving it a ⭐️ at GitHub and/or buy me a ☕️. Thanks!
- Easy state definition
- Allows for none, one or multiple final states
- Event triggered transitions and (automatic) timed transitions
- Possibility to define guard conditions for your transitions
- Callback functions for...
- State entry, staying, exit
- Transition execution
- Final state reached
- the run interval of the state machine
- Definition of an in_state interval
- Functions for tracking the behavior and progress of the state machine
- Creation of a
Graphviz
source file of your state machine definition - TBD: Storage of the current state on files with
LittleFS
or SD card storage (TBD)
To see the latest changes to the library please take a look at the Changelog.
- You first need to define a set of states for your state machine
- Then, define transitions (regular or timed) for these state
- Pass the transitions to your state machine
- Define an initial state
- ...and add the
run()
function in your loop - See SimpleTransitions.ino for a basic example
- A finite state machine has a defined set of states
- A state must have a name...
- ...and can have callback functions for different events (when a state is entered, exited, or stays in a state)
State(
String name,
CallbackFunction on_enter,
CallbackFunction on_state = NULL,
CallbackFunction on_exit = NULL,
bool is_final = false
);
-
Most states will have the entry handler
-
The easiest way to define states is creating using an array, e.g. as shown in MixedTransitions.ino:
State s[] = { State("red", on_red), State("green", on_green), State("BTN", on_button_press) };
-
The inital state must of the state machine must be defined – either via the constructor or the
setup()
function or via thesetInitialState()
function -
None, one, or multiple states can be defined as an end state via
setAsFinal()
-
For the full
State
class definition see State.h
- This library offers two types of Transitions, regular and timed ones
- All transitions must have a from and and a to state
- Transitions can have a callback function for when the transition is executed, a name, and a guard condition
- You can add both types to a state machine, see MixedTransitions.ino for an example
- See Transitions.h for the class definitions of
Transition
andTimedTransition
. - Note: Both classes are based of an abstract class which is not to be used in your code.
Transition(
State* from,
State* to,
int event_id,
CallbackFunction on_run = NULL,
String name = "",
GuardCondition guard = NULL
);
-
Regular transitions must have a a set of states and a trigger (ID):
Transition transitions[] = { Transition(&s[0], &s[1], light_switch_flipped), Transition(&s[1], &s[0], light_switch_flipped) };
-
Define the triggers for your state machine in an enum (and set the first enum value to 1, to be safe):
enum triggers { light_switch_flipped = 1 };
-
To call a trigger use the
trigger()
function:fsm.trigger(light_switch_flipped);
-
See SimpleTransitions.ino and SimpleTransitionWithButtons.ino for more details
TimedTransition(
State* from,
State* to,
int interval,
CallbackFunction on_run = NULL,
String name = "",
GuardCondition guard = NULL
);
-
Timed transitions are automatically executed after a certain amount of time has passed
-
The interval is defined in milliseconds:
TimedTransition timedTransitions[] = { TimedTransition(&s[0], &s[1], 6000), TimedTransition(&s[1], &s[0], 4000), TimedTransition(&s[2], &s[1], 2000) };
-
See TimedTransitions.ino for more details
-
Guard conditions are evaluated before a transition takes places
-
Only if the guard condition is true the transition will be executed
-
Both regular and timed transitions can have guard conditions
-
You define guard conditions as functions:
TimedTransition timedTransitions[] = { TimedTransition(&s[0], &s[1], 1000, NULL, "", zero_yet), TimedTransition(&s[0], &s[0], 1000, NULL, "", not_zero_yet) }; bool not_zero_yet() { return countdown != 0; } bool zero_yet() { return countdown == 0; }
-
See Guards.ino for a complete example
- States can have up to three events...
- when they enter a state
- while they are in a state
- ...and when they leave the state
State(String name, CallbackFunction on_enter, CallbackFunction on_state = NULL, CallbackFunction on_exit = NULL, bool is_final = false);
-
To define how frequent the
on_state
event is called, pass an interval (in ms) to therun()
function in your mainloop()
:void run(int interval = 1000, CallbackFunction tick_cb = NULL);
-
After this interval has passed the
on_state
function of the active state will be called (if it defined) -
Also the
tick_cb
callback function will be called (if defined) in therun()
call
-
SimpleFSM provides a few functions to check on the state of the machine:
State* getState() const; State* getPreviousState() const; bool isInState(State* state) const; int lastTransitionedAt() const; bool isFinished() const;
-
Use the function
getDotDefinition()
to get your state machine definition in the GraphViz dot format -
Here the output for the MixedTransitions.ino example:
digraph G { rankdir=LR; pad=0.5 node [shape=circle fixedsize=true width=1.5]; "red light" -> "green light" [label=" (6000ms)"]; "green light" -> "red light" [label=" (4000ms)"]; "button pressed" -> "green light" [label=" (2000ms)"]; "red light" -> "button pressed" [label=" (ID=1)"]; "red light" [style=filled fontcolor=white fillcolor=black]; }
-
If the machine is running, the current state will be highlighted
-
Currently guard functions and end states are not shown in the graph
-
See MixedTransitionsBrowser.ino to learn how to run a webserver to show the Graphviz diagram of your state machine
- State.h
- Transitions.h for the class definition of both transitions
- SimpleFSM
- SimpleTransitions.ino - only regular transitions and showcasing the different events
- SimpleTransitionWithButtons.ino - event is now triggered via a hardware button
- TimedTransitions.ino - showcasing timed transitions
- MixedTransitions.ino - regular and timed transitions
- MixedTransitionsBrowser.ino - creates a webserver to show the Graphviz diagram of the state machine
- Guards.ino - showing how to define guard functions
- This libary is heavily inspiried by the Arduino-fsm library created by Jon Black. I initally used some of his as a base. Without Jon's work this library would not exist.
- To see the latest changes to the library please take a look at the Changelog.
- And if you find this library helpful, please consider giving it a star at GitHub. Thanks!
Open the Arduino IDE choose "Sketch > Include Library" and search for "SimpleFSM". Or download the ZIP archive (https://github.com/lennarthennigs/SimpleFSM/zipball/master), and choose "Sketch > Include Library > Add .ZIP Library..." and select the downloaded file.
MIT License
Copyright (c) 2023 Lennart Hennigs
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.