knaxuslearn · build · ship

Projects / Line-following robot / Phase 3

Phase 3 of 4 · about 2.5 hours

Steer in proportion

You end with a PD controller that laps the hard track in 6.46 seconds at full speed with a wiggle of 1.0, against 7.69 seconds and a wiggle of 2.13 for bang-bang.

Step 3.1: Turn in proportion to the error (about 30 minutes)

Instead of full turn or nothing, turn as much as the error asks for. A small error gets a small correction, and a big one gets a big one. Multiply the error by a number kp, the gain, and use the result as the steering. This is proportional control.

The new class will also carry a second term, kd, which we meet in the next step. For now we leave it at zero. Add from sim import DT to the imports at the top of control.py, then append this class:

class PD:
    """Turn in proportion to the error, and brake the swing with the error's rate of change."""

    def __init__(self, speed=0.25, kp=0.08, kd=0.0):
        self.speed, self.kp, self.kd = speed, kp, kd
        self.prev = 0.0

    def update(self, readings):
        e = line_position(readings)
        if e is None:
            e = max(-3.0, min(3.0, self.prev * 2))   # lost: assume it is even further away
        steer = self.kp * e + self.kd * (e - self.prev) / DT
        self.prev = e
        return self.speed - steer, self.speed + steer

steer is how much faster one wheel runs than the other. The left wheel gets speed - steer and the right gets speed + steer. If the line is to the left, the error is positive and the robot veers left.

When the line is lost, we assume it is twice as far away as it was a moment ago, up to a limit. That keeps the robot turning the right way.

Sweep kp at 0.5 m/s on the hard track. Create sweep_kp.py:

from run import run
from control import PD
from track import Track, hard_track

hard = Track(hard_track())
print("P only (kd = 0), speed 0.5, hard track")
for kp in (0.08, 0.2, 0.4, 0.8, 1.2, 2.0):
    r = run(hard, PD(speed=0.5, kp=kp))
    lap = f"{r.lap_time:.2f} s, wiggle {r.wiggle:.2f}" if r.lap_time else r.reason
    print(f"  kp {kp:<4}: {lap}, off the line {r.off_time:.2f} s")
P only (kd = 0), speed 0.5, hard track
  kp 0.08: lost the line, off the line 1.54 s
  kp 0.2 : 11.61 s, wiggle 2.27, off the line 0.04 s
  kp 0.4 : 11.43 s, wiggle 1.82, off the line 0.00 s
  kp 0.8 : 11.49 s, wiggle 1.74, off the line 0.00 s
  kp 1.2 : 11.56 s, wiggle 1.63, off the line 0.00 s
  kp 2.0 : 11.72 s, wiggle 1.48, off the line 0.00 s

A very small gain, 0.08, cannot turn hard enough, and the robot loses the line. From 0.2 upwards it finishes. The wiggle drops as the gain grows, from 2.27 down to 1.48, but not by much. The lap times hardly move.

Proportional steering on its own finishes the lap. It still zigzags more than we would like. A small error asks for a small correction, but the robot overshoots, the error flips sign, and it swings back. Something needs to calm that swing down.

Step 3.2: Add the brake (about 30 minutes)

The swing has a tell. When the robot is heading back toward the line, the error is shrinking. A controller that notices how fast the error is changing can ease off before it overshoots. That is the derivative term, the D in PD.

It is already in the class: self.kd * (e - self.prev) / DT. The change in error since the last step, divided by the time that passed, is the rate of change per second. Multiply by kd, add it to the steering, and the controller brakes a swing that is already closing in.

Fix kp at 0.8 and sweep kd. Create sweep_kd.py:

from run import run
from control import PD
from track import Track, hard_track

hard = Track(hard_track())
print("kp 0.8, speed 0.5, hard track")
for kd in (0.0, 0.01, 0.02, 0.04, 0.08, 0.16):
    r = run(hard, PD(speed=0.5, kp=0.8, kd=kd))
    lap = f"{r.lap_time:.2f} s, wiggle {r.wiggle:.2f}" if r.lap_time else r.reason
    print(f"  kd {kd:<5}: {lap}, off the line {r.off_time:.2f} s")
kp 0.8, speed 0.5, hard track
  kd 0.0  : 11.49 s, wiggle 1.74, off the line 0.00 s
  kd 0.01 : 11.26 s, wiggle 1.01, off the line 0.00 s
  kd 0.02 : 11.23 s, wiggle 0.97, off the line 0.00 s
  kd 0.04 : 11.29 s, wiggle 0.96, off the line 0.00 s
  kd 0.08 : 11.64 s, wiggle 0.96, off the line 0.00 s
  kd 0.16 : 12.38 s, wiggle 0.97, off the line 0.00 s

Look at the wiggle column. With no D term it is 1.74. A tiny kd of 0.01 takes it down to 1.01, and larger values leave it there, around 0.96. The lap time improves a little too, from 11.49 to 11.23 seconds at 0.02.

