← About PHYS 351

PHYS 351 · Advanced Instrumentation

Lecture 07 · Distance & acceleration

1 Where Lab 7 Sits

1.1 From outputs to inputs

In Labs 3 to 5 the Pi gave orders: a pin high or low lit an LED, a PWM duty cycle set a motor's speed, a coil pattern or pulse width moved a stepper or servo. From Lab 6 the Pi stops talking and starts listening. Lab 6 introduced a digital sensor that hands you a number over I²C. This week you meet two more, and they could hardly be more different.

The LIS3DH accelerometer is an I²C device like the MCP9808, so the protocol work is already familiar; the difficulty moves to interpreting what an accelerometer actually measures, which is subtler than it first appears. The HC-SR04 range finder uses a simple trigger-and-echo timing interface rather than I²C. It reports distance as the width of a pulse, so the measurement is a time interval you have to capture yourself. That drags every timing limitation from Lecture 03 directly into your measurement accuracy.

Overview. On the left, Labs 3 to 5, where the Raspberry Pi drives outputs: an LED (a pin high or low), a MOSFET and DC motor (PWM duty), and a stepper or servo (coil patterns, pulse width). On the right, Labs 6 and 7, where the Pi listens to inputs: the MCP9808 (an I2C register converted to degrees Celsius), the LIS3DH (I2C registers converted to x, y, z in g) and the HC-SR04 (a pulse width converted to distance).
Figure 1. From outputs to inputs. Left, Labs 3 to 5: the Pi drives an LED (a pin high or low), a MOSFET and DC motor (a PWM duty cycle), and a stepper or servo (coil patterns, pulse width). Right, Labs 6 and 7: the Pi listens to the MCP9808 (an I²C register converted to °C), the LIS3DH (I²C registers converted to x, y, z in g) and the HC-SR04 (a pulse width converted to distance).
The one idea to carry out of this lecture

Both sensors this week return a number that is only meaningful once you supply physics: an acceleration reading gives tilt only when the board is not otherwise accelerating, and a time becomes a distance only if you know the speed of sound. The sensor measures; you convert. Every conversion carries an assumption, and every assumption is a source of error you should be able to quantify.

1.2 Task map

Lab 7 taskWhat you doConcept & section
1Write and show the HC-SR04 script and schematic; build; get approval; output m, cm, mm and inches with sensible significant figuresTime of flight, the Echo divider, timing and timeouts (§11–13)
2Determine zero offset, minimum range, maximum range and accuracy; compare with the datasheetCalibration (§14)
3Connect the LIS3DH; find its I²C address; validate the x-axis outputWiring, i2cdetect, WHO_AM_I, the driver (§3, §4, §6.2)
4100+ points per axis; standard deviation at rest; theorize the effect of tilt; find the smallest detectable angle changeGravity, tilt, noise (§2, §7)
5Average n sequential readings; standard deviation of the averages; plot against time; save CSV and imagesAveraging statistics, live plot or log first (§5, §7.2)
6Extra credit: swing the accelerometer as a pendulum; log all three axes for 10+ s; plot in three colors; analyze the frequenciesPendulum kinematics, axis directions (§8)
7Extra credit: add the MCP9808 and make the range finder temperature-compensated; run the sensors as one loop, as threads and as processes; measure and compare the timing; time a calculation in threads and in processesSpeed of sound vs temperature, distinct addresses (§15); threads, the GIL, processes, measuring jitter (§16)

Task 7 is shared with Lab 8 and is worth up to +10 points total, awarded once on Lab 7 if finished there or on Lab 8 if finished later. You may work across both labs; for partial credit, document clearly which parts you completed. See the Lab 7 manual for the submission policy.

Bring your Lab 6 MCP9808 code, and keep every driver file in the same folder as your scripts (§4.4).

2 What an Accelerometer Measures

This section repays careful reading, because the natural assumption about accelerometers is wrong and it will confuse your Task 4 data.

2.1 A mass on springs

Inside the LIS3DH is a MEMS structure: a tiny silicon proof mass held on springs, carrying comb fingers that sit between fixed electrodes. With no specific force along the sensing axis, each finger sits midway between its two neighbors, so the two capacitances C1 and C2 are equal. When the chip accelerates, the mass lags behind: one gap shrinks and the other grows, C1 rises and C2 falls, and the chip measures the difference C1 − C2.

Sketch of a MEMS accelerometer comb. A proof mass on springs between two anchors carries fingers that sit between fixed electrodes. At rest the two gaps beside each finger are equal, so C1 equals C2. When the chip accelerates to the right the mass lags to the left: the gap on one side shrinks, so C1 rises, and the other grows, so C2 falls.
Figure 2. Sketch of a MEMS accelerometer comb. A proof mass on springs between two anchors carries fingers that sit between fixed electrodes. With no specific force along the sensing axis, the two gaps beside each finger are equal, so C1 = C2. When the chip accelerates to the right the mass lags to the left: one gap shrinks, so C1 rises, and the other grows, so C2 falls.

Well below its resonant frequency, the mass simply sits where the spring force balances its inertia, displaced by x = ma/k. Writing the spring constant through the resonant frequency, k/m = ω0², gives x = a/ω0². The displacements are astonishingly small: for an illustrative 5 kHz resonance, ω0 = 2π × 5000 s−1 ≈ 3.14 × 104 s−1, and 1 g moves the mass

x = gω0² = 9.81 m/s²9.87 × 108 s−2 ≈ 10 nm

That is about a fiftieth of the wavelength of visible light. Measuring that as a capacitance change is what the ADC and charge amplifier on the chip are for (§3.1).

2.2 At rest, the axis pointing up reads +1 g

An accelerometer at rest does not read zero

What the displacement of the proof mass reports is specific force: the force per unit mass from everything except gravity. (Physicists also call it proper acceleration, the acceleration relative to free fall.) It is not the acceleration relative to the ground.

Sitting still on the bench, the device is being held up by the bench against gravity. The proof mass is displaced exactly as it would be under an upward acceleration of g, so a stationary accelerometer reads 1 g along its vertical axis, and 0 on the other two.

The counter-intuitive corollary: an accelerometer in free fall reads zero on all three axes, because nothing is displacing the proof mass. “Zero g” means falling, not resting.

The datasheet says the same thing in its own terms (§3.1.2): lying flat on a table, the LIS3DH reads X = Y = 0 g and Z = +1 g. This is why your stationary readings in Task 4 will show roughly 1 g on one axis and roughly 0 on the others, and it is the entire basis of using an accelerometer to measure tilt.

Side views of a breakout in four orientations with its x and z axes and gravity pointing down. Flat with the chip up it reads x 0, y 0, z +1 g; upside down z reads -1 g; with the x axis pointing up x reads +1 g; with x pointing down x reads -1 g. At rest the axis pointing up reads +1 g because the support pushes the chip up.
Figure 3. Side views of a breakout in four orientations, with its x and z axes and gravity pointing down. Flat with the chip up it reads x 0, y 0, z +1 g; upside down z reads −1 g; with the x axis pointing up x reads +1 g; with x pointing down, −1 g. The axis pointing up reads +1 g because the support pushes the chip up.

2.3 Tilt: gravity shared between two axes

When the board is still, or at least not speeding up, slowing down or turning, the way the 1 g reading is shared between the axes tells you how the board is tilted. It cannot tell you which way the board faces around a vertical axis (its yaw): turning it like a compass needle changes nothing. Tilt the board by an angle θ in the x–z plane, raising the positive x axis, and the reading splits between the axis along the board and the axis normal to it:

ax = g sin θ,     az = g cos θ      so      θ = atan2(ax, az)(1)

At θ = 30°, ax = 0.500 g and az = 0.866 g. A single axis gives the angle too, θ = arcsin(ax/g), but that needs g, and your sensor's idea of g, exactly, and it cannot tell 30° from 150°. math.atan2(ax, az) uses the ratio of two readings, so a common scale error cancels, and it keeps the sign of both components, so it covers the full circle.

A board tilted by theta on a slope. The +1 g reading points straight up and is split into a component along the board, a_x = g sin theta, and one normal to the board, a_z = g cos theta. At theta = 30 degrees, a_x = 0.500 g and a_z = 0.866 g.
Figure 4. A board tilted by θ on a slope. The +1 g reading points straight up and splits into a component along the board, ax = g sin θ, and one normal to it, az = g cos θ. At θ = 30°, ax = 0.500 g and az = 0.866 g.

Task 4 asks you to theorize how a tilted plane affects the readings. Equation (1) is the answer, and the useful thing to notice is that the sensitivity is not uniform. Differentiating,

daxdθ = g cos θ(2)

which is largest at θ = 0 and vanishes at θ = 90°. So an axis is most sensitive to tilt when it is horizontal, and almost blind to tilt when it is pointing straight down. A device lying flat detects small tips very well with its x axis; the same axis stood on end barely notices them. That fact drives the whole of §7.3.

3 The LIS3DH

3.1 Inside the chip: sensor, ADC, registers

The LIS3DH is a three-axis MEMS accelerometer with the same architecture as the MCP9808: a sensing element, an ADC, a bank of registers, and a serial interface. Since it speaks I²C, everything in §5–§9 of the Lecture 06 notes applies unchanged: two wires, pull-ups, a 7-bit address, register pointers, and smbus2 reads.

LIS3DH datasheet Figure 1, block diagram: the X, Y and Z sensing capacitors feed a multiplexer, charge amplifier and A/D converter into control logic with I2C and SPI interfaces. A second A/D converter serves three auxiliary ADC inputs and a temperature sensor. Blocks for self-test, reference, trimming circuits, clock, a 32-level FIFO and interrupt generation sit below.
Figure 5. The LIS3DH block diagram. The X, Y and Z sensing capacitors feed a multiplexer, a charge amplifier and an A/D converter, whose results reach the control logic and the I²C and SPI interfaces. A second converter serves three auxiliary ADC inputs and a temperature sensor; self-test, reference, trimming, clock, a 32-level FIFO and interrupt generation sit below. Source: ST LIS3DH datasheet (DocID17530 Rev 2), Figure 1.
LIS3DH datasheet Figure 2, top view: the package with pin 1 marked, and arrows showing the X, Y and Z directions of the detectable accelerations.
Figure 6. The directions of the detectable accelerations, drawn on the package with pin 1 marked. Your breakout may be mounted in any orientation, so find its axes by the six-orientation test of §6.2. Source: LIS3DH datasheet, Figure 2.

3.2 Twelve bits of data in a 16-bit register

Each axis has two 8-bit registers: for x, OUT_X_L at 0x28 and OUT_X_H at 0x29 (then y at 0x2A–0x2B, z at 0x2C–0x2D). Together they form a 16-bit two's-complement number, but the ADC does not fill all 16 bits. The data are left-justified: the converter's bits occupy the top of the register, and the unused low bits read 0. How many bits are real depends on the operating mode:

