# Worksheet: Sensor integration

*Tactiverge Academy · Embedded Systems, module 4 · https://tactiverge.win/academy/embedded-systems/#sensor-integration*

Name: ______________________    Date: ____________

## Learning objectives

Tick each one when you can do it without looking at your notes.

- [ ] Explain how an analogue-to-digital converter turns a voltage into a number, including resolution.
- [ ] Calibrate a sensor reading against known reference values.
- [ ] Apply a moving-average filter to reduce noise and describe its cost in delay.
- [ ] Recognize common sensor failure modes such as saturation and drift.

## Lesson 1: Reading and calibrating sensors

Turning raw ADC counts into trustworthy physical units: the offset-and-gain model, two-point calibration, and checking the result against a third known value.

Read online: https://tactiverge.win/academy/embedded-systems/sensor-integration/reading-and-calibrating-sensors/

#### Project: Calculator or Python project: calibrate a made-up sensor

The following data are **made up for illustration**. A temperature sensor gives these averaged ADC counts:

- in melting ice (0.0 °C): 621 counts
- in a water bath at 50.0 °C: 2172 counts
- in a water bath at 25.0 °C: 1402 counts

1. Use the 0 °C and 50 °C points to find the offset and gain (in °C per count).
2. Convert the 25 °C reading using your calibration and work out the check-point error.
3. Write a short Python function `counts_to_celsius(raw)` and test it on all three points with `assert` statements that allow a sensible tolerance.
4. In two or three sentences, say whether you would trust this sensor to ±0.5 °C between 0 and 50 °C, and what further test you would run.

No hardware is needed.

**Deliverables**

- Offset and gain with units, showing your working
- The check-point error at 25 °C
- A Python function with assert-based tests
- A short judgement of whether the calibration is good enough

**Safety (adult supervision required):** This project is calculation only. If you later repeat it with a real sensor, use only low-voltage, battery-powered electronics, work with an adult supervising, never put electronics or bare wires into water, and handle hot water with care.

### Check your understanding

1. A load cell reads 300 counts with no load and 2300 counts with a 500 g mass. What is its gain?
   A) 0.25 g per count
   B) 4 g per count
   C) 0.2174 g per count
   D) 1.667 g per count

2. Using that same calibration (offset 300 counts, gain 0.25 g per count), what does a reading of 1100 counts mean?
   A) 275 g
   B) 200 g
   C) 1100 g
   D) 300 g

3. Why should you test a calibration with a third known value?
   A) Because the ADC needs three readings to start
   B) Because two points cannot define a straight line
   C) Because the calibration fits its own two points exactly, so only an independent point reveals non-linearity or a bad reference
   D) Because it doubles the resolution of the sensor

4. A scale reads 4 g with nothing on it but is accurate for the change in weight when items are added. What kind of error is this?
   A) A gain error
   B) Saturation
   C) Aliasing
   D) An offset error

5. Your calibration used 0 g and 200 g. The firmware now reads a value that converts to 900 g. What is the most careful interpretation?
   A) Trust it fully: the line extends forever
   B) Treat it with caution: it is far outside the calibrated range and the sensor may be non-linear or saturating
   C) It must be exactly 900 g because the gain is constant
   D) It proves the reference mass was wrong

### My notes

______________________________________________

______________________________________________

## Lesson 2: Noise and filtering

Why every sensor reading wobbles, and how moving-average and exponential filters smooth it, at the unavoidable cost of delay.

Read online: https://tactiverge.win/academy/embedded-systems/sensor-integration/noise-and-filtering/

#### Project: Python project: the noise–lag trade-off

Using the made-up readings in this lesson (or your own list of at least 30 invented readings with a step in the middle):

1. Run the moving average with N = 2, 4 and 8, and the EMA with α = 0.5, 0.3 and 0.1.
2. For each filter, measure (a) the spread (max − min) of its output over the steady part before the step, and (b) how many samples after the step it takes to get within 1.0 of the new value.
3. Print a small results list and describe the pattern you see in two or three sentences.
4. Add one deliberate spike (for example 55.0) to the steady part and compare an EMA with a 3-sample median filter that you write yourself.

No hardware is needed.

**Deliverables**

- A Python script with your filter functions
- A results list of spread and response time for each setting
- A short written comparison, including the spike experiment

### Check your understanding

1. An EMA has filtered value y = 10.0. A new reading x = 20.0 arrives, and α = 0.25. What is the new y?
   A) 15.0
   B) 12.5
   C) 17.5
   D) 20.0

2. Averaging independent random noise over 16 readings reduces the typical noise size by about what factor?
   A) 16
   B) 8
   C) 2
   D) 4

