Projects / Line-following robot / Phase 2
Phase 2 of 4 · about 2.5 hours
Follow the line, the simple way
You end with a controller that finishes both tracks at every speed we try, and three measurements for judging it: lap time, time off the line, and how much it wiggles.
Step 2.1: Where is the line? (about 20 minutes)
Five numbers are awkward to steer with. We want one: how far is the line from the middle of the robot, and on which side? Use a weighted average. Give the sensors positions from +2 (far left) to -2 (far right), then average those positions, weighting each by how strongly its sensor sees the line.
Create control.py:
"""Controllers: each one turns sensor readings into (left, right) wheel speeds in metres per second."""
from sensors import NUM_SENSORS
def line_position(readings):
"""Where the line is under the array: +2 far left, 0 centred, -2 far right.
Returns None when the line is not seen at all.
"""
total = sum(readings)
if total < 0.05:
return None
centre = (NUM_SENSORS - 1) / 2
return sum((centre - i) * r for i, r in enumerate(readings)) / total
We call this number the error, because it is how far we are from where we want to be. The line should be under the middle sensor, an error of 0. If no sensor sees the line, there is nothing to average and the function returns None.
Try it. Create try_position.py:
from control import line_position
cases = {
"line dead centre": [0.0, 0.0, 1.0, 0.0, 0.0],
"line under left sensor": [1.0, 0.0, 0.0, 0.0, 0.0],
"line under right sensor": [0.0, 0.0, 0.0, 0.0, 1.0],
"between two sensors": [0.0, 0.5, 0.5, 0.0, 0.0],
"line a little to the left": [0.5, 1.0, 0.0, 0.0, 0.0],
"wide line, centred": [0.0, 0.75, 1.0, 0.75, 0.0],
"line not seen": [0.0, 0.0, 0.0, 0.0, 0.0],
}
for label, readings in cases.items():
print(f"{label:<27} {line_position(readings)}")
line dead centre 0.0
line under left sensor 2.0
line under right sensor -2.0
between two sensors 0.5
line a little to the left 1.3333333333333333
wide line, centred 0.0
line not seen None
Notice the fifth row. Two sensors partly see the line, 0.5 and 1.0, and the answer is 1.33. That is between the two positions, closer to the stronger sensor. The robot knows where the line is to a fraction of a sensor gap.
Step 2.2: Bang-bang steering (about 40 minutes)
The simplest controller you can think of. If the line is to the left, turn left. If it is to the right, turn right. If it is close to the middle, drive straight. Nothing in between: it is either full turn or none, like a thermostat clicking on and off. That is called bang-bang control.
Add this to control.py:
class BangBang:
"""Go straight, or turn hard toward the line. Nothing in between."""
def __init__(self, speed=0.25, turn=None, deadband=0.5):
self.speed = speed
self.turn = turn if turn is not None else 1.5 * speed
self.deadband = deadband
self.last = 0.0
def update(self, readings):
e = line_position(readings)
if e is None:
e = self.last # lost: keep turning the way the line was last seen
self.last = e
if e > self.deadband:
return self.speed - self.turn, self.speed + self.turn
if e < -self.deadband:
return self.speed + self.turn, self.speed - self.turn
return self.speed, self.speed
To turn, one wheel gets speed - turn and the other speed + turn. At speed 0.3 the default turn is 0.45, so the wheels get -0.15 and 0.75. The slow one runs backwards, which makes the robot pivot.
Two more details. deadband is how far off the line must be before we bother correcting. And when the line is not seen, we keep turning the way we last saw it, which is usually the way back.
Run a lap of the oval at 0.3 m/s. Create bang_bang_lap.py:
from run import run
from control import BangBang
from track import Track, stadium
from svg import to_svg
track = Track(stadium())
result = run(track, BangBang(speed=0.3))
print(f"{result.reason}: lap {result.lap_time:.2f} s, off the line {result.off_time:.2f} s")
to_svg(track, [("bang-bang", result.trail)], "bang-bang.svg")
print("wrote bang-bang.svg")
ok: lap 14.06 s, off the line 0.00 s
wrote bang-bang.svg
A full lap, 14.06 seconds, never more than 3 cm from the line. Open bang-bang.svg and see how the orange trail hugs the black.
Step 2.3: Measure the wiggle (about 20 minutes)
A lap time is not enough. A robot can finish and still waste effort by zigzagging, and zigzag is what costs you at speed. We need a number for it.
The idea is already in run.py. We add up every bit the robot turns, in either direction (turned += abs(pose.heading - before)), and divide by how much the track itself needs (track.turning). That is the wiggle. A value of 1.0 means the robot turned exactly as much as the line demands. A value of 2.0 means it turned twice as much, and the extra half is zigzag.
Create wiggle.py and run three speeds on the oval:
from run import run
from control import BangBang
from track import Track, stadium
track = Track(stadium())
for speed in (0.3, 0.6, 1.0):
r = run(track, BangBang(speed=speed))
print(f"speed {speed}: lap {r.lap_time:.2f} s, wiggle {r.wiggle:.2f}")
speed 0.3: lap 14.06 s, wiggle 1.02
speed 0.6: lap 7.27 s, wiggle 1.04
speed 1.0: lap 4.71 s, wiggle 1.32
At 0.3 and 0.6 m/s the wiggle is close to 1.0. At full speed it climbs to 1.32. Bang-bang is smooth when it has time to react, and rougher as the robot gets faster.
Step 2.4: Find where it stops being enough (about 35 minutes)
Now the question: how fast can bang-bang go? Sweep the speed on both tracks. Create sweep_speed.py:
from run import run
from control import BangBang
from track import Track, stadium, hard_track
print(f"{'speed':>5} | {'oval lap':>8} {'wiggle':>6} | {'hard lap':>8} {'wiggle':>6}")
oval, hard = Track(stadium()), Track(hard_track())
for speed in (0.3, 0.5, 0.7, 0.8, 0.9, 1.0):
a, b = run(oval, BangBang(speed=speed)), run(hard, BangBang(speed=speed))
print(f"{speed:>5} | {a.lap_time:>7.2f}s {a.wiggle:>6.2f} | {b.lap_time:>7.2f}s {b.wiggle:>6.2f}")
speed | oval lap wiggle | hard lap wiggle
0.3 | 14.06s 1.02 | 18.29s 1.34
0.5 | 8.59s 1.01 | 11.70s 1.76
0.7 | 6.31s 1.01 | 9.45s 2.03
0.8 | 5.58s 0.99 | 8.65s 2.03
0.9 | 5.16s 1.33 | 8.12s 2.11
1.0 | 4.71s 1.32 | 7.69s 2.13
Read the table in three passes.
First, nothing fails. Bang-bang finishes both tracks at every speed, all the way to 1.0 m/s, which is the most our simulated motors can do. The table ends there because the motors run out, and bang-bang does not.
Second, lap times fall as you speed up, as you would expect: the oval from 14 to under 5 seconds, the hard track from 18 to under 8.
Third, and this is the part to remember, the wiggle on the hard track starts at 1.34 and climbs past 2.0 from 0.7 m/s onwards. The robot is turning more than twice as much as the track needs. In this tidy simulator that costs nothing but time. With a real robot's wear, noise and slow motors, it would cost much more. We test that in Phase 4.
Step 2.5: Two knobs and what they do (about 25 minutes)
Bang-bang has two settings: how hard to turn, and how far off the line before turning. Let's see how sensitive it is to each. Create sweep_turn.py:
from run import run
from control import BangBang
from track import Track, hard_track
hard = Track(hard_track())
speed = 0.5
print("turn strength (as a multiple of speed), deadband 0.5")
for k in (0.25, 0.5, 1.0, 1.5, 2.0):
r = run(hard, BangBang(speed=speed, turn=k * speed))
lap = f"{r.lap_time:.2f} s, wiggle {r.wiggle:.2f}" if r.lap_time else r.reason
print(f" turn {k:>4} x speed: {lap}, off the line {r.off_time:.2f} s")
print("deadband, turn 1.5 x speed, speed 0.2")
for band in (0.25, 0.5, 0.75, 1.0):
r = run(hard, BangBang(speed=0.2, deadband=band))
lap = f"{r.lap_time:.2f} s" if r.lap_time else r.reason
print(f" deadband {band:>4}: {lap}, off the line {r.off_time:.2f} s")
turn strength (as a multiple of speed), deadband 0.5
turn 0.25 x speed: lost the line, off the line 0.17 s
turn 0.5 x speed: lost the line, off the line 1.55 s
turn 1.0 x speed: 11.20 s, wiggle 2.06, off the line 0.00 s
turn 1.5 x speed: 11.70 s, wiggle 1.76, off the line 0.00 s
turn 2.0 x speed: 11.98 s, wiggle 1.66, off the line 0.00 s
deadband, turn 1.5 x speed, speed 0.2
deadband 0.25: 26.98 s, off the line 0.00 s
deadband 0.5: 27.25 s, off the line 0.00 s
deadband 0.75: 27.62 s, off the line 0.00 s
deadband 1.0: lost the line, off the line 0.36 s
Turn strength. A gentle turn of a quarter or half the speed cannot swing the robot round the right-angle corners, and it loses the line. From equal to the speed upwards it finishes, but there is no best value. A turn equal to the speed is the fastest at 11.20 seconds and wiggles the most, at 2.06. A turn twice the speed wiggles least, at 1.66, and is the slowest at 11.98.
Deadband. Waiting for a bigger error before correcting makes the lap slower at 0.2 m/s: 26.98, 27.25, then 27.62 seconds. At a band of 1.0 the robot waits too long and loses the line.
Nothing wins everywhere. Every setting trades one thing for another, because a switch with only two states has to compromise between a big reaction and a small one. A controller that reacts in proportion to the error would not need to.
Step 2.6: See the zigzag (about 10 minutes)
Time for a picture. Run bang-bang at 0.8 m/s on the hard track and save the trail. Create bang_bang_hard.py:
from run import run
from control import BangBang
from track import Track, hard_track
from svg import to_svg
hard = Track(hard_track())
result = run(hard, BangBang(speed=0.8))
print(f"lap {result.lap_time:.2f} s, wiggle {result.wiggle:.2f}")
to_svg(hard, [("bang-bang", result.trail)], "bang-bang-hard.svg")
print("wrote bang-bang-hard.svg")
lap 8.65 s, wiggle 2.03
wrote bang-bang-hard.svg
Open bang-bang-hard.svg and zoom in on a straight section. The trail does not run along the middle of the line. It weaves across it, again and again, and at the corners it overshoots and comes back. That weave is the 2.03 in the output.
Phase 2 done
Your robot finishes every lap we asked of it, and you can measure how well it does it. Bang-bang is simple and sturdy, and it pays for that in zigzag. In Phase 3 we replace the on-off switch with something smoother.