← Advanced Instrumentation

PHYS 351 · Advanced Instrumentation

Lecture 07 · Distance & acceleration

PHYS 351 — LECTURE 07 NOTES
Ultrasonic Range Finding and Three-Axis Accelerometry
Covers Lab 7

© Ran Yang, Ph.D.
yangran.org/teaching/phys351/

1Where Lab 7 Sits

Lab 6 introduced a digital sensor that hands you a number over I²C. This week you meet the two other ways a sensor can talk to you, and they could hardly be more different.

The HC-SR04 range finder does not use a protocol at all. It reports distance as the width of a pulse, so the measurement is a time interval you have to capture yourself — which drags every timing limitation from Lecture 03 directly into your measurement accuracy. 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 one idea to carry out of this lecture

Both sensors this week return a number that is only meaningful once you supply physics: a time becomes a distance only if you know the speed of sound, and an acceleration becomes an angle only if you know that gravity is always present. The sensor measures; you convert. Every conversion carries an assumption, and every assumption is a source of error you should be able to quantify.

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; level shifting (§2, §3)
2Determine zero offset, minimum range, maximum range and accuracy; compare with the datasheetCalibration (§5)
3Connect the LIS3DH; find its I²C address; validate the x-axis outputI²C recap; axes and units (§8)
4100+ points per axis; standard deviation at rest; theorise the effect of tilt; find the smallest detectable angle changeGravity, tilt, noise (§7, §9)
5Average n sequential readings; standard deviation of the averages; plot against time; save CSV and imagesAveraging statistics (§9.2)
6Swing the accelerometer as a pendulum; log all three axes for 10+ s; plot in three colours; analyse the frequenciesPendulum kinematics (§10)
7Add the MCP9808 and make the range finder temperature-compensatedSpeed of sound vs temperature (§6)

2Time of Flight

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

2.1  A number worth memorising

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 (2)

So a 10 cm target gives an echo pulse about 580 µs wide, and a 2 m target about 11.7 ms. Keep Equation (2) in mind — it is what §4 uses to turn a timing error into a distance error.

3The HC-SR04 and the 5 V Problem

3.1  The four pins

PinDirectionWhat it does
VCCpower in5 V. The module needs 5 V to drive its transducer; 3.3 V will not work reliably.
Triginput from the PiA brief pulse — nominally 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 PiGoes high when the burst is sent and low when the echo returns. Its high level is 5 V.
GNDgroundShared with the Pi, as always.
Echo must never connect directly to a GPIO pin

This is the one genuinely destructive mistake available in Lab 7. The Pi's GPIO pins are 3.3 V and not 5 V tolerant. Wiring Echo straight to a GPIO pin puts 5 V into the processor and can destroy it — and the module is powered from 5 V precisely so that its output is 5 V.

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

VGPIO = VEcho × R2R1 + R2 (3)

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 — a 1:2 ratio 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.

Measure the divided voltage with the DMM before connecting it to the Pi. Thirty seconds of checking against the cost of a board.

3.2  The measurement sequence

  1. Drive Trig high for about 10 µs, then low. The module emits a short burst of 40 kHz ultrasound.
  2. Echo goes high.
  3. When the echo returns, Echo goes low.
  4. The width of the Echo pulse is the round-trip time t in Equation (1).

Your program therefore has to time a pulse: record when Echo rises, record when it falls, subtract. Use time.perf_counter(), for the reasons given in Lecture 03.

Always include a timeout

If no echo ever returns — the target is too far, too soft, or angled so the sound reflects away — 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.

3.3  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 §4 and §5 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.

4Timing Resolution and What Limits It

This is where Lecture 03 returns with teeth. The distance measurement is a timing measurement, so every microsecond of timing error becomes a distance error through Equation (2).

Δd = vsound × Δt2   ≈   0.017 cm per µs of timing error (4)
Worked example — how good can Python be?

Suppose your loop can detect an edge on the Echo pin to within about 100 µs — a plausible figure for Python on a non-real-time Linux system, and one you measured the ingredients of in Lab 3.

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

So software timing jitter alone puts a floor of roughly a centimetre or two on your distance measurement — regardless of how good the sensor is. The HC-SR04 datasheet may claim 3 mm resolution; you will not achieve it this way, and understanding why is worth more than the number.

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 number is your real resolution, and it belongs in the Task 2 accuracy discussion.

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 at least a few tens of milliseconds between measurements.
  • Averaging helps — up to a point. Random timing jitter averages down as 1/√n (§9.2). A systematic offset does not average away at all, which is exactly what Task 2's zero-offset measurement is for.

