21  Sensor Quiz and Practice Exercises

In 60 Seconds

This quiz chapter tests core sensor concepts: resolution vs accuracy (high resolution does not mean high accuracy), power budgeting (150 mA continuous drains a 2000 mAh battery in ~13 hours), Nyquist sampling (sample at 2x the highest frequency or get aliasing), I2C troubleshooting (check pull-ups, addresses, voltage levels), and systematic sensor selection using a requirements matrix.

Learning Objectives

After completing this chapter, you will be able to:

  • Distinguish between sensor resolution and accuracy in practical measurement scenarios
  • Calculate battery life for duty-cycled IoT sensor systems using power budgets
  • Diagnose aliasing errors by applying the Nyquist sampling theorem
  • Debug I2C communication failures using a systematic troubleshooting checklist
  • Evaluate competing sensor options using a requirements-based selection matrix

21.1 Prerequisites

  • Complete all previous chapters in the Sensor Fundamentals series

21.2 Knowledge Check Quiz

Test your mastery of sensor fundamentals with these practice questions.

21.2.1 Question 1: Resolution vs Accuracy

A temperature sensor has 16-bit resolution (0.01 degree C steps) and +/-3 degree C accuracy. You need to detect temperature changes of 1 degree C. Is this sensor suitable?

21.2.2 Question 2: Power Consumption

You are designing a battery-powered soil moisture monitor with a 2000 mAh battery. The sensor draws 150 mA continuously with no sleep mode. How long will the battery last?

21.2.3 Question 3: Nyquist Sampling

A vibration sensor detects frequencies up to 500 Hz. You are sampling at 600 Hz and see a 100 Hz pattern that should not exist. What is happening?

21.2.3.1 Try It: Aliasing Frequency Calculator

Experiment with different signal and sampling frequencies to see when aliasing occurs and what false frequency appears.

21.2.4 Question 4: I2C Troubleshooting

Your BMP280 pressure sensor is not detected on the I2C bus. The wiring looks correct. What should you check first?

21.2.5 Question 5: Sensor Selection

You need to measure room temperature for a smart thermostat. Requirements: +/-0.5 degree C accuracy, I2C interface, under $10, low power. Which sensor fits best?

21.3 Practice Exercises

21.3.1 Exercise 1: Calibration

Your DHT22 consistently reads 2.3°C higher than a reference thermometer. Write the calibration code.

import dht
import machine

sensor = dht.DHT22(machine.Pin(4))

def read_calibrated_temperature():
    sensor.measure()
    raw = sensor.temperature()
    # Apply offset correction (sensor reads 2.3°C high)
    offset = -2.3
    calibrated = raw + offset
    return calibrated

# Example usage
temp = read_calibrated_temperature()
print(f"Calibrated temperature: {temp:.1f}°C")

Note: For a more robust approach, use a two-point calibration (slope + offset) rather than a single offset correction. A single offset assumes the error is constant across the entire temperature range.

21.3.2 Exercise 2: Moving Average Filter

Implement a moving average filter for an ultrasonic distance sensor that occasionally produces outliers.

from collections import deque

class MovingAverage:
    def __init__(self, window_size=5):
        self.window = deque(maxlen=window_size)

    def filter(self, value):
        self.window.append(value)
        return sum(self.window) / len(self.window)

Challenge: Modify to use a median filter instead for better outlier rejection.

Click to reveal median filter solution
from collections import deque

class MedianFilter:
    def __init__(self, window_size=5):
        self.window = deque(maxlen=window_size)

    def filter(self, value):
        self.window.append(value)
        sorted_window = sorted(self.window)
        mid = len(sorted_window) // 2
        if len(sorted_window) % 2 == 0:
            return (sorted_window[mid - 1] + sorted_window[mid]) / 2
        return sorted_window[mid]

# Example: outlier at reading 3 is rejected
filt = MedianFilter(window_size=5)
readings = [100, 102, 999, 101, 103]  # 999 is an outlier
for r in readings:
    print(f"Raw: {r} cm -> Filtered: {filt.filter(r):.1f} cm")
# Output: 100.0, 101.0, 102.0, 101.5, 102.0
The median filter completely ignores the 999 cm outlier, while a moving average would have been pulled toward it.

21.3.3 Exercise 3: Battery Life Calculation

Calculate battery life for this system:

  • Battery: 3000 mAh
  • MCU: 10 mA active, 10 µA sleep (active for 500 ms during each sensor reading)
  • Sensor: 1 mA active (500 ms per reading), 0.1 µA sleep
  • Reading interval: Every 10 minutes
Click to reveal solution

Calculation:

Convert time to hours for mAh: 500 ms = 0.5 s = 0.5/3600 h = 0.000139 h; 9.5 min = 570 s = 570/3600 h = 0.1583 h.

