knaxuslearn · build · ship

Projects / Line-following robot / Phase 1

Phase 1 of 4 · about 2.5 hours

Build the robot's world

You end with a simulator where a robot drives, five sensors read a track under it, and a picture shows a robot with no steering rolling off the line after about 2.6 seconds.

Why start with a simulator? You can run a thousand laps in a minute, redraw the track in a second, and get the same answer every time. There are no flat batteries and no loose wires while you are still learning how the control works. The price is that a simulator leaves things out. We add the awkward ones back in Phase 4, and we say plainly what is still missing at the end.

Step 1.1: Plan the robot (about 15 minutes)

Here is the robot we will build. Two wheels, one on each side, 10 cm apart. Five light sensors in a row, 12 mm from each other, sitting 5 cm in front of the wheels.

          sensors (12 mm apart)
            o  o  o  o  o
                  |
                  |  5 cm
                  |
   left wheel ----+---- right wheel
          (10 cm apart)

There is no steering wheel. The robot turns by running one wheel faster than the other. This is called differential drive. The robot's position and direction at any moment is its pose: an x, a y and a heading, which is the angle it faces.

We use metres, seconds and radians everywhere. Heading 0 means facing along the x axis, and a positive turn is a turn to the left.

Create sim.py and write down the numbers we will rely on:

"""The robot: two wheels, two motors, and the maths that moves it."""
import math

WHEEL_BASE = 0.10          # metres between the two wheels
DT = 0.005                 # one simulation step: 5 ms
MOTOR_TAU = 0.06           # a motor reaches about 63% of a new speed in this many seconds
MAX_SPEED = 1.0            # fastest a wheel can turn, metres per second

DT is how long one simulation step lasts: 5 milliseconds. Everything in the simulator moves forward in steps of that size. MOTOR_TAU and MAX_SPEED describe the motors, and you will meet them in Step 1.3.

Check that Python finds the file:

0.1

Step 1.2: Move the robot (about 30 minutes)

Two wheel speeds go in, a new pose comes out. Two ideas are enough. The robot's forward speed is the average of the two wheels. Its turn rate is the difference between them, divided by how far apart the wheels are. Add this to sim.py:

class Pose:
    def __init__(self, x, y, heading):
        self.x, self.y, self.heading = x, y, heading


def drive(pose, v_left, v_right, dt=DT):
    """Move a two-wheeled robot for dt seconds. Speeds are in metres per second."""
    v = (v_right + v_left) / 2                 # forward speed
    omega = (v_right - v_left) / WHEEL_BASE    # turn rate, positive = turning left
    pose.x += v * math.cos(pose.heading) * dt
    pose.y += v * math.sin(pose.heading) * dt
    pose.heading += omega * dt

Each call moves the robot for one tiny step. Forward speed v pushes it along the direction it faces, and omega turns that direction a little. Do that 200 times a second and you get smooth motion.

Try three cases. Create try_drive.py:

import math
from sim import Pose, drive

def show(label, left, right, steps):
    pose = Pose(0, 0, 0)
    for _ in range(steps):           # each step is 5 ms
        drive(pose, left, right)
    print(f"{label:<28} x={pose.x:.3f} y={pose.y:.3f} turned {math.degrees(pose.heading):.0f} degrees")

show("both wheels 0.5, 1 s", 0.5, 0.5, 200)
show("left 0.25, right 0.75, 0.2 s", 0.25, 0.75, 40)
show("left -0.25, right 0.25, 0.2 s", -0.25, 0.25, 40)
python3 try_drive.py
both wheels 0.5, 1 s         x=0.500 y=0.000 turned 0 degrees
left 0.25, right 0.75, 0.2 s x=0.085 y=0.045 turned 57 degrees
left -0.25, right 0.25, 0.2 s x=0.000 y=0.000 turned 57 degrees

