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
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.
Putting Numbers to It
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.
Interactive: RMSE Calculator
Enter your own sensor error values (comma-separated) to compute RMSE before and after calibration.
31.3 Chapter Contents
This section is organized into five focused chapters:
31.3.1 1. Temperature Sensor Labs
Temperature Sensor Labs - Interface DS18B20 1-Wire sensors, explore thermocouple fundamentals, and compare humidity sensing technologies.
Topics covered:
- DS18B20 digital temperature sensor implementation
- Thermocouple-based temperature measurement
- DHT22 temperature and humidity sensing
- Multi-sensor 1-Wire bus configuration
31.3.2 2. Motion and Environmental Sensors
Motion and Environmental Sensor Labs - Interface accelerometers, gyroscopes, and barometric pressure sensors for motion tracking and environmental monitoring.
Topics covered:
- MPU6050 6-axis IMU (accelerometer + gyroscope)
- Calculating pitch and roll from accelerometer data
- BMP280 barometric pressure and altitude sensing
- Motion detection algorithms
31.3.3 3. Light and Proximity Sensors
Light and Proximity Sensor Labs - Build light-sensing systems, motion detection with PIR, and ultrasonic distance measurement.
Topics covered:
- BH1750 digital lux meter
- LDR (photoresistor) analog light sensing
- PIR motion sensor interfacing
- HC-SR04 ultrasonic distance measurement
- I2C bus management and scanning
- Circuit fundamentals (voltage dividers, RC filters)
31.3.4 4. Best Practices and Hands-On Labs
Sensor Implementation Best Practices and Labs - Apply professional implementation techniques through hands-on labs covering filtering, fusion, and health monitoring.
Topics covered:
- Data validation and error handling
- Moving average and noise filtering
- Lab 1: DHT22 with filtering
- Lab 2: Multi-sensor fusion
- Lab 3: Two-point calibration
- Lab 4: Sensor health monitoring
- Temperature-controlled relay systems
31.3.5 5. Calibration Lab (Wokwi Simulation)
Sensor Calibration Lab - Master professional calibration techniques through interactive Wokwi simulation with comprehensive code examples.
Topics covered:
- Two-point calibration (offset + gain correction)
- Multi-point interpolation for non-linear sensors
- Drift detection and compensation
- Accuracy vs precision demonstration
- Calibration verification with RMSE and R-squared
- Non-volatile storage of calibration coefficients
31.4 Learning Path
Recommended Order
For best results, complete these chapters in sequence:
- Start with Temperature Sensors - Simplest interfacing with well-documented sensors
- Progress to Motion Sensors - Learn I2C communication and calibration basics
- Explore Light and Proximity - Multiple sensor types and circuit fundamentals
- Apply Best Practices - Complete hands-on labs
- 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.
Decision Framework: Choosing Sensor Lab Sequence Based on Your Background
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:
- Document as you go: Take photos of working circuits, save working code snippets
- Break labs over multiple days: Better retention than marathon sessions
- Repeat tricky parts: If MPU6050 took 3 tries to work, do it again next week
- Vary parameters: Change ADC resolution, filter window sizes, thresholds
- Intentionally break things: What happens if you swap SDA/SCL? Remove pull-ups?
- 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:
- Build a project combining 3+ sensors (e.g., weather station: temp, humidity, pressure, light)
- Deploy outdoors for 1 week (reveals issues not seen in lab)
- Add data logging (SD card or cloud storage)
- Implement alerts (SMS, email, MQTT when thresholds exceeded)
- Optimize power (run on battery for 1 month+)
- 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):
- Can you explain the difference between I2C and SPI without looking it up?
- Can you calculate required pull-up resistor values for I2C?
- Do you understand why moving average reduces noise by √N?
- Can you explain accuracy vs precision with real examples?
- 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.
For Kids: Meet the Sensor Squad!
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 |
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
- Sensor Fundamentals - Comprehensive sensor characteristics and theory
- Sensor Circuits - Signal conditioning and circuit design
- Electronics Basics - Electronic component fundamentals
- Prototyping Hardware - Development boards and platforms