8  Sensor Introduction and Fundamentals

sensors
fundamentals
analog
digital
specifications

Learning Objectives

After completing this chapter, you will be able to:

  • Define what sensors are and articulate why they matter for IoT
  • Compare the relationship between sensors and human senses
  • Distinguish between analog and digital sensors and select the appropriate type for a given application
  • Classify common sensor types by measurement principle, output, and power source
  • Differentiate between accuracy, precision, and resolution when evaluating sensor specifications
In 60 Seconds

Sensors bridge the physical and digital worlds by converting physical phenomena — temperature, pressure, motion, light — into electrical signals a microcontroller can read. Every sensor is characterized by five key specifications: accuracy (closeness to true value), precision (repeatability), resolution (smallest detectable change), range (measurement limits), and response time (how quickly the output tracks a change). Always read the datasheet before selecting a sensor for a project.

Key Concepts
  • Sensor: A device that converts a physical quantity (temperature, pressure, light, motion) into an electrical signal (voltage, current, resistance change, digital data) that an electronic system can measure and process
  • Accuracy: How close the sensor’s reading is to the true value; expressed as +-X% of full scale or +-X units; a temperature sensor with +-0.5 C accuracy reads no more than 0.5 C above or below actual temperature
  • Precision: The repeatability of measurements under identical conditions; a sensor can be precise (consistent) but inaccurate (consistently wrong) — high precision is necessary but not sufficient for accurate measurements
  • Resolution: The smallest change in the measured quantity that the sensor can detect; set by the sensor’s analog sensitivity and the ADC bit depth; a 12-bit ADC over 100 C range has approximately 0.024 C resolution
  • Measurement Range: The minimum and maximum values the sensor can measure while staying within its specified accuracy; readings outside the range may be nonlinear or produce undefined output
  • Response Time: How quickly the sensor output settles after a step change in the measured quantity; specified as time to reach 63.2% (one time constant) or 90% of final value; important for detecting rapid events
  • Sensitivity: The change in sensor output per unit change in the measured quantity; e.g., 10 mV/C means the output voltage changes 10 mV for every 1 C temperature change; higher sensitivity makes small changes easier to detect
  • Transducer: The physical element within a sensor that performs the energy conversion from the measured domain (mechanical, thermal, optical) to the electrical domain; the rest of the sensor conditions and communicates the signal

8.1 Prerequisites

Before diving into this chapter, you should be familiar with:

  • Electricity Fundamentals: Understanding basic electrical concepts like voltage, current, and resistance is essential for working with sensor circuits and power requirements.
  • Electronics Fundamentals: Knowledge of semiconductors and basic electronic components helps you understand how sensors convert physical phenomena into electrical signals.
  • Analog and Digital Electronics: Familiarity with ADC/DAC concepts and digital vs. analog signals prepares you for interfacing sensors with microcontrollers.

8.2 For Kids: Meet the Sensor Squad!

Hi there! Let’s meet some special friends who help computers understand our world!

8.2.1 The Sensor Squad

Imagine if your toys could tell you things! That’s what sensors do - they’re like little helpers that can:

  • Feel if it’s hot or cold (like Temperature Terry!)
  • See if the lights are on or off (like Light Lucy!)
  • Notice when something moves (like Motion Marley!)
  • Feel if it’s going to rain (like Pressure Pete!)
  • Send messages through the air (like Signal Sam!)

8.2.2 What Do Sensors Do? (A Fun Story!)

Temperature Terry’s Job: > “Hi! I’m Temperature Terry! I sit in your room and feel if it’s warm or cold. When it gets too hot, I tell the air conditioner to turn on. When it’s cold, I ask the heater to warm things up. I’m like a magic thermometer that can talk to machines!”

How Sensors Are Like Your Senses:

Your Body Sensor Friend What It Feels
Your skin feels hot/cold Temperature Terry How warm or cold it is
Your eyes see light Light Lucy How bright or dark it is
Your ears hear sounds Sound Simon Loud or quiet noises
Your nose smells things Gas Gary If the air smells funny
You feel if something touches you Touch Tina When something presses on it

8.2.3 A Day in the Life of a Smart Home Sensor