Read the three lines. Both wheels at 0.5 m/s for one second: the robot moved 0.5 m straight ahead. Left slower than right for 0.2 seconds: it curved to the left and turned 57 degrees. You can check that by hand. The turn rate is (0.75 - 0.25) / 0.10 = 5 radians a second, and 5 × 0.2 = 1 radian, which is 57.3 degrees.

The last line is the special trick of differential drive. Wheels at equal and opposite speeds give a forward speed of zero, so the robot spins on the spot. A car cannot do that.

We simplified a few things. The wheels never slip, the robot has no weight to push around, and each 5 ms step moves it along a straight segment. For a small robot on a flat floor, that is close enough for what we want to learn.

Step 1.3: Add motors that lag (about 25 minutes)

Real motors do not jump to the speed you ask for. They speed up over a short time. If we skip that, our controller will find life far too easy. Add this to sim.py:

class Motors:
    """Two motors that follow their commands with a delay, like real ones."""

    def __init__(self):
        self.left = 0.0
        self.right = 0.0

    def step(self, cmd_left, cmd_right, dt=DT):
        cmd_left = max(-MAX_SPEED, min(MAX_SPEED, cmd_left))
        cmd_right = max(-MAX_SPEED, min(MAX_SPEED, cmd_right))
        self.left += (cmd_left - self.left) * dt / MOTOR_TAU
        self.right += (cmd_right - self.right) * dt / MOTOR_TAU
        return self.left, self.right

On every step the motor closes a small fraction of the gap between its current speed and the speed requested. That fraction is dt / MOTOR_TAU. The max and min at the top keep the request inside what the motor can really do: no faster than 1 m/s in either direction.

Try it. Create try_motors.py:

from sim import Motors, DT

motors = Motors()
for step in range(1, 201):
    left, right = motors.step(1.0, 1.0)
    if step in (12, 24, 60, 200):
        print(f"{step * DT:.2f} s: left wheel at {left:.3f} m/s")
0.06 s: left wheel at 0.648 m/s
0.12 s: left wheel at 0.876 m/s
0.30 s: left wheel at 0.995 m/s
1.00 s: left wheel at 1.000 m/s

After 0.06 seconds, one MOTOR_TAU, the wheel is at about 65% of the way to 1.0. This is what the name time constant means: the time to cover roughly two thirds of the gap. After 0.3 seconds it is within half a percent.

Pitfall: a 60 ms lag is tiny, and it still matters. At 0.5 m/s the robot travels 3 cm in that time, and the line is only 2 cm wide. Every correction your controller makes arrives a little late. Keep this number in mind. It is the first thing that makes control hard.

Step 1.4: Draw a track (about 30 minutes)

The line on the floor is a list of points about a centimetre apart, joined into a closed loop. Create track.py with the Track class:

"""A closed line on the floor, stored as points about one centimetre apart."""
import math


class Track:
    """A closed line, stored as points about one centimetre apart."""

    def __init__(self, corners):
        self.points = []
        for (x0, y0), (x1, y1) in zip(corners, corners[1:] + corners[:1]):
            steps = max(1, round(math.hypot(x1 - x0, y1 - y0) / 0.01))
            for i in range(steps):
                t = i / steps
                self.points.append((x0 + (x1 - x0) * t, y0 + (y1 - y0) * t))
        pairs = list(zip(self.points, self.points[1:] + self.points[:1]))
        self.length = sum(math.dist(a, b) for a, b in pairs)
        self.headings = [math.atan2(b[1] - a[1], b[0] - a[0]) for a, b in pairs]

    @property
    def turning(self):
        """How much a robot must turn to follow the line once round, in radians."""
        pairs = zip(self.headings, self.headings[1:] + self.headings[:1])
        return sum(abs((h2 - h1 + math.pi) % (2 * math.pi) - math.pi) for h1, h2 in pairs)

    def nearest(self, x, y, near=None):
        """Distance to the line, and which point is closest. Pass the previous answer as
        `near` and only the points around it are searched, which keeps this fast."""
        n = len(self.points)
        best, best_i = 1e9, 0
        if near is not None:
            for k in range(-25, 26):
                i = (near + k) % n
                px, py = self.points[i]
                d = math.hypot(x - px, y - py)
                if d < best:
                    best, best_i = d, i
        if near is None or best > 0.08:  # first look, or we wandered off: search everywhere
            for i, (px, py) in enumerate(self.points):
                d = math.hypot(x - px, y - py)
                if d < best:
                    best, best_i = d, i
        return best, best_i

