A Finite State Machine has predefined states. Each state can have an optional Entry and an Exit method. When machine is in certain state, it can take actions based on the state and the input.
Arduino has been a versatile platform for creating hobby and proof of concept hardware projects. One can connect various shields to it, read data from them and perform operations on them.
In some projects, Arduino sketch needs to perform actions based on the readings from the shields. The actions are simply changing the state(s) of the output digital pins based on the readings and the current state. In such cases, Finite State Machine design pattern would be the most suitable solution. It is easy to maintain and ready for expansion.
It can be implemented in Arduino sketch with a simplistic approach. To implement the pattern, define all the required States and declare a variable to host current state. Apart from Arduino’s setup and loop methods, add two methods to the Arduino’s sketch.
- ChangeState
This method will be responsible for calling exit method for the old state, changing the current state and calling init method for the new state. The init method will initialize the state. (e.g. reset timer counter, turn pin high/low etc.)
(The example code calls only the init method, as the sample does not require processing of any exit state) - ProcessState
This will be called in the loop. Based on the current state, the loop method will call the appropriate method to process the current state. The method will take the required actions for the state (e.g. turn pin high/low, check if the timer interval has reached, check the value(s) of the pin/shield input(s)) and call ChangeState, as required.
The initial state can be set by calling ChangeState in the setup method. This implementation can be extended by declaring additional states and corresponding the init and process methods for the new states.
An example of the above can be found on hackster.io:
https://www.hackster.io/sameerk/keep-the-wifi-on-4f32ba
The code for it, is on GitHub:
https://github.com/sameerkapps/KeepTheWiFiOn