Stage 02 · Lesson 15/15

Programming & Python · Lesson 15

Capstone — Build a Robot Controller

Est. 45–60 min

Try it · Python in your browser

Run this lesson's example (capstone_ctrl.py), change a number, run it again.

Why

Why stitch the whole Stage 2 toolkit

By the end you will run and explain a vertical slice that uses validation, policy, and slew together.

Concept

The big idea: validate → decide → slew → act

  • Pipeline: raw → validate → decide(target) → slew(actual) → log/act.
  • Keep functions small and testable.
  • Show a table of dist / tgt / speed / note.
  • Name failure modes: reject streaks → STOP.

How it works

How it actually works, step by step

  1. Feed a scripted stream

    Stand-in for sensor ticks.

  2. Validate each sample

    Skip impossibles.

  3. Map distance → target speed

    STOP / SLOW / GO bands.

  4. Slew toward target

    Respect max_delta.

  5. Print the portfolio table

    Proof for your notebook.

Visual

Visualise it: controller challenge

Play the challenge: your mental model should now match sense → decide → (slew) → act.

Interactive · Robot controller challenge

Wire a sense → decide → act loop. Tune the stop threshold, then step the controller.

walldist=55 cm
distance = sensor.read()  # 55
if distance < 20:
    stop(); turn_left()
elif distance < 35:
    drive_forward(slow=True)
else:
    drive_forward()
# last action: idle

Decision now: drive_forward · turns=0 · t=0

Code lab

Code lab: capstone controller

capstone_ctrl.py · Python
#!/usr/bin/env python3
"""Capstone: tiny sensor → decision → slewed actuator controller."""

def validate(cm: float):
    return cm if 2.0 <= cm <= 400.0 else None

def slew(cur: float, tgt: float, max_d: float) -> float:
    d = max(-max_d, min(max_d, tgt - cur))
    return cur + d

def decide(distance_cm: float) -> float:
    """Return target speed 0..1 from distance."""
    if distance_cm < 15:
        return 0.0
    if distance_cm < 40:
        return 0.3
    return 0.8

readings = [55.0, 42.0, 30.0, 18.0, 10.0, 12.0]
speed = 0.0
print(f"{'dist':>6}  {'tgt':>5}  {'speed':>6}  note")
for raw in readings:
    v = validate(raw)
    if v is None:
        print(f"{raw:6.1f}  skip invalid")
        continue
    tgt = decide(v)
    speed = slew(speed, tgt, 0.2)
    note = "STOP" if speed == 0 else ("SLOW" if speed < 0.5 else "GO")
    print(f"{v:6.1f}  {tgt:5.1f}  {speed:6.2f}  {note}")

Expected output

  dist    tgt   speed  note
  55.0    0.8    0.20  SLOW
  42.0    0.8    0.40  SLOW
  30.0    0.3    0.30  SLOW
  18.0    0.3    0.30  SLOW
  10.0    0.0    0.10  SLOW
  12.0    0.0    0.00  STOP

Real world

What “done” looks like for this stage

  • Desk demos with ultrasonic + differential drive stubs.
  • Host watchdogs that rate-limit jog commands.
  • Portfolio piece before Linux / electronics stages.

Mistakes

Common mistakes and confusions

Hardware & safety

Hardware lab and safety notes

Run the capstone on real parts if you have them: HC-SR04 for distance, an Uno streaming readings over serial, and the target speed printed (or sent to a motor driver with the wheels lifted).

  • Desk-safe first: scripted readings, then live sensor readings with the motors disconnected, then motors with wheels off the ground.
  • Motor driver (e.g. L298N or TB6612FNG) gets its own battery; join its GND to the Uno GND.
  • Keep a physical off switch on the motor supply.
Arduino Uno R3 board
Arduino Uno — streams sensor readings to your Python controller over USB.Photo: SparkFun Electronics · CC BY 2.0 · Source: Wikimedia Commons · resized, converted to WebP

Debugging

Debugging: when it doesn’t work

Symptom → likely cause → fix
SymptomLikely causeFix
Speed jumps straight to 0.8Slew not appliedPass every target through slew()
Controller crashes on a spikeNo validate stepCall validate() before decide()
Never shows STOPSpeed only ramps down 0.2 per tickExpected — slew limits braking too; tune if unsafe
Log file is unreadablePrinted text, not JSONUse json.dumps(row) per line
NoteRead the last line of a Python error first — it names the problem — then the line number above it. Change one thing at a time and re-run.

Think

Think about it

Think

In the sample table, why is speed 0.10 when target already went to 0.0 at dist 10?

Experiment

Try it in the lab: portfolio run

Experiment

Portfolio run

  1. Run capstone_ctrl.py; match the printed table.
  2. Change max slew to 0.05; observe longer STOP approach.
  3. Add one invalid reading to the list; ensure it is skipped.
  4. Use the controller challenge interactive to explain your policy aloud.

Interactive · Robot controller challenge

Wire a sense → decide → act loop. Tune the stop threshold, then step the controller.

walldist=55 cm
distance = sensor.read()  # 55
if distance < 20:
    stop(); turn_left()
elif distance < 35:
    drive_forward(slow=True)
else:
    drive_forward()
# last action: idle

Decision now: drive_forward · turns=0 · t=0

Knowledge check

Check your understanding

Knowledge check

1. Capstone pipeline order is…

2. At dist 10 with slew 0.2 from 0.30, first new speed…

3. A good Stage 2 portfolio includes…

4. Invalid readings should…

5. Next stages after Python typically harden…

Practice quiz

Loading practice quiz…

Coding practice

Loading coding exercises…

Mini assignment

Hands-on assignment

Mini assignment

Controller portfolio

Ship a personalised capstone: validate + decide + slew + JSONL log + short README of thresholds.

Deliverables

  • capstone_custom.py
  • sample_run.jsonl
  • README thresholds & failure modes (≤1 page)

Do this, step by step

  1. Run capstone_ctrl.py and copy the table into your notebook.
  2. Add a spike 999.0 to readings and confirm it prints “skip invalid”.
  3. Add JSONL logging of every row (Lesson 10).
  4. Write your README: thresholds, max_delta, and 2 failure modes with safe defaults.

Stuck? Hints, one at a time

NoteTry the task first. Read one hint, try again, and only then read the next one.
  1. Hint 1: With max_delta 0.2 the speed rises 0.20, 0.40, then falls toward the targets.
  2. Hint 2: Put validate → decide → slew in a function tick(raw, speed) that returns the new speed.
  3. Hint 3: Good failure modes: “no reading for 0.5 s → STOP” and “battery below 10.5 V → STOP”.

Challenges (pick by level)

  • 🟢 Easy: Change the STOP band to 20 cm and re-run.
  • 🟡 Medium: Allow faster braking than speeding up (two max_delta values).
  • 🟠 Hard: Feed real HC-SR04 readings over pyserial and log a 30-second run.

Next step

You have finished Stage 2! Look back at Lesson 14: Python + Robot Control if slew still feels new. Next stage: Stage 3 — Linux & Dev Environment. Related: Stage 7 — Control Systems & PID.

Sources

Self-attested for now — keep artifacts in your lab notebook.

Complete

Today's goal

0 of 1 done today

0-day streak
Daily goal:lessons, quizzes or assignments a day

Mark this lesson complete when you have worked the experiment, knowledge check, and assignment (even roughly).

Stuck somewhere?

Ask a doubt about this lesson

Saved with this lesson's id and your email so we can reply. Privacy · or email contact@aihubstation.in