Four things come out of it:

  • points: the line, as (x, y) pairs about 1 cm apart.
  • length: how far you travel to go once around.
  • turning: how much a robot must turn to follow the line once around, counting left and right turns alike. We use it in Phase 2 to judge how smooth a run was.
  • nearest(x, y): how far a spot is from the line, and which point is the closest one.

nearest takes an optional near, the answer from the last time you asked. It then checks only 25 points on each side of that and skips the rest, about a tenth of the work on our tracks. If the robot is far from where we expected, it falls back to searching everything.

Now two tracks. An oval with straights and curves, and a harder one with eight right-angle corners and a chicane. Add these to track.py:

def stadium(straight=1.0, radius=0.35, per_arc=40):
    """An oval: two straights joined by two half circles."""
    pts = [(0.0, 0.0), (straight, 0.0)]
    for i in range(1, per_arc):
        a = -math.pi / 2 + math.pi * i / per_arc
        pts.append((straight + radius * math.cos(a), radius + radius * math.sin(a)))
    pts += [(straight, 2 * radius), (0.0, 2 * radius)]
    for i in range(1, per_arc):
        a = math.pi / 2 + math.pi * i / per_arc
        pts.append((radius * math.cos(a), radius + radius * math.sin(a)))
    return pts


def hard_track():
    """Right angles, a chicane and short straights."""
    return [(0, 0), (1.6, 0), (1.6, 0.6), (1.2, 0.6), (1.2, 0.3), (0.8, 0.3), (0.8, 0.9), (0.0, 0.9)]

Check them. Create try_track.py:

import math
from track import Track, stadium, hard_track

oval = Track(stadium())
print(f"oval: {len(oval.points)} points, {oval.length:.2f} m long, turns {oval.turning:.2f} rad")
hard = Track(hard_track())
print(f"hard: {len(hard.points)} points, {hard.length:.2f} m long, turns {hard.turning:.2f} rad")
print(f"one full turn is {2 * math.pi:.2f} rad, eight right angles are {8 * math.pi / 2:.2f} rad")
d, i = oval.nearest(0.5, 0.03)
print(f"3 cm above the start of the straight: {d:.3f} m from the line, near point {i}")
oval: 440 points, 4.20 m long, turns 6.28 rad
hard: 560 points, 5.60 m long, turns 12.57 rad
one full turn is 6.28 rad, eight right angles are 12.57 rad
3 cm above the start of the straight: 0.030 m from the line, near point 50

The oval is 4.2 m around and turns exactly one full circle, 6.28 radians, which is a good sign. The hard track is 5.6 m long. It has eight right-angle corners, and 8 × π/2 = 12.57 radians. The point 3 cm above the straight is 0.030 m from the line, as it should be.

Step 1.5: Give the robot eyes (about 25 minutes)

Each sensor answers one question: is there line under me? We turn that into a number from 0.0 (bare floor) to 1.0 (line). The line is 2 cm wide, and a sensor that is only partly over its edge gives something in between. Create sensors.py:

"""Five reflectance sensors across the front of the robot."""
import math

SENSOR_AHEAD = 0.05        # sensors sit this far in front of the wheel axle
SENSOR_SPACING = 0.012     # metres between neighbouring sensors
NUM_SENSORS = 5
LINE_HALF_WIDTH = 0.01     # the line is 2 cm wide


