A finite-state machine (FSM) is a mathematical model of computation. It is an abstract machine that can only be one state, out of a limited number of states at any given time. The FSM can change state in response to an input or event. An FSM is defined by a list of its states, its initial state, and the inputs that trigger each transition. FSM are useful for a number of situations to code interactive behaviour.
This simple FSM below describes the behaviour of a robot that attempts to avoid obstacles based on a distance sensor pointing forward. Whenever the distance sensor measures an obstacle less than 100 millimetres in front, it will reverse and then try to steer to the left. Similar algorithms allow vacuum-cleaning robots to navigate around complex spaces.
A change from one state to another is called a transition. In the example above, these transitions are sometimes triggered by timing events and sometimes by external inputs.
The example below demonstrates a simple approximation of an FSM
const byte START = 0; const byte FORWARD = 1; const byte LEFT = 2; const byte REVERSE = 3; byte myState; void setup() { Serial.begin(9600); myState = START; // Initial State } void loop() { switch (myState) { case START: Serial.println("START state"); delay(10); myState = FORWARD; break; case FORWARD: Serial.println("Move Forward"); if (analogRead(A0)<100) { myState = REVERSE; } delay(500); break; case REVERSE: Serial.println("Move Backward"); myState = LEFT; delay(500); break; case LEFT: Serial.println("Move Left"); delay(500); myState = FORWARD; break; } }