Finite State Machine, Arduino style
So I set out to build a FSM in C on the Arduino, using events.
The FSM is modeled as a set of states and a set of transitions between states. This is the state diagram for the state machine that was implemented:
The system transitions between states depending on its current state and the event that was triggered. Unfortunately there are no events in straight up C for the Atmega328, so we have to “fake it”. Events are fired when a button or light dependent resistor changes state (low to high). Thus, if a button was unpressed, an EVENT_BUTTON_DOWN event is fired when the button is pushed.
During each iteration of the main loop, the system checks to see if a new event was fired. It if was, it checks up the transitions available at the current state in the transition table. If a transition at the current state has an event that matches the most recently fired event, then that transition is taken, and the current system state is changed. This allows the system to move between states.
This is the way the circuit is set up:
And here’s a video of it in action:
Finally, here’s the code:MTI_EX_8
I highly recommend reading the code to see exactly how it works, its commented and gives a more indepth explanation of how the system works.