def sensor_reading(distance):
    """1.0 on the line, fading to 0.0 a few millimetres beyond its edge."""
    if distance <= LINE_HALF_WIDTH:
        return 1.0
    return max(0.0, 1.0 - (distance - LINE_HALF_WIDTH) / 0.008)


class SensorArray:
    """Five reflectance sensors across the front of the robot."""

    def __init__(self, track):
        self.track = track
        self.hints = [None] * NUM_SENSORS

    def read(self, pose):
        """Left to right, from 0.0 (floor) to 1.0 (line)."""
        out = []
        for i in range(NUM_SENSORS):
            side = ((NUM_SENSORS - 1) / 2 - i) * SENSOR_SPACING   # left is positive
            x = pose.x + SENSOR_AHEAD * math.cos(pose.heading) - side * math.sin(pose.heading)
            y = pose.y + SENSOR_AHEAD * math.sin(pose.heading) + side * math.cos(pose.heading)
            d, self.hints[i] = self.track.nearest(x, y, self.hints[i])
            out.append(sensor_reading(d))
        return out

sensor_reading takes the distance from the sensor to the line. Within 1 cm it reads 1.0. Beyond that it fades to 0.0 over the next 8 mm.

SensorArray.read works out where each of the five sensors sits for the current pose. It starts at the robot, goes 5 cm forward, then sideways by the sensor's offset, using the heading to rotate. Then it asks the track how far away the line is. The sensors are listed from left to right.

Try some positions. Create try_sensors.py:

from sim import Pose
from track import Track, stadium
from sensors import SensorArray

track = Track(stadium())
sensors = SensorArray(track)

def show(label, pose):
    print(f"{label:<22}", [round(r, 2) for r in sensors.read(pose)])

show("centred on the line", Pose(0.5, 0, 0))
show("1 cm to the left", Pose(0.5, 0.01, 0))
show("2 cm to the left", Pose(0.5, 0.02, 0))
show("1 cm to the right", Pose(0.5, -0.01, 0))
show("far off", Pose(0.5, 0.2, 0))
centred on the line    [0.0, 0.75, 1.0, 0.75, 0.0]
1 cm to the left       [0.0, 0.0, 1.0, 1.0, 0.5]
2 cm to the left       [0.0, 0.0, 0.0, 1.0, 1.0]
1 cm to the right      [0.5, 1.0, 1.0, 0.0, 0.0]
far off                [0.0, 0.0, 0.0, 0.0, 0.0]

Read it from the robot's point of view. When it sits 1 cm to the left of the line, the line is under its right-hand sensors, so the readings lean to the right. The last row is the problem to solve: far from the line, every sensor reads 0.0, and the robot knows nothing.

The first row shows something useful. With the robot dead centre, the neighbours of the middle sensor read 0.75. They are seeing the edge of the line. That partial information will let us locate the line to better than the 12 mm gap between sensors.

Step 1.6: Run a lap and draw it (about 25 minutes)

Two last pieces. First, a function that drops a robot on a track, lets a controller drive, and reports how it went. Second, something that draws the track and the path the robot took.

Create run.py:

"""Run a controller on a track and report how it did."""
import math
from sim import DT, Motors, Pose, drive
from sensors import SensorArray

OFF_LINE = 0.03   # robot centre this far from the line counts as "off the line"
LOST = 0.10       # this far away, we give up


class Result:
    def __init__(self):
        self.lap_time = None      # seconds, or None if no lap was finished
        self.off_time = 0.0       # seconds spent off the line
        self.reason = "ok"
        self.wiggle = 0.0         # how much the robot turned, compared with what the line needs
        self.trail = []           # (x, y) every 50 ms, for drawing


