This program may seem logical and will probably work—at least at first. The first part, where the sensor detects black and the robot moves forward, is simple:
However, the second part—when the sensor is no longer over the black line—is quite difficult, if not impossible to implement directly.
Let's say the robot is to the right of the line:
In this case, the robot needs to turn left to return to the line. Now, if the robot is on the left side of the line:
It must turn right to return. That’s all good, but here’s the problem: the sensor values on both sides of the line (left and right) are very similar—sometimes even identical.
So, the robot cannot tell which way to turn.
That’s why, when we say we're programming the robot to “follow the line,” we’re actually simplifying the truth. What the robot really does is follow one of the edges of the line.
The edge is an imaginary boundary between the black line and the background (shown here as red dashed lines). Every line has two edges—one on the left and one on the right.
When following an edge using only one color sensor, the robot can determine if it's on the left or right side of that edge.
For example, if the robot is following the right edge of the black line:
-
If the sensor reads black, the robot is too far to the left of the edge and should turn right:
-
If the sensor reads white, the robot is too far to the right and should turn left:
So, the proper logic for following a black line should be: if the sensor reads black, turn right; otherwise, turn left.
This decision-making process is continuously repeated in a loop.
Continue to the next exercises and try it out—see if your robot can follow the line correctly!