Morning: Light Lucy notices the sun coming up and tells your smart blinds to open slowly.

Afternoon: Temperature Terry feels it getting warm and asks the fan to turn on.

Evening: Motion Marley notices you walking into your room and turns on the lights for you!

Night: All the sensors go into “sleep mode” - they’re still watching, but very quietly to save energy (like when you sleep but can still hear if someone calls your name).

8.2.4 Try This at Home!

Be a Human Sensor! Close your eyes and: 1. Feel if your hand is warm or cold (you’re being Temperature Terry!) 2. Listen for sounds nearby (you’re being Sound Simon!) 3. Feel the floor with your feet - is it soft carpet or hard wood? (you’re being Touch Tina!)

You just used YOUR built-in sensors! The sensors in IoT devices work the same way, but they can tell computers what they feel.

8.2.5 Key Words for Kids

Word What It Means
Sensor A tiny helper that can feel one thing really well
Temperature How hot or cold something is
Motion Movement - when things go from one place to another
Light The bright stuff that helps you see
Signal A message sent through the air, like invisible mail

8.2.6 The Sensor Squad Promise

Sensors make our world smarter! They help: - Keep us comfortable (not too hot, not too cold) - Keep us safe (smoke detectors are sensors!) - Save energy (lights turn off when nobody’s there) - Make life easier (doors open automatically when you walk up)

Now you know what sensors are! They’re like tiny friends with super-senses who help computers understand the real world!

8.3 Introduction

~15 min | Foundational | P06.C08.U01

Sensors are the fundamental building blocks of IoT systems, serving as the bridge between the physical and digital worlds. They convert physical phenomena (temperature, pressure, motion, light, etc.) into electrical signals that can be processed by microcontrollers and computers.

MVU: Sensors - The IoT Building Blocks

Core Concept: Sensors are transducers that convert physical phenomena (temperature, light, motion, pressure) into electrical signals that digital systems can process and act upon. Why It Matters: Without sensors, IoT systems are blind - they cannot perceive the physical world they are designed to monitor and control. Sensor selection (accuracy, resolution, power, cost) determines what your system can reliably detect. Key Takeaway: Accuracy and resolution are independent specifications - a 16-bit sensor with poor accuracy gives you more decimal places of a wrong answer. Always match sensor specifications to your application’s actual requirements.

Cross-Hub Connections

Explore Related Learning Resources:

  • Video Library: Watch hands-on sensor tutorials including DHT22 setup, calibration techniques, and multi-sensor projects
  • Interactive Simulations: Try the Sensor Calibration Demo and Quick Sensor Selector tool featured in this chapter
  • Knowledge Gaps: Learn about common sensor mistakes like confusing resolution with accuracy
  • Self-Assessment Quizzes: Test your understanding of sensor specifications and selection criteria

Cross-Reference with Other Topics:

Common Misconception: “Higher Resolution = Better Accuracy”

The Misconception: Many beginners believe a 16-bit sensor (65,536 levels) is automatically more accurate than a 12-bit sensor (4,096 levels).

The Reality: Resolution and accuracy are completely independent specifications!

Real-World Example - Temperature Sensors:

Sensor Resolution Accuracy What This Means
Cheap 16-bit sensor 0.01C steps +/-3C error Measures 23.47C when actual is 20-26C range
Quality 12-bit sensor 0.0625C steps +/-0.3C error Measures 22.5C when actual is 22.2-22.8C

The 16-bit sensor gives you more decimal places in a wrong answer! It’s like using a ruler with millimeter markings that’s bent by 3 centimeters - the fine markings are meaningless.

Quantified Impact:

  • In a $2M smart building HVAC project, engineers initially selected 16-bit thermistors with +/-2C accuracy
  • System oscillated heating/cooling because it couldn’t reliably detect 1C setpoint differences
  • Switching to 12-bit sensors with +/-0.5C accuracy saved $180,000/year in energy costs
  • Lesson: Always check accuracy specification first, then ensure resolution is finer than your required accuracy