def run(track, controller, seconds=60.0):
    n = len(track.points)
    (x0, y0), (x1, y1) = track.points[0], track.points[1]
    pose = Pose(x0, y0, math.atan2(y1 - y0, x1 - x0))
    sensors, motors, result = SensorArray(track), Motors(), Result()
    hint, travelled, turned = 0, 0.0, 0.0
    step_len = track.length / n
    for step in range(int(seconds / DT)):
        command = controller.update(sensors.read(pose))
        before = pose.heading
        drive(pose, *motors.step(*command))
        turned += abs(pose.heading - before)
        d, idx = track.nearest(pose.x, pose.y, hint)
        delta = (idx - hint + n // 2) % n - n // 2     # signed, handles the wrap-around
        travelled += delta * step_len
        hint = idx
        if d > OFF_LINE:
            result.off_time += DT
        if step % 10 == 0:
            result.trail.append((pose.x, pose.y))
        if d > LOST:
            result.reason = "lost the line"
            return result
        if travelled >= track.length:
            result.lap_time = (step + 1) * DT
            result.wiggle = turned / track.turning
            return result
    result.reason = "ran out of time"
    return result

A controller is any object with an update(readings) method that returns two wheel speeds. run calls it on every step, so we can swap controllers freely.

Four numbers come out. lap_time is how long one lap took, or None if the robot never finished. off_time is how long the robot's centre was more than 3 cm from the line. reason says why a run ended early: the robot got more than 10 cm away ("lost the line"), or ran out of time. And trail is the path, one point every 50 milliseconds.

A lap counts when the robot has made progress along the whole line. We measure progress by how the nearest point on the line moves, so driving in circles earns nothing. The delta line handles the jump when the index wraps from the last point back to the first.

Now the drawing. Create svg.py:

"""Draw a track and the path a robot took as an SVG file."""


def to_svg(track, trails, path, colours=("#d9480f", "#1971c2", "#2f9e44")):
    xs = [p[0] for p in track.points]
    ys = [p[1] for p in track.points]
    pad = 0.15
    x0, y0, w, h = min(xs) - pad, min(ys) - pad, max(xs) - min(xs) + 2 * pad, max(ys) - min(ys) + 2 * pad
    scale = 500 / w

    def pt(p):
        return f"{(p[0] - x0) * scale:.1f},{(h - (p[1] - y0)) * scale:.1f}"

    line = " ".join(pt(p) for p in track.points + track.points[:1])
    out = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 {h * scale:.0f}">',
           '<rect width="100%" height="100%" fill="#f8f9fa"/>',
           f'<polyline points="{line}" fill="none" stroke="#212529" stroke-width="{0.02 * scale:.1f}" stroke-linejoin="round"/>']
    for i, (label, trail) in enumerate(trails):
        pts = " ".join(pt(p) for p in trail)
        out.append(f'<polyline points="{pts}" fill="none" stroke="{colours[i % 3]}" stroke-width="1.5"><title>{label}</title></polyline>')
    out.append("</svg>")
    with open(path, "w") as f:
        f.write("\n".join(out))

It writes an SVG file: the track as a thick dark line, and each trail in its own colour on top. SVG is plain text that every browser can draw, so there is nothing to install.

Let's see a robot with no steering at all. It ignores its sensors and drives straight at 0.5 m/s. Create blind.py:

from run import run
from track import Track, stadium
from svg import to_svg


class Blind:
    """Ignores the sensors and drives straight."""

    def update(self, readings):
        return 0.5, 0.5


track = Track(stadium())
result = run(track, Blind())
print(f"{result.reason}, after {len(result.trail) / 20:.1f} s, lap_time={result.lap_time}")
to_svg(track, [("blind", result.trail)], "blind.svg")
print("wrote blind.svg")
python3 blind.py
lost the line, after 2.6 s, lap_time=None
wrote blind.svg

Open blind.svg in your browser. The robot follows the bottom straight of the oval for a while and then carries straight on while the line curves away. In 2.6 seconds it is more than 10 cm off the line, and the run stops. Zoom in on the picture and you will see the orange trail sliding off the end of the black line.

You now have a world, a robot and a way to look at what it does.

Phase 1 done

You can put a robot on a track, give it wheel speeds, read its sensors and see where it went. Everything from here is about the controller: the code that turns those five numbers into two wheel speeds.