Stage 02 · Lesson 13/15

Programming & Python · Lesson 13

Python + Sensors

Est. 35–45 min

Try it · Python in your browser

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

Why

Why raw sensor numbers need validation

By the end you will reject out-of-range samples and apply a simple exponential moving average.

Concept

The big idea: validate then lightly filter

  • Validate with physical limits (e.g. 2–400 cm for a hobby ultrasonic).
  • EMA: alpha*new + (1-alpha)*prev.
  • On reject: keep previous smooth or enter a safe mode — decide explicitly.
  • Log rejects; silence hides hardware faults.

How it works

How it actually works, step by step

  1. Read raw

    Stub or serial float.

  2. Validate

    None if outside [lo, hi].

  3. Smooth

    EMA with chosen alpha.

  4. Feed decide

    Never feed raw rejects into motion.

Visual

Visualise it: distance sensor demo

Move the distance demo. Imagine spikes — your filter should not trust impossible jumps.

Interactive · Distance-sensor decision

Measured distance

80 cm

FORWARD

Policy: distance ≤ stop → STOP · else ≤ turn → TURN · else FORWARD. Real robots add hysteresis to avoid chatter.

Code lab

Code lab: validate + smooth

sensor_filter.py · Python
#!/usr/bin/env python3
"""Validate + lightly smooth a noisy distance stream."""

def validate(cm: float, lo: float = 2.0, hi: float = 400.0):
    if cm < lo or cm > hi:
        return None  # reject spike / open-air garbage
    return cm

def smooth(prev: float | None, new: float, alpha: float = 0.4) -> float:
    """Exponential moving average. alpha closer to 1 = trust new more."""
    if prev is None:
        return new
    return alpha * new + (1 - alpha) * prev

raw_stream = [40.0, 38.0, 900.0, 37.0, 36.5, 1.0, 35.0]
prev = None
for raw in raw_stream:
    v = validate(raw)
    if v is None:
        print(f"raw={raw:6.1f} → REJECT")
        continue
    prev = smooth(prev, v)
    print(f"raw={raw:6.1f} → valid={v:5.1f} smooth={prev:5.2f}")

Expected output

raw=  40.0 → valid= 40.0 smooth=40.00
raw=  38.0 → valid= 38.0 smooth=39.20
raw= 900.0 → REJECT
raw=  37.0 → valid= 37.0 smooth=38.32
raw=  36.5 → valid= 36.5 smooth=37.59
raw=   1.0 → REJECT
raw=  35.0 → valid= 35.0 smooth=36.56

Real world

Where noisy sensors bite

  • Ultrasonic / ToF range limits.
  • Encoders jump detection.
  • Battery ADC spike rejection.

Mistakes

Common mistakes and confusions

Hardware & safety

Hardware lab and safety notes

Real data is noisy. Point an HC-SR04 at a wall, log 50 readings, and you will see spikes and dropouts — exactly what validate() and smooth() are for. The HC-SR04 datasheet range is about 2–400 cm.

  • Uno prints distance_cm lines; Python reads them with pyserial (pip install pyserial, then serial.Serial(port, 9600)).
  • Soft or angled surfaces (cloth, a tilted book) give the wildest readings — test on them.
  • Record a log first, then tune alpha on the recorded file, not on a moving robot.
HC-SR04 ultrasonic sensor module
HC-SR04 — reliable from about 2 cm to 4 m; anything outside is rejected.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
TypeError: unsupported operand type(s) for |float | None needs Python 3.10+Upgrade Python, or use Optional[float]
Smoothed value lags far behindalpha too smallRaise alpha (e.g. 0.4 → 0.6)
Robot stops for no reasonRejected reading treated as 0 cmSkip rejects; never turn them into 0
SerialException: could not open portWrong port or Serial Monitor still openClose the monitor; check /dev/ttyACM0 or COM port
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

What should decide() do if three rejects arrive in a row?

Experiment

Try it in the lab: validate + smooth

Experiment

Validate + smooth

  1. Run sensor_filter.py; confirm 900 and 1.0 REJECT.
  2. Change alpha to 0.8; notice smoother tracks new values faster.
  3. Use the distance-sensor interactive; note a “too close” reading.

Interactive · Distance-sensor decision

Measured distance

80 cm

FORWARD

Policy: distance ≤ stop → STOP · else ≤ turn → TURN · else FORWARD. Real robots add hysteresis to avoid chatter.

Knowledge check

Check your understanding

Knowledge check

1. Validation should…

2. EMA alpha closer to 1…

3. In the lab, 900 cm was…

4. Feeding rejects as 0 cm is dangerous because…

5. Logging rejects helps…

Practice quiz

Loading practice quiz…

Coding practice

Loading coding exercises…

Mini assignment

Hands-on assignment

Mini assignment

Filter stub

Implement validate + EMA; print a table for a noisy stream you invent (include 2 rejects).

Deliverables

  • sensor_filter_custom.py
  • Output table

Do this, step by step

  1. Run sensor_filter.py; check 900.0 and 1.0 are rejected and the second smooth value is 39.20.
  2. Change alpha to 0.8 and compare how fast the smooth value follows.
  3. Invent a 10-reading stream with 2 spikes and run it.
  4. Write sensor_filter_custom.py and print the output table.

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: 0.4 × 38 + 0.6 × 40 = 39.2.
  2. Hint 2: Higher alpha trusts the new reading more — faster, but noisier.
  3. Hint 3: If you have no sensor, generate noise with random.gauss(35, 1.5) and add two spikes by hand.

Challenges (pick by level)

  • 🟢 Easy: Count how many readings were rejected.
  • 🟡 Medium: Replace the EMA with a median of the last 3 readings and compare.
  • 🟠 Hard: Read 50 real readings with pyserial, save them to JSONL, and tune alpha offline.

Next step

Next, Lesson 14: Python + Robot Control. Related: sensors in Stage 0 — Sensors and filters in Stage 11 — Computer Vision.

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