A small, reusable Finite State Machine (FSM) library for Arduino, ESP32, and other embedded platforms.
- Lightweight and generic
- Automatic state transitions using exit codes
- Optional timeouts per state
- Recoverable fallback to the previous state
- Works with Arduino IDE and PlatformIO
- Cycle-driven: no threading, just main loop execution
- Download the library ZIP from GitHub
- Open Sketch → Include Library → Add .ZIP Library
- Select the ZIP file
Add this to platformio.ini:
lib_deps =
https://github.com/TimothyFran/StateMachine.gitOr copy the StateMachine folder into your project's lib/ directory.
Use StateMachine to register a sequence of states, then call initialize() in setup() and handleCurrentState() in loop().
Each state inherits from BaseState and implements:
boot()— called when the state startshandle()— called repeatedly while the state is activeclose()— called when the state finishesgetStateName()— optional debug name
States return a StateExitCode to decide what happens next.
#include <StateMachine.h>
class MyState : public BaseState {
public:
MyState() : BaseState(500, 5000, false) {}
void boot() override {
Serial.println("State started");
}
StateExitCode handle() override {
if (someCondition) {
return StateExitCode::PROCEED_TO_NEXT;
}
return StateExitCode::CONTINUE;
}
void close() override {
Serial.println("State ended");
}
const char* getStateName() const override {
return "MY_STATE";
}
};
StateMachine stateMachine;
void setup() {
std::vector<std::unique_ptr<BaseState>> states;
states.push_back(std::make_unique<MyState>());
states.push_back(std::make_unique<AnotherState>());
stateMachine.registerStates(std::move(states));
stateMachine.initialize();
}
void loop() {
stateMachine.handleCurrentState();
}- Register your states
- Initialize the machine in
setup() - Call
handleCurrentState()repeatedly inloop() - The library runs the current state, checks its exit code, and transitions as needed
- Use
BaseStateconstructors to set state timeout and check interval StateExitCode::FAILEDcan fallback to the previous stateStateExitCode::TIMED_OUThandles state timeout conditions
MIT