← All course materialsLecture 07 · Distance & accelerationReading notes →

Lecture 07: Sensors, Drivers, and Time-of-Flight Ranging

1 / 32
PHYS 351 · Lecture 0701

Lecture 07

Sensors, Drivers, and Time-of-Flight Ranging

Part 1 · from outputs to inputs · Part 2 · the LIS3DH accelerometer · Part 3 · the HC-SR04 range finder

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0702

Part 1 · The Pi stops talking and starts listening

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

The LIS3DH answers over I²C, like the MCP9808. The HC-SR04 answers with the width of a pulse, and Python has to time it.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0703

Part 2 · Inside an accelerometer: a mass on springs

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.

The mass lags by x=ma/kx = ma/k; the chip measures C1−C2C_1 - C_2. Take a 5 kHz resonance as an example: 1 g moves it only g/ω02≈10g/\omega_0^2 \approx 10 nm.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0704

At rest, the axis pointing up reads +1 g

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.

It measures specific force, not motion: +1 g at rest, 0 in free fall. Datasheet §3.1.2: flat on a table, X = Y = 0 g and Z = +1 g.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0705

Tilt: gravity shared between two axes

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.
ax=gsin⁡θ,az=gcos⁡θa_x = g\sin\theta,\qquad a_z = g\cos\thetaθ=atan2⁡(ax, az)\theta = \operatorname{atan2}(a_x,\ a_z)

atan2 keeps the sign and does not need gg exactly.

Sensitivity daxdθ=gcos⁡θ\dfrac{da_x}{d\theta} = g\cos\theta: best when the axis lies flat.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0706

12 bits of data in a 16-bit register

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.

Two bytes per axis, L at 0x28 and H at 0x29. The data are left-justified: shift right 4 for the 12-bit count, 1 mg per count at ±2 g in high-res mode.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0707

Inside the LIS3DH: sensor, ADC, registers

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.
Datasheet, 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 2: the axes

Like the MCP9808: sensor → ADC → register.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0708

Wiring the breakout to the Pi

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.

The same four wires as the MCP9808. i2cdetect -y 1 shows 18 (19 with SDO to 3.3 V). WHO_AM_I (0x0F) must read 0x33.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0709

The driver module: registers behind method names

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.

Each layer hides the one below it: the application never sees a register, and the driver never sees SDA.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0710

Two control registers set up the whole chip

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.

setRange, setDataRate, setHighResolution and setBDU each read a register, change a few bits and write it back. BDU keeps H and L from the same sample.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0711

Driver script vs. application script

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.

Driver: facts about the chip, tested once. Application: facts about the experiment, one per task. Fix a scaling bug once and every script gets the fix.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0712

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
├── pendulum.py      application
└── data/
    └── tilt_run1.csv
# tilt_log.py
import time
import LIS3DHMOD as acc  # no .py
import hcsr04            # your module
sensor = acc.LIS3DH()

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

import searches the script's own folder first.

Run it from there: python3 tilt_log.py.

Driver self-tests go under if __name__ == "__main__":.

© Ran Yang, Ph.D.Example code only: learn from it, then write your ownAdvanced Instrumentation
PHYS 351 · Lecture 0713

Walkthrough 1: inside the provided driver

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)

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

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.

Condensed from LIS3DHMOD.py. getRange() reads CTRL_REG4: 3 reads per axis.

© Ran Yang, Ph.D.Example code only: learn from it, then write your ownAdvanced Instrumentation
PHYS 351 · Lecture 0714

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.

Settings live in the application.

Record tt from perf_counter(), not from the loop count.

Nine I²C reads at 100 kHz: 3.24 ms or more. Add the sleep, and a pass takes well over 10 ms.

© Ran Yang, Ph.D.Example code only: learn from it, then write your ownAdvanced Instrumentation
PHYS 351 · Lecture 0715

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

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.

Carries on from the last example (sensor, time, t0). The sleep stops you reading one sample twice; the timestamps show the real spacing.

© Ran Yang, Ph.D.Example code only: learn from it, then write your ownAdvanced Instrumentation
PHYS 351 · Lecture 0716

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