ModeBitsShift right bySensitivity at ±2 g
Low-power8816 mg per digit
Normal1064 mg per digit
High resolution (the driver's default)1241 mg per digit
The 16 bits of one LIS3DH axis: OUT_X_H at 0x29 holds 0x3D and OUT_X_L at 0x28 holds 0x40, giving 0011 1101 0100 0000 with bit 15 as the sign. Below, the bits each mode fills from the top: low-power 8 bits at 16 mg per digit, normal 10 bits at 4 mg per digit, high resolution 12 bits at 1 mg per digit. Data are left-justified and the unused low bits read 0.
Figure 7. The 16 bits of one LIS3DH axis: OUT_X_H at 0x29 holds 0x3D and OUT_X_L at 0x28 holds 0x40, giving 0011 1101 0100 0000 with bit 15 as the sign. Below, the bits each mode fills from the top: low-power 8 bits at 16 mg per digit, normal 10 bits at 4 mg, high resolution 12 bits at 1 mg. The unused low bits read 0.

Raw values come back as signed integers in two's complement, the same representation you handled for negative temperatures in Lecture 06 §11.2, and the same trap: a sign bug is invisible while readings are positive. The worked example in §6.1 decodes one positive and one negative reading.

The device is configurable to a full-scale range of ±2, ±4, ±8 or ±16 g. The trade is the familiar one:

Range versus resolution

The ADC produces a fixed number of counts across whatever range is selected. Choosing a wider range means each count represents a larger acceleration, so the resolution gets coarser. Take the step sizes from the datasheet rather than assuming each range doubles the last; the ±16 g step does not. In high-resolution mode they are 1, 2, 4 and 12 mg per digit for ±2, ±4, ±8 and ±16 g.

For tilt measurement and a gentle pendulum, the smallest range is the right choice: the signals are all around 1 g, and you want the finest resolution you can get. Switch to a wider range only if the readings clip at the extremes, which a vigorously swung pendulum can do. Check for clipping by looking for flat tops in your Task 6 plot.

3.3 Wiring the breakout and bringing it up

The LIS3DH uses the same four wires as the MCP9808: 3.3 V, ground, SDA and SCL. It is a 3.3 V part on a 3.3 V bus; the 5 V header pins are not used.

Wiring an LIS3DH breakout to the Pi header. Pin 1 (3V3) goes to Vin, pin 3 (SDA) to SDA, pin 5 (SCL) to SCL and pin 6 (GND) to GND; the 5 V pins 2 and 4 are not used. SDO sets the address: open gives 0x18, tied to 3V3 gives 0x19. 3Vo, CS, INT and A1 to A3 stay open for I2C. Pins should be matched by their printed labels, because the header order differs between board versions.
Figure 8. Wiring an LIS3DH breakout to the Pi header: pin 1 (3V3) to Vin, pin 3 (SDA) to SDA, pin 5 (SCL) to SCL and pin 6 (GND) to GND; the 5 V pins 2 and 4 are not used. On the breakout shown, SDO is pulled low for 0x18; tying it to 3V3 selects 0x19. Its CS pull-up enables I²C, so CS needs no external wire. Leave 3Vo, INT and A1–A3 unconnected. Match pins by their printed labels, because the header order differs between board versions.

Task 3 asks you to detect its address from the terminal, which is the same i2cdetect -y 1 you used last week. On the breakout shown, a fitted pull-down selects 0x18 when SDO has no external connection; tying SDO to 3.3 V selects 0x19. (A bare LIS3DH, or a different breakout, may need you to wire these yourself: SDO must be tied high or low, and CS must be high for I²C. Check the board's schematic.) The MCP9808 also defaults to 0x18, so in Task 7, when both share the bus, the LIS3DH must move to 0x19 (§15.3). Read the address off the scan rather than assuming it. When both sensors are connected, both should appear in the grid at once, a satisfying sign that a shared bus really does work.

Like the MCP9808, the LIS3DH has an identification register containing a fixed known value: WHO_AM_I, at 0x0F, reads 0x33. Read it first, for exactly the reason given in Lecture 06 §8.2: it proves the wiring, address, and library in a single step and separates hardware problems from decoding problems.

i2cdetect -y 1              # expect 18 (or 19 with SDO to 3.3 V)
i2cget -y 1 0x18 0x0f       # WHO_AM_I: expect 0x33

4 The Driver Module

4.1 Registers behind method names

You could read the LIS3DH with nothing but smbus2 calls, but you would soon be copying register addresses, bit masks and scale factors into every script. The provided LIS3DHMOD.py is a driver: a module that knows the chip and hides its registers behind method names such as getX(). Each layer in Figure 9 hides the one below it: the application never sees a register, and the driver never sees SDA.

Five software and hardware layers. The application tilt_log.py calls sensor.getX() and knows the experiment. The driver LIS3DHMOD.py reads registers 0x28 and 0x29 and converts to g; it knows the chip. The smbus2 library calls read_byte_data(0x18, 0x28) and knows I2C transactions. The Linux kernel device /dev/i2c-1 sends START, address, ACK and STOP and drives SDA and SCL. The LIS3DH registers, such as 0x0F ID, 0x20 CTRL_REG1 and 0x28 OUT_X_L, make the numbers. Requests go down and data come back up.
Figure 9. Five layers. The application tilt_log.py calls sensor.getX() and knows the experiment. The driver LIS3DHMOD.py reads registers 0x28 and 0x29 and converts to g; it knows the chip. The smbus2 library calls read_byte_data(0x18, 0x28) and knows I²C transactions. The Linux device /dev/i2c-1 sends START, address, ACK and STOP on SDA and SCL. The LIS3DH registers (0x0F ID, 0x20 CTRL_REG1, 0x28 OUT_X_L) make the numbers. Requests go down and data come back up.

4.2 Two control registers set up the whole chip

Two registers hold almost every setting that matters here. CTRL_REG1 (0x20) sets the output data rate (ODR), low-power mode and which axes are enabled. CTRL_REG4 (0x23) sets block data update (BDU), the full-scale range and high-resolution mode. The driver's setRange, setDataRate, setHighResolution and setBDU each read one of these registers, change a few bits, and write it back, leaving the other bits alone.

Bit fields after the driver's defaults and setDataRate(0b0101). CTRL_REG1 at 0x20: ODR 0101, LPen 0, Zen Yen Xen 1 1 1, which is 0x57: 100 Hz, not low-power, all axes on. CTRL_REG4 at 0x23: BDU 1, BLE 0, FS 00, HR 1, ST 00, SIM 0, which is 0x88: block data update, plus or minus 2 g, 12-bit high resolution.
Figure 10. The two control registers after the driver's defaults and setDataRate(0b0101). CTRL_REG1 at 0x20: ODR 0101, LPen 0, Zen Yen Xen 1 1 1, which is 0x57: 100 Hz, not low-power, all axes on. CTRL_REG4 at 0x23: BDU 1, BLE 0, FS 00, HR 1, ST 00, SIM 0, which is 0x88: block data update, ±2 g, 12-bit high resolution.

BDU matters because each axis is two registers read one after the other. Without it, the chip can finish a new conversion between your read of the low byte and your read of the high byte, and you combine halves of two different samples. With BDU set, the output registers are not updated until both bytes of the current sample have been read, so H and L for an axis come from the same sample. BDU does not, however, make the three axes come from the same sample, since the driver reads them one after another, and it does not promise that each read is a new sample. If you need all three axes from one instant, wait for the chip’s data-ready flag and read all six bytes in one burst; the datasheet explains how.

4.3 Driver script against application script

Keep the facts about the chip in one file and the facts about the experiment in others. The driver is tested once (WHO_AM_I, scaling, sign handling) and every experiment reuses it. If a scaling bug turns up, you fix it in one place and every script gets the fix. An application stays short enough to read in one go, one per task.

Two ways to organize code. Left: one long script that mixes register addresses, bit masks, plotting, CSV writing, two's complement, a divisor and experiment loops, and gets copied into every lab. Right: one driver file, LIS3DHMOD.py, holding registers, bits and scaling, imported by three small applications (check_axes.py, tilt_log.py, pendulum.py). The driver is tested once and every experiment reuses it.
Figure 11. Two ways to organize code. Left: one long script mixing register addresses, bit masks, plotting, CSV writing, two's complement, a divisor and the experiment loop, copied into every lab. Right: one driver file, LIS3DHMOD.py, holding registers, bits and scaling, imported by three small applications: check_axes.py, tilt_log.py and pendulum.py.

4.4 A Lab 7 project folder

lab07/
├── LIS3DHMOD.py     driver, given
├── mcp9808_mod.py   driver, Lab 6
├── hcsr04.py        your functions
├── check_axes.py    application
├── tilt_log.py      application
├── threads_demo.py  application
├── procs_demo.py    application
└── data/
    └── tilt_run1.csv

import LIS3DHMOD as acc (no .py) finds the driver because Python searches the running script's own folder first. So keep the drivers beside your scripts and run each script from that folder, python3 tilt_log.py. Your own HC-SR04 functions can live in a module of the same kind, hcsr04.py. A driver's self-test belongs under if __name__ == "__main__":, so that it runs when you execute the driver directly and not when an application imports it.

4.5 Walkthrough 1: inside the provided driver

Condensed from LIS3DHMOD.py, as on the slide:

def __init__(self, address=0x18):
    self.bus = smbus2.SMBus(1)  # /dev/i2c-1
    self.address = address      # or 0x19
    # WHO_AM_I (0x0F) must read 0x33
    if not self._device_connected():
        raise Exception("No LIS3DH ...")
    self.configure_defaults()

def configure_defaults(self):
    self.setAxisStatus(self.AXIS_X, True)
    self.setAxisStatus(self.AXIS_Y, True)
    self.setAxisStatus(self.AXIS_Z, True)
    self.setDataRate(self.DATARATE_400HZ)
    self.setHighResolution()    # 12 bits
    self.setBDU()               # BDU = 1
    self.setRange(self.RANGE_2G)

def getAxis(self, axis):  # 0 X, 1 Y, 2 Z
    base = self.REG_OUT_X_L + 2 * axis
    low = self.bus.read_byte_data(self.address, base)
    high = self.bus.read_byte_data(self.address, base + 1)
    value = low | (high << 8)     # 16 bits
    value = self.twosComp(value)  # signed
    # counts per g: 16 / (mg per digit)
    divisors = {self.RANGE_2G: 16000,
                self.RANGE_4G: 8000,
                self.RANGE_8G: 4000,
                self.RANGE_16G: 1333.33}
    divisor = divisors[self.getRange()]
    return float(value) / divisor

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

Three points are worth reading closely. The constructor refuses to continue unless WHO_AM_I reads 0x33, and its message tells you what to do if the MCP9808 is sitting at 0x18. The divisor folds two steps into one: shifting right by 4 (divide by 16) and multiplying by 1 mg per digit gives 16 / 0.001 = 16000 counts per g at ±2 g. And getRange() reads CTRL_REG4 each time, so one axis costs three I²C reads, not two.

4.6 Walkthrough 2: the application reads the axes

import time
import LIS3DHMOD as acc

sensor = acc.LIS3DH()     # WHO_AM_I check, defaults
sensor.setRange(acc.LIS3DH.RANGE_2G)
sensor.setDataRate(acc.LIS3DH.DATARATE_100HZ)

t0 = time.perf_counter()
for i in range(100):
    t = time.perf_counter() - t0
    x = sensor.getX()
    y = sensor.getY()
    z = sensor.getZ()
    print(f"{t:6.3f} s  x={x:+.3f}  "
          f"y={y:+.3f}  z={z:+.3f} g")
    time.sleep(0.01)

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

The settings for the experiment live in the application, not the driver. Record t from perf_counter() rather than computing it from the loop count, because sleep(0.01) is only part of each pass. The nine I²C reads (three axes, three reads each) add at least 3.24 ms at 100 kHz: each read_byte_data clocks four bytes with acknowledgment bits, or 36 clocks (0.36 ms), plus START, STOP and driver delays, and print adds more. The loop therefore runs at well under 100 passes per second, and only the timestamps tell you the truth.

5 Recording the Data

Task 5 asks for plots of acceleration against time, and CSV and image files. There are two strategies, and they suit different jobs.

5.1 Strategy 1: plot while you record

from collections import deque
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
t = deque(maxlen=500)  # latest 500 readings
z = deque(maxlen=500)
fig, ax = plt.subplots()
line = ax.plot([], [])[0]  # the plotted line
ax.set_ylim(-2, 2)

def update(frame):
    for i in range(10):   # read in batches
        t.append(time.perf_counter() - t0)
        z.append(sensor.getZ())
        time.sleep(0.01)  # pace the reads
    line.set_data(t, z)
    ax.set_xlim(t[0], t[-1] + 0.01)
ani = FuncAnimation(fig, update, interval=10,
                    cache_frame_data=False)
plt.show()

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

This fragment continues from §4.6 and uses its sensor, time and t0. A deque with maxlen=500 keeps only the newest 500 readings. The short sleep between reads stops the loop from reading the same sample over and over, but the reads and the drawing still make the intervals uneven, and interval=10 only asks for a pause between redraws; it is not a 100 Hz clock. So rely on the timestamps, and log first (§5.2) when timing matters.

Simulated accelerometer data over 10 seconds: z starts at 1 g and x at 0; a 30 degree tilt moves x to 0.5 g and z to 0.87 g, then back; a shake near 8 seconds makes x and y oscillate. The last 5 seconds are shaded as the window a live plot would show.
Figure 12. Simulated accelerometer data over 10 s: z starts at 1 g and x at 0; a 30° tilt moves x to 0.5 g and z to 0.87 g, then back; a shake near 8 s makes x and y oscillate. The last 5 s are shaded: the window a live plot would show.

5.2 Strategy 2: log to CSV, analyze later

import csv, os, time
os.makedirs("data", exist_ok=True)
# sensor: set up as in Walkthrough 2
with open("data/tilt_run1.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["t_s", "x_g", "y_g", "z_g"])  # header
    t0 = time.perf_counter()
    for i in range(1000):
        t = time.perf_counter() - t0
        x = sensor.getX()
        y = sensor.getY()
        z = sensor.getZ()
        w.writerow([t, x, y, z])
        time.sleep(0.01)

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

and later, in a separate script:

import numpy as np
f = "data/tilt_run1.csv"
d = np.loadtxt(f, delimiter=",", skiprows=1)
x = d[:, 1]  # column 1: x_g
print(x.mean(), x.std(ddof=1))

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

One row per sample and one header row; with closes the file even after Ctrl-C. Logging first keeps the sampling loop clean, and it keeps the run: every average, fit or plot can be redone later without repeating the experiment. For Tasks 4 to 6 that is usually the better strategy; the live plot is for watching, not for measuring. std(ddof=1) is the sample standard deviation, the one to report.

6 From Register Bytes to g

6.1 Worked example

Worked example: two readings decoded

Positive. OUT_X_H = 0x3D and OUT_X_L = 0x40 combine to 0x3D40 = 15680. Bit 15 is 0, so it is positive. Shift right by 4 (divide by 16): 980 counts. At 1 mg per digit that is +0.980 g. The driver does it in one step: 15680 / 16000 = 0.980.

Negative. 0xE0 and 0xC0 combine to 0xE0C0 = 57536. Bit 15 is 1, so subtract 65536: −8000. Divide by 16: −500 counts, −0.500 g; in one step, −8000 / 16000.

Skip the two's-complement step and the second reading becomes 57536 / 16000 ≈ +3.6 g: an absurd number for a board at rest, which is at least easy to spot.

Converting two register bytes to g in five steps. H = 0x3D and L = 0x40 combine to 0x3D40 = +15680, which divided by 16 is +980 counts, which at 1 mg per digit is +0.980 g; the driver does this in one step as 15680 / 16000. H = 0xE0 and L = 0xC0 combine to 0xE0C0; the top bit is 1, so subtracting 65536 gives -8000, then -500 counts and -0.500 g, or -8000 / 16000 in one step.
Figure 13. Converting two register bytes to g in five steps. H = 0x3D and L = 0x40 combine to 0x3D40 = +15680, which divided by 16 is +980 counts, which at 1 mg per digit is +0.980 g; the driver does this as 15680 / 16000. H = 0xE0 and L = 0xC0 combine to 0xE0C0; the top bit is 1, so subtracting 65536 gives −8000, then −500 counts and −0.500 g, or −8000 / 16000 in one step.

6.2 Validating the axes

Validating the x-axis (Task 3)

You do not need a calibration rig. Gravity is a known, free, extremely stable 1 g reference, and it is always available.

Lay the board flat and the vertical axis should read about +1 g with the other two near zero. Turn it over and that axis should read about −1 g. Stand it on each edge in turn and the 1 g should move to the appropriate axis with the appropriate sign. Six orientations, and you have checked every axis, both signs, and the scale factor, and you have found which physical direction each axis label corresponds to, which you will need for Task 6.

Any axis that reads 0 in all six orientations, or 1 g in all of them, is telling you something is wrong before you take a single data point.

6.3 Calibrating by flipping

The 1 mg per digit in the datasheet is the typical sensitivity, not your chip's, and each axis also has a small zero-g offset. The same six orientations measure both. Point an axis straight up and record its reading rup (ideally +1 g), then straight down, rdown (ideally −1 g). This is the procedure of datasheet §3.1.1:

scale = rup − rdown2       offset = rup + rdown2(3)

and the corrected reading is (r − offset)/scale. For example, rup = +1.030 and rdown = −0.990 give scale 1.010 and offset +0.020 g. Average many readings in each orientation (§7.2), so that the calibration is not limited by noise.

7 Noise, Averaging and the Smallest Detectable Tilt

7.1 The standard deviation at rest

Task 4 asks for the standard deviation with the accelerometer stationary. With nothing moving, every deviation from the mean is noise, from the sensor, the ADC, the supply and building vibration. That standard deviation σ is your noise floor, and it sets everything that follows.

For a rough idea of what to expect: the datasheet’s noise density is 220 µg/√Hz, and in high-resolution mode the chip filters to a bandwidth of about ODR/9, or 11.1 Hz at 100 Hz. Multiplying, 220 µg/√Hz × √(11.1 Hz) gives σ ≈ 0.7 mg. Treat that as an estimate, not a promise: the datasheet quotes its noise density under other conditions, and the filter’s real noise bandwidth is not exactly ODR/9. Measure it at your own settings. (The same filter also makes each reading slightly correlated with the one before, which matters in §7.2.)

Take the readings with the device on a solid surface, not held in your hand and not on a bench someone is leaning on. Report σ for each axis separately, in g or milli-g; they are often not equal, and the vertical axis frequently differs from the two horizontal ones.

7.2 Averaging

Task 5 asks you to average n sequential measurements and find the standard deviation of those averages. For independent random noise, theory predicts

σmean = σ√n(4)

so averaging 100 readings should reduce the scatter tenfold. Test this rather than assuming it; that is what the task is really asking. Compute σmean for several values of n and plot it against 1/√n. Use separate, non-overlapping groups of readings for the averages, and make sure each reading is a new sample, not a repeat. If your points follow the line, the noise is behaving as independent noise should; if they do not, look for whatever links one sample to the next.

Relative scatter versus averaging count on logarithmic axes. Independent noise falls as one over the square root of count. An illustrative drift floor prevents continued improvement at large counts.
Figure 14. Relative scatter of an average against the number of readings averaged, on logarithmic axes. Independent noise follows 1/√n (dashed), a straight line of slope −½. An illustrative drift floor (solid) makes real data flatten at large n; where your data leaves the line is the useful result.
When averaging stops helping: the interesting result

Equation (4) only holds for independent noise. Drift, a slow thermal trend or building vibration at one frequency all link each sample to the next, and then Equation (4) no longer predicts the reduction. A long enough average can smooth out vibration, but no average removes a fixed offset.

So at large n your measured σmean will usually fall above the 1/√n line and eventually flatten out. Where it flattens tells you the longest average worth making before slow, systematic effects take over.

7.3 The smallest detectable angle change

Now combine the two halves. Task 4 asks for the smallest angle change the accelerometer can detect, and the answer follows directly from §2.3 and §7.1. Rearranging Equation (2), an acceleration change of Δa corresponds to an angle change of

Δθ ≈ Δag cos θ(5)

What should Δa be? If you compare one reading with a well-known reference, use σ, or a stated multiple of it. If you compare two readings with each other, each has uncertainty σ, so their difference has √2 σ. (The same goes for averages, with σmean in place of σ.) Whatever criterion you pick, one σ or two, state it, because the answer depends on it.

Accelerometer tilt response ax/g equals sine theta, while angular sensitivity is proportional to cosine theta. Sensitivity is greatest near a horizontal axis and tends to zero near 90 degrees.
Figure 15. Tilt response of an axis that starts horizontal. The reading ax/g = sin θ (solid) rises steeply near θ = 0 and flattens near 90°; its slope, proportional to cos θ (dashed), is the sensitivity of Equation (2). Equation (5) turns that sensitivity into an angle resolution.

Two things are worth drawing out. First, the answer depends on θ: near horizontal, cos θ ≈ 1 and sensitivity is best; near vertical it degrades badly. Quote the angle you evaluated at. Second, averaging improves it: use σmean from Equation (4) instead of σ and the detectable angle shrinks by √n, at the cost of measurement time. That trade between resolution and speed is the same one you met in the MCP9808's resolution register, and you will meet it again in Lab 8.

Worked example: tilt resolution near horizontal

Suppose a horizontal axis has a measured σ = 0.004 g, several times the estimate of §7.1, which a bench with people and equipment on it can easily give. With a 2σ detection criterion, Δa = 0.008 g, and near θ = 0, cos θ ≈ 1, so Equation (5) gives

Δθ ≈ 0.008 gg = 0.008 rad ≈ 0.46°

Averaging 64 independent readings reduces σ by √64 = 8, so the detectable change falls to 0.001 rad ≈ 0.057°. The price is time: each averaged value needs 64 sample intervals, 1.28 s at 50 samples per second. Remember that Equation (5) gives Δθ in radians.

Practice 7

(a) An axis reads a mean of 0.012 g with σ = 0.006 g while horizontal. Using a 2σ criterion, what is the smallest detectable tilt near θ = 0?

(b) Repeat at θ = 60°. By what factor has the sensitivity degraded?

(c) Averaging 25 readings, what does the answer to (a) become, assuming Equation (4) holds? How long does that take at 50 samples per second?

(d) Your measured σmean flattens out at n ≈ 200 instead of continuing to fall. Give two plausible physical causes.

(e) Flipping an axis gives rup = +0.985 g and rdown = −1.025 g. Find the scale and offset, and correct a reading of +0.480 g.

8 The Pendulum Experiment

Task 6 mounts the accelerometer on a pendulum, logs all three axes for at least ten seconds, plots them in three colors, and asks whether the observed frequencies match the physical motion, and to explain any discrepancies. That last clause is the heart of the task, and there is a specific piece of physics behind it.

8.1 The swing frequency

For small amplitudes, a simple pendulum of length L has period and frequency

T = 2π√(L/g)      fswing = 12π√(g/L)(6)

For a compact bob on a light string, measure L from the pivot to the bob's center of mass. For an extended rigid assembly, use T = 2π√(I/(mgh)), where I is the moment of inertia about the pivot and h is the pivot-to-center-of-mass distance. Its equivalent simple-pendulum length is I/(mh). Note that the period does not depend on mass, and only weakly on amplitude provided the swing is modest.

8.2 What each axis reads, and why

Start from §2.2: an accelerometer reports specific force, the non-gravitational force on it per unit mass. Gravity pulls on the proof mass and on the chip around it equally, so it never shows up on its own. On a string pendulum the only other force on the bob is the tension in the string. So the sensor reads the tension divided by the mass, and nothing else, and the tension points along the string, toward the pivot. Mount the breakout on the bob with one axis along the string (radial) and one across it (tangential), and everything follows from that one fact.

What each axis of a swinging accelerometer reads, computed for a 1 Hz swing of 0.2 rad (11.5 degrees). Left: a string pendulum at angle theta with the sensor at the bob; its radial axis points along the string toward the pivot and its tangential axis across it; the string's tension acts along the string, and gravity, drawn pointing down, is not sensed. Right, top: the angle swings between plus and minus 11.5 degrees at frequency f. Middle: the radial reading, g cos theta plus v squared over L, swings between 0.98 and 1.04 g, peaking at the bottom twice per swing, so at 2f. Bottom: the tangential reading is 0 for the string pendulum; for a sensor at the far end of a swinging rod it is minus one half g theta, plus and minus 0.1 g, at f.
Figure 16. What each axis reads, computed for a 1 Hz swing of 0.2 rad (11.5°). Left: a string pendulum with the sensor at the bob; the radial axis lies along the string and the tangential axis across it; the tension acts along the string, and gravity is not sensed. Right: the angle swings at f; the radial reading, g cos θ + v²/L, runs from 0.98 to 1.04 g and peaks at the bottom twice per swing, so at 2f; the tangential reading is 0 on a string, and −½ gθ, at f, for a sensor at the far end of a swinging rod.

Radial: 2f. The tension must hold up the component of the bob's weight along the string, mg cos θ, and also supply the centripetal force, mv²/L, that bends the bob's path into a circle:

aradial = Tm = g cos θ + v²L(7)

Both terms are largest at the bottom of the swing, where θ = 0 and the bob is fastest, and both are smallest at the two turning points, where the bob stops. The bob passes the bottom twice per period (once going each way), so the radial reading goes up and down twice per swing: its main oscillation is at 2f, around a mean slightly above 1 g. For the 0.2 rad swing of Figure 16 it runs from cos 0.2 = 0.980 g at the ends to 1 + 0.2² = 1.040 g at the bottom (for small swings, v²/gL = θ0² there). The direction of the swing makes no difference to it, which is why the frequency doubles.

Tangential: zero. The tension has no component across the string, so an ideal tangential axis reads 0 throughout the swing. This surprises most people, because the bob plainly speeds up and slows down along its path. But that tangential acceleration, −g sin θ, is caused entirely by gravity, and gravity is exactly what the accelerometer cannot feel: the proof mass and the chip speed up together, so the springs never stretch.

Where a signal at f comes from. If your tangential trace does show the swing frequency, the pendulum is not a point mass on a string. On a rigid pendulum (a ruler or rod pivoted at one end), a point at distance r from the pivot reads

atangential = r θ̈ + g sin θ ≈ g θ (1 − rLeq)(8)

where Leq is the equivalent simple-pendulum length; the point that far from the pivot is the center of oscillation. The term rθ̈ is how fast that point actually speeds up; g sin θ is the part gravity would supply for free. At r = Leq they cancel, as for the string. Nearer the pivot the acceleration toward equilibrium is smaller than gravity alone would produce, so the constraint opposes that gravitational component and the reading is in phase with θ. Farther out the required acceleration is larger, so the constraint adds to gravity and the reading is opposite in phase. Both are at f, because they follow θ. For a light sensor at the far end of a uniform rod of length ℓ, Leq = 2ℓ/3, so the reading is gθ(1 − 3/2) = −½ gθ: ±0.1 g for the swing of Figure 16 (the dashed trace).

Predict your own traces before you swing
  • The radial axis, positive toward the pivot, swings mainly at 2f. Its mean and the size of its swing depend on how far the sensor sits from the pivot.
  • The tangential axis shows almost nothing on a string, and f on a rigid pendulum unless the sensor sits at its center of oscillation.
  • A breakout mounted at a tilt to the string shares the tension between its axes, so the leak onto the “wrong” axis is also at 2f, not f.
  • The third axis, perpendicular to the swing plane, should read about zero. Signal there means the pendulum is swinging in an ellipse or twisting.

The sensor twisting on the string, air drag and the pull of the cable add smaller signals at other frequencies. Write down exactly how the sensor is mounted, predict the traces for that mounting, and only then decide which peak is which.

Ideal pendulum with a 1 Hz swing: the swing angle oscillates at 1 Hz, while the inward radial specific force, in units of g, peaks each time the bob passes the bottom and so oscillates at 2 Hz around a mean near 1 g.
Figure 17. An ideal point pendulum swinging at 1 Hz with a 0.2 rad (11.5°) amplitude, over four periods, computed rather than measured. Top: the swing angle. Bottom: the radial specific force of Equation (7), in units of g. It peaks each time the bob passes the bottom, twice per swing, so its main component is at 2 Hz around a mean near 1 g.

8.3 Getting data worth analyzing

  1. Know your axis orientation. Do the six-orientation check from §6.2 with the sensor mounted as it will swing, so you know before you start which axis is radial and which tangential. Without that, the frequency analysis is guesswork.
  2. Sample fast enough. A pendulum might swing at 1–2 Hz, and you need to resolve 2f as well. Sampling at a few tens of Hz is ample; sampling at 2 Hz would be useless. This is a sampling-rate argument you will meet formally in Lab 8.
  3. Swing in one plane. A pendulum allowed to trace an ellipse puts signal on all three axes and muddles the interpretation. Release it carefully, without a sideways push.
  4. Keep the amplitude modest. Equation (6) is a small-angle result. A large swing changes the period measurably and is a legitimate thing to investigate, but do it deliberately rather than by accident.
  5. Mind the cable. The wires to the Pi add stiffness and damping and can dominate a light pendulum. Strain-relieve them and note how you managed this.
  6. Record at least ten seconds and 100 points as the task requires, and enough oscillations that a frequency can be read confidently from the plot.

To extract the frequencies, counting peaks over a known interval is perfectly acceptable and transparent. Compare the result against Equation (6), quote both, and account for the difference: pivot friction, air resistance, the cable, a center of mass that is not where you assumed, or an amplitude beyond the small-angle regime.

9 Challenge: A Tilt Alarm

The slides end Part 2 with a design problem, posed here without a solution.

Practice 9: the tilt alarm

Write a program that prints TILT once when the tilt angle passes 20° for 5 samples in a row. It then stays quiet until the angle falls below 15°, and only then rearms.

(a) Why two thresholds? What would a single 20° threshold do when the true angle sits near 20° and the reading is noisy?

(b) Why 5 samples in a row? What does that requirement cost you in response time at 100 samples per second?

(c) What does a sharp shake of the board do to Equation (1)'s angle, and does your rule reject it?

(d) How would you choose the gap between the two thresholds from the σ you measured in Task 4?

Simulated noisy tilt angle rising from about 10 degrees above 20 and back below 15. Dashed lines mark an arm threshold at 20 degrees and a rearm threshold at 15 degrees. Below, a simple 'angle above 20 degrees' test switches on and off many times as noise crosses the line, while an alarm with a 5-sample rule and a separate rearm threshold switches on once and off once.
Figure 18. A simulated noisy tilt angle rising from about 10° to above 20° and back below 15°. Dashed lines mark an arm threshold at 20° and a rearm threshold at 15°. Below, a simple “angle above 20°” test switches on and off many times as noise crosses the line, while an alarm with a 5-sample rule and a separate rearm threshold switches on once and off once.

10 Accelerometer Pitfalls

MistakeWhat you seeFix
No two's complement−0.5 g reads +3.6 gSubtract 65536 if bit 15 is set (§6.1)
Range too smallFlat tops at ±2 gNext range up; look at the plot (§3.2)
Skipping calibration±1 g reads a few per cent offFlip each axis: scale and offset (§6.3)
Two chips at 0x18Garbage, or one sensor missingLIS3DH SDO to 3.3 V → 0x19 (§3.3)
Redraw every sampleSample rate collapsesPlot every N samples, or log first (§5)
Loose pendulum cableSpikes and dropoutsStrain-relieve the wires (§8.3)

Three more that cost afternoons: expecting a stationary accelerometer to read zero (§2.2); not knowing which axis points where before running the pendulum (§8.3); and sampling too slowly to resolve 2f, then concluding the physics is wrong.

11 From the Accelerometer to the Range Finder

Part 3 turns to a sensor that answers in a completely different way.

LIS3DHHC-SR04
Answers withI²C registersOne pulse width
Supply (in the lab)3.3 V5 V
Python's jobAsk for bytesTime an edge
One reading≈ 3.4 ms (§4.6)Up to about 25 ms, then a rest before the next (§12.1)
HC-SR04 user guide cover: photos of the module front and back, and a sketch of the transmitter sending a chirp to a cylindrical target and receiving its echo, with a start pulse in and an echo time pulse out.
Figure 19. The HC-SR04, front and back, with a sketch of the transmitter sending a chirp to a target and the receiver hearing its echo: a start pulse in, an echo-time pulse out. Source: Handson Technology HC-SR04 user guide (MDU-1014, V2.0), p. 1.

11.1 Sound as a ruler

The principle is the same one bats, sonar and radar use. Emit a pulse, wait for the echo, and time the round trip. If the pulse travels at speed v and returns after time t, it has covered vt, but that is there and back, so the distance to the object is half of it:

d = vsound × t2(9)
The factor of two

Forgetting it gives readings exactly twice the true distance: a large error that nonetheless looks perfectly self-consistent, because it scales correctly with distance. Everything tracks, everything is wrong. Catch it by measuring one known distance with a ruler before you trust anything else.

The HC-SR04 uses 40 kHz, above the range of hearing. Its wavelength in air is

λ = vf = 343 m/s40 kHz ≈ 8.6 mm

so objects much smaller than a centimetre or so scatter the sound rather than reflecting it back. The guide gives an effective beam angle of 15°, and flat, hard targets square to the sensor echo best (§14).

HC-SR04 user guide Figure 1: a transmitter sends ultrasound toward a wall and the receiver hears the reflection, compared with a bat's echolocation; the distance between transmitter and wall is labeled.
Figure 20. The measuring principle: a transmitter sends ultrasound toward a wall and the receiver hears the reflection, as a bat does. Source: HC-SR04 user guide, Figure 1.

12 One Pulse In, One Pulse Out

12.1 The measurement sequence

HC-SR04 user guide Figure 4, timing diagram: a trigger pulse of at least 10 microseconds, an 8-cycle sonic burst from the module, and an echo pulse of 100 microseconds to 18 ms, about 36 ms if no object is detected; allow 10 ms from the end of the echo to the next trigger.
Figure 21. The HC-SR04 timing diagram: a trigger pulse of at least 10 µs, an 8-cycle sonic burst from the module, and an echo pulse of 100 µs to 18 ms, about 36 ms if no object is detected. Source: HC-SR04 user guide, Figure 4.
  1. Drive Trig high for at least 10 µs, then low. The module emits a burst of 8 cycles of 40 kHz ultrasound.
  2. Echo goes high.
  3. When the echo returns, Echo goes low. If nothing returns, Echo stays high for about 36 ms and then falls anyway.
  4. The width of the Echo pulse is the round-trip time t in Equation (9).

Your program therefore has to time a pulse: record when Echo rises, record when it falls, subtract (§13.2). The guide suggests a measurement cycle of at least 60 ms, so that the next trigger cannot catch an echo from the previous burst.

12.2 Pins and voltage: which HC-SR04 do you have?

HC-SR04 user guide pin drawing and table: pins VCC (3.3 to 5 V), TRIG (triggering input, 10 microsecond TTL pulses), ECHO (TTL logic output proportional to distance) and GND.
Figure 22. Pins of the V2.0 module: VCC (3.3 to 5 V), TRIG (a 10 µs TTL pulse starts a measurement), ECHO (a TTL pulse whose width is proportional to distance) and GND. Source: HC-SR04 user guide, p. 5.
PinDirectionWhat it does
VCCpower in5 V in Lab 7. The classic module needs 4.8–5 V; the newer V2.0 module of the user guide accepts 3.3–5 V.
Triginput from the PiA pulse of at least 10 µs starts a measurement. A 3.3 V pulse is comfortably above the module's logic threshold, so this direction needs no conversion.
Echooutput to the PiHigh while the sound is in flight. Its high level is about VCC, which is 5 V in the lab.
GNDgroundShared with the Pi, as always.

The two versions look almost identical, and on both Echo swings to about VCC. Lab 7 powers the module from 5 V, so Echo is a 5 V signal whichever version you have. Check Echo’s high level with an oscilloscope before you connect it to anything. A DMM is no use here: it averages the short pulses and reads well below their peak.

12.3 Echo at 5 V, GPIO at 3.3 V: a divider

Echo must never connect directly to a GPIO pin

This connection can damage the Pi. The Pi's GPIO pins are 3.3 V and not 5 V tolerant. Wiring Echo straight to a GPIO pin puts 5 V on a pin rated for 3.3 V, and can destroy the Pi.

The standard fix is a resistive voltage divider on the Echo line:

VGPIO = VEcho × R2R1 + R2(10)

with R1 from Echo to the GPIO node and R2 from that node to ground. Choose the ratio so 5 V maps comfortably below 3.3 V, yet well above the Pi's logic-high threshold. A ratio of R1 : R2 = 1 : 2 gives 3.33 V, which is marginal, so err on the lower side. Work the arithmetic yourself for the resistors in your kit, and show the divider on the schematic you present for approval in Task 1.

Before you connect the divider to the GPIO pin, trigger the sensor and look at the divider’s output on the scope, including any overshoot on the edges. Leave some margin for resistor tolerance and for a 5 V supply that runs a little high.

HC-SR04 Echo voltage divider: the 5 V Echo output feeds a resistor divider, and its midpoint feeds a Raspberry Pi GPIO input. The lower resistor returns to common ground, reducing the input voltage to a safe level.
Figure 23. The Echo divider: the 5 V Echo output feeds R1, the midpoint feeds a GPIO input, and R2 returns to the common ground, reducing the input voltage to a safe level. Trig needs no divider: the module reads the Pi's 3.3 V as high.

13 From Echo Time to Distance

13.1 A number worth memorizing

At about 20 °C, sound travels at roughly 343 m/s, or 34.3 cm per millisecond. Inverting that for the round trip gives a rule of thumb that makes every later estimate easy:

1 cm of distance → 2 cm of travel → ≈ 58 µs of echo time(11)

This is the user guide's “µs / 58 = cm”. So a 10 cm target gives an echo pulse about 580 µs wide, and a 2 m target about 11.7 ms. The guide's range of 2–400 cm corresponds to echoes of 117 µs to 23.3 ms. Going the other way, a 2.90 ms echo gives d = 343 m/s × 2.90 ms / 2 ≈ 0.497 m. A much longer pulse is outside the stated range and should be rejected; it may be a no-object indication or a late reflection.

Distance against echo pulse width, d = v t / 2 with v = 343.2 m/s at 20 degrees Celsius: a straight line through the origin. Marked points: 1 m at 5.8 ms, 2 m at 11.7 ms and 4 m at 23.3 ms. The timing diagram's echo range of 100 microseconds to 18 ms is shaded, and about 36 ms is marked as the no-object pulse.
Figure 24. Distance against echo pulse width, d = vt/2 with v = 343.2 m/s at 20 °C: a straight line through the origin. Marked points: 1 m at 5.8 ms, 2 m at 11.7 ms and 4 m at 23.3 ms. The timing diagram's echo range, 100 µs to 18 ms, is shaded, and the no-object pulse of about 36 ms is marked.

The guide is not self-consistent here: its timing diagram gives echoes of 100 µs to 18 ms (about 1.7 to 309 cm), while its range table says 2–400 cm. Task 2 is where you find out what your module actually does.

13.2 Pulse timing: from microseconds to Python

The distance measurement is a timing measurement, so every microsecond of timing error becomes a distance error. It is the timing problem of Lecture 03 again, now in millimetres.

HC-SR04 timing, not to scale, annotated with Python. Trig: a 10 microsecond pulse from GPIO.output(TRIG, 1), sleep(10e-6), GPIO.output(TRIG, 0). Sound: a burst of 8 cycles at 40 kHz. Echo: goes high and later low; its width is the round-trip time. A loop 'while ECHO reads 0' records start at the rising edge and a loop 'while ECHO reads 1' records end at the falling edge; t = end minus start, and no edge within the timeout returns None.
Figure 25. HC-SR04 timing, not to scale, annotated with the Python that handles each part. Trig: a 10 µs pulse from GPIO.output(TRIG, 1), sleep(10e-6), GPIO.output(TRIG, 0). Sound: a burst of 8 cycles at 40 kHz. Echo: its width is the round-trip time. A loop “while ECHO reads 0” records start at the rising edge, a loop “while ECHO reads 1” records end at the falling edge; t = end − start, and no edge within the timeout returns None.

Use time.perf_counter(), the clock meant for measuring intervals. (time.get_clock_info('perf_counter') reports its resolution, which is far finer than you need.) The clock is not the limit. What limits the measurement is how quickly the loop notices that the pin has changed, and how often the operating system interrupts it:

Δd = vsound × Δt2   ≈   0.17 mm per µs of timing error(12)
Worked example: how good can Python be?

Suppose the measured pulse width has an uncertainty of about 100 µs, a plausible figure for Python on Linux, and one whose ingredients you measured in Lab 3.

Δd = 343 m/s × 100 µs2 = 0.017 m ≈ 1.7 cm

So timing alone contributes about 1.7 cm, several times the guide’s ±3 mm. Your own Pi may do better or worse. The point is to find out, and to say in your report whether the sensor or the timing limits your result.

Measure your own timing scatter rather than assuming 100 µs: point the sensor at a fixed target, take a hundred readings without moving anything, and take the standard deviation. That spread is your repeatability for this target and setup; it includes the sensor’s and the room’s own variation as well as timing jitter. Compare the mean with a ruler separately to find any bias.

Two other timing considerations matter:

  • Do not poll faster than the physics allows. A 2 m round trip takes about 12 ms, and the module needs time for residual echoes to die away before the next burst. Triggering again too soon lets a late echo from the previous burst be mistaken for the current one. Leave the guide's 60 ms between measurements.
  • Averaging helps, up to a point. Random timing jitter averages down as 1/√n (§7.2). A systematic offset does not average away at all, which is exactly what Task 2's zero-offset measurement is for.

13.3 A range reading that cannot hang

Always include a timeout

If no echo ever returns (the target is too far, too soft, or angled so the sound reflects away), or a wire is loose, Echo may never change state, and a naive while loop waiting for it will hang the program forever.

Every reliable HC-SR04 routine has a timeout on both waits, and returns a clearly invalid result (or raises) when it expires. Deciding what “no reading” should look like in your output is part of the design, and it matters for Task 2, where you are deliberately pushing past the maximum range.

The version on the slides refuses to start if Echo is already high, puts a time limit on both waits, and rejects pulses longer than the useful range:

import time
import RPi.GPIO as GPIO

TRIG = 23            # BCM pin
ECHO = 24            # BCM, via divider
TIMEOUT = 0.040      # s, wait per edge
MAX_ECHO = 0.025     # s, ≈ 4.3 m: no object

GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(ECHO, GPIO.IN)

def echo_time():   # width in s, or None
    if GPIO.input(ECHO) == 1:
        return None  # Echo is still high
    GPIO.output(TRIG, GPIO.HIGH)
    time.sleep(10e-6)          # ≥ 10 µs
    GPIO.output(TRIG, GPIO.LOW)
    t_trig = time.perf_counter()
    start = t_trig
    end = t_trig
    while GPIO.input(ECHO) == 0:
        start = time.perf_counter()
        if start - t_trig > TIMEOUT:
            return None  # never rose
    while GPIO.input(ECHO) == 1:
        end = time.perf_counter()
        if end - start > TIMEOUT:
            return None  # stuck high
    width = end - start
    if width <= 0 or width > MAX_ECHO:
        return None  # no good echo
    return width

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

Each while loop reads the clock on every pass. When the first loop ends, start holds the last time Echo read 0, right before the rising edge. When the second loop ends, end holds the last time Echo read 1, right before the falling edge. Both are set before the loops, so they always exist. A width of zero or less means the program missed the pulse.

MAX_ECHO of 25 ms is 343 × 0.025 / 2 ≈ 4.3 m, just beyond the guide's 4 m, so the 36 ms no-object pulse is rejected. On top of echo_time(), a distance_m(T) function returns v(T) t/2 (§15), or None when there was no echo. Wait at least 60 ms between triggers. The simple examples sleep 60 ms after each reading, which gives a slightly longer cycle.

13.4 Significant figures

Task 1 asks for output in m, cm, mm and inches, with significant figures handled appropriately, and that last clause is graded.

The trap is that unit conversion invents precision. If your measurement is good to about a centimetre, then printing 0.4372 m, 43.72 cm, 437.2 mm and 17.21 in claims a precision of a tenth of a millimetre that you do not have. The underlying measurement does not improve because you changed units.

Decide the real uncertainty from §13.2 and §14 first, then choose the number of digits to match it, and use the same physical precision in every unit. Say in your report what uncertainty you assumed and why.

14 Calibrating the Range Finder

Task 2 asks for four numbers and a comparison with the datasheet: the user guide's 2–400 cm, ±3 mm and 15° beam. Each has a specific meaning, and each needs a stated method.

QuantityWhat it meansHow to measure it
Zero offsetThe constant difference between reported and true distance, from the transducer face not being the reference point, from fixed processing delay, and from your code's overheadMeasure several known distances with a ruler or tape, plot reported against true, and fit a straight line. The intercept is the zero offset; the slope should be 1 and any departure is a scale error
Minimum rangeBelow this the echo returns before the module is ready to listen, and readings become wrong or absentMove a flat target slowly closer until the readings stop tracking reality. Note the distance where it breaks down, not where it becomes merely noisy
Maximum rangeBeyond this the returned echo is too weak to detectMove a large flat target away until readings become erratic or time out. It depends strongly on target size, material and angle, so state what you used
AccuracyTwo separate things: repeatability (scatter over many readings of one fixed target) and trueness (how close the mean is to the ruler)Standard deviation of 100 readings for the first; comparison against the ruler for the second. Report both: they are different quantities and can be very different numbers
Things that will contaminate your calibration
  • Target angle. Ultrasound reflects specularly. A target tilted away from perpendicular sends the echo elsewhere, and the reading vanishes or jumps to something further away. Keep targets square to the sensor and say so.
  • Target material. A hard flat board reflects well; cloth, foam or a soft jumper absorbs. Maximum range measured against a curtain is a different number from maximum range against plywood.
  • Beam width. The module’s beam is roughly fifteen degrees wide, so it does not see a point; it sees a cone, and it responds to the first echo from that cone that is strong enough to detect. That is not always the object you meant. Bench clutter, a nearby wall, or your own hand can take over the reading.
  • Stray echoes. Sound bounces off the bench, the wall behind the target and the equipment around you. A measurement made in a cluttered corner behaves differently from one in an open space.

15 Temperature Compensation

15.1 The speed of sound depends on temperature

Task 7 brings the MCP9808 back and connects the two halves of the lab. Equation (9) needs the speed of sound, and the speed of sound in air is not a constant. It goes as the square root of absolute temperature, and over ordinary room conditions the dependence is very nearly linear:

vsound = 331.3 √(1 + T/273.15)  ≈  331.3 + 0.606 T   m/s,    T in °C(13)

The square-root model gives 337.3 m/s at 10 °C, 343.2 at 20 °C and 349.0 at 30 °C; the linear form is within 0.5 m/s of it from 0 to 30 °C, and 0.8 m/s high at 40 °C.

Speed of sound against air temperature from 0 to 40 degrees Celsius: the exact form 331.3 times the square root of 1 + T/273.15 and the linear approximation 331.3 + 0.606 T nearly coincide. Marked values: 337.3 m/s at 10 degrees, 343.2 at 20 and 349.0 at 30. Assuming 20 degrees in 30 degree air makes the distance 1.7 percent short, 17 mm at 1 m.
Figure 26. Speed of sound against air temperature from 0 to 40 °C: the square-root model 331.3 √(1 + T/273.15) and the linear approximation 331.3 + 0.606 T nearly coincide. Marked values: 337.3 m/s at 10 °C, 343.2 at 20 and 349.0 at 30. Assuming 20 °C in 30 °C air makes the distance 1.7% short, 17 mm at 1 m.
Temperature error and timing error

Assume 20 °C (343.2 m/s) when the air is really at 30 °C (349.0 m/s), and every distance comes out (349.0 − 343.2)/349.0 ≈ 1.7% short: 17 mm at 1 m. Using the 0 °C value, 331.3 m/s, in 30 °C air underestimates distance by about 5.1%.

Near 20 °C, a 1 °C temperature uncertainty gives a fractional speed uncertainty of about 0.606/343.4 = 0.0018. At 1 m this is about 1.8 mm, while 60 µs of pulse-width uncertainty gives about 10 mm. At longer distances the temperature contribution grows proportionally to distance. Compare both terms before deciding which dominates.

15.2 In code

Read the MCP9808, calculate the sound speed, and use it in d = vt/2. The slides' outline:

from mcp9808_mod import MCP9808
import hcsr04          # your module
ts = MCP9808(0x18)
# your Lab 6 function: 0.125 °C steps
temp_c = read_temp_high_res(ts)
d = hcsr04.distance_m(temp_c)

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

Measure the air along the sound path, not just the air at the sensor (§15.4).

15.3 Two sensors, one Pi

The MCP9808 and LIS3DH share the I²C bus, and both default to 0x18. Tie the LIS3DH's SDO to 3.3 V and construct it with LIS3DH(address=0x19); the MCP9808 stays at 0x18. Both revised drivers check which chip answers at their address, and stop with this advice if the wrong one does. The HC-SR04 is not on the bus at all: it still uses its own Trig and Echo GPIO connections.

Block wiring for Lab 7 Task 7. The Pi's pin 1 (3V3), pin 3 (SDA) and pin 5 (SCL) form an I2C bus shared by an MCP9808 at address 0x18 (A0 to A2 open) and an LIS3DH at 0x19 (SDO to 3V3). Pin 2 (5 V) powers the HC-SR04; pin 16 (GPIO 23) drives Trig; Echo returns through a 5 V to 3.3 V divider to pin 18 (GPIO 24). All grounds are joined.
Figure 27. Block wiring for Task 7. The Pi's pin 1 (3V3), pin 3 (SDA) and pin 5 (SCL) form an I²C bus shared by an MCP9808 at 0x18 (A0–A2 open) and an LIS3DH at 0x19 (SDO to 3V3). Pin 2 (5 V) powers the HC-SR04; pin 16 (GPIO 23) drives Trig; Echo returns through a 5 V to 3.3 V divider to pin 18 (GPIO 24). All grounds are joined.

15.4 A valid experiment

A valid compensation experiment

Measure the temperature of air that is typical of the sound’s path, not just of the sensor. Point the range finder at one fixed target, and log the raw pulse width, the temperature, and the distance both with and without compensation. Then compare both distances with the ruler as the room warms or cools.

Warming only the thermometer (with a finger, say) changes its reading but not the air the sound travels through. That shows your arithmetic responds, but it does not show that compensation improves the distance. Temperature differences along the path, and the thermometer’s slow response, can still leave errors.

Practice 15

(a) Compute the speed of sound at 18 °C and at 26 °C. What percentage distance error results from using the 18 °C value in a 26 °C room?

(b) An echo pulse is 1.45 ms wide and the MCP9808 reads 22.5 °C. Find the distance in cm.

(c) Your timing is good to ±80 µs and the room temperature is known to ±0.5 °C. At 1.5 m, which error dominates? Support the answer with numbers.

16 Two Sensors at Once: Threads and Processes

16.1 Four cores, one Python loop

The Pi 5 has four 2.4 GHz Cortex-A76 cores, but a plain Python script runs one thread on one of them. While that thread waits for an echo or sleeps between range readings, nothing reads the accelerometer. Put both sensors in one loop and the range finder's 60 ms rest sets the accelerometer's sample rate too.

Illustrated timelines over 130 ms. Top, one loop: an accelerometer read of about 3.4 ms, then a range measurement, then a 60 ms sleep, so accelerometer samples are 70 ms apart. Bottom, two threads: the accelerometer is read every 10 ms while the range finder runs every 66 ms.
Figure 28. Illustrated timelines over 130 ms. Top, one loop: an accelerometer read of about 3.4 ms, then a range measurement, then a 60 ms sleep, so accelerometer samples are 70 ms apart. Bottom, two threads: the accelerometer is read every 10 ms while the range finder runs every 66 ms.

Python offers two ways out: the threading module and the multiprocessing module. They look almost the same in code and behave very differently on the Pi. Task 7 asks you to build both and to measure what each one buys you, so this section explains how each works, what it costs, and how to measure it.

16.2 Concurrency, parallelism, threads and processes

Four words, used carefully:

  • Concurrency means several jobs are in progress over the same stretch of time. They may take turns on one core.
  • Parallelism means several jobs are executing at the same instant, on different cores. Parallelism is one way to get concurrency; taking turns is another.
  • A process is a running program with its own memory. python3 tilt_log.py starts one process, and in it one Python interpreter. Linux can run each process on any core.
  • A thread is a line of execution inside a process. All threads of a process share its memory: a list one thread appends to is the same list the other thread reads. Python's threads are real Linux threads, and the kernel is free to put them on different cores.

A second distinction decides which tool fits. A job is I/O-bound when it spends most of its time waiting: for time.sleep(), for an I²C transfer, for a pin to change. It is CPU-bound when it spends its time calculating: a long pure-Python loop, a fit, an analysis of a big record. Reading the accelerometer is I/O-bound: about 3.4 ms of bus transfers and then a sleep. The range finder is a special case: it too is waiting for the echo, but the busy-wait loop of §13.3 does its waiting by running Python as fast as it can, so to the interpreter it looks CPU-bound.

Threads (threading.Thread)Processes (multiprocessing.Process)
MemoryShared with the other threadsIts own; data must be sent
Python code at the same instantOne thread at a time (the GIL, §16.3)One per process, on different cores
Passing dataqueue.Queue: the object itself, no copymultiprocessing.Queue: a pickled copy through a pipe
Stop flagthreading.Eventmultiprocessing.Event
Start-upMuch quicker than a processSlower: milliseconds, longer when a fresh interpreter must import your modules again (§16.6)
GPIO pinsAny thread may use pins set up in the processSet up the pins in the process that uses them (§16.8)
Best forLoops that mostly waitCalculation, or keeping a timing-critical loop away from other Python code
Drawing comparing threads and processes on the Raspberry Pi 5's four cores. Left, threading: one process with one Python interpreter, shared memory holding the sensors, queue and stop flag, and one GIL; the range thread holds the GIL and the accel thread waits for it, so although two cores are in use only one thread runs Python at a time. Right, multiprocessing: a main process running the accel loop and a child process running the range loop, each with its own memory and its own GIL, on cores 0 and 2; a Queue carries copies of the data from the child to the main process, and both run Python at once.
Figure 29. Threads and processes on the Pi 5's four cores, a drawing rather than a measurement. Left, threading: one process with one Python interpreter and one GIL; the threads share memory (the sensor objects, the queue, the stop flag). The range thread holds the GIL while the accelerometer thread waits for it, so although the kernel may use two cores, only one thread runs Python at a time. Right, multiprocessing: a main process running the accelerometer loop and a child process running the range loop, each with its own memory and its own GIL, on different cores. A Queue carries copies of the readings from the child to the main process, and both run Python at once.

16.3 Threads take turns: the GIL

In the standard Python on the lab Pis, a thread must hold the global interpreter lock (GIL) to run Python code, and there is one GIL per process. The lock exists because the interpreter's own bookkeeping (above all the reference counts that decide when an object can be freed) is not safe to update from two cores at once. So however many threads you start, only one of them executes Python at any instant. Threads give you concurrency, not parallel Python.

That is less of a limit than it sounds, because a thread gives the GIL up whenever it waits. time.sleep() releases it, and so do file and bus I/O: every smbus2 call ends in a system call into the kernel's I²C driver, and the GIL is free while the kernel moves the bytes. One thread's waiting is then another thread's running time. For two I/O-bound loops, threads work very well.

The exception is a busy-wait, like the while GPIO.input(ECHO) == 0 loops of §13.3: it never sleeps, so it keeps the GIL. A thread that wants the GIL asks for it, and if the holder has not let go within the switch interval (5 ms by default; sys.getswitchinterval() returns 0.005), the interpreter forces the holder to drop it at its next safe point. Two things follow. First, the accelerometer thread may wait several milliseconds while the range thread spins, and now and then longer, because 5 ms is a target, not a guarantee. Second, the forced switch can land just as Echo changes, so the range thread notices the edge late.

Illustration of the GIL over 10 ms. The Echo pin is high from 1.0 to 6.3 ms. The range thread's busy-wait loop holds the GIL; the accelerometer thread's I2C byte comes back at 1.2 ms and it waits 5 ms for the GIL, then a forced switch at 6.2 ms lets it run for 0.2 ms. The range thread sees the falling edge 0.1 ms late, which adds 17 mm to the distance.
Figure 30. An illustration of the GIL over 10 ms. Echo is high from 1.0 to 6.3 ms. The range thread's busy-wait loop holds the GIL; the accelerometer thread's I²C byte comes back at 1.2 ms and it waits 5 ms for the GIL, until a forced switch at 6.2 ms lets it run for 0.2 ms. The range thread sees the falling edge 0.1 ms late, which adds 17 mm to the distance.

A 0.1 ms delay is 17 mm through Equation (12), so threads cost the range finder some timing precision. The switch interval is adjustable:

import sys
print(sys.getswitchinterval())   # 0.005 s by default
sys.setswitchinterval(0.0005)    # ask for switches after 0.5 ms

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

A shorter interval makes the waiting thread less late, at the price of more time spent switching. It is a knob to measure, not a fix: Task 7 asks you to find out what it changes on your Pi.

16.4 Threading code: both sensors at once

import threading
import queue
import time
import RPi.GPIO as GPIO
import LIS3DHMOD as acc
import hcsr04             # your module: distance_m(T)

samples = queue.Queue()   # safe to share between threads
stop = threading.Event()  # stop.set() tells the loops to finish
sensor = acc.LIS3DH()

def accel_loop(period=0.01):
    next_t = time.perf_counter()
    while not stop.is_set():
        t = time.perf_counter()
        x = sensor.getX()
        y = sensor.getY()
        z = sensor.getZ()
        samples.put(("acc", t, x, y, z))
        next_t += period  # fixed schedule
        wait = next_t - time.perf_counter()
        if wait > 0:
            time.sleep(wait)

def range_loop(period=0.06):
    while not stop.is_set():
        t = time.perf_counter()
        d = hcsr04.distance_m(20.0)  # assume 20 °C
        samples.put(("dist", t, d))
        time.sleep(period)

ta = threading.Thread(target=accel_loop)
tr = threading.Thread(target=range_loop)
ta.start()
tr.start()
try:
    while True:
        print(samples.get())
except KeyboardInterrupt:
    pass
finally:
    stop.set()
    ta.join()
    tr.join()
    GPIO.cleanup()

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

Four ideas carry this program. A queue.Queue is safe to share: each thread puts timestamped tuples and the main thread gets them, so no two threads touch the same list. A threading.Event is a shared stop flag that every loop checks. The accelerometer loop keeps a fixed schedule: it adds the period to next_t and sleeps only for what remains, so time spent reading does not accumulate as drift. And the finally block sets the flag, joins both threads so they finish their current pass, and releases the GPIO pins, even after Ctrl-C. With both sensors on one Pi, acc.LIS3DH() would take address=0x19 (§15.3), and the range loop would use the measured temperature instead of 20 °C.

Three more points matter once a third sensor joins:

  • One bus, several threads. The MCP9808 and LIS3DH drivers each open their own smbus2.SMBus(1), and the kernel's I²C driver completes one transaction before it starts the next. Two threads reading two chips on the same bus therefore do not corrupt each other's transfers; one simply waits a fraction of a millisecond. (Reading one axis takes two transactions, low byte then high byte; the BDU bit of §4.2 keeps the pair consistent.)
  • Slow things belong in slow loops. Air temperature changes over minutes, so a temperature thread that reads the MCP9808 once a second and stores the latest value is plenty. The range loop then uses that value.
  • Shared variables need a lock. A Queue handles its own locking, but a plain variable that two threads change does not. count += 1 is a read, an add and a write, and a thread switch between them loses an update. Guard such a variable with a threading.Lock:
import threading

lock = threading.Lock()
latest_temp_c = 20.0   # written by one thread, read by another

def set_temp(value):
    global latest_temp_c
    with lock:         # one thread at a time inside
        latest_temp_c = value

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

16.5 Measuring what concurrency costs

A claim that threads "work" needs numbers. Every sample in the programs above carries its time stamp from time.perf_counter(), and that is what you analyze:

  1. Accelerometer timing. The differences between successive time stamps are the sample intervals. Their mean should be 10 ms at 100 Hz; their standard deviation is the timing jitter; their maximum shows the worst delay, which is what a missed sample in the pendulum data looks like.
  2. Range-finder jitter. Point the HC-SR04 at a fixed target about 0.5 m away, take at least 100 readings, and find the standard deviation of the distance. Through Equation (12), 0.17 mm of scatter corresponds to 1 µs of timing scatter.
  3. Compare like with like. Run the same measurements for the single loop, the threaded program and the multiprocessing program, with the same target, the same periods and nothing else running on the Pi. Repeat each run at least three times: the spread between runs is part of your uncertainty.
import numpy as np

t_acc = np.array(t_acc)        # accelerometer time stamps, s
dt = np.diff(t_acc) * 1e3      # sample intervals, ms
print(f"interval {dt.mean():.2f} ms, "
      f"SD {dt.std(ddof=1):.2f} ms, max {dt.max():.2f} ms")

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

Keep in mind what the numbers can and cannot show. Linux is not a real-time operating system: the kernel can pause any thread or process for its own work, and a desktop session, a browser or a file copy adds more. Some jitter remains whatever you do in Python. The question Task 7 asks is how much each design adds on top of it.

16.6 Processes: one GIL each

The multiprocessing module mirrors threading: Process instead of Thread, with the same start() and join(), plus its own Queue and Event. The difference is underneath. Each Process is a separate Linux process with its own Python interpreter, its own memory and its own GIL. Two processes can therefore run Python code on two cores at the same instant: true parallelism (Figure 29). A busy-waiting range finder can no longer hold up the other process, although the two still share the rest of the machine.

Separate memory has consequences you must design for:

  • Data must be sent, not shared. A list changed in the child is not the parent's list; the parent never sees the change. Send results through a multiprocessing.Queue, which pickles each object (turns it into bytes), passes the bytes through a pipe, and rebuilds a copy on the other side. Tuples of numbers and strings pickle cheaply. Hardware objects such as an open SMBus cannot be sent at all: open them in the process that uses them.
  • Starting a process is slow. Linux has three ways to start one. fork copies the running parent; it was the default on Linux up to Python 3.13. spawn starts a fresh interpreter, which imports your script again. forkserver, the Linux default from Python 3.14, forks children from a small clean server process, and they too import your script. Check your version with python3 --version. Either way, start processes once, at the beginning of a run, never once per reading.
  • The if __name__ == "__main__": guard is required. With spawn and forkserver the child imports your file. Everything outside the guard runs again in the child, including (without the guard) the code that starts the child. Write the guard every time and your program works with all three start methods.
  • Time stamps agree. On Linux, time.perf_counter() reads the kernel's monotonic clock, which is the same clock in every process, so time stamps from the parent and the child can be compared directly.

16.7 A test you can run: calculating in threads and in processes

The GIL is easiest to see with a job that only calculates. This program runs 1, 2 and 4 copies of the same loop, first as threads and then as processes, and times each run:

import time
import threading
import multiprocessing as mp

N = 5_000_000              # loop passes per worker

def work(n):
    """Pure-Python arithmetic: needs the GIL while executing."""
    total = 0
    for i in range(n):
        total += i * i
    return total

def timed(kind, k):
    """Run k copies of work() as threads or processes."""
    workers = []
    for i in range(k):
        if kind == "threads":
            w = threading.Thread(target=work, args=(N,))
        else:
            w = mp.Process(target=work, args=(N,))
        workers.append(w)
    t0 = time.perf_counter()
    for w in workers:
        w.start()
    for w in workers:
        w.join()
    return time.perf_counter() - t0

if __name__ == "__main__":
    for k in [1, 2, 4]:
        t_threads = timed("threads", k)
        t_procs = timed("processes", k)
        print(f"{k} workers: threads {t_threads:.2f} s, "
              f"processes {t_procs:.2f} s")

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

What to expect, and to check on your own Pi: with threads, the total time grows roughly in proportion to k, because the four copies take turns holding one GIL. With processes it stays roughly flat up to k = 4, one process per core, plus the start-up cost of §16.6. Watch it happen: run top in a second terminal. With threads there is one python3 process that never uses much more than 100 % (one core); with processes there are several python3 processes, each near 100 %.

Each worker here does the same fixed amount of work, so report the throughput speedup: k workers do k times the work of one, so S = k T1 / Tk, where T1 is the one-worker time and Tk the time for k workers. Perfect parallel scaling gives S = k; taking turns on one GIL gives S ≈ 1. Repeat each timing several times and quote the mean and standard deviation; a background task on the Pi shows up as one slow run.

16.8 Multiprocessing code: the range finder in its own process

Here the busy-waiting range finder runs alone in a child process, and the main process keeps the accelerometer on its 100 Hz schedule:

import multiprocessing as mp
import time

def range_proc(samples, stop, period=0.06):
    """Runs in the child process: its GPIO is set up here."""
    import RPi.GPIO as GPIO
    import hcsr04            # your module: claims Trig, Echo
    try:
        while not stop.is_set():
            t = time.perf_counter()
            d = hcsr04.distance_m(20.0)  # assume 20 °C
            samples.put(("dist", t, d))
            time.sleep(period)
    except KeyboardInterrupt:
        pass                 # Ctrl-C reaches every process
    finally:
        GPIO.cleanup()

if __name__ == "__main__":   # the child must not run this
    import LIS3DHMOD as acc
    samples = mp.Queue()     # carries copies between processes
    stop = mp.Event()        # shared stop flag
    pr = mp.Process(target=range_proc, args=(samples, stop))
    pr.start()               # start it before opening the bus
    sensor = acc.LIS3DH()
    next_t = time.perf_counter()
    try:
        while True:
            t = time.perf_counter()
            x = sensor.getX()
            y = sensor.getY()
            z = sensor.getZ()
            print("acc", round(t, 4), x, y, z)
            while not samples.empty():   # collect range readings
                print(samples.get())
            next_t += 0.01               # fixed 100 Hz schedule
            wait = next_t - time.perf_counter()
            if wait > 0:
                time.sleep(wait)
    except KeyboardInterrupt:
        pass
    finally:
        stop.set()
        pr.join()

Example only. Do not copy this code as it is: read it, learn from it, then write your own.

Read it against the threaded version of §16.4; the shape is the same, and every difference comes from separate memory:

  • GPIO lives in the child. On the Pi 5, Linux lets only one process claim a GPIO line at a time. The pins are set up in the process that uses them, so hcsr04 is imported inside range_proc(). Importing it at the top of the file would make the parent claim Trig and Echo. For the same reason the child, not the parent, calls GPIO.cleanup().
  • The bus opens after the child starts. The parent creates the LIS3DH object only after pr.start(), so a forked child does not inherit a copy of the parent's open I²C file.
  • Ctrl-C reaches every process. The terminal sends the interrupt to the parent and the child. Each catches its own KeyboardInterrupt; the parent sets the stop flag and joins the child, and the child releases its pins.
  • samples.empty() is only a hint. Between processes it can briefly report empty when an item is on its way. Here that is harmless: the reading is collected on the next 10 ms pass.

A separate process removes the GIL delay, but not the operating system’s. If you want to go further, pin the range process to one core by making os.sched_setaffinity(0, {3}) the first line of range_proc(), and measure whether the jitter changes. That keeps your process on core 3; it does not keep other programs off it.

16.9 Which one to use

SituationUse
Several loops that mostly wait: sleep, I²C, SPI, filesThreads. Simple, shared memory, cheap to start.
Heavy calculation in pure PythonProcesses, one per core. (NumPy does most array work in compiled code, often without holding the GIL, so vectorizing can beat both.)
A busy-wait timing loop that shares the Pi with other Python workPut the timing loop in its own process.
Edge times to a microsecond or betterNeither. Python cannot promise microseconds, but hardware can: a microcontroller’s timer, for example, captures each edge by itself, with no loop to be late. (Linux can also timestamp GPIO edges in the kernel, which avoids Python’s delay, but check how accurate those timestamps really are.)

Newer Python versions can also be built without the GIL (“free-threaded” builds), and there threads can run Python in parallel. This section assumes the ordinary build on the lab Pis, so record your Python version when you compare timings. The Python threading documentation has more.

Practice 16

(a) A single loop reads the accelerometer (3.4 ms), then measures a target 1 m away (0.6 ms of trigger and burst plus a 5.8 ms echo), then sleeps 60 ms. What is the accelerometer's sample rate?

(b) Given the default switch interval, roughly how long might the accelerometer thread wait during a busy-wait, and why could it occasionally wait longer? What fraction of the 10 ms sample period is that, and how would it show up in np.diff(t_acc)?

(c) work(N) takes 1.2 s in one thread on your Pi. Predict the total time for 4 threads and for 4 processes, and name two reasons the 4-process time could come out above 1.2 s.

(d) Why is hcsr04 imported inside range_proc() rather than at the top of the multiprocessing program?

(e) A child process appends each distance to a global list distances. After join(), the parent's distances is empty. Why, and what should the program do instead?

17 Common Mistakes and Bench Safety

17.1 Things that destroy hardware

  • HC-SR04 Echo wired directly to a GPIO pin. 5 V into a 3.3 V input. Fit and verify the divider first (§12.3).
  • 5 V to the LIS3DH. It is a 3.3 V part on a 3.3 V bus.
  • Swapping VCC and GND on either module.
  • Wiring a live bus. Power down before changing connections.

17.2 Things that waste your afternoon

  • Forgetting the factor of two in Equation (9): every distance exactly doubled.
  • No timeout on the Echo wait, so the program hangs the moment a target is out of range (§13.3).
  • Measuring maximum range against a soft or angled target and reporting it as the module's specification.
  • Triggering faster than residual echoes decay, giving occasional wild readings.
  • Reporting four decimal places of a centimetre-accurate measurement (§13.4).
  • Two sensors at 0x18 on one bus (§15.3).
  • A multiprocessing script without the if __name__ == "__main__": guard, or with the GPIO pins set up in the parent instead of the process that uses them (§16.6, §16.8).
  • Expecting a list changed in a child process to change in the parent (§16.6).
  • Claiming threads or processes "improved" the timing without time stamps, a standard deviation and repeated runs to show it (§16.5).
  • A pendulum swinging in an ellipse instead of a plane.
  • The accelerometer mistakes of §10.

17.3 Bench safety

The pendulum is the hazard here. Use a light bob, keep the swing modest, secure the pivot to something that will not tip, and make sure the arc is clear of glassware, monitors and other people. Strain-relieve the sensor cable so a swing cannot yank the breakout board off the breadboard or drag the Pi off the bench.

17.4 Before you leave

Copy scripts, CSV files and saved plots to your own machine and verify they open. Then remove your directory from the shared Pi and shut down cleanly.

18 Self-Check

  1. What does a stationary accelerometer read, and why? What does one in free fall read?
  2. Derive the tilt angle from two axis readings. At what orientation is an axis most sensitive to tilt, and why?
  3. The high byte is 0xF8 and the low byte is 0x30 in high-resolution mode at ±2 g. What acceleration is that?
  4. What does the BDU bit protect against, and why does reading one axis take two separate register reads?
  5. Why keep the driver and the application in separate files? What goes in each?
  6. State how the standard deviation of an average depends on n, and name one reason real data stops following it.
  7. A pendulum swings at 1.2 Hz. For an ideal sensor rotating with the bob, what is the main radial signal frequency, and why is the tangential specific force nearly zero? How would a different mounting change the prediction?
  8. Write the time-of-flight equation and explain the factor of two. What symptom does omitting it produce?
  9. An echo pulse is 2.90 ms wide at 20 °C. What is the distance in cm?
  10. Why must the HC-SR04's Echo pin not connect directly to a GPIO pin, and what is the standard remedy?
  11. Your pulse width has a standard uncertainty of 60 µs. What distance uncertainty does that imply? How would the answer change if each edge independently had that uncertainty?
  12. Distinguish repeatability from trueness. Which does a standard deviation measure?
  13. By what percentage does the speed of sound change between 15 °C and 30 °C? What distance error does that cause at 1.5 m?
  14. Why does a busy-wait loop in one thread delay another thread, while time.sleep() does not?
  15. Distinguish concurrency from parallelism. Which of the two does threading give you for Python code in standard Python, and which does multiprocessing give you?
  16. Four threads each run the same pure-Python calculation. Why does the total take about four times as long as one, and what changes with four processes?
  17. Give two things a multiprocessing program must do that a threaded program need not, and say why each is needed.
Lab takeaway

An accelerometer measures specific force, so it reads 1 g at rest and zero in free fall, and gravity becomes a free, permanent reference for both calibration and tilt. A range finder measures time, so your timing precision sets your distance precision, alongside the uncertainty in the speed of sound; compare the two for your own setup. In both cases the sensor gives you a number and the physics gives it meaning.

19 Practical Engineering Connections

  1. MEMS accelerometers. Phone screen rotation, step counters, camera stabilization, laptop drop protection, and the crash detection that fires an airbag are all the sensor you used this week.
  2. Tilt sensing from gravity. Digital levels, camera horizon indicators and platform stabilizers all exploit the fact that gravity is a free, permanently available reference vector.
  3. Inertial navigation. Combining accelerometers with gyroscopes tracks position without external references, in aircraft, submarines and spacecraft. Drift accumulates, which is why they are usually fused with GPS.
  4. Device drivers. Every operating system is built the way §4 describes: a driver that knows the chip, and applications that know only method names.
  5. Ultrasonic ranging. Car parking sensors, robot obstacle avoidance, tank level gauges and automatic door openers all use exactly this pulse-echo method.
  6. Other time-of-flight systems. Lidar, radar and GPS all time a propagating signal. Because light is a million times faster than sound, lidar needs picosecond timing to reach centimetre resolution: the same Equation (12) argument, scaled.
  7. Medical ultrasound. The same physics with an array of transducers and beam forming, timing echoes from tissue boundaries.
  8. Level shifting. Mixing 5 V and 3.3 V parts is routine, and the divider you build here is the simplest member of a family that includes transistor shifters and dedicated translator ICs.
  9. Sensor fusion. Task 7, using a thermometer to improve a range finder, is a miniature version of what every serious instrument does: measure the thing that corrupts your measurement, and correct for it.
  10. Concurrent data acquisition. Laboratory and industrial acquisition software splits acquisition, processing, logging and display into separate threads or processes joined by queues, exactly as §16 does. Where timing must be guaranteed, the time-critical part moves into hardware (a microcontroller, an FPGA, or a data-acquisition card with its own clock) or onto a real-time operating system.

← All course materials