Using Finite State Machine with Arduino

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.

  1. 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)
  2. 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

The code for it, is on GitHub:


Published by: Sameer Khandekar

I am a passionate software engineer who loves to work on Azure microservices, REST API, SDKs, and .NET apps using WPF, Xamarin, and MAUI. The work includes highly scalable geo-distributed services and an authentication library with nearly 500 million downloads. I also had fun integrating with hardware using Bluetooth (BLE). More here:

Categories Arduino, Design PatternsTags, Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s