How to Choose Correctly:

  1. Start with accuracy requirement: “I need to detect +/-0.5C changes”
  2. Select sensor with matching accuracy: +/-0.3C or better
  3. Check resolution is adequate: Resolution should be <=1/3 of accuracy (<=0.1C in this case)
  4. Don’t overpay for excessive resolution: 0.01C resolution with +/-2C accuracy is wasteful

8.4 Getting Started (For Beginners)

New to Sensors? Start Here!

This section is designed for beginners. If you’re already familiar with sensor characteristics and types, feel free to skip to the technical sections below.

8.4.1 What is a Sensor? (Simple Explanation)

Analogy: Think of sensors as the “five senses” for electronic devices. Just like you use your eyes to see light, ears to hear sound, and skin to feel temperature, IoT devices use sensors to perceive their environment.

Tradeoff: Analog vs Digital Sensors

Decision context: When selecting sensors for an IoT project, you must choose between analog sensors (continuous voltage output) and digital sensors (discrete data via protocols like I2C/SPI).

Factor Analog Sensors Digital Sensors
Power consumption Varies (passive types very low) Medium (active circuitry)
Latency Immediate (no processing) Slight delay (ADC on-chip)
Complexity Higher (external ADC, calibration) Lower (plug-and-play)
Cost Generally lower Generally higher
Noise immunity Poor (susceptible to EMI) Good (digital transmission)
Resolution Depends on external ADC Fixed by sensor design

Choose Analog when:

  • Cost is critical and you have many identical sensors
  • You need custom signal conditioning (amplification, filtering)
  • Maximum flexibility in sampling rate and resolution is needed
  • Simple sensors like photoresistors, thermistors, or potentiometers suffice

Choose Digital when:

  • Noise immunity is critical (long wire runs, industrial environments)
  • Multiple sensors share a bus (I2C/SPI reduces wiring)
  • On-chip calibration and temperature compensation are valuable
  • Rapid prototyping and simpler code are priorities

Default recommendation: Digital sensors (like DHT22, BMP280) unless you need very low cost, custom filtering, or specific analog characteristics.

Human Senses vs Electronic Sensors:

Human Sense What It Detects Electronic Sensor IoT Example
Eyes Light, colors, motion Photoresistor, Camera Security camera detecting motion
Ears Sound, vibrations Microphone, Sound sensor Smart speaker listening for “Alexa”
Nose Chemicals, odors Gas sensor, Air quality CO detector monitoring carbon monoxide levels
Tongue Taste, chemicals pH sensor, Chemical Water quality monitor
Skin Temperature, pressure, touch Temperature sensor, Touch sensor Smart thermostat feeling room temp

8.4.2 Why Sensors are Critical for IoT

Without sensors, IoT devices are blind, deaf, and numb! Every smart device depends on sensors:

  • Smart thermostat: Temperature sensor tells it when to heat/cool
  • Fitness tracker: Accelerometer counts your steps, heart rate sensor monitors pulse
  • Smart parking: Magnetic sensor detects if car is present
  • Weather station: Temperature, humidity, pressure sensors collect climate data
  • Security system: Motion sensors detect intruders

8.4.3 The Sensor’s Job (4 Simple Steps)

Four-step sensor signal processing flow diagram showing physical phenomenon being measured by sensor, sensor converting to electrical signal, signal conditioning and amplification, and finally digital conversion via ADC for microcontroller processing

Four-step sensor signal processing flow

Example - Smart Thermostat:

  1. Physical: Room is 72 F (22.2 C)
  2. Sensing: Thermistor resistance changes based on temperature (e.g., 10 kOhm NTC reads ~11.4 kOhm at 22C because NTC resistance increases as temperature drops below 25C)
  3. Signal: Resistance converted to voltage via voltage divider (e.g., 1.54V with a 10 kOhm reference resistor and 3.3V supply)
  4. Processing: ESP32 reads voltage via ADC, calculates temperature using Steinhart-Hart equation, decides to turn on AC

8.4.4 Common Sensor Types You’ll Use (With Real Numbers)

