...
A change from one state to another is called a transition. In the example state diagram above, these transitions are sometimes triggered by timing events and sometimes by external inputs.
The example below demonstrates a simple approximation of an FSMFSM using the switch statement, and one variable to store the state.
Code Block | ||
---|---|---|
| ||
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("Enter START state"); delay(10); myState = FORWARD; break; case FORWARD: Serial.println("Enter FORWARD state"); Serial.println("Move Forward"); // action if (analogRead(A0)<100) { myState = REVERSE; } delay(500); break; case REVERSE: Serial.println("Enter REVERSE state"); Serial.println("Move Backward"); // action myState = LEFT; delay(500); break; case LEFT: Serial.println("Enter LEFT state"); Serial.println("Move Left"); // action delay(500); myState = FORWARD; break; } } |
If you use an FSM library for Arduino, you can use some more advanced features such as enter, exit and transition functions that might be useful for organising your code and solving some more specific challenges. For example, you can use the enter function to record a timestamp, then use the exit function to print out over serial how long the Arduino was in a given state based on the timestamp.
It’s also common to see an enumeration declaration used to keep track of states.
Code Block | ||
---|---|---|
| ||
enum machineStates { START, // blink disable FORWARD, // blink enable LEFT, // we want the led to be on for interval REVERSE // we want the led to be off for interval }; enum machineStates myState; |