Robot Behaviors and Autonomous Navigation
Welcome, maker — this is the chapter you've been building toward!
Motors, sensors, displays, functions, loops — you've built every piece separately. In this chapter, we wire them all together into a robot that navigates on its own. Collision avoidance. Line following. Even a dance routine. Computational thinking is YOUR superpower — and this chapter is proof.
Summary
This chapter is where all prior skills converge into autonomous robot behavior. Students implement open-loop and closed-loop (feedback) motor control, build a full collision avoidance algorithm with obstacle detection, distance thresholds, and random turn logic, and construct a dual-sensor line follower with motor differential adjustment. The chapter also covers robot dance sequences, timed motor patterns, and the config/secrets/gitignore file patterns that every well-organized robot project should use.
Concepts Covered
This chapter covers the following 18 concepts from the learning graph:
- Open-Loop Motor Control
- Closed-Loop Feedback
- Feedback Loop
- Collision Avoidance
- Obstacle Detection
- Distance Threshold
- Random Turn Direction
- Collision Avoidance Code
- Line Following
- Dual IR Sensor Reading
- Motor Differential Adjust
- Line Following Code
- Robot Dance Sequence
- Timed Motor Patterns
- Config File Pattern
- Pin Assignment Constants
- Secrets File Pattern
- Gitignore File
Prerequisites
This chapter builds on concepts from:
- Chapter 4: Control Flow, Functions, and Exception Handling
- Chapter 5: Data Structures, Modular Programming, and Version Control
- Chapter 7: PWM, Motor Speed Control, and Actuators
- Chapter 8: Sensors and Data Input
Open-Loop vs. Closed-Loop Motor Control
Before building behaviors, we need to understand two fundamentally different approaches to motor control. This distinction is the foundation of robotics and control engineering.
Open-Loop Motor Control
Open-loop motor control sends a command to the motors and does nothing to verify the result. You say "go forward at 50% speed" and trust that it happens. No sensor checks. No correction.
Open-loop is simple and works fine for timed patterns — "drive forward for 2 seconds, then turn for 0.5 seconds." The problem is that real motors are imperfect. One motor may be slightly faster than the other. The battery voltage drops as it drains. These factors cause drift — the robot veers off course over time.
1 2 3 4 5 6 7 8 9 10 11 | |
Open-loop works for choreographed sequences where the path is pre-planned. It fails for reactive navigation.
Closed-Loop Feedback
Closed-loop feedback continuously measures the output (what is actually happening) and compares it to the goal (what should be happening). If there is a difference (called the error), the controller adjusts its output to reduce that error.
The feedback loop is the cycle:
- Sense — read the current state (sensor value)
- Compare — how far is the current state from the goal?
- Act — adjust the motor output to reduce the difference
- Repeat — go back to step 1
For collision avoidance, the sensor is the ToF distance sensor. The goal is "maintain a safe distance." When the measured distance drops below the threshold, the motors respond. That is a closed feedback loop.
Diagram: Open-Loop vs. Closed-Loop Control
Run Open-Loop vs. Closed-Loop Control Fullscreen
Interactive diagram comparing open-loop and closed-loop control systems
Type: diagram
sim-id: open-closed-loop-comparison
Library: Mermaid
Status: Specified
Create two Mermaid flowcharts side by side (use subgraph):
Left subgraph "Open-Loop": Controller → Actuator (Motors) → Output (Robot Motion) No feedback arrow.
Right subgraph "Closed-Loop": Controller → Actuator (Motors) → Output (Robot Motion) → Sensor (Distance) → Error Calculation → Controller (loop back)
Every node has a click directive opening an infobox explaining that component's role. Error node infobox explains: "Error = Goal distance - Measured distance. If error > 0, speed up. If error < 0, slow down or stop."
Canvas: 700 × 300 px. Responsive on window resize.
Why does feedback matter?
Think about riding a bicycle. You don't look at your hands once, set the handlebar angle, and close your eyes — you constantly check where you're going and adjust. That's closed-loop control. Your eyes are the sensor, your brain is the controller, your arms are the actuators. The robot works the same way.
Collision Avoidance
Collision avoidance is the behavior of detecting an obstacle and changing course before hitting it. It is the most fundamental autonomous robot behavior — and the first one we will fully implement.
Obstacle Detection and Distance Threshold
Obstacle detection means determining whether an object is close enough to be a concern. We use the ToF sensor to measure distance, then compare it to a distance threshold — a fixed value that defines "too close."
In this course, we use two thresholds:
- Warning threshold (50 cm): slow down
- Stop threshold (20 cm): stop and turn
Before the code, here is the decision logic: if distance is above 50 cm, drive forward at full speed. If it drops to 20–50 cm, slow down. If it drops below 20 cm, stop and pick a random turn direction.
Random Turn Direction
Random turn direction prevents the robot from getting stuck in a corner. If the robot always turned left when it hit an obstacle, it could end up running in tight circles or stuck in a left-corner trap. By randomly choosing left or right, the robot explores the space more efficiently.
Before the code, here is how randomness works in MicroPython: random.choice([True, False]) returns True or False with equal probability. We interpret True as "turn left" and False as "turn right."
1 2 3 4 | |
The Complete Collision Avoidance Algorithm
Now let's build the full collision avoidance behavior. Before the code, here is the overall structure: we have five movement functions (go_forward, go_slow, stop_motors, turn_left, turn_right). The main loop reads the sensor, decides the response, and calls the appropriate function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | |
This is a complete, production-quality collision avoidance program. The constants STOP_DIST_CM and SLOW_DIST_CM are easy to tune without touching the logic. The finally block guarantees the motors stop.
Tune your thresholds on the actual floor
The 20 cm and 50 cm values are starting points, not magic numbers. Run the robot on your actual test surface, observe where it stops, and adjust. A robot on carpet needs different thresholds than one on tile. A competition arena is different from a classroom floor. Tuning is part of the engineering process — expect to iterate.
Line Following
Line following is the behavior of keeping the robot on a track — usually a black tape line on a white surface. It is one of the classic competitions in educational robotics.
Dual IR Sensor Reading
Line-following robots use two infrared sensors mounted at the front, spaced about the width of the line apart. The sensors point down at the surface. When a sensor is over the black line, it reads LOW (line detected). When over the white surface, it reads HIGH (no line).
This dual-sensor arrangement gives four possible states:
| Left IR | Right IR | Meaning | Action |
|---|---|---|---|
| HIGH | HIGH | Both off the line | Turn — line is lost |
| LOW | HIGH | Left on line, right off | Turn right to center |
| HIGH | LOW | Right on line, left off | Turn left to center |
| LOW | LOW | Both on line (wide line) | Drive straight |
1 2 3 4 5 | |
Motor Differential Adjust
Motor differential adjust means running one motor faster than the other to steer back onto the line. Rather than making sharp turns, we adjust speed gradually — smoother tracking.
For example, when the left sensor detects the line and the right doesn't (robot drifted left), we need to turn right. We slow the left motor and keep the right at full speed:
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
The Complete Line Following Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
IR sensors are sensitive to surface and light
Bright sunlight or fluorescent flicker can confuse IR sensors. Test your line follower in the same lighting conditions you'll use for the actual run. If the robot misbehaves in a specific area, check for shadows, shiny surfaces, or light reflections — not always the code's fault.
Robot Dance Sequence
A robot dance sequence is a choreographed series of timed motor patterns. Unlike the reactive behaviors above (which respond to sensor input), a dance is fully open-loop — every move is timed in advance. This is a great creative challenge: design a dance using only forward, backward, left turn, right turn, and spin.
Timed motor patterns are just calls to motor functions followed by sleep(). The key is counting beats: if your song is 120 BPM (beats per minute), one beat = 60/120 = 0.5 seconds.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
Encourage creativity here: try adding buzzer tones, NeoPixel color changes, and OLED face changes synchronized with motor moves. A robot that blinks, beeps, and dances is memorable.
Config, Secrets, and .gitignore in Production
This is a good moment to revisit the file organization patterns from Chapter 5, now that you have a complete robot program. Every production-quality robot project should use all three.
Config File Pattern and Pin Assignment Constants
Config file pattern: All hardware pin numbers and calibration constants live in config.py, not in main.py. This was introduced in Chapter 5. Here is the complete config.py for the full course robot:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
Pin assignment constants in UPPERCASE signal that these values are fixed hardware facts, not runtime variables.
Secrets File Pattern
Secrets file pattern: WiFi credentials live in secrets.py, a separate file that is never committed to version control:
1 2 3 | |
In main.py, import only what you need:
1 | |
Gitignore File
The .gitignore file in your project root prevents secrets.py (and other unwanted files) from being committed:
1 2 3 4 | |
With these three files in place (config.py, secrets.py, .gitignore), your project follows professional engineering standards: hardware facts are separated from logic, credentials are protected, and your repository is clean.
Key Takeaways
- Open-loop control sends commands without feedback — good for timed sequences, drifts over time
- Closed-loop feedback continuously senses and corrects — essential for reactive navigation
- Collision avoidance uses distance thresholds to trigger stop and random turn behaviors
- Random turn direction prevents the robot from getting trapped in corners
- Line following reads dual IR sensors and uses motor differential to stay on a track
- Motor differential adjust steers by running one wheel faster than the other — no steering servo needed
- Robot dance sequences are open-loop timed patterns — combine with sound and lights for performance
- config.py holds all pin constants; secrets.py holds WiFi credentials; .gitignore protects secrets
Your robot navigates the world on its own — you did that!
Double thumbs-up, engineer! Collision avoidance, line following, a dance routine — these behaviors combine every skill from the past nine chapters. The next chapter adds WiFi: your robot becomes internet-connected and browser-controlled. The journey keeps going!