Sensor Type What It Measures Common Models Specs Typical Cost
Temperature Heat in C or F DHT22, DS18B20, LM35 +/-0.5C accuracy1, -40 to 80C range (DHT22); DS18B20 +/-0.5C over -10 to +85C, +/-2C over full range $2-5
Humidity Moisture in air (%) DHT22, BME280 +/-2-3% RH, 0-100% range, slow response (~2s) $3-8
Light Brightness (lux) Photoresistor, BH1750 1-65535 lux range, BH1750 has 16-bit resolution $1-5
Motion Movement, presence PIR sensor, RCWL-0516 7m range (PIR), 110-120 degree detection angle $2-5
Distance Object distance (cm) HC-SR04 ultrasonic 2-400cm range, +/-3mm accuracy at 30cm (ideal: flat perpendicular surface, room temp) $2-4
Pressure Air/water pressure BMP280, MS5611 300-1100 hPa (altitude 9000m to -500m), +/-1 hPa $3-10
Gas Air quality, smoke MQ-2, MQ-135 10-10000 ppm detectable range, requires 48h burn-in $2-8

1 DHT22 accuracy varies by manufacturer; verify datasheet (typically +/-0.5C to +/-1C)

Scenario: You’re building a smart greenhouse that needs to:

  1. Monitor temperature (needs to detect 0.5C changes)
  2. Detect when someone enters (binary detection OK)
  3. Measure soil moisture (rough estimate OK)

Which sensors from the table above would you choose?

Click for recommended solution

Recommended sensors:

  1. Temperature: DHT22 or DS18B20 (+/-0.5C accuracy matches requirement)
  2. Motion detection: PIR sensor (binary output perfect for presence detection)
  3. Soil moisture: Analog soil moisture sensor (capacitive type recommended - resistive corrodes)

Why not BME280 for temperature? While BME280 is excellent, its +/-0.5C to +/-1C accuracy (depending on temperature range) might not reliably detect 0.5C changes. DS18B20 with +/-0.5C accuracy over its -10C to +85C range is a strong match.

Total cost: ~$10-15 for all three sensors

8.4.5 Key Terms You’ll See

Understanding these terms is critical for selecting the right sensor:

Sensor specification terminology diagram showing relationships between accuracy, precision, resolution, range, and response time with examples from DHT22 sensor

Sensor specification terminology
Term Definition Example Why It Matters
Accuracy How close the reading is to the true value Thermometer reads 25.0C when actual is 25.0C Determines if you can trust the measurement
Precision How repeatable measurements are Reads 25.0C, 25.1C, 25.1C, 25.0C consistently (tight cluster) High precision + calibration = good accuracy
Resolution Smallest change the sensor can detect DHT22: 0.1C (detects 25.0C vs 25.1C) Must be finer than required accuracy
Range Min to max measurable value DHT22: -40C to 80C Must cover all expected conditions
Response Time How quickly sensor reacts DHT22: ~2 seconds to update Critical for fast-changing phenomena

Question: A temperature sensor gives these readings when the actual temperature is 25.0C:

  • Reading 1: 27.3C
  • Reading 2: 27.2C
  • Reading 3: 27.4C
  • Reading 4: 27.3C

Is this sensor accurate? Is it precise?

Click for answer

Answer:

  • Accurate? NO - All readings are ~2.3C higher than the true value (25.0C)
  • Precise? YES - All readings cluster tightly together (within 0.2C of each other)

This is a classic example of a precise but inaccurate sensor. The sensor is consistent (precise) but consistently wrong (inaccurate).

Good news: This type of error can be fixed with calibration! You could apply a -2.3C offset to correct the systematic error and turn this precise sensor into an accurate one.

Takeaway: A precise sensor with calibration can be very useful. An imprecise sensor cannot be easily corrected.

8.4.6 Quick Self-Check

Q: Your smart garden needs to water plants only when soil is dry. The soil moisture sensor outputs 0-5V (0V = dry, 5V = wet). If the sensor reads 1.2V, what does this mean?

Click to see the answer

A: The soil is mostly dry (1.2V out of 5V = 24% moisture). The sensor’s analog voltage represents moisture level: - 0V = 0% moisture (completely dry) -> WATER NOW - 1.2V = 24% moisture (dry) -> SHOULD WATER - 2.5V = 50% moisture (moist) -> OK - 5V = 100% moisture (saturated) -> DON’T WATER