# later, 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, one header row.

with closes the file even after Ctrl-C.

Log first, analyze later: the run is kept, and every average or fit can be redone.

© Ran Yang, Ph.D.Example code only: learn from it, then write your ownAdvanced Instrumentation
PHYS 351 · Lecture 0717

Worked example: register bytes to g

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.

1 mg/digit is the typical sensitivity, not your chip's. Calibrate by flipping each axis (§3.1.1): scale =(rup−rdown)/2= (r_{\mathrm{up}} - r_{\mathrm{down}})/2, offset =(rup+rdown)/2= (r_{\mathrm{up}} + r_{\mathrm{down}})/2.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0718

Noise sets the smallest tilt you can see

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.
Δθ≈Δagcos⁡θσaˉ=σn\Delta\theta \approx \frac{\Delta a}{g\cos\theta} \qquad \sigma_{\bar a} = \frac{\sigma}{\sqrt{n}}

Rough estimate: 220 µg/√Hz over 11.1 Hz gives ≈ 0.7 mg rms. The datasheet's test conditions differ from yours.

Task 4: measure σ\sigma at your own data rate and compare.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0719

Pendulum: the sensor feels the string, not gravity

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.

The pull lies along the string and peaks at the bottom, twice per swing: radial at 2f2f. Tangential reads 0 on a string; on a rod, gθ(1−r/Leq)g\theta(1 - r/L_{\mathrm{eq}}) at ff. Sample well above 2f2f.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0720

Challenge: write a tilt alarm

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.

Print TILT once when the tilt passes 20° for 5 samples in a row.

Stay quiet until it falls below 15°, then rearm.

Why two thresholds? Why 5 samples? What does a shake do?

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0721

Accelerometer pitfalls, and how they show up

MistakeWhat you seeFix
No two's complement−0.5 g reads +3.6 gsubtract 65536 if bit 15 is set
Range too smallflat tops at ±2 gnext range up; look at the plot
Skipping calibration±1 g reads a few % offflip each axis: scale, offset
Two chips at 0x18garbage, or one sensor missingLIS3DH SDO to 3.3 V → 0x19
Redraw every samplesample rate collapsesplot every N samples, or log first
Loose pendulum cablespikes and dropoutsstrain-relieve the wires
© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0722

Part 3 · From the accelerometer to the range finder

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.
HC-SR04 user guide, p. 1
LIS3DHHC-SR04
Answers withI²C registersone pulse width
Supply (lab)3.3 V5 V
Python's jobask for bytestime an edge
One reading≈ 3.4 ms≤ 25 ms, then 60 ms rest
© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0723

Sound as a ruler

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.
User guide, Figure 1

40 kHz, above hearing:

λ=vf=343 m/s40 kHz≈8.6 mm\lambda = \frac{v}{f} = \frac{343\ \mathrm{m/s}}{40\ \mathrm{kHz}} \approx 8.6\ \mathrm{mm}

Out, reflect, back: time the round trip.

Beam ≈ 15°. Flat, hard targets echo best.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0724

One pulse in, one pulse out

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.

User guide, Figure 4. Trig ≥ 10 µs → 8 cycles at 40 kHz → Echo high until the sound returns (≈ 36 ms if it never does). Allow ≥ 60 ms between triggers.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0725

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.
User guide, p. 5
classicV2.0 (guide)
VCC4.8–5 V3.3–5 V
Echo high≈ VCC≈ VCC

Lab 7: VCC = 5 V, so Echo = 5 V.

GPIO is 3.3 V and not 5 V tolerant.

Measure Echo before you connect it.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0726

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

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.
VGPIO=VEcho R2R1+R2V_{\mathrm{GPIO}} = V_{\mathrm{Echo}}\,\frac{R_2}{R_1 + R_2}

Choose R1R_1, R2R_2: well above logic high, safely below 3.3 V.

Trig needs no divider: the module reads the Pi's 3.3 V as high.

Check the pulse peak with an oscilloscope before wiring GPIO.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0727