Then look at the last row. A kd of 0.16 brings the wiggle no lower and the lap gets slower, 12.38 seconds. Too much braking holds the robot back at the corners. There is a middle.

Pitfall: notice the division by DT. The derivative is a rate, change per second, and a rate needs the time between measurements. If we forget it, or if the real time between updates is not DT, the effective kd changes with it. Phase 4 shows what that does.

Step 3.3: Tune it with a sweep (about 40 minutes)

You have two knobs now, and the best pair depends on how fast you drive. Rather than guess, let the computer try them. Create grid.py:

from run import run
from control import PD
from track import Track, hard_track

hard = Track(hard_track())
kds = (0.0, 0.02, 0.04, 0.08)
print("lap time on the hard track at speed 0.8 (seconds; - means it lost the line)")
print("   kp \\ kd " + "".join(f"{kd:>8}" for kd in kds))
for kp in (0.2, 0.4, 0.6, 0.8, 1.0, 1.5):
    cells = []
    for kd in kds:
        r = run(hard, PD(speed=0.8, kp=kp, kd=kd))
        cells.append(f"{r.lap_time:>8.2f}" if r.lap_time else f"{'-':>8}")
    print(f"   {kp:<8}" + "".join(cells))
lap time on the hard track at speed 0.8 (seconds; - means it lost the line)
   kp \ kd      0.0    0.02    0.04    0.08
   0.2            -    7.79    7.77    8.30
   0.4         8.81    7.63    7.65    7.92
   0.6         8.38    7.61    7.53    7.83
   0.8         8.50    7.54    7.47    7.74
   1.0         8.63    7.57    7.49    7.62
   1.5         8.76    7.69    7.63    7.67

Read it like a map of a valley. Each row is a kp, each column a kd, and the number is the lap time at 0.8 m/s. Smaller is better, and a dash means the robot lost the line.

Three things stand out. The first column, no D term, is the slowest in every row. The top-left cell fails outright: a small gain and no braking cannot cope at this speed. And the fastest cell is kp 0.8 with kd 0.04, at 7.47 seconds, with its neighbours close behind. That flat floor around the best cell is good news, because it means small errors in tuning will not hurt much.

We will use 0.8 and 0.04.

Step 3.4: Push the speed (about 30 minutes)

Does PD beat bang-bang? Let's compare at four speeds. Create compare.py:

from run import run
from control import BangBang, PD
from track import Track, hard_track

hard = Track(hard_track())
print(f"{'speed':>5} | {'bang-bang':>16} | {'PD (0.8, 0.04)':>16}")
for speed in (0.3, 0.5, 0.8, 1.0):
    b = run(hard, BangBang(speed=speed))
    p = run(hard, PD(speed=speed, kp=0.8, kd=0.04))
    print(f"{speed:>5} | {b.lap_time:>6.2f}s  w {b.wiggle:.2f} | {p.lap_time:>6.2f}s  w {p.wiggle:.2f}")
speed |        bang-bang |   PD (0.8, 0.04)
  0.3 |  18.29s  w 1.34 |  18.23s  w 0.96
  0.5 |  11.70s  w 1.76 |  11.29s  w 0.96
  0.8 |   8.65s  w 2.03 |   7.47s  w 0.96
  1.0 |   7.69s  w 2.13 |   6.46s  w 1.01

At 0.3 m/s they are nearly equal, 18.23 against 18.29 seconds. When there is plenty of time to react, a clumsy controller does fine. As the speed rises the gap opens. At 1.0 m/s PD takes 6.46 seconds and bang-bang 7.69, about 16% faster, and the wiggle is 1.01 against 2.13.

That is what proportional steering and a brake buy you: a robot that turns about as much as the track demands and no more.

Step 3.5: Put the two side by side (about 20 minutes)

The last look in this phase. Run both controllers on the hard track at 1.0 m/s and draw them on one picture. Create overlay.py:

from run import run
from control import BangBang, PD
from track import Track, hard_track
from svg import to_svg

hard = Track(hard_track())
b = run(hard, BangBang(speed=1.0))
p = run(hard, PD(speed=1.0, kp=0.8, kd=0.04))
to_svg(hard, [("bang-bang", b.trail), ("PD", p.trail)], "compare.svg")
print(f"bang-bang: {b.lap_time:.2f} s, wiggle {b.wiggle:.2f}")
print(f"PD:        {p.lap_time:.2f} s, wiggle {p.wiggle:.2f}")
bang-bang: 7.69 s, wiggle 2.13
PD:        6.46 s, wiggle 1.01

Open compare.svg. The orange trail is bang-bang and the blue one is PD. On a straight, blue sits on the line and orange weaves around it. Zoom in on a corner and compare how each one turns in.

Phase 3 done

A PD follower laps the hard track in 6.46 seconds, which is 1.2 seconds ahead of bang-bang, while turning half as much. You tuned it with a sweep rather than by feel. So far, though, the robot has lived in a very kind world. Phase 4 makes the world unkind.