Debugging code
What you’ll learn
- The three kinds of bug
- A step-by-step debugging method
- Tools: error messages, prints, and testing in isolation
Three kinds of bug
| Kind | What happens | Example |
|---|---|---|
| Syntax | The code won’t compile or run | Missing ; or } |
| Runtime | It runs, then crashes or freezes | A loop that never ends |
| Logic | It runs but does the wrong thing | < instead of > |
The method
- Reproduce it. Make the bug happen on purpose, reliably.
- Read the error message, including the line number (and the line before it).
- Print what’s really happening: sensor values, which
ifbranch ran, variable values. - Isolate: test the smallest piece alone (just the sensor, just one motor).
- Change one thing, test, and repeat.
- Explain it out loud (“rubber duck debugging”): describing the code line by line often reveals the bug.
Common robot bugs
=(assign) instead of==(compare) in anif.- Wrong pin number in code versus wiring.
- Sensor logic upside down (HIGH vs LOW).
- Motors wired backwards, so “left” turns right.
intused formillis().- A
delay()so long the robot can’t react.
Example: printing which branch ran
function loop() { const d = distance(); if (d < 25) { print("TURN, d=" + d); motors(-40, 40); } else { motors(60, 60); }}If “TURN” never prints even when the robot hits a wall, the condition or the sensor reading is wrong.
Example: a logic bug
if (distance > 20) { // bug: this stops when the path is CLEAR stopMotors();}Printing distance and “stopping” shows it stops at 80 cm and drives at 10 cm. The fix: <.
Try it: fix the broken robot
This code is meant to drive forward and turn away from obstacles, but it has three bugs. Use print() to find them.
Robot commands
motors(left, right): wheel power, −100 to 100lineLeft(),lineRight():trueover the black linedistance(): cm to the nearest thing ahead (max 200)distanceLeft(),distanceRight(): cm to the sideslinePosition(): where the line is, −1 (left) to 1 (right), ornullmillis(): milliseconds since Runprint(value): show a message belowsetup()runs once;loop()runs 50 times a second
Find bug 1Easy
The robot spins in the open and drives into walls. Why?
The condition is backwards: it should be if (d < 25).
Find bug 2Medium
“very close!” prints all the time. Why?
d = 5 assigns 5 to d (which counts as true) instead of comparing. Use d < 5 (or === for an exact match).
Find bug 3Hard
After fixing both, the robot sometimes scrapes past box corners. What’s the cause, and how would you find it?
Print distanceLeft() and distanceRight() while it drives past a box.
Only the front sensor is checked, and corners slip past it. Also turn away when a side distance is very small, for example if (d < 25 || distanceLeft() < 8 || distanceRight() < 8).
Quick check
Finished this lesson?