5Calibrating the Range Finder

Task 2 asks for four numbers and a comparison with the datasheet. 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 — 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 has a beam of roughly fifteen degrees, so it does not see a point — it sees a cone, and reports the nearest thing in it. Bench clutter, a nearby wall, or your own hand can dominate 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.

6Temperature Compensation

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

vsound ≈ 331.3 + 0.606 T   m/s,    T in °C (5)
Worked example — does it actually matter?

At 0 °C, Equation (5) gives 331.3 m/s. At 30 °C it gives 331.3 + 18.2 = 349.5 m/s — a change of about 5.5% across that range.

Since distance is proportional to speed, a 5.5% speed error is a 5.5% distance error. At 2 m that is 11 cm — far larger than the centimetre-level timing floor from §4. Assuming a fixed 343 m/s in a cold or hot room is therefore a bigger error than anything in your software.

That comparison is the point of Task 7, and it deserves stating explicitly in your report: temperature compensation removes the dominant systematic error, which is why it is worth adding a second sensor to do it.

The implementation is pleasingly small: read the MCP9808, compute vsound from Equation (5), and use that value in Equation (1) instead of a constant. Both sensors share the same I²C bus at different addresses — exactly the multi-device situation §4 of the Lecture 06 notes described — so no extra pins are needed.

How to demonstrate it worked

A compensated reading at room temperature looks almost identical to an uncompensated one, which proves nothing. Show the effect instead: log both the compensated and uncompensated distance for the same fixed target, then change the sensor's temperature (a hand cupped around it, or a cold pack nearby) and show that the uncompensated reading drifts while the compensated one holds steady. That is a real experiment rather than a code listing.

Practice 6

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

7What an Accelerometer Measures

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

An accelerometer at rest does not read zero

An accelerometer contains a small proof mass on springs, and measures how far that mass is displaced. What that displacement reports is proper acceleration — acceleration relative to free fall — not 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.

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.

7.1  Tilt from gravity

Because gravity always points down, the way the 1 g vector distributes across the three axes tells you the device's orientation. Tilt by an angle θ from horizontal and the component along that axis is

ax = g sin θ      so      θ = arcsin(axg) (6)

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

dax = g cos θ (7)

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; the same device stood on end barely notices them. That fact drives the whole of §9.3.

8The LIS3DH

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 §4–§6 of the Lecture 06 notes applies unchanged — two wires, pull-ups, a 7-bit address, register reads.

8.1  Bringing it up

Task 3 asks you to detect its address from the terminal, which is the same i2cdetect -y 1 you used last week. The LIS3DH's address depends on how its address pin is tied, and breakout boards differ, so read the address off the scan rather than assuming it. If two devices share the bus in Task 7, both should appear in the grid at once — a satisfying confirmation that a shared bus really does work.

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

8.2  Full scale, sensitivity and raw counts

The device is configurable to a full-scale range of roughly ±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 in exact proportion.

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.

Raw values come back as signed integers in two's complement — the same representation you handled for negative temperatures in Lecture 06 §10.2, and the same trap: a sign bug is invisible while readings are positive. Converting counts to g uses the sensitivity figure for the selected range, which the datasheet tabulates in milli-g per count.

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

9Noise, Averaging and the Smallest Detectable Tilt

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

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.

9.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 (8)

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. A straight line through the origin confirms the noise is independent and random.

When averaging stops helping — the interesting result

Equation (8) only holds for independent noise. If there is drift, a slow thermal trend, or building vibration at a particular frequency, those are correlated between samples and averaging does not remove them.

So at large n your measured σmean will usually fall above the 1/√n line and eventually flatten out. Where it flattens tells you how long you can usefully average before systematic effects dominate — a genuinely useful piece of instrument characterisation, and a far better Task 5 discussion than simply reporting that averaging reduced the noise.

9.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 §7.1 and §9.1. Rearranging Equation (7), an acceleration change of Δa corresponds to an angle change of

Δθ = Δag cos θ (9)

Take Δa to be your measured noise floor σ (or a small multiple of it, if you want a confident detection rather than a marginal one), and you have the answer. State your criterion — one σ, two σ, whatever you choose — because the number depends on it.

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

Practice 9