From echo time to distance

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.

d=vt/2d = vt/2: 58 µs of echo per cm (the guide's "µs / 58 = cm"). 2 cm ↔ 117 µs, 4 m ↔ 23.3 ms. Anything longer means no echo.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0728

Pulse timing: from microseconds to Python

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.

perf_counter() is monotonic, with sub-µs resolution. How fast the loop polls the pin limits the timing, not the clock: 1 µs = 0.17 mm.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0729

Code walkthrough: measuring an Echo pulse

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)

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

    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.

Convert with d=v(T)t/2d=v(T)t/2. Wait at least 60 ms between triggers.

© Ran Yang, Ph.D.Example code only: learn from it, then write your ownAdvanced Instrumentation
PHYS 351 · Lecture 0730

Lab 6 meets Lab 7: correct the speed of sound

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.
v=331.31+T273.15v = 331.3\sqrt{1 + \tfrac{T}{273.15}}≈331.3+0.606 T  m/s\approx 331.3 + 0.606\,T\ \ \mathrm{m/s}
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 sensor.

© Ran Yang, Ph.D.Example code only: learn from it, then write your ownAdvanced Instrumentation
PHYS 351 · Lecture 0731

Two sensors, one Pi

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.

Both chips default to 0x18: tie the LIS3DH's SDO to 3.3 V and use LIS3DH(address=0x19). The drivers stop with this advice if the wrong chip answers.

© Ran Yang, Ph.D.Advanced Instrumentation
PHYS 351 · Lecture 0732

Summary: what each Lab 7 task needs from today

TaskWhat you need
1 · HC-SR04 script, schematicEcho divider, timing, timeouts, d=vt/2d = vt/2
2 · Range calibrationruler targets, offset, min and max range
3 · LIS3DH setupwiring, i2cdetect, WHO_AM_I = 0x33, the driver
4 · Noise and smallest angleσ\sigma at rest, Δθ≈Δa/(gcos⁡θ)\Delta\theta \approx \Delta a / (g\cos\theta)
5 · Averaging, plots, CSVσ/n\sigma/\sqrt{n}, live plot or log first, CSV
6 · Pendulumaxis directions, ff and 2f2f, sample rate
7 · Temperature compensationMCP9808 at 0x18, v(T)v(T); the rest: notes §16

Bring your Lab 6 MCP9808 code, and keep every driver beside your scripts.

© Ran Yang, Ph.D.Advanced Instrumentation

Use ← → to move, Home / End to jump, and F for fullscreen.

Figure descriptions

Slide 2 · Part 1 · The Pi stops talking and starts listening

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

Slide 3 · Part 2 · Inside an accelerometer: a mass on springs

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.

Slide 4 · At rest, the axis pointing up reads +1 g

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.

Slide 5 · Tilt: gravity shared between two axes

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.

Slide 6 · 12 bits of data in a 16-bit register

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.

Slide 7 · Inside the LIS3DH: sensor, ADC, registers

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.

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.

Slide 8 · Wiring the breakout to the Pi

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.

Slide 9 · The driver module: registers behind method names

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.

Slide 10 · Two control registers set up the whole chip

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.

Slide 11 · Driver script vs. application script

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.

Slide 15 · Data strategy 1: plot while you record

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.

Slide 17 · Worked example: register bytes to g

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.

Slide 18 · Noise sets the smallest tilt you can see

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.

Slide 19 · Pendulum: the sensor feels the string, not gravity

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.

Slide 20 · Challenge: write a tilt alarm

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.

Slide 22 · Part 3 · From the accelerometer to the range finder

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.

Slide 23 · Sound as a ruler

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.

Slide 24 · One pulse in, one pulse out

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.

Slide 25 · 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.

Slide 26 · Echo at 5 V, GPIO at 3.3 V: a divider

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.

Slide 27 · From echo time to distance

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.

Slide 28 · Pulse timing: from microseconds to Python

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.

Slide 30 · Lab 6 meets Lab 7: correct the speed of sound

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.

Slide 31 · Two sensors, one Pi

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.