Skip to content
Tactiverge

School/△ Builder/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?

About 40 min · 3 goals · Checked by automated tests

1.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.

2.Predict

to_celsius(to_volts(232)): which function runs first?

Guess first. Being wrong here is how the surprise works.

3.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).

Can't use the interactive? Read a description instead

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'.

4.Checkpoint: guided practice

Check what you just discovered before going on. Hints appear after a wrong answer.

Practice 1 · a fresh version every time

A 10-bit ADC reads raw = 307. to_volts(raw) returns raw * 3.3 / 1023, and to_celsius(v) returns (v - 0.5) * 100 (a TMP36-style sensor: 10 mV per °C with a 0.5 V offset). What is to_celsius(to_volts(307)), in °C?

°C

Practice 2

Which function does one job?

5.Watch

→ 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.

Length: see YouTube · captions on YouTube · source

Nothing loads from YouTube until you press play.

The video is optional: everything you need is also in the lesson text and the interactive.

6.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

Like a production line with separate stations: cutting, drilling, painting. If the paint is wrong, you check the painting station, not the whole factory.

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.

7.Practice on your own

Practice, not a test. Wrong answers get a hint and another try.

Practice 3

Why test to_volts and to_celsius separately before the whole pipeline?

Practice 4

With volts = raw × 3.3 / 1023, how many millivolts is one ADC count, to 2 decimal places?

mV

8.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.

9.Reflect

Concepts: Functions and decomposition · Analog-to-digital conversion