Per reading cycle (10 minutes):

  • MCU active: 0.000139 h x 10 mA = 0.00139 mAh
  • MCU sleep: 0.1583 h x 0.01 mA = 0.00158 mAh
  • Sensor active: 0.000139 h x 1 mA = 0.000139 mAh
  • Sensor sleep: 0.1583 h x 0.0001 mA = 0.0000158 mAh

Total per cycle: ~0.00311 mAh

Cycles per day: 144 (one reading every 10 minutes)

Daily consumption: 144 x 0.00311 = 0.448 mAh/day

Battery life: 3000 / 0.448 = 6,696 days (~18.3 years)

Note: Real-world factors (self-discharge, temperature, aging, voltage regulator quiescent current) significantly reduce this. A practical estimate with a 3x safety factor would be ~6 years, which is still excellent.

21.3.3.1 Interactive Battery Life Calculator

Use this calculator to experiment with different duty-cycle parameters and see how they affect battery life.

21.3.4 Exercise 4: Sensor Selection Matrix

Create a selection matrix for a weather station that needs: - Temperature (+/-0.5°C) - Humidity (+/-3%) - Pressure (+/-1 hPa) - Budget: <$15 total

Requirement BME280 DHT22 + BMP280 SHT31 + BMP280
Temp accuracy +/-1°C +/-0.5°C +/-0.3°C
Humidity accuracy +/-3% +/-2% +/-2%
Pressure accuracy +/-1 hPa +/-1 hPa +/-1 hPa
Cost ~$8 ~$5 + $5 = $10 ~$12 + $5 = $17
Complexity 1 chip 2 chips 2 chips

Decision: BME280 for simplicity and lowest cost (single chip, single I2C address), or DHT22 + BMP280 for better temperature accuracy within budget. The SHT31 + BMP280 exceeds the $15 budget.

Scenario: Design a temperature data logger for a cold storage facility that must operate for 1 year on batteries without replacement.

Requirements:

  • Temperature range: -30°C to +10°C (cold storage)
  • Accuracy: +/- 0.5°C (regulatory compliance)
  • Sampling interval: Every 10 minutes (144 readings/day)
  • Data storage: Local SD card (no wireless transmission)
  • Battery: Standard alkaline AA batteries (2× in series = 3V, ~2500 mAh effective capacity)

Step 1: Choose Temperature Sensor

Sensor Range Accuracy Interface Power Cost Suitable?
DHT22 -40 to 80°C +/- 0.5°C Digital 1.5 mA active, 2 sec read $4 ⚠️ Marginal (slow 2 sec reads waste power)
DS18B20 -55 to 125°C +/- 0.5°C 1-Wire digital 1.5 mA active, 750 ms $2 ✅ Yes
Thermistor -50 to 150°C +/- 1-2°C Analog <0.1 mA $0.50 ❌ No (accuracy)
BME280 -40 to 85°C +/- 1°C I2C 0.7 mA active $5 ❌ No (accuracy marginal)

Choice: DS18B20 — meets temperature range, accuracy, and has digital output

Step 2: Select Microcontroller

Requirement: Ultra-low sleep current (<10 µA) since device sleeps 99.9% of the time

MCU Sleep Current Active Current Price Suitable?
ESP32 10 µA 80 mA $5 ✅ Yes (but overkill)
ATmega328P 0.1 µA 8 mA $2 ✅ Yes (perfect)
STM32L0 0.3 µA 5 mA $3 ✅ Yes (ultra-low)

Choice: ATmega328P (Arduino Nano) — excellent sleep current, cheap, simple

Step 3: Power Budget Calculation

Per 10-minute cycle:

Component State Current Duration Energy (µAh)
ATmega328P Sleep 0.1 µA 9 min 59 sec (599 sec) 0.017
ATmega328P Active 8 mA 1 sec 2.22
DS18B20 Read 1.5 mA 0.75 sec 0.31
SD Card Write 20 mA 0.1 sec 0.56
Total 10 min 3.1 µAh

Daily consumption:

144 cycles/day × 3.1 µAh = 446 µAh/day = 0.446 mAh/day

Yearly consumption:

0.446 mAh/day × 365 days = 163 mAh/year

Putting Numbers to It: Battery lifetime is capacity divided by consumption rate: \(t = \frac{Q}{I_{avg}}\) where Q is capacity (mAh) and \(I_{avg}\) is average draw (mA). With a 2500 mAh battery and 0.446 mAh/day draw, applying a 2x safety factor for cold temperature derating gives effective capacity = \(\frac{2500}{2} = 1250\text{ mAh}\). Lifetime: \(\frac{1250}{163/365} = 2800\text{ days} \approx 7.7\text{ years}\).

Battery life check:

Battery capacity: 2500 mAh (2× AA alkaline)
Required: 163 mAh/year
Safety factor (temperature derating + aging): 2×
Effective capacity: 2500 / 2 = 1250 mAh