Your microcontroller would read this 1.2V through an ADC (Analog-to-Digital Converter) and trigger the watering system.

8.5 Sensor Classification Overview

Now that you understand what sensors are and how they work, the next step is learning how to categorize them. Understanding how sensors are classified helps you navigate the vast landscape of available sensors and select the right one for your application:

Hierarchical sensor classification framework showing four main categories: measurement type (physical, chemical, biological), output type (analog vs digital), power source (active vs passive), and detection method (contact vs non-contact). Each category branches into specific sensor examples and applications

Sensor classification framework

This classification framework helps you ask the right questions when selecting sensors:

  1. What physical phenomenon? -> Determines measurement type category
  2. How will it connect? -> Analog vs Digital output decision
  3. What power is available? -> Active vs Passive sensor choice
  4. Can you touch the object? -> Contact vs Non-contact method

Scenario: You need to measure the temperature of a rotating motor shaft that spins at 3000 RPM. The measurement must be accurate to within 1C, and the sensor will be 2 meters away from your microcontroller.

Based on the classification framework above, which categories would be most appropriate?

Click for answer

Answer:

  1. Measurement Type: Physical -> Temperature
  2. Output Type: Digital (I2C or SPI) - because 2m cable runs make analog signals susceptible to noise
  3. Power Source: Active - most accurate temperature sensors require power for on-chip calibration
  4. Detection Method: Non-contact - you cannot touch a shaft spinning at 3000 RPM!

Recommended sensors:

  • MLX90614 Infrared Thermometer (non-contact, digital I2C, +/-0.5C object temperature accuracy)
  • FLIR Lepton or industrial pyrometer (for higher accuracy non-contact measurement at distance)

Why not a thermocouple? While thermocouples are passive and can handle high temperatures, attaching one to a spinning shaft requires expensive slip rings or wireless transmitters.

Key insight: The “spinning” requirement immediately eliminates all contact sensors, dramatically narrowing your options to infrared or pyrometer solutions.

8.6 Chapter Overview: Sensor Fundamentals Series

This introduction is part of a comprehensive sensor fundamentals series. Continue your learning with:

  1. Biomimetic Sensing - Learn from nature’s perfect sensor: human skin
  2. Sensor Specifications - Understanding accuracy, response time, and range
  3. Signal Processing - Filtering, conditioning, and avoiding pitfalls
  4. Sensor Classification - Types by measurement, output, and power
  5. Calibration Techniques - How to calibrate sensors properly
  6. Reading Datasheets - Decode sensor specifications
  7. Common IoT Sensors - Popular sensors and MEMS technology
  8. Hands-On Labs - Interactive exercises with real sensors
  9. Selection Guide - Tools and techniques for choosing sensors
  10. Common Mistakes - Avoid the top 10 sensor pitfalls

8.7 Worked Example: Selecting a Temperature Sensor

Scenario: A pharmaceutical company needs to monitor vaccine storage temperatures. Requirements:

  • Temperature range: 2C to 8C (vaccine storage requirement)
  • Must detect 0.5C deviations from setpoint
  • Battery-powered loggers (low power critical)
  • 1000 units needed (cost matters)

Step-by-step sensor selection:

Step 1: Determine accuracy requirement

  • Need to detect 0.5C changes reliably
  • Sensor accuracy should be at least 2-3x better: +/-0.2C or better

Step 2: Check range requirement

  • Operating range: 2C to 8C
  • Should have margin: -10C to +20C would be safe

Step 3: Evaluate candidates

Sensor Accuracy Range Power Cost Verdict
DHT22 +/-0.5C -40 to 80C 2.5mA $5 Accuracy marginal
DS18B20 +/-0.5C (over -10 to +85C) -55 to 125C 1mA $3 Accuracy marginal
TMP117 +/-0.1C (over -20 to +50C) -55 to 150C 3.5uA $8 Excellent but costly
MCP9808 +/-0.25C -40 to 125C 200uA $4 Good balance

Step 4: Final selection

MCP9808 - Best balance of accuracy (+/-0.25C meets 0.5C detection), low power (200uA), and reasonable cost ($4 x 1000 = $4000 total).

