31  Sensors: Labs & Review

31.1 Learning Objectives

  • Interface common IoT sensors (temperature, motion, light, proximity) with ESP32 microcontrollers using appropriate protocols and libraries
  • Apply data filtering, sensor fusion, and calibration techniques to obtain accurate and reliable sensor measurements
  • Implement professional sensor health monitoring including error detection, validation, and graceful degradation
  • Perform two-point and multi-point sensor calibration using Wokwi simulation, including drift detection and verification
In 60 Seconds

This section provides a complete roadmap for hands-on sensor implementation, organized into five focused chapters: temperature sensors (DS18B20, DHT22), motion and environmental sensors (MPU6050, BMP280), light and proximity sensors (BH1750, PIR, ultrasonic), implementation best practices (filtering, fusion, health monitoring), and a professional calibration lab using Wokwi simulation.

Key Concepts
  • Lab Implementation Workflow: Standard sequence: read the datasheet, wire the circuit, flash the firmware, verify serial output, troubleshoot with a multimeter if readings are wrong, then add filtering and calibration
  • I2C Scanner Sketch: A small Arduino program that probes all 128 I2C addresses and reports which ones respond; the first diagnostic step when an I2C sensor is not communicating
  • ESP32 ADC Characteristics: The ESP32 internal ADC has 12-bit resolution but significant nonlinearity above 3.1 V and below 0.1 V; stay within 0.15-3.1 V for accurate readings or use an external ADC like the ADS1115
  • Library Dependency Management: Arduino/PlatformIO libraries must match the sensor model and protocol variant; using the wrong library version is a common source of compile errors and incorrect readings
  • Structured Data Logging: Printing sensor data as CSV (timestamp, sensor_id, value, unit) to serial or SD card enables later analysis in Python/Excel and is essential for any multi-session lab project
  • Firmware Iteration Cycle: Embedded development loop: write code, compile, flash, test, observe, revise; short cycles under 5 minutes are essential for effective learning and debugging
  • Oscilloscope Interpretation: Reading waveforms to verify signal levels, timing, and noise; key measurements: period, duty cycle, rise time, and peak-to-peak amplitude of the conditioned sensor output
  • Lab Report Documentation: Recording wiring diagrams, firmware version, raw readings, calibration coefficients, and test results; enables reproducibility and future debugging of the same hardware

31.2 Overview

Sensor labs bridge the gap between theory and practice. Each sub-chapter below targets a specific sensor family or skill, letting you jump directly to what you need or work through the full sequence for comprehensive coverage.

Calibration quality should be measured, not guessed. A standard metric is root-mean-square error (RMSE):

\[ \text{RMSE} = \sqrt{\frac{1}{n}\sum_{i=1}^{n} (\hat{y}_i - y_i)^2} \]

Worked example: Suppose raw sensor errors at five checkpoints are \(\{0.8,-0.4,0.2,-0.6,0.3\}^\circ\)C. Then RMSE is:

\[ \sqrt{\frac{0.64+0.16+0.04+0.36+0.09}{5}} \approx 0.508^\circ\text{C} \]

After calibration, errors become \(\{0.2,-0.1,0.1,-0.2,0.0\}^\circ\)C, giving RMSE:

\[ \sqrt{\frac{0.04+0.01+0.01+0.04+0}{5}} \approx 0.141^\circ\text{C} \]

That is about a 3.6x accuracy improvement, which is the kind of result your lab verification should report.

Enter your own sensor error values (comma-separated) to compute RMSE before and after calibration.

Step-by-step sensor lab implementation workflow diagram showing the complete process from planning to deployment. Steps include: (1) Planning - select sensor, review datasheet, gather components; (2) Wiring - breadboard layout, power connections, signal wiring with pull-ups; (3) Software Setup - install libraries, write initialization code, implement read functions; (4) Testing - serial monitor debugging, verify readings against known references, check for noise; (5) Calibration - two-point or multi-point calibration, create correction formula; (6) Integration - combine with other sensors, add data logging, implement error handling. Includes common troubleshooting tips at each stage.

Sensor lab implementation workflow
Figure 31.1: AI-generated sensor lab workflow showing the complete implementation process

31.3 Chapter Contents

This section is organized into five focused chapters:

31.4 Learning Path

Recommended Order

For best results, complete these chapters in sequence:

  1. Start with Temperature Sensors - Simplest interfacing with well-documented sensors
  2. Progress to Motion Sensors - Learn I2C communication and calibration basics
  3. Explore Light and Proximity - Multiple sensor types and circuit fundamentals
  4. Apply Best Practices - Complete hands-on labs
  5. Master Calibration - Advanced techniques with Wokwi simulation

31.5 Quick Reference

