Lite / Building Machines That Respond / Week 7
Decompose a program into functions
Raw ADC counts in, a temperature report out. Should that be one long block of code, or three small functions?
Why should I care?
Real sensor software is a pipeline: convert raw counts, apply calibration, check plausibility, summarise, decide. Each stage as a small, tested function means you can find a bug in minutes and reuse a stage for the next sensor.
- Split a data-processing program into small functions that each do one job.
- Chain functions so the output of one is the input of the next.
- Test each function on its own before testing the whole program.
Predict
to_celsius(to_volts(232)): which function runs first?
- to_celsius
- to_volts
- Both at the same time
Guess first, then reveal
to_volts. Python works out the argument first, so the inner call runs and its result is passed to to_celsius.
Discover
In the Code Lab, type the three-function pipeline from this lesson. Run it and check the report. Then test each function on its own: to_volts(1023) should be 3.3 and to_celsius(0.75) should be 25.0 (within a tolerance). Finally, add a fourth function count_over(values, limit_c).
What the interactive shows (text version)
The Code Lab exercise can be done by hand: for raw counts 228, 231, 235 and 240, volts = raw × 3.3 / 1023 and temperature = (volts − 0.5) × 100 give about 23.5, 24.5, 25.8 and 27.4 °C, so the report reads 'mean 25.3 °C, range 23.5 to 27.4 °C'.
Watch (optional)
Watch for: Watch how big programs are broken into functions and modules that different people can build and test separately.
How big programs are broken into functions and modules, tested and built by teams.
“Software Engineering: Crash Course Computer Science #16” by CrashCourse (opens YouTube; streaming video uses a lot of data)
The video is optional. Everything you need is in this lesson's text.
Understand
Three small functions
def to_volts(raw):
"""10-bit ADC count (0–1023) to volts, 3.3 V reference."""
return raw * 3.3 / 1023
def to_celsius(volts):
"""TMP36-style sensor: 10 mV per °C, 0.5 V at 0 °C."""
return (volts - 0.5) * 100
def summarise(values):
"""Return (mean, minimum, maximum) of a non-empty list."""
return sum(values) / len(values), min(values), max(values)Chain them in the main program
raw_counts = [228, 231, 235, 240]
temps_c = []
for raw in raw_counts:
temps_c.append(to_celsius(to_volts(raw)))
mean_c, low_c, high_c = summarise(temps_c)
print(f"mean {mean_c:.1f} °C, range {low_c:.1f} to {high_c:.1f} °C")Run after the three functions above, it prints mean 25.3 °C, range 23.5 to 27.4 °C.
One job per function
If you can't describe a function in one sentence without 'and', split it. Small functions are easy to test (to_volts(0) is 0.0, to_volts(1023) is 3.3), easy to reuse (the same to_volts serves a light sensor) and easy to replace (a new sensor needs only a new to_celsius).
Explain it another way
Intuitive
Like a production line with separate stations: cutting, drilling, painting. If the paint is wrong, you check the painting station, not the whole factory.
Technical
Decomposition into pure functions (output depends only on inputs, no side effects) makes each unit independently testable and composable: f(g(x)). The main program becomes a short, readable description of the pipeline.
Mathematical
V = raw × 3.3/1023 and T = (V − 0.5) × 100 compose into T = (raw × 3.3/1023 − 0.5) × 100. For raw = 232: V ≈ 0.748 V and T ≈ 24.8 °C. Each count is about 3.2 mV, about 0.32 °C: the sensor's resolution.
Applied
Embedded and data teams structure sensor code exactly like this, often in separate files, so a calibration change touches one small, tested function.
Worked example 1
The sensor is re-calibrated: it reads 0.3 °C too high. Where does the fix go?
In one place: a new function calibrate(temp_c) that returns temp_c - 0.3, called between to_celsius and summarise. Nothing else changes, and calibrate gets its own test: calibrate(25.0) should be 24.7 (within a tolerance).
Common mix-ups
Splitting code into functions makes it slower and longer, so it is worse.
✓ The tiny cost is repaid many times over in clarity, testing and reuse.A function should print its result so you can see it.
✓ Return it. Print only in the main program, so the function stays reusable and testable.
Practice
Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.
Apply it
Add plausible(temp_c) (True from −40 to 125 °C) and count_over(values, limit_c) to the pipeline, each with a docstring and two asserts. Then rewrite your main program so it reads like a short list of steps.
Reflect
How did splitting the program change how confident you are that it is right?
Write your answer on paper or in your own notes. Lite never stores what you write.