3. What is the main cost of increasing a moving-average window from 4 to 16 samples?
   A) The filter output responds more slowly to real changes
   B) The noise gets larger
   C) The output can never reach the true value
   D) It stops working on integer data

4. A sensor is usually calm but occasionally produces a single wildly wrong reading. Which filter handles this best?
   A) An EMA with α = 0.9
   B) A short median filter
   C) No filter: spikes average out by themselves
   D) A moving average with a window of 2

5. You sample at 50 Hz (dt = 0.02 s) and want an EMA with time constant τ = 0.18 s. Which α should you use?
   A) 0.18
   B) 0.02
   C) 0.1
   D) 0.9

### My notes

______________________________________________

______________________________________________

## Lesson 3: Combining sensors

Why two imperfect sensors can beat one good one: complementary strengths, the complementary filter, and a first look at the idea behind the Kalman filter.

Read online: https://tactiverge.win/academy/embedded-systems/sensor-integration/combining-sensors/

### Check your understanding

1. Why is a gyroscope's angle estimate said to drift?
   A) Its readings are delayed by several seconds
   B) Small errors in measured rate are added up over time, so the angle error keeps growing
   C) It only works when the robot is moving
   D) It measures the direction of gravity, which changes

2. A complementary filter runs at 50 Hz (dt = 0.02 s) with α = 0.95. What is its crossover time constant τ?
   A) 0.95 s
   B) 0.019 s
   C) 0.02 s
   D) 0.38 s

3. Two sensors measure the same quantity with σ₁ = 1 cm and σ₂ = 2 cm. With inverse-variance weighting, what weight goes on sensor 1?
   A) 0.8
   B) 0.5
   C) 0.33
   D) 0.2

4. In a complementary filter, what happens if you raise α closer to 1?
   A) The output follows the absolute sensor more closely
   B) Drift is removed faster
   C) The output is smoother, but drift from the relative sensor is corrected more slowly
   D) The filter becomes a Kalman filter

5. What can a Kalman filter do that a basic complementary filter cannot?
   A) Work without any sensors
   B) Track its own uncertainty and adjust how much it trusts each measurement accordingly
   C) Guarantee zero error
   D) Avoid needing a model of how the system moves

### My notes

______________________________________________

______________________________________________

## Lesson 4: Sampling rate and aliasing

What happens between samples: the Nyquist limit, how fast signals masquerade as slow ones, and how to choose a sample rate and an anti-aliasing filter.

Read online: https://tactiverge.win/academy/embedded-systems/sensor-integration/sampling-and-aliasing/

#### Project: Python project: an alias hunter

1. Extend the alias example: sample a 7 Hz cosine at fs = 8, 10, 14, 15 and 50 Hz. For each, print the first 10 samples and predict the alias frequency with `alias_frequency` before you run it.
2. For fs = 10 Hz, print the apparent frequency of every whole-number input frequency from 0 to 30 Hz. Describe the zig-zag pattern you see, and explain where it turns around.
3. Calculate the RC cutoff frequency for three resistor and capacitor combinations of your choice, and say which would be a sensible anti-aliasing filter for a sensor read at 100 Hz.

This is a paper-and-Python activity. No hardware is required.

**Deliverables**

- Python output with your predictions alongside
- A short description of the folding pattern for fs = 10 Hz
- Three RC cutoff calculations with a recommendation

**Safety (adult supervision required):** This is a calculation-only activity. If you go on to build an RC filter on a breadboard, use only low-voltage battery power, check component ratings, and work with an adult supervising.

### Check your understanding

1. A sensor is sampled at 200 Hz. What is its Nyquist frequency?
   A) 400 Hz
   B) 200 Hz
   C) 100 Hz
   D) 50 Hz

2. A 45 Hz vibration is sampled at 50 Hz. What frequency does it appear to have?
   A) 5 Hz
   B) 45 Hz
   C) 95 Hz
   D) 25 Hz

3. Your data shows a mysterious slow oscillation. You suspect aliasing. Which fix will NOT help?
   A) Adding an analogue low-pass filter before the ADC
   B) Increasing the sample rate
   C) Applying a moving-average filter to the samples already recorded
   D) Shielding wires and moving them away from the interference source

4. Using the rule of thumb from this lesson, roughly what loop rate suits a joint whose important behaviour reaches about 20 Hz?
   A) About 40 Hz exactly
   B) About 20 Hz
   C) About 4 Hz
   D) About 200 Hz or more

