Stage 02 · Lesson 01/15

Programming & Python · Lesson 01

Why Programming Matters in Robotics

Est. 30–40 min

Try it · Python in your browser

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

Why

Why hardware alone is not a robot

By the end you will explain sense → decide → act in plain words, say why Python is a friendly host language for lab robots, and sketch one behavior brief (what to sense, what to decide, what to command).

NoteScope: ideas and a tiny script stub. Later lessons teach syntax, loops, sensors, and a full controller. We are not claiming a specific commercial robot brand or API here.

Concept

The big idea: software turns sensors and motors into behavior

Behavior is what the robot does over time: stop, turn, grasp, log, recover. Hardware supplies capability; software supplies policy.

  • Sense: read sensors or messages (distance, joint angle, battery).
  • Decide: apply rules or controllers (if too close → stop).
  • Act: send commands (speed, joint setpoints) with timeouts and limits.
  • Log: write what happened so you can debug tomorrow morning.

Why Python in this lab?

Python reads almost like English, has a huge library ecosystem, and runs well on a laptop that talks to an Arduino / Raspberry Pi / ROS machine. Firm real-time loops may live in C++ on a microcontroller — Python still shines for host logic, tests, and data.

How it works

How it actually works, step by step

  1. Pick a behavior

    Example: “If something is closer than 20 cm in front, stop; else creep forward.”

  2. Name the inputs

    distance_cm from an ultrasonic (or a stub that returns a number).

  3. Write the policy

    if / elif / else — or a tiny function decide(distance_cm).

  4. Send one command

    Print or publish STOP / SLOW / GO. On real hardware you would talk to a driver; here we keep it honest and simulated.

  5. Repeat on a clock

    Robots loop. Sense again. Decide again. Act again.

Visual

Visualise it: sense → decide → act playground

Try a tiny policy in the playground. Notice how changing the rule changes motion — that is programming.

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

Worked example

Worked example: parking-sensor style stop

You stand behind a car with a parking beeper. Distance falls. Beep rate rises. Below a threshold the car must not roll further. That is sense → decide → act without jargon.

Code lab

Code lab: sense → decide → act stub

Copy into sense_act_story.py and run python3 sense_act_story.py. Your terminal should match the output below.

sense_act_story.py · Python
#!/usr/bin/env python3
"""Mini sense → decide → act story (no hardware)."""

def read_distance_cm():
    # Pretend ultrasonic reading (lab stub)
    return 22.0

def decide(distance_cm: float) -> str:
    if distance_cm < 15:
        return "STOP"
    if distance_cm < 40:
        return "SLOW"
    return "GO"

def act(command: str) -> None:
    print(f"actuator ← {command}")

distance = read_distance_cm()
cmd = decide(distance)
print(f"sensor distance_cm = {distance}")
print(f"decision = {cmd}")
act(cmd)

Expected output

sensor distance_cm = 22.0
decision = SLOW
actuator ← SLOW

Real world

Where programming shows up in the lab

  • Factory arms: weld / pick programs are software policies over joint paths.
  • Vacuum robots: map + decide + drive in a loop.
  • Your desk arm: even a “wave hello” demo is a scripted sequence of joint commands.

Mistakes

Common mistakes and confusions

Hardware & safety

Hardware lab and safety notes

You do not need hardware yet. If you have a kit, wire an HC-SR04 ultrasonic sensor to an Arduino Uno and let it print distance_cm on the Serial Monitor — that number is the *sense* part of sense_act_story.py.

  • HC-SR04: VCC → Uno 5 V, GND → GND, Trig → pin 9, Echo → pin 10. The sensor draws only ~15 mA, so the Uno can power it.
  • For now, *act* is a print(). Only drive a real motor later, through a motor driver with its own supply.
  • No kit? Keep read_distance_cm() as a stub that returns a number — the logic is the same.
HC-SR04 ultrasonic distance sensor module with two round transducers
HC-SR04 ultrasonic sensor — the “eyes” of many first robots. It measures roughly 2–400 cm.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
python3: command not foundPython not installed or not on PATHInstall Python 3 or try python / py -3 on Windows
Decision is always GOStub always returns a big numberChange read_distance_cm() to 10.0 and re-run
IndentationErrorMixed spaces and tabs after copy-pasteRe-indent with 4 spaces
Serial Monitor shows garbageBaud rate mismatchMatch Serial.begin(9600) and the monitor setting
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

A robot has perfect motors but no program. What can it do on its own?

Experiment

Try it in the lab: name the loop

Write the three boxes of behavior for one robot task you care about.

Experiment

Name the loop

You will need

  • Lab notebook
  • This lesson’s interactive

Steps

  1. Pick a task (e.g. “creep forward until 20 cm, then stop”).
  2. Write Sense: which reading(s)?
  3. Write Decide: thresholds and outcomes.
  4. Write Act: what command leaves the laptop?
  5. Run the playground once with a “too close” case and once with a “clear” case.

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

You should be able to point at each box and say what changed when distance changed.

Knowledge check

Check your understanding

Knowledge check

1. Sense → decide → act means…

2. Hardware without software is closest to…

3. Why is Python popular on the host PC in labs?

4. A good first behavior brief includes…

5. In the stub, distance_cm = 22 led to…

Practice quiz

Loading practice quiz…

Coding practice

Loading coding exercises…

Mini assignment

Hands-on assignment

Mini assignment

Behavior brief

Write a one-page behavior brief for a desk-arm or mobile demo: sense, decide, act, and one failure mode (e.g. sensor timeout).

Deliverables

  • Behavior brief (≤1 page)
  • One failure mode + safe default command

Do this, step by step

  1. Run sense_act_story.py and copy its three output lines.
  2. Change the stub to return 10.0, then 50.0. Write down the decision each time.
  3. Draw the sense → decide → act loop for your own demo (desk arm or small rover) on paper.
  4. Write the behaviour brief: one sense, one rule, one action, and one failure mode with a safe default.

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: 22.0 cm gives SLOW, 10.0 gives STOP, 50.0 gives GO — the thresholds are 15 and 40 cm.
  2. Hint 2: A good failure mode: “sensor gives no reading for 0.5 s”. Safe default: STOP.
  3. Hint 3: Keep the brief to plain sentences first; the code comes in Lessons 4 and 11.

Challenges (pick by level)

  • 🟢 Easy: Add a fourth band: below 5 cm print BACK UP.
  • 🟡 Medium: Make read_distance_cm() return a value from a list so each run tests a different number.
  • 🟠 Hard: If you have an HC-SR04, copy one Serial Monitor reading into the stub and check the decision matches what you see.

Next step

Next, Lesson 2: Python Fundamentals — your first real script. Related: sensors in Stage 0 — Orientation and the terminal in Stage 3 — Linux & Dev Environment.

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