Macros to create a finite state machine in Arduino
Create a finite state machine in 8 steps
- Include efsm.h
- Define states
- Define inital state
- Define events
- Define transitions
- Define executions
- Define triggers
- Enjoy you fsm!
efsm define C Macros to make easy create a fsm.
#include <efsm.h>
STATES {start, step1, step2, finish};
Is translate to:
enum States{start, step1, step2, finish};
INIT(start);
Is translate to:
enum States state = start;
EVENTS {next, back, end};
Is translate to:
enum Events{next, back, end};
Transitions define changes in state when an event is launched:
TRANSITION(event,initalState,finalState,function())
if(event && state == initalState){
state = finalState;
call function();
}
START_TRANSITIONS
TRANSITION(next,start,step1,printf("next\n"))//execute a function
TRANSITION(next,step1,step2,)//no execute function
END_TRANSITIONS
Executions define funtions to call in each state
EXECUTION(executionState,function())
if(state == executionState){ function(); }
START_EXECUTIONS
EXECUTION(start,printf("start\n"))
EXECUTION(step1,printf("step1\n"))
END_EXECUTIONS
It is not mandatory to use EXECUTIONS
Define conditions to launch events
There are 3 types:
COUNTER(initalState,number,event);
In pseudocode:
if(state == intialState && timesTriggerIsCalledSinLastEvent >= number){
launchEvent(event);
}
TIMER(initalState,milliseconds,event);
In pseudocode:
if(state == intialState && millisecondsSinceLastEvent >= milliseconds){
launchEvent(event);
}
CONDITIONAL(initalState,condition,event);
In pseudocode:
if(state == intialState && condition){
launchEvent(event);
}
START_TRIGGERS
COUNTER(start,5,next); //State start wait 5 iterations and launch event next
TIMER(step1,2000,next); //State step1 wait 2 sg and launch event next
CONDITIONAL(start, digitalRead(buttonPin) == HIGH, restart); //State finish wait until push button an launch event restart
END_TRIGGERS
You need add to loop function:
efsmExecute();
efsmTriggers();
ANY_EVENT
ANY_STATE
Usefull to define events, transactions and triggers
isState(state);
Is true is machine state is state
changeState(state);
Put machine state to state
resetTimer();
Reset time since last event
resetCounter();
Reset counter since last event