5. What is the cutoff frequency of an RC filter with R = 1 kΩ and C = 1 µF?
   A) About 1.6 Hz
   B) About 159 Hz
   C) About 1000 Hz
   D) About 15.9 kHz

### My notes

______________________________________________

______________________________________________

## Lesson 5: Units, scaling and fixed-point arithmetic

Doing accurate maths with integers on small processors: choosing scaled units, ordering operations to avoid truncation and overflow, and Q-format fixed point.

Read online: https://tactiverge.win/academy/embedded-systems/sensor-integration/units-scaling-fixed-point/

#### Project: Programming project: integer-only conversion

Write a C99 or Python program (in Python, use only `//` integer division and no floats) that converts 10-bit ADC readings (0 to 1023) with a 5000 mV reference into millivolts using only integers.

1. Implement truncating and rounding versions, and compare both with the exact floating-point answer for every input from 0 to 1023. Report the largest error for each.
2. Work out the largest intermediate value and state the smallest integer type that safely holds it.
3. Implement an integer exponential filter with α = 1/8, with and without 3 extra fractional bits, and show where each settles for a constant input of 500.

This is a computer-only activity. No hardware is needed.

**Deliverables**

- Source code with units in every variable name
- The largest error of the truncating and rounding conversions
- The largest intermediate value and chosen type, with reasoning
- Settled values of both integer filters

### Check your understanding

1. In C integer arithmetic, what is 3000 / 4096 * 3300?
   A) 2416
   B) 3300
   C) 0
   D) It causes a compile error

2. Why does counts * 3300 risk overflow on a processor with a 16-bit int?
   A) Because 3300 is not a power of two
   B) Because the product can reach millions, far beyond the 16-bit maximum of 65,535
   C) Because multiplication is not allowed on 16-bit processors
   D) Because counts is unsigned

3. What value represents 0.75 in Q16.16 format?
   A) 75
   B) 65536
   C) 0.75
   D) 49152

4. An integer filter y += (x − y) / 8 stops changing before it reaches the input. What is the best fix?
   A) Keep the filter state with extra fractional bits and round only on output
   B) Use a larger α so that it overshoots
   C) Reset the filter every second
   D) Use an unsigned type

5. Why is temp_cdeg a better variable name than temp?
   A) Shorter names compile faster
   B) It states the unit, hundredths of a degree, so nobody misreads 2500 as 2500 degrees
   C) The compiler checks units written in names
   D) It makes the variable floating point

### My notes

______________________________________________

______________________________________________

## Lesson 6: Building a reliable sensor pipeline

Designing sensor code that notices when something is wrong: range and plausibility checks, timeouts, status flags and safe responses to failure.

Read online: https://tactiverge.win/academy/embedded-systems/sensor-integration/reliable-sensor-pipelines/

#### Project: Paper and Python project: design a fault table

Choose a sensor from this module, for example the load cell in a gripper or a distance sensor on a small wheeled robot.

1. List at least **five** ways it could fail or mislead (for example: broken wire, saturation, frozen bus device, electrical noise, sensor knocked out of alignment).
2. For each failure, write how your pipeline would detect it (which check, with what threshold and why) and what the safe response would be.
3. Extend the Python example so that after **three** consecutive rejected readings that agree with each other to within 5 cm, the new value is accepted and a message is printed. Test it with a made-up list containing a genuine jump.

This is a paper-and-computer activity. No hardware is required.

**Deliverables**

- A fault list with detection method, threshold and safe response for each item
- Extended Python code with its test data and output
- Two sentences on one fault your checks could still miss

### Check your understanding

1. A distance sensor rated for 2–400 cm reports 250 cm, immediately after reporting 60 cm, 0.05 s earlier, on a robot that moves at most 1 m/s. Which check flags it?
   A) The range check
   B) The timeout check
   C) The rate-of-change plausibility check
   D) None: the reading is fine

2. Why should each published sensor value carry the time it was measured?
   A) So that users can detect stale data and align it with other sensors
   B) Because the ADC requires it
   C) To make the values more precise
   D) So the filter can run faster

3. A sensor on a bus locks up and keeps returning exactly the same number. Which check is most likely to notice?
   A) A range check
   B) A stuck-value check or a cross-check with another sensor
   C) A rate-of-change check
   D) Converting to physical units

4. What is the weakness of a plausibility check that always compares against the last good value?
   A) It uses too much memory
   B) It cannot detect spikes
   C) It only works with integers
   D) After a genuine large jump it may reject every new reading forever unless it has a way to recover

5. Why is the freshness check run every loop rather than only when a new reading arrives?
   A) Because a sensor that stops sending produces no new readings, so a check that waits for one would never run
   B) To make the robot faster
   C) Because readings arrive every loop anyway
   D) To save power

