Learning goals
- Be able to design a state machine to model user interaction with a device
- Be able to implement a state machine in a Processing sketch
Introduction
A state machine is an abstract machine that consists of states and transitions. State machines are an extremely useful model for the behavior of computer-based systems.
A state represents “what the system is currently doing”. At any given instance in time, one state is the “current” state. Each state machine has a designated initial state, which is the state that the system will be in when it starts.
A transition represents an event that the system processes. A transition is represented as an arrow leading from one state to another. Usually, transitions lead to a different state, but sometimes a transition might result in the system staying in the same state.
In designing an interactive system such as the one you proposed, modeling its behavior as a state machine is a great way to translate your system requirements into code. State machines are especially useful for interactive systems, where input from sensors will be used to determine the system’s behavior.
Your Task
Your group has two tasks:
- Draw a state machine representing the user interaction model for your system
- Create an Arduino sketch (using the Arduino Processing library) that implements the state machine to carry out the system’s intended dynamic behavior
Example state machine
This is an application (using Processing and Arduino) which detects proximity using a range finder. Normally, the system is “comfortable”, and flashes green. If the proximity falls below a threshold, then someone is “too close” and the application reacts by flashing red. When the proximity increases above the threshold again, the system “cools” off (showing blue until a timer expires) and then returns to the “comfortable” state.
Here is the state diagram:
Translating to Processing
Translating a state machine to Processing is pretty easy.
First, we make an enumeration from the system states:
There is a global (visible to all functions) variable to keep track of the current state:
The draw
function of the Processing sketch will look something like this:
Each state is associated with a function. A state’s function has two responsibilities:
- Generate the outputs for the state
- Read inputs and switch to another state if appopriate
For example, here is the exec_TOO_CLOSE
function:
Each state function returns the next system state. Note that when a function decides to switch to another state, it may need to do some cleanup and/or initialization to get ready for the next state.
Here is the complete sketch: