Stage 02 · Lesson 11/15

Programming & Python · Lesson 11

Python for Robotics

Est. 35–45 min

Try it · Python in your browser

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

Why

Why structure the host app as sense → decide → act

By the end you will sketch and run a 3-function SPA skeleton with a shrinking distance demo.

Concept

The big idea: a tiny robot application skeleton

  • sense: return a state dict (readings + flags).
  • decide: pure-ish policy from state → command.
  • act: side effects (print / publish / serial write).
  • main: loop ticks; keep timing simple for now.

How it works

How it actually works, step by step

  1. Define state keys

    distance_cm, battery_v, …

  2. Write decide()

    No printing inside if you can help it — return a command.

  3. Write act()

    One place that talks to the world.

  4. Loop in main

    Tick, log, repeat with a budget.

Visual

Visualise it: controller challenge

Connect policy to motion in the challenge playground — SPA in miniature.

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: SPA skeleton

spa_skeleton.py · Python
#!/usr/bin/env python3
"""Sense → Decide → Act application skeleton."""

def sense():
    return {"distance_cm": 28.0, "battery_v": 11.8}

def decide(state: dict) -> str:
    if state["battery_v"] < 10.5:
        return "ABORT"
    if state["distance_cm"] < 20:
        return "STOP"
    if state["distance_cm"] < 45:
        return "SLOW"
    return "CRUISE"

def act(cmd: str) -> None:
    print(f"act({cmd})")

def main():
    for tick in range(3):
        state = sense()
        # pretend distance shrinks each tick
        state["distance_cm"] = 28.0 - tick * 8
        cmd = decide(state)
        print(f"tick={tick} state={state} → {cmd}")
        act(cmd)

if __name__ == "__main__":
    main()

Expected output

tick=0 state={'distance_cm': 28.0, 'battery_v': 11.8} → SLOW
act(SLOW)
tick=1 state={'distance_cm': 20.0, 'battery_v': 11.8} → SLOW
act(SLOW)
tick=2 state={'distance_cm': 12.0, 'battery_v': 11.8} → STOP
act(STOP)

Real world

Where SPA shows up

  • Host PCs supervising microcontrollers.
  • Simulation using the same decide() as hardware.
  • Unit tests on decide() with fake state.

Mistakes

Common mistakes and confusions

Hardware & safety

Hardware lab and safety notes

Map the skeleton to real parts: sense() = HC-SR04 + battery voltage, decide() = pure Python, act() = the only function that talks to a motor driver. Test it all with stubs on the desk first.

  • Battery voltage: a 3S LiPo is about 12.6 V full and ~11.1 V nominal; 10.5 V is a sensible abort level.
  • Measure battery voltage only through a resistor divider into an ADC — never connect the pack straight to a pin.
  • Keep the robot's wheels off the desk (on a block) for the first real act() test.
Electronics workbench with tools and boards
A tidy bench — test act() with the wheels lifted off the table.Photo: James Bastow · CC BY-SA 2.0 · Source: Wikimedia Commons · resized, converted to WebP

Debugging

Debugging: when it doesn’t work

Symptom → likely cause → fix
SymptomLikely causeFix
KeyError: 'battery_v'sense() returned a dict without that keyReturn all keys every tick
Robot ignores ABORTBattery check is not firstCheck hazards first in decide()
Hard to unit-test decide()It prints or drives motorsReturn a command; do side effects in act()
No idea why it stoppedNo tick logPrint state → cmd every tick
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

Why is decide() easier to test than a mixed script?

Experiment

Try it in the lab: architecture box

Experiment

Architecture box

  1. Run spa_skeleton.py; confirm tick 2 → STOP.
  2. Change thresholds; predict new outputs; verify.
  3. Draw boxes Sense / Decide / Act for your capstone idea.

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. SPA here means…

2. In the demo, tick 2 distance became…

3. act() should…

4. State is often a…

5. Keeping decide pure-ish helps…

Practice quiz

Loading practice quiz…

Coding practice

Loading coding exercises…

Mini assignment

Hands-on assignment

Mini assignment

App skeleton

Fork spa_skeleton.py with your own thresholds and a battery abort path; print tick logs.

Deliverables

  • spa_custom.py
  • Sample run output

Do this, step by step

  1. Run spa_skeleton.py: distances 28, 20, 12 → SLOW, SLOW, STOP.
  2. Set battery_v to 10.2 and check every tick says ABORT.
  3. Write 3 asserts for decide() (one per command).
  4. Fork it as spa_custom.py with your thresholds and print the tick log.

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: 20 is not < 20, so tick 1 is SLOW, not STOP.
  2. Hint 2: assert decide({"distance_cm": 10, "battery_v": 12}) == "STOP".
  3. Hint 3: Pass the tick number into a fake sense(tick) to make test runs repeatable.

Challenges (pick by level)

  • 🟢 Easy: Run 6 ticks instead of 3.
  • 🟡 Medium: Add a time.sleep(0.1) and print the loop rate.
  • 🟠 Hard: Replace act() with a function that writes the command to a JSONL log (Lesson 10).

Next step

Next, Lesson 12: NumPy Fundamentals. Related: nodes and topics in Stage 10 — ROS 2 and motor drivers in Stage 4 — Electronics & Embedded Systems.

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