Motion · Lesson 02a
Follow the line
This is the written walk-through of the lesson: the idea, stage by stage, plus the deeper asides. The interactive version, where you write real Python in the browser and drive a simulated robot, lives on the lesson page.
A sensor out front
Your robot can drive, but it wanders: nothing tells it where the line is. This lesson gives it eyes. A line sensor is mounted out front, and you write the logic to steer back.
The sensor reads one number every tick, the offset: how far off-center the robot sits from the line, in pixels. Watch the readout on the right as the bot drives. When the offset is positive the robot has drifted to the right of the line; when it is negative, to the left; at zero it is dead on.
That signed number is the error, the gap between where the robot is and where it should be. Every controller you build from here reads an error and returns a correction. This one is the simplest possible version: look at the sign, and steer the other way.
React to which side you drifted
The starter drives dead straight and sails off the first curve. Give it a decision. Look at the sign of offset: if it is positive you have drifted right of the line, so lean left to chase it, and the other way when it is negative.
Leaning means splitting the wheels. Run the two wheels at slightly different speeds and the robot turns toward the slower side. Speed up the right wheel and it curves left; speed up the left wheel and it curves right. Build the correction as an even split off the base speed, one way on each side of the line, and press Run. Once the sensor rides the line you have caught it.
Ride it to the flag
Catching the line is not the same as keeping it. The correction has to be strong enough to hold the robot on through the curves and carry it all the way to the green flag.
This is where you get to tinker. The turn value in the code sets how hard the robot leans. If it catches the line but slides off a curve, change turn and Run again: lean too hard and it rings itself off the line, too soft and it cannot hold the bend, so nudge it and keep the value that carries it home. It will wobble across the line the whole way, and that wobble is the point: reacting to the sign alone can only overcorrect and swing back. Ride it to the flag to finish the lesson. Next you will smooth that shiver out.
Ready to build it? The interactive lesson is where you write the code and watch the robot run.