Sensor Interface Chapter
DS18B20 1-Wire Temperature
DHT22 Single-wire Temperature
MPU6050 I2C Motion
BMP280 I2C Motion
BH1750 I2C Light
PIR HC-SR501 Digital Light
HC-SR04 Digital Light

31.6 Videos

These lecture recordings cover sensor fundamentals and interfacing techniques that apply across all five lab chapters.

Sensor Fundamentals (Part 1)
From Lesson 3 - core definitions, characteristics, and classifications.
Sensor Interfaces and Signal Conditioning
From Lesson 3 - interfacing sensors to microcontrollers and conditioning signals.

Different learning paths work better depending on your prior experience. Use this decision framework to choose which labs to prioritize:

Your Background Start With Why Then Progress To
Complete beginner Temperature Labs (DS18B20) Single-wire digital interface, visual temperature results, immediate feedback Motion sensors → Light sensors → Best practices
Arduino experience Motion & Environmental Labs (MPU6050, BMP280) I2C protocol practice, multiple axes of data, reinforces concepts Sensor fusion → Calibration
Embedded C expert Best Practices Labs (health monitoring, fusion) Focuses on production-quality code patterns All labs for breadth
Electrical engineering Light & Proximity Labs (analog circuits, ADC) Leverages circuit design knowledge Signal conditioning → Calibration
Data science Sensor Fusion & Calibration Labs Statistical methods, Kalman filtering All sensors for data source variety
Quick prototype needed Skip to sensor matching your project Get specific sensor working fast Return to fundamentals later

Lab Difficulty Progression:

EASIEST ─────────────────────────────────────► HARDEST

DS18B20    DHT22    BH1750    MPU6050    Multi-sensor    Calibration
(1-Wire)   (timing) (I2C)     (I2C+math)    Fusion       (statistics)
  ↓          ↓        ↓          ↓             ↓             ↓
1 day     1 day    2 days    3 days        4 days        5 days

Time Estimates by Lab:

Lab Chapter Minimum Time Comfortable Time Thorough Time
Temperature Sensors 2 hours (DS18B20 only) 4 hours (all sensors) 8 hours (including debugging)
Motion & Environment 3 hours (one sensor) 6 hours (both sensors + math) 12 hours (with sensor fusion)
Light & Proximity 2 hours (BH1750 only) 5 hours (all 4 sensors) 10 hours (with circuits)
Best Practices Labs 4 hours (Labs 1-2) 8 hours (all 4 labs) 16 hours (with variations)
Calibration Lab (Wokwi) 2 hours (basic) 4 hours (all exercises) 8 hours (with challenges)

Decision Tree for Lab Selection:

START: What is your goal?
  |
  ├─ Learn sensor fundamentals systematically
  │   └─ Follow complete sequence: Temp → Motion → Light → Practices → Calibration
  |
  ├─ Build a specific project
  │   ├─ Need temperature? → Temperature Labs
  │   ├─ Need motion/tilt? → Motion & Environmental Labs
  │   ├─ Need distance/light? → Light & Proximity Labs
  │   └─ Need production quality? → Best Practices Labs
  |
  ├─ Prepare for job interview
  │   └─ Priority order:
  │       1. Best Practices Labs (shows professional skills)
  │       2. Calibration Lab (shows mathematical understanding)
  │       3. One sensor from each category (shows breadth)
  |
  └─ Teaching/mentoring others
      └─ Master all labs in sequence to understand common pitfalls

Common Time-Saving Mistakes to Avoid:

Shortcut Why It Backfires Better Approach
Skip temperature labs “too simple” Miss fundamental 1-Wire and timing concepts Do DS18B20 as warm-up, even if experienced
Jump to calibration first Calibration makes no sense without raw sensor data Do at least one sensor lab first
Skip best practices “just need it working” Code breaks in production deployment Spend 1 hour on Lab 4 (health monitoring) minimum
Use ChatGPT/AI for all code Don’t internalize concepts, can’t debug Use AI for reference, type code yourself
Skip breadboarding, go straight to PCB Wiring errors costly to fix Prove concept on breadboard first

Lab Completion Checklist:

For each lab, you should be able to:

Learning Efficiency Tips:

  1. Document as you go: Take photos of working circuits, save working code snippets
  2. Break labs over multiple days: Better retention than marathon sessions
  3. Repeat tricky parts: If MPU6050 took 3 tries to work, do it again next week
  4. Vary parameters: Change ADC resolution, filter window sizes, thresholds
  5. Intentionally break things: What happens if you swap SDA/SCL? Remove pull-ups?
  6. Explain to others: Best way to solidify understanding

If You Get Stuck:

Problem Quick Checks Next Steps
Sensor not detected Power? Wiring? I2C address? Run bus scan, check with multimeter
Garbage readings Units? Calibration? Datasheet? Read raw values, check expected ranges
Code won’t compile Library installed? Board selected? Check error message first 3 words
Intermittent failures Loose wires? Power supply? Noise? Add decoupling capacitors, check ground

