Concept
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: