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
Read raw
Stub or serial float.
Validate
None if outside [lo, hi].
Smooth
EMA with chosen alpha.
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
Policy: distance ≤ stop → STOP · else ≤ turn → TURN · else FORWARD. Real robots add hysteresis to avoid chatter.
Code lab
Code lab: validate + smooth
#!/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_cmlines; Python reads them withpyserial(pip install pyserial, thenserial.Serial(port, 9600)). - Soft or angled surfaces (cloth, a tilted book) give the wildest readings — test on them.
- Record a log first, then tune
alphaon the recorded file, not on a moving robot.

Debugging
Debugging: when it doesn’t work
| Symptom | Likely cause | Fix |
|---|---|---|
TypeError: unsupported operand type(s) for | | float | None needs Python 3.10+ | Upgrade Python, or use Optional[float] |
| Smoothed value lags far behind | alpha too small | Raise alpha (e.g. 0.4 → 0.6) |
| Robot stops for no reason | Rejected reading treated as 0 cm | Skip rejects; never turn them into 0 |
SerialException: could not open port | Wrong port or Serial Monitor still open | Close the monitor; check /dev/ttyACM0 or COM port |
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
- Run sensor_filter.py; confirm 900 and 1.0 REJECT.
- Change alpha to 0.8; notice smoother tracks new values faster.
- Use the distance-sensor interactive; note a “too close” reading.
Interactive · Distance-sensor decision
Measured distance
80 cm
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
Coding practice
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
- Run
sensor_filter.py; check 900.0 and 1.0 are rejected and the second smooth value is 39.20. - Change
alphato 0.8 and compare how fast the smooth value follows. - Invent a 10-reading stream with 2 spikes and run it.
- Write
sensor_filter_custom.pyand print the output table.
Stuck? Hints, one at a time
- Hint 1: 0.4 × 38 + 0.6 × 40 = 39.2.
- Hint 2: Higher alpha trusts the new reading more — faster, but noisier.
- 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
- Wikipedia — Exponential smoothing
- pySerial documentation
- HC-SR04 datasheet (SparkFun CDN)
- Photos: Wikimedia Commons (credits under each image).
Self-attested for now — keep artifacts in your lab notebook.
Complete
Today's goal
0 of 1 done today
Mark this lesson complete when you have worked the experiment, knowledge check, and assignment (even roughly).