Key insight: The cheapest sensor (DS18B20) would have been a $3000 savings but its +/-0.5C accuracy means some 0.5C deviations might be missed, potentially spoiling vaccines worth far more.

8.8 Worked Example: Smart Building Occupancy System

Scenario: A company with 50 conference rooms finds that rooms booked for meetings are actually empty 35% of the time (“ghost bookings”). They want sensors to detect actual occupancy and release unused rooms.

Step 1: Choose the sensing approach

Approach Sensor Pros Cons Cost/Room
PIR motion HC-SR501 Cheap, simple Misses stationary people USD 3
CO2 level SCD40 Counts approximate people 3-5 min response delay USD 25
mmWave radar LD2410 Detects stationary people Higher cost, requires tuning USD 8
Thermal array AMG8833 (8x8 pixels) Counts people, privacy-safe Moderate cost, limited range USD 35

Step 2: Accuracy analysis with real numbers

Testing PIR motion sensors in 10 conference rooms for 2 weeks:

Total meeting hours booked: 1,400 hours
Hours rooms actually occupied: 910 hours (65%)
Hours rooms empty (ghost bookings): 490 hours (35%)

PIR detection results:
  True positives (occupied, detected):    865 / 910  = 95.1%
  False negatives (occupied, not detected): 45 / 910  = 4.9%
    -> People sitting still for 15+ minutes without moving
  True negatives (empty, detected empty): 485 / 490  = 99.0%
  False positives (empty, false trigger):   5 / 490  = 1.0%
    -> HVAC airflow triggering sensor

A 4.9% false negative rate means the system would incorrectly release 45 hours of rooms while people are still meeting – unacceptable.

Step 3: Combined sensor solution

Using PIR + CO2 together eliminates both weaknesses:

PIR:  Fast detection (< 1 second), misses stationary people
CO2:  Detects breathing (stationary OK), slow response (3-5 min)

Combined logic:
  Room occupied = PIR triggered OR CO2 > 600 ppm
  Room empty = PIR silent for 5 min AND CO2 < 500 ppm

Combined results:
  True positives:  906 / 910 = 99.6%
  False negatives:   4 / 910 = 0.4% (borderline 1-person meetings)
  Cost per room: USD 3 (PIR) + USD 25 (SCD40) + USD 5 (ESP32) = USD 33
  Total 50 rooms: USD 1,650

Step 4: ROI calculation

Ghost booking cost (wasted room-hours):
  490 hours/2-week-period x 26 periods/year = 12,740 hours/year
  Average room hourly cost (HVAC, lighting): USD 8/hour
  Annual waste: 12,740 x USD 8 = USD 101,920

System recovery rate: 99.6% detection
  Recovered hours: 12,740 x 0.996 = 12,689 hours
  Annual savings: 12,689 x USD 8 = USD 101,512
  System cost: USD 1,650 + USD 500 (installation) = USD 2,150
  Payback period: USD 2,150 / USD 101,512 = 8 days

8.9 Worked Example: Sensor Calibration with MicroPython

Analog soil moisture sensors output a voltage proportional to moisture, but the raw ADC reading does not directly correspond to a percentage. Two-point calibration maps known conditions to readings.

# MicroPython for ESP32 - Soil Moisture Calibration
from machine import ADC, Pin
import time

# Setup ADC on GPIO34
soil_sensor = ADC(Pin(34))
soil_sensor.atten(ADC.ATTN_11DB)  # ~0-3.6V range (accurate up to ~3.1V)
soil_sensor.width(ADC.WIDTH_12BIT) # 0-4095

# Step 1: Calibration - record values for known conditions
# Dry air reading (sensor in open air): ~3200
# Wet reading (sensor in glass of water): ~1400
# These values are sensor-specific -- measure YOUR sensor

CAL_DRY = 3200   # ADC reading in dry air
CAL_WET = 1400   # ADC reading in water

def read_moisture_percent():
    """Read soil moisture as calibrated percentage (0-100%)."""
    # Average 10 readings to reduce noise
    readings = []
    for _ in range(10):
        readings.append(soil_sensor.read())
        time.sleep_ms(10)
    raw = sum(readings) // len(readings)

    # Map raw ADC to percentage (inverted: lower ADC = wetter)
    moisture = (CAL_DRY - raw) / (CAL_DRY - CAL_WET) * 100.0

    # Clamp to 0-100% range
    moisture = max(0.0, min(100.0, moisture))
    return moisture, raw