### My notes

______________________________________________

______________________________________________

---

## Answer key (for self-checking after you try)

**Lesson 1: Reading and calibrating sensors**

1. A — The change in counts is 2300 − 300 = 2000, and 500 g / 2000 counts = 0.25 g per count. Using 2300 alone would ignore the offset.
2. B — Subtract the offset first: (1100 − 300) × 0.25 = 800 × 0.25 = 200 g.
3. C — Any line passes exactly through the two points it was built from. An independent check point is the only real test of whether the model and references are sound.
4. D — A constant shift present even at zero is an offset error. Re-measuring the zero point, like pressing a tare button, removes it.
5. B — A calibration only describes behaviour over the range you tested. Far beyond it, non-linearity or saturation can make the extrapolated value wrong.

**Lesson 2: Noise and filtering**

1. B — y = y + α(x − y) = 10.0 + 0.25 × 10.0 = 12.5. The filter moves a quarter of the way towards the new reading.
2. D — For independent noise the reduction is about √N, and √16 = 4. This is why halving noise needs four times as many readings.
3. A — A longer window averages over more of the past, so it is smoother but lags more and takes longer to follow a genuine step.
4. B — A median filter picks the middle value, so one outlier among three or five readings is simply ignored. Averaging filters smear the spike across several outputs instead.
5. C — α = dt / (τ + dt) = 0.02 / 0.20 = 0.1.

**Lesson 3: Combining sensors**

1. B — Integrating rate to get angle also integrates any bias. A constant 0.5 °/s bias becomes 30° of error after a minute.
2. D — τ = α · dt / (1 − α) = 0.95 × 0.02 / 0.05 = 0.38 s.
3. A — w₁ = σ₂² / (σ₁² + σ₂²) = 4 / 5 = 0.8. The less noisy sensor gets the larger weight.
4. C — A larger α trusts the prediction more, so less absolute-sensor noise gets through, but the correction that removes drift becomes weaker and slower.
5. B — A Kalman filter keeps an estimate of its own uncertainty, which grows during predictions and shrinks with each measurement, and uses it to choose the weighting at every step.

**Lesson 4: Sampling rate and aliasing**

1. C — The Nyquist frequency is half the sample rate: 200 / 2 = 100 Hz. Signal content above it will alias.
2. A — The nearest multiple of 50 Hz is 50, and |45 − 50| = 5 Hz. The fast vibration masquerades as a slow 5 Hz wobble.
3. C — Once aliasing has happened, the false low frequency is indistinguishable from real data. Filtering in software afterwards cannot separate them.
4. D — Nyquist sets a minimum of just over 40 Hz, but control loops usually sample around ten times faster than the fastest behaviour, so 200 Hz or more.
5. B — fc = 1 / (2π × 1000 × 0.000001) = 1 / 0.00628 ≈ 159 Hz.

**Lesson 5: Units, scaling and fixed-point arithmetic**

1. C — Integer division happens first and truncates 3000 / 4096 to 0, and 0 × 3300 = 0. Multiply first to keep the precision.
2. B — 4095 × 3300 = 13,513,500, which needs at least 24 bits. Widening to a 32-bit type before multiplying avoids the wrap-around.
3. D — Q16.16 stores value × 65,536, and 0.75 × 65,536 = 49,152.
4. A — When the gap falls below 8, the division truncates to zero. Extra fractional bits in the state let tiny corrections still accumulate.
5. B — The compiler does not understand units, so naming them is how humans avoid mixing them up, the kind of mistake that has caused real engineering failures.

**Lesson 6: Building a reliable sensor pipeline**

1. C — 250 cm is inside the sensor's range, but changing by 190 cm in 0.05 s would require 38 m/s. Only a plausibility check based on physics catches this.
2. A — A value's age matters as much as the value. Timestamps let code reject stale data and line up readings from different sensors.
3. B — A frozen value is in range and changes by zero, so range and rate checks pass it. Real noisy sensors rarely repeat exactly, and a second sensor would disagree as the world changes.
4. D — If the true value really jumps, all new readings disagree with the old reference. Counting consistent rejections, then re-accepting or raising a fault, avoids getting stuck.
5. A — Silence is itself the symptom. Only a check that runs regardless of new data can notice that data has stopped arriving.

---

This work is licensed under the Creative Commons Attribution 4.0 International licence (CC BY 4.0): https://creativecommons.org/licenses/by/4.0/. Attribute as: Tactiverge Academy, https://tactiverge.win.
