knaxuslearn · build · ship

Projects / Line-following robot / Phase 4

Phase 4 of 4 · about 2.5 hours

Make it ready for real hardware

You end with a controller written in integer maths that finishes three tracks, one of them never used for tuning, with noisy sensors, late readings, a slow loop and a motor dead zone, plus a test that fails when the robot does.

The simulator has been generous so far. Sensors were perfect, the controller acted on the freshest reading every 5 ms, and motors responded to any command. Real hardware gives you none of that. In this phase we add each problem, watch what it does, and fix it.

Step 4.1: Noisy sensors (about 30 minutes)

A real sensor does not read exactly 0.0 on the floor. It reads a little above or below, and the value jitters. We model that by adding a small random number to every reading. The size of the jitter is the noise.

Three changes go in. First, in control.py, line_position learns a noise floor: anything below floor counts as 0, and if the total signal across all sensors is under min_total, the line counts as not seen. Replace the old function with this one:

def line_position(readings, floor=0.0, min_total=0.05):
    """Where the line is under the array: +2 far left, 0 centred, -2 far right.

    Returns None when the line is not seen. Readings below `floor` count as noise, and
    less than `min_total` of line in total counts as "not seen".
    """
    cleaned = [max(0.0, (r - floor) / (1.0 - floor)) for r in readings]
    total = sum(cleaned)
    if total < min_total:
        return None
    centre = (NUM_SENSORS - 1) / 2
    return sum((centre - i) * r for i, r in enumerate(cleaned)) / total

Without those two checks, five readings of pure jitter produce a random position, and the robot veers off at nothing.

Second, PD passes floor and min_total along, and takes a period, which we use in the next step. Replace the old PD class with:

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, period=DT, floor=0.0, min_total=0.05):
        self.speed, self.kp, self.kd, self.period = speed, kp, kd, period
        self.floor, self.min_total = floor, min_total
        self.prev = 0.0

    def update(self, readings):
        e = line_position(readings, self.floor, self.min_total)
        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) / self.period
        self.prev = e
        return self.speed - steer, self.speed + steer

Third, run gets three new parameters: noise, delay and period. This is its final form, and we use noise now and the other two in the next step. It needs two more imports, so replace the imports at the top of run.py with these:

import math
import random
from collections import deque
from sim import DT, Motors, Pose, drive
from sensors import SensorArray

Then replace the old run function with:

def run(track, controller, seconds=60.0, noise=0.0, delay=0.0, period=DT, seed=1):
    """Drive one lap.

    noise   standard deviation added to every sensor reading (0.0 to 1.0)
    delay   seconds between the robot being somewhere and the controller hearing about it
    period  seconds between controller updates; it only acts this often
    """
    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 = SensorArray(track)
    motors = Motors()
    rng = random.Random(seed)
    result = Result()
    hint, travelled, turned = 0, 0.0, 0.0
    step_len = track.length / n
    steps_per_update = max(1, round(period / DT))
    late = deque([[0.0] * len(sensors.hints)] * (round(delay / DT) + 1), maxlen=round(delay / DT) + 1)
    command = (0.0, 0.0)
    for step in range(int(seconds / DT)):
        readings = sensors.read(pose)
        if noise:
            readings = [min(1.0, max(0.0, r + rng.gauss(0, noise))) for r in readings]
        late.append(readings)
        if step % steps_per_update == 0:
            command = controller.update(late[0])
        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

Now compare. Create noise.py. It runs the Phase 3 gains at 0.8 m/s with growing noise, with and without the floor:

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

hard = Track(hard_track())

def show(label, r):
    out = f"{r.lap_time:.2f} s, off the line {r.off_time:.2f} s" if r.lap_time else f"{r.reason} after {len(r.trail) / 20:.1f} s"
    print(f"{label:<34} {out}")

speed = 0.8
for noise in (0.0, 0.02, 0.05, 0.1):
    print(f"sensor noise {noise}")
    show("  PD, no noise floor", run(hard, PD(speed=speed, kp=0.8, kd=0.04), noise=noise))
    show("  PD, floor 0.15, min total 0.3", run(hard, PD(speed=speed, kp=0.8, kd=0.04, floor=0.15, min_total=0.3), noise=noise))
sensor noise 0.0
  PD, no noise floor               7.47 s, off the line 0.00 s
  PD, floor 0.15, min total 0.3    7.51 s, off the line 0.00 s
sensor noise 0.02
  PD, no noise floor               7.76 s, off the line 0.00 s
  PD, floor 0.15, min total 0.3    7.72 s, off the line 0.00 s
sensor noise 0.05
  PD, no noise floor               9.06 s, off the line 0.00 s
  PD, floor 0.15, min total 0.3    8.65 s, off the line 0.00 s
sensor noise 0.1
  PD, no noise floor               12.01 s, off the line 0.00 s
  PD, floor 0.15, min total 0.3    11.43 s, off the line 0.00 s

Noise slows the robot down even though it never loses the line. At a noise of 0.05 the lap goes from 7.47 to 9.06 seconds, and a noise of 0.1 pushes it to 12.01. The noise floor wins back a share of that, 8.65 and 11.43 seconds. It also changes the clean case slightly, from 7.47 to 7.51: you give up a sliver of precision for robustness.

Pitfall: the floor and the minimum are guesses. Set them too high and you throw away real signal, such as the 0.15 or 0.3 readings from the edge of the line. Measure your real sensors before you pick numbers.

Step 4.2: Slow loops and late readings (about 30 minutes)

Two more problems. A chip may only read the sensors and update the motors every 10 milliseconds, not every 5. And what the controller sees can be old: the sensors take time to settle, the readings go through filters, and the data takes a moment to arrive. We model that as period (time between updates) and delay (age of the data).

First, see what these do to bang-bang. Create conditions.py:

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

hard = Track(hard_track())
for label, kw in [("noise 0.05 only", dict(noise=0.05)),
                  ("20 ms delay only", dict(delay=0.02)),
                  ("10 ms loop only", dict(period=0.01)),
                  ("all three", dict(noise=0.05, delay=0.02, period=0.01))]:
    for speed in (0.3, 0.8):
        r = run(hard, BangBang(speed=speed), **kw)
        out = f"{r.lap_time:.2f} s" if r.lap_time else f"{r.reason} after {len(r.trail) / 20:.1f} s"
        print(f"bang-bang, speed {speed}, {label:<17} {out}")
bang-bang, speed 0.3, noise 0.05 only   18.21 s
bang-bang, speed 0.8, noise 0.05 only   lost the line after 2.4 s
bang-bang, speed 0.3, 20 ms delay only  lost the line after 9.1 s
bang-bang, speed 0.8, 20 ms delay only  lost the line after 6.2 s
bang-bang, speed 0.3, 10 ms loop only   18.29 s
bang-bang, speed 0.8, 10 ms loop only   9.40 s
bang-bang, speed 0.3, all three         lost the line after 7.8 s
bang-bang, speed 0.8, all three         lost the line after 2.3 s

This is the most important table in the project, so read it slowly. A slow 10 ms loop on its own does little harm: 18.29 seconds at 0.3 m/s, the same as before, and 9.40 at 0.8 m/s, about 0.75 seconds slower than in Phase 2. Noise on its own is fine at 0.3 m/s and fatal at 0.8. And a 20 ms delay on its own loses the line at both speeds.

A delay of 20 ms sounds like nothing. But at 0.8 m/s the robot moves 1.6 cm in that time, close to the width of the line. Bang-bang acts on where the line was 20 ms ago, with a full-strength turn. Late and strong is a bad pair.

Now PD, in the same conditions. Create late.py:

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

hard = Track(hard_track())

def show(label, r):
    out = f"{r.lap_time:.2f} s, off the line {r.off_time:.2f} s" if r.lap_time else f"{r.reason} after {len(r.trail) / 20:.1f} s"
    print(f"{label:<44} {out}")

speed = 0.8
base = dict(speed=speed, kp=0.8, kd=0.04, floor=0.15, min_total=0.3)
show("5 ms loop, no delay", run(hard, PD(**base), noise=0.05))
show("10 ms loop, no delay, dt told wrongly", run(hard, PD(**base), noise=0.05, period=0.01))
show("10 ms loop, no delay, dt told correctly", run(hard, PD(**base, period=0.01), noise=0.05, period=0.01))
show("10 ms loop, 20 ms delay, dt correct", run(hard, PD(**base, period=0.01), noise=0.05, period=0.01, delay=0.02))
show("10 ms loop, 40 ms delay, dt correct", run(hard, PD(**base, period=0.01), noise=0.05, period=0.01, delay=0.04))
show("bang-bang, 10 ms loop, 20 ms delay", run(hard, BangBang(speed=speed), noise=0.05, period=0.01, delay=0.02))
5 ms loop, no delay                          8.65 s, off the line 0.00 s
10 ms loop, no delay, dt told wrongly        9.34 s, off the line 0.00 s
10 ms loop, no delay, dt told correctly      8.03 s, off the line 0.00 s
10 ms loop, 20 ms delay, dt correct          10.51 s, off the line 0.00 s
10 ms loop, 40 ms delay, dt correct          23.57 s, off the line 0.00 s
bang-bang, 10 ms loop, 20 ms delay           lost the line after 2.3 s

Every PD row finishes. The last row is bang-bang in the same conditions, for comparison, and it loses the line after 2.3 seconds. The PD rows teach two things.

The first is the third row against the second. With a 10 ms loop, the D term must be told the real time between updates, period=0.01. If we leave it at the default DT of 5 ms, the derivative is calculated as if the time between samples were half what it is, so the D term comes out twice as strong as intended. The lap is 9.34 seconds instead of 8.03.

The second is the delay. A 20 ms delay costs about 2.5 seconds, and a 40 ms delay nearly triples the lap, to 23.57 seconds. PD survives but pays. The lesson for real hardware is to keep the delay as small as you can.

Step 4.3: Tune again under real conditions (about 30 minutes)

The gains from Phase 3 were tuned for a perfect world. Let's tune for the one we have now: noise 0.05, 20 ms delay, a 10 ms loop. We sweep speed, kp and kd, and keep the settings that finish both tracks without leaving the line. Create retune.py:

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

oval, hard = Track(stadium()), Track(hard_track())
real = dict(noise=0.05, delay=0.02, period=0.01)
rows = []
for speed in (0.6, 0.8, 1.0):
    for kp in (0.3, 0.5, 0.8):
        for kd in (0.0, 0.02, 0.04):
            def make():
                return PD(speed=speed, kp=kp, kd=kd, period=0.01, floor=0.15, min_total=0.3)
            h, o = run(hard, make(), **real), run(oval, make(), **real)
            if h.lap_time and o.lap_time and h.off_time == 0 and o.off_time == 0:
                rows.append((h.lap_time, o.lap_time, speed, kp, kd))
rows.sort()
print(f"{len(rows)} of 27 settings finish both tracks without leaving the line")
print("fastest five (hard lap, oval lap, speed, kp, kd):")
for h, o, speed, kp, kd in rows[:5]:
    print(f"  {h:5.2f} s  {o:5.2f} s   speed {speed}  kp {kp}  kd {kd}")
print("the gains from Phase 3 (0.8, 0.04) at speed 1.0:")
r = run(hard, PD(speed=1.0, kp=0.8, kd=0.04, period=0.01, floor=0.15, min_total=0.3), **real)
print(f"  {r.lap_time:.2f} s" if r.lap_time else f"  {r.reason}")
17 of 27 settings finish both tracks without leaving the line
fastest five (hard lap, oval lap, speed, kp, kd):
   7.37 s   4.86 s   speed 1.0  kp 0.5  kd 0.04
   7.73 s   4.75 s   speed 1.0  kp 0.5  kd 0.02
   8.34 s   5.38 s   speed 1.0  kp 0.8  kd 0.04
   8.40 s   5.49 s   speed 0.8  kp 0.5  kd 0.02
   8.58 s   5.58 s   speed 1.0  kp 0.8  kd 0.02
the gains from Phase 3 (0.8, 0.04) at speed 1.0:
  8.34 s