# Step 2: Continuous monitoring
while True:
    percent, raw_adc = read_moisture_percent()
    print(f"Moisture: {percent:.1f}%  (raw ADC: {raw_adc})")

    if percent < 30:
        print("  -> Soil is DRY, consider watering")
    elif percent < 60:
        print("  -> Soil moisture is GOOD")
    else:
        print("  -> Soil is WET, no watering needed")

    time.sleep(60)  # Read every 60 seconds

What to observe: The raw ADC value (0-4095) is meaningless without calibration. The two known reference points (dry air and water) create a linear mapping. In practice, add a third calibration point (field capacity soil) for better accuracy between extremes.

Common mistake: Forgetting to average multiple readings. A single ADC read on an ESP32 can vary by +-50 counts due to noise. Averaging N readings improves SNR by sqrt(N); for 10 readings, sqrt(10) = 3.16x improvement, yielding approximately 12 + log2(3.16) = 13.7-bit effective resolution.

8.10 Concept Relationships

Concept Related To Connection Type
Accuracy Calibration Poor accuracy requires frequent calibration to maintain
Resolution ADC Bit Depth 12-bit ADC gives 4096 steps regardless of sensor accuracy
Digital Sensors I2C Protocol Multiple sensors share 2-wire bus with unique addresses
Analog Sensors Signal Conditioning Require amplification and filtering before ADC
Passive Sensors Battery Life Draw minimal power enabling years of operation

8.11 Summary: Key Takeaways

Core sensor specification concepts showing accuracy, precision, resolution, range, and response time with DHT22 examples and practical guidelines

Core sensor specification concepts
Concept Key Point
What sensors do Convert physical phenomena to electrical signals microcontrollers can process
Accuracy vs Precision Accuracy = closeness to truth; Precision = repeatability. Both matter, but accuracy cannot be calibrated if precision is poor
Resolution trap Higher resolution does not mean higher accuracy - a 16-bit sensor can still be +/-3C off
Selection process Start with accuracy requirement, verify range, then consider cost/power/interface
Analog vs Digital Digital sensors (I2C/SPI) simpler to use; Analog sensors offer more flexibility but need ADC

8.12 Knowledge Check

Comprehensive Scenario: A startup is building a portable air quality monitor for hikers. Requirements:

  • Must measure CO2 levels (400-5000 ppm range needed)
  • Must detect changes of 50 ppm or better
  • Battery-powered (coin cell, 3V, 220mAh capacity)
  • Target battery life: 1 week with readings every 5 minutes
  • Budget: Under $30 per unit for sensors
  • Operating conditions: -10C to +40C, 20-80% humidity

Questions:

  1. What accuracy specification should you look for?
  2. What’s the minimum resolution needed?
  3. Calculate the maximum acceptable sensor power consumption
  4. Which sensor interface would you recommend?
Click for complete analysis

1. Accuracy Specification:

  • Need to detect 50 ppm changes over time (trending, not instantaneous)
  • For instantaneous detection the 2-3x rule would require +/-25 ppm, but no affordable NDIR sensor meets this
  • Practical approach: accept +/-(50 ppm + 5% of reading) and use time-averaged trending to detect 50 ppm shifts reliably (averaging N readings improves effective accuracy by sqrt(N))
  • At 400 ppm baseline: +/-(50 + 20) = +/-70 ppm per single reading, but averaging 10 readings over 50 minutes yields ~+/-22 ppm effective accuracy

2. Minimum Resolution:

  • Resolution should be <=1/3 of required accuracy
  • 8-10 ppm resolution minimum
  • Most digital CO2 sensors have 1 ppm resolution, so this is rarely a constraint

3. Power Budget Calculation:

Battery capacity: 220mAh at 3V
Target life: 7 days = 168 hours
Average current: 220mAh / 168h = 1.3mA average

