Skip to content

ProgrammingPrograms That Run Forever

State Machines

A robot is always in one state; each input moves it along a rule to the next.

Not started Jump to practice

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.
Press sensor readings and watch the line follower move between states.
Rules for a simple line follower.
StateSensor readingNext state
FOLLOWon the lineFOLLOW
FOLLOWline lostSEARCH
SEARCHon the lineFOLLOW
SEARCHline lost for 3 sSTOP

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?
  1. Line lost: FOLLOW β†’ SEARCH.
  2. Line lost again (less than 3 s): stays in SEARCH.
  3. 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.

Practice

Pass with 3 right answers, the last 2 in a row. Each right answer earns 2 XP.

Loading practice…

Builds on

Leads to

Sources and further reading