Two findings. Only 17 of the 27 settings survive, so there is real danger in the other ten. And the best setting has changed. The Phase 3 gains, kp 0.8 and kd 0.04, give 8.34 seconds at full speed. A lower kp of 0.5 does better: 7.37 seconds, nearly a second faster. With a delay in the loop, a gentler steering gain does better, most likely because a late correction that is too big overshoots.

We take the winner: speed 1.0, kp 0.5, kd 0.04.

Pitfall: the winner on one track can be a loser on another. We kept an eye on two tracks here. The final test in Step 4.6 uses a third one that we never tuned on.

Step 4.4: Integers only (about 30 minutes)

A small microcontroller often has no hardware for decimal numbers, and doing them in software is slow. Firmware for such a chip typically sticks to whole numbers. Let's rewrite the controller that way and make sure it still behaves.

Three changes. The sensors become integers from 0 to 1023, which is what a 10-bit analog-to-digital converter hands you. The error becomes thousandths of a sensor gap, so the range is -2000 to 2000. And the motors take a PWM value from -255 to 255, instead of metres per second.

The gains become fractions of a PWM step. Our kp of 0.5 m/s per sensor gap is 0.5 x 255 = 127.5 PWM per gap, so each thousandth of error adds 0.127 PWM: kp_num=127 over den=1000. The D term was kd * change / period, which is 0.04 / 0.01 = 4 m/s for each gap of change. That is 4 x 255 = 1020 PWM per gap, so each thousandth of change adds 1.02 PWM: kd_num=1020 over den=1000. We keep the numerators as whole numbers and divide once at the end.

Create firmware.py:

"""What the controller looks like on a small chip: integers only, no floats.

Sensors give 0..1023 (a 10-bit ADC). Motors take a PWM value from -255 to 255.
"""
from sim import MAX_SPEED

ADC_MAX = 1023
PWM_MAX = 255


def to_adc(readings):
    """Turn the simulator's 0.0..1.0 readings into what an ADC would hand us."""
    return [int(round(max(0.0, min(1.0, r)) * ADC_MAX)) for r in readings]


class IntPD:
    """The PD controller again, in integer maths.

    Position is in thousandths of a sensor gap: 2000 is far left, -2000 far right.
    Gains are fractions: steer = (kp_num * e + kd_num * (e - prev)) / den.
    """

    def __init__(self, base=255, kp_num=127, kd_num=1020, den=1000, floor=150, min_total=300):
        self.base, self.kp_num, self.kd_num, self.den = base, kp_num, kd_num, den
        self.floor, self.min_total = floor, min_total
        self.prev = 0

    def position(self, adc):
        cleaned = [max(0, r - self.floor) for r in adc]
        total = sum(cleaned)
        if total < self.min_total:
            return None
        weighted = sum((2 - i) * 1000 * r for i, r in enumerate(cleaned))
        return weighted // total

    def update(self, adc):
        e = self.position(adc)
        if e is None:
            e = max(-3000, min(3000, self.prev * 2))
        steer = (self.kp_num * e + self.kd_num * (e - self.prev)) // self.den
        self.prev = e
        left = max(-PWM_MAX, min(PWM_MAX, self.base - steer))
        right = max(-PWM_MAX, min(PWM_MAX, self.base + steer))
        return left, right

to_adc is the bridge from the simulator's decimals to what an ADC would give the chip. IntPD is the same controller as before, now in integers. Look for //, integer division, in position and update.

The last piece is Board, the stand-in for everything between the firmware and the wheels. Add it to firmware.py:

class Board:
    """Everything between the firmware and the wheels: the ADC, the PWM and the motors.

    Real motors do nothing below some PWM value, then jump to life. `dead` is that
    value (0 means a perfect motor). With `compensate`, any non-zero request is lifted
    so it starts just above the dead zone.
    """

    def __init__(self, firmware, dead=0, compensate=False):
        self.fw, self.dead, self.compensate = firmware, dead, compensate

    def _motor(self, pwm):
        if self.compensate and pwm != 0:
            span = PWM_MAX - self.dead
            pwm = (1 if pwm > 0 else -1) * (self.dead + abs(pwm) * span // PWM_MAX)
        if abs(pwm) < self.dead:
            return 0.0
        return MAX_SPEED * pwm / PWM_MAX

    def update(self, readings):
        left, right = self.fw.update(to_adc(readings))
        return self._motor(left), self._motor(right)

For now dead is 0, which makes Board a plain translator: ADC values in, PWM out, speeds back to the simulator. We use its other settings in the next step.

Did the rewrite change anything? Create parity.py:

from run import run
from control import PD
from firmware import IntPD, Board
from track import Track, stadium, hard_track

oval, hard = Track(stadium()), Track(hard_track())
real = dict(noise=0.05, delay=0.02, period=0.01)

def float_pd():
    return PD(speed=1.0, kp=0.5, kd=0.04, period=0.01, floor=0.15, min_total=0.3)

def int_pd():
    return Board(IntPD(base=255, kp_num=127, kd_num=1020), dead=0)   # no dead zone yet

for label, make in (("float PD", float_pd), ("integer PD", int_pd)):
    h, o = run(hard, make(), **real), run(oval, make(), **real)
    print(f"{label:<11} hard {h.lap_time:.2f} s (wiggle {h.wiggle:.2f})   oval {o.lap_time:.2f} s (wiggle {o.wiggle:.2f})")
float PD    hard 7.37 s (wiggle 1.35)   oval 4.86 s (wiggle 1.19)
integer PD  hard 7.37 s (wiggle 1.36)   oval 4.86 s (wiggle 1.19)

The lap times match to the hundredth, 7.37 and 4.86 seconds, and the wiggle differs by at most 0.01. Rounding to whole numbers costs almost nothing here.

Pitfall: two things bite when you move this to a real chip. First, // in Python rounds towards minus infinity, and / in C rounds towards zero. They differ for negative numbers, so after you port it, run the same test again. Second, the weighted sum in position can reach about 2 million. That does not fit in a 16-bit integer, whose largest value is 32767. Use 32-bit integers for it.

Step 4.5: The motor dead zone (about 20 minutes)

One more real-world habit. A small motor does not move at all until the PWM value passes some minimum. Below it, there is not enough torque to overcome friction, and the wheel sits still. Then at one value it starts, with a jump. That range of values that do nothing is the dead zone.

It hurts a controller most when it asks for small speeds: a weak correction does nothing, and the robot ignores small errors until they get big. One fix is to skip over the dead zone in firmware. Any non-zero request is lifted so that it starts just above the dead zone.

That is the other half of Board._motor from the last step. Try it at two base speeds. The gains were tuned for full speed, so the half-speed rows use half the kd_num. Create dead_zone.py:

from run import run
from firmware import IntPD, Board
from track import Track, hard_track

hard = Track(hard_track())
real = dict(noise=0.05, delay=0.02, period=0.01)
# Gains for each speed: base 255 is about 1.0 m/s, base 128 about 0.5 m/s.
for base, kd_num in ((255, 1020), (128, 510)):
    print(f"base {base} (kp_num 127, kd_num {kd_num}), hard track")
    for dead, compensate in ((0, False), (60, False), (60, True), (90, True)):
        fw = Board(IntPD(base=base, kp_num=127, kd_num=kd_num), dead=dead, compensate=compensate)
        r = run(hard, fw, **real)
        label = "no dead zone" if dead == 0 else f"dead zone {dead}, {'compensated' if compensate else 'plain'}"
        print(f"  {label:<28} {r.lap_time:.2f} s, wiggle {r.wiggle:.2f}")
base 255 (kp_num 127, kd_num 1020), hard track
  no dead zone                 7.37 s, wiggle 1.36
  dead zone 60, plain          7.32 s, wiggle 1.30
  dead zone 60, compensated    7.28 s, wiggle 1.34
  dead zone 90, compensated    7.17 s, wiggle 1.28
base 128 (kp_num 127, kd_num 510), hard track
  no dead zone                 11.55 s, wiggle 2.19
  dead zone 60, plain          12.06 s, wiggle 2.62
  dead zone 60, compensated    9.79 s, wiggle 1.52
  dead zone 90, compensated    9.20 s, wiggle 1.43

At a base of 255, which is full speed, the dead zone hardly matters: the wheels are rarely asked for small values, so the lap stays between 7.17 and 7.37 seconds.

At a base of 128, half speed, it bites. A dead zone of 60 makes the lap slower, 12.06 against 11.55 seconds, and the wiggle goes from 2.19 to 2.62. The compensation brings it to 9.79 seconds with a wiggle of 1.52.

Be careful reading that last number. The compensated robot is faster than one with no dead zone at all, which sounds impossible. The reason is that compensation lifts every small command to at least 60, so the robot also ends up driving faster. It is fixing the dead zone and speeding up at once. Compare "plain" against "compensated" for the benefit of the fix, and do not compare "compensated" against "no dead zone".

Try it: the values 60 and 90 are made up for practice. On a real motor, lift the wheel off the floor, raise the PWM value slowly from 0, and note where it first turns. Use that number.

Step 4.6: A final test (about 10 minutes)

Last, an automatic check that says yes or no. It runs the robot on three tracks, five different noise seeds each, with all the realistic conditions on. The third track, holdout, was never used for tuning, so it tells us whether we have tuned for the tracks or for tracks in general. Create final.py:

"""The last check: every track, five noise seeds, the conditions of a real robot."""
from run import run
from firmware import IntPD, Board
from track import Track, stadium, hard_track

TRACKS = {
    # name: (track, slowest lap we accept in seconds)
    "oval": (Track(stadium()), 5.5),
    "hard": (Track(hard_track()), 8.0),
    "holdout": (Track([(0, 0), (1.2, 0), (1.2, 0.4), (0.9, 0.4), (0.9, 0.2),
                       (0.6, 0.2), (0.6, 0.4), (0.3, 0.4), (0.3, 0.8), (0, 0.8)]), 7.0),
}


def robot():
    return Board(IntPD(base=255, kp_num=127, kd_num=1020), dead=60, compensate=True)


failed = False
print(f"{'track':<8} {'worst lap':>9} {'limit':>6} {'off line':>9} {'wiggle':>7}")
for name, (track, limit) in TRACKS.items():
    results = [run(track, robot(), noise=0.05, delay=0.02, period=0.01, seed=s) for s in range(1, 6)]
    done = all(r.lap_time for r in results)
    worst = max(r.lap_time for r in results) if done else None
    off = max(r.off_time for r in results)
    wiggle = max(r.wiggle for r in results) if done else 0
    ok = done and off == 0 and worst <= limit
    failed = failed or not ok
    lap = f"{worst:.2f}s" if done else "no lap"
    print(f"{name:<8} {lap:>9} {limit:>5.1f}s {off:>8.2f}s {wiggle:>7.2f}  {'pass' if ok else 'FAIL'}")
raise SystemExit(1 if failed else 0)
python3 final.py
track    worst lap  limit  off line  wiggle
oval         4.81s   5.5s     0.00s    1.12  pass
hard         7.28s   8.0s     0.00s    1.34  pass
holdout      6.24s   7.0s     0.00s    1.24  pass

robot() is the whole thing: IntPD with the tuned gains, behind a Board with a dead zone of 60 and compensation on. The limits are ones we chose, with 10 to 15% of room over what it does. Every row passes: the robot finishes all five runs on every track, never leaves the line, and stays inside the lap time limit. The exit status is 0 as well, so a script or a build system can use this check as a gate.

A test that cannot fail is not worth much. Swap the robot for plain bang-bang at 0.8 m/s, the controller from Phase 2, and run it again. Change the robot function to:

def robot():
    from control import BangBang
    return BangBang(speed=0.8)

Here is what you get:

track    worst lap  limit  off line  wiggle
oval        no lap   5.5s     0.67s    0.00  FAIL
hard        no lap   8.0s     0.53s    0.00  FAIL
holdout     no lap   7.0s     0.34s    0.00  FAIL

All three fail, and the exit status is 1. Put the original robot function back before moving on.

Phase 4 done

The controller you built survives noisy sensors, a slow loop, late readings and a stubborn motor. It uses only whole numbers, and it passes a test that fails for a robot that is not up to the job. That is the core of a line follower, built in about 10 hours.