State machines: how a robot decides what to do next
As a robot gets smarter, its code turns into a jungle of nested if-statements that nobody can follow. The cure is a state machine: a clean way to organize behavior.
The idea
At any moment the robot is in exactly one state, a mode like "following the line", "avoiding an obstacle", or "searching for a victim". Each state does one job. Transitions are the rules that move it from one state to another when something happens.
FOLLOW_LINE --(sees obstacle)--> AVOID_OBSTACLE
AVOID_OBSTACLE --(back on line)--> FOLLOW_LINE
FOLLOW_LINE --(sees silver strip)--> ENTER_ZONE
Why it helps
- One job at a time: the code for "avoid obstacle" does not have to worry about victims or intersections.
- Predictable: you can draw the whole behavior as a diagram and reason about it.
- Debuggable: print the current state and you instantly know what the robot thinks it is doing.
A Rescue Line example
A camera-based robot might have a "line" machine (following, gaps, obstacles, intersections, ramp) and a "zone" machine (find victims, pick up, deposit, find exit). A top-level mode switches between them when the robot enters or leaves the evacuation zone.
The practical tip
Give every state a name and, while debugging, show it on screen. When something goes wrong, the state tells you where to look: is it stuck in "search", flipping between two states, or entering the wrong one? A named state machine is the difference between a robot you can improve and one you can only pray over.