1250 mAh / 163 mAh/year = 7.7 years ✅ Exceeds 1-year requirement!

Step 4: Complete Bill of Materials

Component Quantity Unit Price Total
DS18B20 temperature sensor 1 $2 $2
Arduino Nano (ATmega328P) 1 $3 $3
MicroSD card module 1 $2 $2
4 GB MicroSD card 1 $3 $3
2× AA battery holder 1 $1 $1
2× AA alkaline batteries 1 $2 $2
Waterproof enclosure (IP65) 1 $5 $5
4.7kΩ resistor (1-Wire pull-up) 1 $0.10 $0.10
Total $18.10

Key Design Decisions:

  1. No wireless — Wi-Fi/LoRa would consume 10-100× more power, reducing battery life to months instead of years
  2. Local storage — SD card uses power only during brief writes (~100 ms), sleeps the rest of the time
  3. Slow sampling — 10-minute intervals adequate for cold storage (temperature changes slowly)
  4. ATmega328P over ESP32 — 100× lower sleep current (0.1 µA vs 10 µA) when sleeping 99.9% of the time

Result: A $18 temperature logger that runs for 7+ years on $2 worth of AA batteries. Perfect for “install and forget” cold storage monitoring.

21.4 Concept Relationships

Concept Related To Connection Type
Resolution ADC Bit Depth Higher bit depth gives finer steps (e.g., 0.01°C), but does not improve accuracy
Aliasing Nyquist Theorem Sample at >2× highest frequency to avoid false patterns
Battery Life Sleep Current µA sleep current enables years; mA kills batteries in days
Calibration Drift Sensor Aging Factory calibration degrades over months/years
I2C Pull-ups Open-drain Bus 4.7 kohm resistors required for HIGH state

Key Takeaway

Sensor fundamentals form a connected knowledge web: understanding specifications (accuracy, resolution, range) enables informed selection, which leads to correct interfacing and calibration, which produces reliable data for your IoT application. The most common errors – voltage mismatch, missing pull-ups, ignoring timing, and skipping validation – are all preventable with systematic checklist-based practices.

21.5 Summary

You’ve completed the Sensor Fundamentals quiz and exercises. Key concepts tested:

  1. Resolution vs accuracy distinction
  2. Power consumption calculations
  3. Nyquist sampling and aliasing
  4. I2C troubleshooting
  5. Sensor selection process
  6. Calibration techniques
  7. Filtering strategies

Congratulations! You have reached the end of Sensor School! The Sensor Squad is SO proud of you!

Sammy the Sensor gives you a gold star: “You learned the difference between accuracy (being right) and resolution (having lots of decimal places). Remember – a sensor can show 25.37°C but still be wrong by 2°C!”

Max the Microcontroller high-fives you: “You can calculate battery life, understand I2C troubleshooting, and know about Nyquist sampling. You are basically a sensor engineer now!”

Lila the LED blinks happily: “You know how to wire sensors, validate data, apply filters, and calibrate. Those are real-world skills!”

Bella the Battery has one last reminder: “Power matters! A sensor drawing 150 mA continuously will drain me in 13 hours. Always look for sleep modes and smart duty-cycling to make me last years instead of hours!”

The whole Squad cheers: “Now go build amazing IoT projects! And remember – always read the datasheet, check your voltage, and validate your data!”

21.6 See Also

Common Pitfalls

Quiz questions test specific concepts from the sensor types chapter. Attempting questions without first reading the relevant section produces random guesses rather than learning. Review the section before attempting each question block, then use incorrect answers to identify knowledge gaps.

Good distractors represent common misconceptions or partial knowledge. If a distractor seems obviously wrong, re-read the question. The correct answer requires understanding a specific nuance, not just eliminating nonsense options.

Some exercises require numerical calculations (SNR, ADC resolution, RC filter cutoff frequency). Skipping these and memorizing formulas without applying them leaves a critical gap in understanding. Work through at least one numerical example for each formula covered in the chapter.

Each question error represents a real design mistake you could make in an actual IoT project. After reviewing the correct answer, ask: when would I make this mistake in a real circuit? Converting abstract quiz errors into concrete design lessons is the highest-value use of assessment exercises.

21.7 What’s Next

Congratulations on completing the Sensor Fundamentals series! Continue building your IoT expertise with these related topics:

Chapter Focus Area
Sensor Interfacing and Processing Advanced connection techniques, signal conditioning, and data pipelines
Sensor Labs: Implementation and Review Hands-on projects applying sensor fundamentals to real hardware
Sensor Calibration Lab Practical calibration workflows for improving measurement accuracy
Actuators and Control Complete the sensing-actuation feedback loop in IoT systems
Sensor Fundamentals and Types Return to the series index for review or to revisit specific topics