A robot that only reacts to what it senses right now forgets what it was doing. A state machine gives it a memory.
Key idea
A state machine has a set of states (like SEARCH, FOLLOW, LOST). The robot is in exactly one state at a time. Each loop it reads its sensors, and a table of rules says which state comes next.
| State | Sensor reading | Next state |
|---|---|---|
| FOLLOW | on the line | FOLLOW |
| FOLLOW | line lost | SEARCH |
| SEARCH | on the line | FOLLOW |
| SEARCH | line lost for 3 s | STOP |
Why it works
Writing the states and rules down first makes the behavior easy to check. It also makes timeouts possible: the robot can know how long it has been searching.
Worked example: Follow the rules
The robot is in FOLLOW. It reads: line lost, line lost, on the line. Which state is it in after each reading?
- Line lost: FOLLOW β SEARCH.
- Line lost again (less than 3 s): stays in SEARCH.
- On the line: SEARCH β FOLLOW.
Answer: SEARCH, SEARCH, FOLLOW.
Common mistake
Long chains of if statements with no state variable. The robot then cannot tell "I just lost the line" from "I have been lost for a minute."
In code, keep one variable such as state = 'FOLLOW', and in the main loop use if and elif on it to decide what to do and what state comes next.