Programming Robot Behavior
Use sequences, loops, conditionals and state machines to plan robot behavior, read flowcharts and write a small obstacle-avoidance function in code.
Welcome back!
Step 1 of 11Learn
The robot that drove into the hallway
A team programs their robot to drive a square: forward 1 meter, turn right 90 degrees, repeat four times. In the classroom, it works. In the hallway, the floor is slicker, the wheels slip on each turn, and after four "right angles" the robot is pointing in a different direction and heading for the stairs.
That program was a pure sequence: a list of instructions run in order, with no sensing. Sequences are the simplest way to program a robot, and they're fine when the world is predictable. But robots exist to deal with an unpredictable world, so real robot programs also use loops and conditionals, and they read sensors constantly.
The three basic building blocks of any program:
- Sequence: do this, then this, then this.
- Loop: repeat some steps, either a set number of times ("repeat 4 times") or forever, or until something happens ("until the bump switch is pressed").
- Conditional (if/else): choose what to do based on a test. "If the distance is less than 20 cm, turn; otherwise, drive forward."
Almost every robot program has a main loop that runs forever, many times a second: read the sensors, decide, set the motors, repeat. That's the sense-think-act cycle written in code.
Step 2 of 11Practice · Put in order
Put the steps of a typical robot main loop in order, starting from the top of the loop.
Drag the items, or use the arrow buttons, to put them in order.
- Go back to the top and repeat
- Decide what to do based on the readings
- Send commands to the motors
- Read the sensors
Step 3 of 11Diagram
The main loop, round and round
Tap a shape with to see more.
- Read sensors
Distance, line, encoders, buttons.
- Decide
If-statements or the current state choose an action.
- Command motors
Set speeds and directions.
- Short pause
Optional: keeps the loop timing steady.
Step 4 of 11Learn
Pseudocode and flowcharts
Before writing real code, roboticists often plan in pseudocode, plain-language steps that look like code but ignore exact syntax, or draw a flowchart, where boxes are actions, diamonds are decisions and arrows show the order.
Here's pseudocode for a simple obstacle-avoiding robot:
forever: distance = read ultrasonic sensor if distance < 20 cm: stop turn right for 0.5 seconds else: drive forward
In a flowchart, "distance < 20 cm?" would be a diamond with two arrows: yes leads to the stop-and-turn boxes, no leads to "drive forward." Both paths loop back to "read sensor."
Planning this way catches logic mistakes before they turn into crashes. Common ones:
- Forgetting the loop, so the robot checks the sensor once and then drives forever.
- Blocking waits. If the robot waits for two seconds during a turn, it can't read any sensors in that time and may turn into something else.
- Missing cases. What happens if the sensor gets no echo at all? Some sensors report 0 or a huge number, which the code must handle.
- Wrong comparisons, such as > instead of <, which makes the robot turn when the path is clear and charge ahead when it's blocked.
Step 5 of 11Practice · Spot the mistake
This pseudocode should make a robot turn when an obstacle is close. Tap the line with the logic error.
Step 6 of 11Practice · Code challenge
Write a function decide(distanceCm) for an obstacle-avoiding robot. Return "forward" when the distance is 20 cm or more, "turn" when it is at least 5 cm but less than 20 cm, and "reverse" when it is less than 5 cm (too close to turn safely).
decide(50)decide(20)decide(12)decide(5)decide(3)
Step 7 of 11Practice · Diagram
The decide() rules on a distance line
Which reading is the edge case most likely to catch a bug (using < instead of <=, for example)?
Tap the shape that answers the question, then press Check.
- 3 cm
3 cm
- 12 cm
12 cm
- exactly 20 cm
20 cm
- 35 cm
35 cm
Step 8 of 11Learn
State machines: robots with moods
As behavior gets more complex, nested if-statements become a tangle. Roboticists organize behavior with a state machine: the robot is always in exactly one state, and specific events cause transitions to other states.
A robot vacuum might have these states:
- CLEANING: drive around, brushes on. If bumped, go to AVOIDING. If battery is low, go to RETURNING.
- AVOIDING: back up and turn a random angle. When done, go back to CLEANING.
- RETURNING: follow the dock's signal. When docked, go to CHARGING.
- CHARGING: wait. When full, go to CLEANING.
Each state has simple rules, and the program only has to ask, "What state am I in, and did anything happen that should change it?" This makes behavior easier to design, test and explain. You can draw the whole thing as circles (states) connected by labeled arrows (transitions).
State machines also fix the blocking-wait problem. Instead of freezing for two seconds during a turn, the robot enters a TURNING state, notes the start time and keeps looping, reading sensors each time, until two seconds have passed. Video game characters, traffic lights, elevators and vending machines are all commonly built as state machines.
Step 9 of 11Note
Step 10 of 11Practice · Diagram
The traffic light as a state machine
The light is RED and its timer runs out. Which state comes next?
Tap the shape that answers the question, then press Check.
- GREEN
Leaves after a set time.
- YELLOW
Leaves after a short time.
- RED
Leaves after a set time, or sooner if the pedestrian cycle ends.
Step 11 of 11Practice · Choose one
A delivery robot is in its DRIVING state when its bumper is pressed. Using a state machine, what is the clearest design?
Lesson complete!