Next Steps After Completing All Labs:

  1. Build a project combining 3+ sensors (e.g., weather station: temp, humidity, pressure, light)
  2. Deploy outdoors for 1 week (reveals issues not seen in lab)
  3. Add data logging (SD card or cloud storage)
  4. Implement alerts (SMS, email, MQTT when thresholds exceeded)
  5. Optimize power (run on battery for 1 month+)
  6. Create custom PCB (move from breadboard to permanent install)

Recommended Learning Path for Different Timelines:

1-Day Crash Course (8 hours): - DS18B20 temperature (2h) - BH1750 light (2h) - Sensor health monitoring (2h) - Two-point calibration concepts (2h)

1-Week Intensive (40 hours): - All temperature labs (1 day) - All motion & environmental labs (1.5 days) - All light & proximity labs (1 day) - All best practices labs (1 day) - Full calibration lab with exercises (0.5 days)

1-Month Comprehensive (80 hours): - Follow sequence as written with thorough exploration - Complete all challenge exercises - Build 2-3 projects integrating multiple sensors - Read referenced datasheets in detail - Implement custom improvements

Self-Assessment Questions (answer these to gauge readiness):

  1. Can you explain the difference between I2C and SPI without looking it up?
  2. Can you calculate required pull-up resistor values for I2C?
  3. Do you understand why moving average reduces noise by √N?
  4. Can you explain accuracy vs precision with real examples?
  5. Would you know how to diagnose a sensor reading constant zero?

If you answered “no” to 3+ questions, slow down and review fundamentals before proceeding.

Welcome to Sensor Lab School! The Sensor Squad is here to help you learn how to build real sensor projects, step by step.

Sammy the Sensor (a temperature sensor) says: “Start with me! I am the easiest sensor to wire up. Just one wire for data, one for power, and one for ground. I will tell you the temperature!”

Max the Microcontroller adds: “Once you can read Sammy, try my friend the accelerometer – he can tell if something is moving, tilting, or even falling! He uses a special two-wire language called I2C.”

Lila the LED is excited: “Then we learn about light sensors and motion detectors! I can blink to show you what the sensors are reading!”

Bella the Battery reminds everyone: “And do not forget to check your readings! Always make sure the numbers make sense. If Sammy says it is 500 degrees in your room, something is wrong with the wiring!”

Follow the five lab chapters in order, and soon you will be a sensor expert!

31.7 What’s Next?

Start your sensor implementation journey with temperature sensors, the most approachable entry point for hands-on learning. Use the table below to navigate to any lab chapter or related topic.

Next Step Description
Temperature Sensor Labs Begin with DS18B20 and DHT22 – the simplest sensor interfacing
Motion and Environmental Sensor Labs Interface MPU6050 accelerometer/gyroscope and BMP280 barometric sensor
Light and Proximity Sensor Labs Build light-sensing and ultrasonic distance measurement systems
Sensor Implementation Best Practices Apply filtering, fusion, and health monitoring techniques
Sensor Calibration Lab (Wokwi) Master two-point and multi-point calibration with simulation
Actuators and Control Continue to output devices after completing all sensor labs

Exercise: Create a complete weather station that reads temperature, humidity, and light levels.

Components needed:

  • ESP32 development board
  • DHT22 (temperature + humidity)
  • BH1750 (light sensor)
  • Breadboard and jumper wires

Challenge:

  1. Wire all three sensors to the ESP32
  2. Read all sensors every 10 seconds
  3. Display readings on Serial Monitor
  4. Calculate a “comfort index” combining temperature and humidity
  5. Add LED indicators: green (comfortable), yellow (borderline), red (uncomfortable)

Hint: Start with one sensor working, then add others incrementally. Use the I2C scanner code to verify the BH1750 address.

Solution approach:

// Thermal comfort approximation (simplified from Steadman's apparent temperature)
float comfort = temperature - (0.55f * (1.0f - humidity / 100.0f) * (temperature - 14.5f));
// Green: 18-24°C, Yellow: 15-18 or 24-27, Red: <15 or >27

31.8 Concept Relationships

Core Concept Related Concepts Why It Matters
DS18B20 1-Wire Multi-Sensor Bus, Unique Addressing Enables multiple sensors on single GPIO
I2C Communication SDA/SCL, Pull-up Resistors, Address Scanning Standard interface for digital sensors
Data Filtering Moving Average, EMA, Kalman Filter Reduces noise for reliable readings
Sensor Fusion Complementary Data, Weighted Averaging Combines sensors for better accuracy
Calibration RMSE, Two-Point, Multi-Point Interpolation Corrects systematic sensor errors
Power Management Deep Sleep, Duty Cycling Critical for battery-powered deployments

31.9 See Also