Readings per day: 24h x 60min / 5min = 288 readings
If sensor takes 30 seconds per reading:
  Active time: 288 x 30s = 8,640s = 2.4 hours/day
  Sleep time: 24h - 2.4h = 21.6 hours/day

Power budget:
  If sleep current = 0.01mA (typical MCU sleep)
  Active current budget = (1.3mA x 24h - 0.01mA x 21.6h) / 2.4h
  Active current budget = ~13mA during measurement

Answer: Sensor should draw <13mA during measurement at 30s reading time, or <19.5mA if reading time can be reduced to 20s

Battery life determines maximum average current. For 220 mAh coin cell over 7 days:

\[I_{avg} = \frac{220 \text{ mAh}}{168 \text{ h}} = 1.31 \text{ mA}\]

With 288 readings/day (5 min intervals), 30 s per reading: \(t_{active} = 288 \times 30 = 8{,}640\) s/day = 2.4 h/day. Charge budget:

\[Q_{daily} = I_{active} \times 2.4\text{h} + I_{sleep} \times 21.6\text{h} = 1.31 \times 24 = 31.4 \text{ mAh/day}\]

With \(I_{sleep} = 0.01\) mA: \(I_{active} = \frac{31.4 - 0.01 \times 21.6}{2.4} = 12.98\) mA. The SCD40’s 17 mA exceeds this — solution: reduce reading time from 30 s to 20 s, cutting active budget to 1.6 h/day and allowing 19.5 mA peak current.

4. Recommended Interface:

  • I2C - Low pin count (2 wires), power efficient, good for battery devices
  • Not SPI (4+ wires, more complex)
  • Not analog (CO2 sensors are inherently digital due to NDIR technology)

Recommended Sensors: | Sensor | Accuracy | Power | Cost | Verdict | |——–|———-|——-|——|———| | SCD40 | +/-(50 ppm + 5% of reading) | 17mA active, 0.4uA sleep | $25 | Best choice - trending approach viable; fits power budget with 20s reading time (see analysis above) | | SCD30 | +/-(30 ppm + 3% of reading) | 19mA active | $35 | Over budget | | MH-Z19C | +/-(50 ppm + 5% of reading) | 18mA active | $20 | Good budget option |

Final Recommendation: Sensirion SCD40

  • I2C interface
  • 17mA active (exceeds 13mA base budget, but reducing reading time from 30s to 20s raises the allowable active current to 19.5mA – see power analysis above)
  • Ultra-low power sleep mode (0.4uA)
  • $25 meets budget
  • Temperature/humidity built-in (bonus!)

8.13 See Also

For the full sensor fundamentals series, see Chapter Overview above. Additional cross-module resources:

8.14 Practice Quizzes

Common Pitfalls

Accuracy and precision describe fundamentally different error types. A sensor consistently reading 3 C high is precise but inaccurate — calibration can fix this offset. A sensor reading randomly between -3 C and +3 C from the true value is imprecise — filtering reduces the effect but calibration cannot fix random noise.

Datasheets specify accuracy at 25 C unless stated otherwise. A sensor accurate to +-0.5 C at 25 C may only achieve +-2 C at -20 C or +80 C. Always check accuracy vs. temperature curves and confirm the sensor meets requirements across the full deployment temperature range.

Many sensors (barometric, gas, humidity) require a power-on stabilization period before their output is accurate. Reading a BME280 humidity sensor 100 ms after power-on gives incorrect results. Implement the manufacturer’s recommended warm-up delay in firmware startup sequences.

The most accurate available sensor may use an interface conflicting with the chosen microcontroller’s available peripherals. Confirm protocol, GPIO availability, and library support before finalizing sensor selection.

8.15 What’s Next

Now that you understand the basics of what sensors are and why they matter, continue your learning with the chapters below.

Next Step Chapter Why Read It
Learn from nature Biomimetic Sensing Discover how human skin inspires IoT sensor design
Deep dive into specs Sensor Specifications Master accuracy, precision, range, and response time
Get hands-on Hands-On Labs Build real sensor projects with ESP32 simulations
Understand signal flow Signal Processing Learn filtering, conditioning, and noise reduction
Classify all sensor types Sensor Classification Explore sensors by measurement type, output, and power

Continue to Biomimetic Sensing ->