(a) An axis reads a mean of 0.012 g with σ = 0.004 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 64 readings, what does the answer to (a) become, assuming Equation (8) 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.

10The Pendulum Experiment

Task 6 mounts the accelerometer on a pendulum, logs all three axes for at least ten seconds, plots them in three colours, 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.

10.1  The swing frequency

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

T = 2π√(L/g)      fswing = 1√(g/L) (10)

Measure L — from the pivot to the centre of mass of the swinging assembly, not to the end of the string — and you have a prediction to compare against. Note that the period does not depend on mass, and only weakly on amplitude provided the swing is modest.

10.2  Why one axis oscillates at twice the swing frequency

The discrepancy Task 6 is asking you to explain

Resolve the acceleration of the bob into two components in the pendulum's own frame:

  • The tangential component, along the direction of travel, is proportional to sin θ. It goes positive and negative once per swing, so it oscillates at fswing.
  • The radial (centripetal) component, along the string, is v²/L. Because it depends on speed squared, it is always positive — and it peaks at the bottom of the swing, which happens twice per period. So it oscillates at 2fswing.

The radial axis also carries the component of gravity along the string, which likewise maximises at the bottom of each swing. Both effects push the same way.

So finding one axis at f and another at 2f is not an error — it is the correct and expected behaviour, and identifying which axis is which is exactly the analysis the task wants. A report that notices the doubling, explains it by the v² dependence, and identifies the axes correctly is a strong answer.

10.3  Getting data worth analysing

  1. Know your axis orientation. Do the six-orientation check from §8.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 (10) 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. 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 (10), quote both, and account for the difference — pivot friction, air resistance, the cable, a centre of mass that is not where you assumed, or an amplitude beyond the small-angle regime.

11Common Mistakes and Bench Safety

11.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 (§3.1).
  • 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.

11.2  Things that waste your afternoon

  • Forgetting the factor of two in Equation (1) — every distance exactly doubled.
  • No timeout on the Echo wait, so the program hangs the moment a target is out of range (§3.2).
  • 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 (§3.3).
  • Expecting a stationary accelerometer to read zero (§7).
  • Two's complement sign bug on the accelerometer, invisible until an axis goes negative.
  • Not knowing which axis points where before running the pendulum (§10.3).
  • Sampling too slowly to resolve 2f, then concluding the physics is wrong.
  • A pendulum swinging in an ellipse instead of a plane.

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

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

12Self-Check

  1. Write the time-of-flight equation and explain the factor of two. What symptom does omitting it produce?
  2. An echo pulse is 2.90 ms wide at 20 °C. What is the distance in cm?
  3. Why must the HC-SR04's Echo pin not connect directly to a GPIO pin, and what is the standard remedy?
  4. Your edge timing is uncertain by 60 µs. What distance uncertainty does that imply?
  5. Distinguish repeatability from trueness. Which does a standard deviation measure?
  6. 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?
  7. What does a stationary accelerometer read, and why? What does one in free fall read?
  8. Derive the tilt angle from a single axis reading. At what orientation is an axis most sensitive to tilt, and why?
  9. State how the standard deviation of an average depends on n, and name one reason real data stops following it.
  10. A pendulum swings at 1.2 Hz. What frequency would you expect on the tangential axis, and on the radial axis? Explain the difference.
Lab takeaway

A range finder measures time, so your timing precision is your distance precision — and the speed of sound is a bigger error than your code unless you measure the temperature. An accelerometer measures proper acceleration, so it reads 1 g at rest and zero in free fall, and gravity becomes a free, permanent reference for both calibration and tilt. In both cases the sensor gives you a number and the physics gives it meaning.

13Practical Engineering Connections

  1. Ultrasonic ranging. Car parking sensors, robot obstacle avoidance, tank level gauges and automatic door openers all use exactly this pulse-echo method.
  2. 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 (4) argument, scaled.
  3. Medical ultrasound. The same physics with an array of transducers and beam forming, timing echoes from tissue boundaries.
  4. 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.
  5. MEMS accelerometers. Phone screen rotation, step counters, camera stabilisation, laptop drop protection, and the crash detection that fires an airbag are all the sensor you used this week.
  6. Tilt sensing from gravity. Digital levels, camera horizon indicators and platform stabilisers all exploit the fact that gravity is a free, permanently available reference vector.
  7. 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.
  8. 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.

PHYS 351 · Lecture 07 Notes · © Ran Yang, Ph.D. · yangran.org/teaching/phys351/

← All course materials