3  Sensor Interfacing and Processing

Complete Guide to IoT Sensor Integration

sensing
protocols
data-processing
power-management
Author

IoT Textbook

Published

March 22, 2026

Keywords

sensor interfacing, I2C, SPI, calibration, filtering, power management, IoT sensors

3.1 Learning Objectives

  • Compare I2C, SPI, and UART communication protocols and select the appropriate interface for a given sensor integration scenario
  • Implement data processing techniques including moving average, Kalman, and median filters to improve sensor measurement quality
  • Design power management strategies using deep sleep modes and transmission buffering to extend battery life in IoT sensor nodes
  • Build end-to-end sensor integration pipelines from physical interfacing through calibration, filtering, and cloud connectivity
In 60 Seconds

Sensor interfacing covers the complete pipeline from physical sensor to useful IoT data: communication protocols (I2C for multi-sensor buses, SPI for high-speed data), data processing (moving average for noise, Kalman filter for tracking, median filter for outliers), power management (deep sleep for months-long battery life, transmission buffering for 3x battery extension), real-world applications (MQTT-connected smart homes, hysteresis-controlled actuators), and hands-on calibration labs. Master these five topics and you can build production-quality IoT sensor systems.

3.2 Introduction

This section covers the complete sensor integration pipeline for IoT systems, from physical communication protocols to data processing and real-world applications. The content is organized into five focused chapters that build progressively from fundamentals to advanced techniques.

Sensor interfacing is the art of connecting physical sensors to your microcontroller and making sense of the data they produce. Just like learning a new language, you need to understand how sensors “speak” (protocols like I2C and SPI), how to clean up their “accent” (filtering noise), and how to translate their words into useful information (calibration). This section teaches all these skills through practical examples.

3.2.1 1. Sensor Communication Protocols

Focus: I2C, SPI, and UART interfaces for connecting sensors to microcontrollers.

Topics Covered:

  • I2C two-wire bus protocol with 7-bit addressing
  • SPI four-wire full-duplex high-speed interface
  • Protocol selection decision tree
  • Common pitfalls: pull-up resistors, SPI mode configuration
  • Interactive I2C bus scanner demonstration

Estimated Time: 30 minutes


3.2.2 2. Sensor Data Processing

Focus: Filtering techniques and calibration procedures for accurate measurements.

Topics Covered:

  • Moving average filters for noise reduction
  • Kalman filters for optimal state estimation
  • Median filters for spike/outlier removal
  • Two-point calibration for offset and gain correction
  • Multi-point calibration for non-linear sensors
  • Worked example: Calibrating a soil moisture sensor

Estimated Time: 45 minutes


3.2.3 3. Sensor Networks and Power Management

Focus: Multi-sensor aggregation and battery optimization strategies.

Topics Covered:

  • Multi-sensor data aggregation with JSON payloads
  • Deep sleep modes for microamp-level consumption
  • Power budget calculations for battery life estimation
  • Transmission buffering for 3x+ battery life extension
  • Sensor fusion tradeoffs: complementary vs Kalman filters
  • Wake source configuration pitfalls

Estimated Time: 40 minutes


3.2.4 4. Sensor Applications (Sensor Applications module)

Focus: Real-world IoT implementation examples with complete code.

Topics Covered:

  • Smart home environmental monitoring with MQTT
  • Servo-controlled automated blinds
  • Temperature-controlled relay switching with hysteresis
  • Sensor selection guide for common applications
  • Practice exercises for hands-on learning

Estimated Time: 45 minutes


3.2.5 5. Sensor Calibration Lab

Focus: Hands-on Wokwi workshop for calibration techniques.

Topics Covered:

  • Interactive browser-based calibration lab
  • Two-point calibration procedure step-by-step
  • Moving average filter implementation
  • EEPROM storage for calibration persistence
  • Challenge exercises: three-point calibration, drift compensation

Estimated Time: 60 minutes (hands-on)


3.3 Learning Path

Flowchart showing recommended learning sequence: start with Communication Protocols, then Data Processing, Power Management, Applications, and finish with hands-on Calibration Lab
Figure 3.1: Recommended learning path through sensor interfacing topics

Recommended Order:

  1. Start with Communication Protocols to understand how sensors connect
  2. Move to Data Processing for filtering and calibration theory
  3. Study Power Management for battery-powered deployments
  4. Apply knowledge with Applications examples
  5. Solidify skills with the hands-on Calibration Lab

3.4 Key Concepts Summary

Concept Chapter Description
I2C Protocol Protocols Two-wire bus, 7-bit addressing, multi-device support
SPI Protocol Protocols Four-wire full-duplex, high-speed data transfer
Moving Average Processing Noise reduction through sample averaging
Kalman Filter Processing Optimal adaptive state estimation
Two-Point Calibration Processing Offset and gain correction
Deep Sleep Power Microamp-level power consumption
Transmission Buffering Power Batch transmissions for battery savings
Hysteresis Control Applications Prevent rapid switching in control systems

3.5 Prerequisites

Before starting this section, you should be familiar with:

  • Basic Arduino/C++ programming
  • Digital I/O and analog inputs
  • Serial communication concepts
  • Sensor Fundamentals chapter content

3.6 What You Will Build

By completing all chapters, you will have the skills to:

  • Interface any I2C or SPI sensor with an ESP32 or Arduino
  • Remove noise from sensor readings using appropriate filters
  • Calibrate sensors for production-quality accuracy
  • Design battery-powered sensor nodes lasting months to years
  • Build complete sensor-to-cloud IoT applications

3.7 Quick Reference

Common I2C Addresses:

Sensor Address Alternate
BMP280 0x76 0x77
BME280 0x76 0x77
MPU6050 0x68 0x69
BH1750 0x23 0x5C
SSD1306 0x3C 0x3D

Power Consumption Typical Values:

State ESP32 ESP8266
Active + Wi-Fi 150-200 mA 70-80 mA
Deep Sleep 10 µA 20 µA
Light Sleep 800 µA 1 mA

I2C Pull-up Resistor Sizing

I2C requires pull-up resistors on SDA and SCL. Too low wastes power, too high causes communication errors.

\[R_{min} = \frac{V_{DD} - V_{OL(max)}}{I_{OL}} = \frac{3.3V - 0.4V}{3mA} = 967\Omega\]

\[R_{max} = \frac{t_{rise}}{0.8473 \times C_{bus}} = \frac{300ns}{0.8473 \times 200pF} = 1770\Omega\]

For 400 kHz I2C with 200 pF bus capacitance: Use resistors within the calculated R_min to R_max range (typically 1kΩ to 1.8kΩ). For 100 kHz standard mode (t_rise = 1000 ns), the range widens and 4.7kΩ is commonly used.

Moving average filter noise reduction:

\[\sigma_{filtered} = \frac{\sigma_{raw}}{\sqrt{N}}\]

With 10-sample averaging on ±0.5°C sensor noise:

\[\sigma_{filtered} = \frac{0.5°C}{\sqrt{10}} = 0.158°C \text{ (3.16× noise reduction)}\]

Deep sleep power savings:

\[\text{Avg current} = \frac{I_{active} \times t_{active} + I_{sleep} \times t_{sleep}}{t_{total}}\]

Reading every 15 min (900 s), active for 5 s:

\[I_{avg} = \frac{150mA \times 5s + 0.01mA \times 895s}{900s} = 0.843 \text{ mA}\]

Battery life: \(2500 \text{ mAh} \div 0.843 \text{ mA} = 2966 \text{ hours} \approx 124 \text{ days}\) (vs 16.7 hours without sleep)

Sammy the Sensor was showing the squad how sensors talk to microcontrollers.

“There are different ways we communicate!” Sammy explained. “It’s like how people use phones, email, and walkie-talkies!”

Max the Microcontroller demonstrated: “I2C is like a classroom roll call. I have two wires – SDA for data and SCL for the clock. I call out each sensor’s address: ‘Sensor at address 0x76, what’s the temperature?’ And they answer one by one. I can talk to up to 112 sensors on just two wires!”

“SPI is different,” added Lila the LED. “It’s like having a separate phone line for each sensor. Faster, but needs more wires. Four wires shared, plus one extra for each sensor. Use it when speed matters!”

Bella the Battery raised the most important topic: “But all this talking uses MY energy! That’s why we use DEEP SLEEP. It’s like Max taking a nap between readings. When he’s asleep, he uses only 10 microamps – that’s 15,000 times less than when he’s awake and chatting on Wi-Fi!”

“And we make our readings more accurate with FILTERS!” Sammy added. “A moving average is like asking 10 friends for the temperature and taking the average – smoother than one reading. A median filter is like ignoring the friend who always exaggerates – you take the middle answer instead!”

Max put it all together: “So the whole process is: Connect the sensor (I2C or SPI), clean up the signal (filters), save battery (deep sleep), and send the data (Wi-Fi or LoRa). That’s sensor interfacing in a nutshell!”

“And that,” said Bella with a yawn, “is why I can last for months instead of hours. Now if you’ll excuse me, it’s time for deep sleep mode… zzzzz…”

Choosing the right filter depends on the characteristics of your noise and signal. This decision framework helps you select between moving average, median, Kalman, and exponential moving average (EMA) filters.

Noise Characteristic Recommended Filter Window/Parameter Why This Filter?
Gaussian (random, zero-mean) Moving Average N=10-50 samples Averages out random variations, noise reduced by √N
Occasional spikes/outliers Median N=5-11 (odd) Ignores extreme values, takes middle value
Smoothly varying signal Kalman Process/measurement noise tuned Optimal state estimation, adapts to signal dynamics
Need fast response EMA (α=0.2-0.5) Alpha = 0.2-0.5 Recent samples weighted more, lower lag than MA
Periodic noise (50/60 Hz) Notch filter or sample at integer multiple Depends on frequency Cancels specific frequency
Combination: random + spikes Median → Moving Average Median N=5, MA N=10 Median removes spikes first, then MA smooths random noise

Quick Selection Decision Tree:

START: You have noisy sensor data
  |
  ├─ Do you see occasional extreme spikes (outliers)?
  │   ├─ YES → How frequent?
  │   │   ├─ <10% of readings → **MEDIAN FILTER** (N=5 to 11)
  │   │   └─ >10% of readings → Your sensor may be faulty, check wiring
  │   └─ NO → Continue to next question
  |
  ├─ Is your signal constantly changing (motion, tracking)?
  │   ├─ YES → Do you know the signal dynamics (velocity, acceleration)?
  │   │   ├─ YES → **KALMAN FILTER** (optimal tracking)
  │   │   └─ NO → **EMA** with α=0.2 (good general-purpose tracking)
  │   └─ NO → Signal is slow-changing or static
  |
  ├─ How fast does your signal change?
  │   ├─ Very slow (>10 seconds per significant change)
  │   │   └─ **MOVING AVERAGE** with large window (N=50-100)
  │   ├─ Moderate (1-10 seconds per change)
  │   │   └─ **MOVING AVERAGE** with medium window (N=10-20)
  │   └─ Fast (<1 second per change)
  │       └─ **EMA** with α=0.3 or **MOVING AVERAGE** with small window (N=5)
  |
  └─ Do you have periodic noise (50/60 Hz power line hum)?
      ├─ YES → Can you sample at integer multiple of noise frequency?
      │   ├─ YES → Sample at 50Hz/60Hz and average N readings per cycle
      │   └─ NO → Use notch filter (requires signal processing library)
      └─ NO → Use filter from above based on signal dynamics

Example Scenarios with Specific Choices:

1. Temperature Sensor in HVAC System

  • Signal: Slow-changing (room temp changes over minutes)
  • Noise: Random, Gaussian, ±0.2°C
  • Choice: Moving Average, N=30
  • Reasoning: Temperature is slow, large window smooths noise without lag
  • Code:
float movingAvg(float newValue) {
    static float buffer[30] = {0};
    static int idx = 0;
    static int count = 0;  // Track how many samples collected
    buffer[idx] = newValue;
    idx = (idx + 1) % 30;
    if (count < 30) count++;  // Increment until buffer is full
    float sum = 0;
    for (int i = 0; i < count; i++) sum += buffer[i];
    return sum / (float)count;  // Divide by actual sample count
}

2. Accelerometer for Step Counter

  • Signal: Fast-changing (steps = sudden accelerations)
  • Noise: Random vibrations, occasional spikes from bumps
  • Choice: Median filter (N=5) → EMA (α=0.2)
  • Reasoning: Median removes bump spikes, EMA tracks steps without excessive lag
  • Code:
float medianFilter(float newValue) {
    static float buffer[5] = {0};
    static int idx = 0;
    static int count = 0;  // Track how many samples collected
    buffer[idx] = newValue;
    idx = (idx + 1) % 5;
    if (count < 5) count++;  // Increment until buffer is full
    float sorted[5];
    memcpy(sorted, buffer, count * sizeof(float));
    // Simple bubble sort for small array
    for (int i = 0; i < count - 1; i++)
        for (int j = 0; j < count - 1 - i; j++)
            if (sorted[j] > sorted[j+1]) {
                float temp = sorted[j];
                sorted[j] = sorted[j+1];
                sorted[j+1] = temp;
            }
    return sorted[count / 2]; // Middle value of filled portion
}

float emaFilter(float newValue) {
    static float ema = 0;
    static bool initialized = false;
    if (!initialized) { ema = newValue; initialized = true; }
    ema = 0.2 * newValue + 0.8 * ema;
    return ema;
}

// Usage
float rawAccel = readAccelerometer();
float median = medianFilter(rawAccel);
float smoothed = emaFilter(median);

3. Soil Moisture for Irrigation

  • Signal: Very slow (hours to change significantly)
  • Noise: Random + occasional false readings from air pockets
  • Choice: Median (N=7) → Moving Average (N=60)
  • Reasoning: Median rejects air pocket outliers, large MA window smooths random noise
  • Result: One filtered reading per minute, stable over 1-hour window

4. Distance Sensor (Ultrasonic) for Robot Navigation

  • Signal: Moderate speed (robot moving 0.5 m/s)
  • Noise: Occasional bad echoes (returns 0 or max range)
  • Choice: Median (N=5) → EMA (α=0.3)
  • Reasoning: Median removes bad echoes, EMA provides fast response for collision avoidance
  • Tradeoff: Some lag acceptable, safety requires spike removal

Filter Performance Comparison Table:

Filter Type Latency Spike Rejection Random Noise Reduction Computational Cost
Moving Avg N/2 samples Poor Excellent (√N) Low (sum/divide)
Median (N-1)/2 samples Excellent Poor Medium (sorting)
EMA ~1/α samples Poor Good Very Low (multiply/add)
Kalman 0-2 samples Good Excellent High (matrix ops)

Key Parameters:

Moving Average Window Size (N):

  • N=5: Fast response, 2.2× noise reduction
  • N=10: Balanced, 3.2× noise reduction
  • N=50: Slow response, 7× noise reduction
  • N=100: Very smooth, 10× noise reduction

EMA Alpha (α) (equivalent MA window: N = 2/α − 1): - α=0.1: Very smooth, slow response (equivalent to MA with N≈19) - α=0.2: Balanced for tracking (equivalent to MA with N≈9) - α=0.5: Fast response, minimal smoothing (equivalent to MA with N≈3)

Rule of Thumb: Start with Moving Average N=10 for slow sensors, Median N=5 followed by EMA α=0.2 for fast sensors. Tune based on observed performance.

3.8 Summary

  • Communication Protocols: I2C uses two shared wires (SDA, SCL) with unique addresses for multi-sensor buses, while SPI provides higher-speed full-duplex transfer at the cost of additional wiring per device
  • Digital Filtering Techniques: Moving average smooths random noise, median filters reject outlier spikes, and Kalman filters provide optimal state estimation for tracking applications – filter choice depends on the noise characteristics
  • Power Management: Deep sleep modes reduce microcontroller consumption to microamps, and transmission buffering extends battery life by 3x or more by batching data before wireless sends
  • Calibration for Accuracy: Two-point calibration corrects offset and gain errors, while multi-point calibration handles non-linear sensors – calibration data should be stored persistently in EEPROM
  • End-to-End Pipeline: Production-quality IoT sensor systems follow five stages – connect (choose protocol), condition (amplify and filter), process (calibrate and digitally filter), manage power (duty cycle), and communicate (MQTT, HTTP, LoRaWAN)

Sensing Deep Dives:

Data Processing:

Architecture:

Learning Hubs:

3.9 Knowledge Check

3.10 What’s Next

Topic Chapter Description
Communication Protocols Sensor Communication Protocols Dive into I2C, SPI, and UART interfaces for connecting sensors to microcontrollers
Data Processing Sensor Data Processing Apply filtering techniques and calibration procedures for accurate sensor measurements
Power Management Sensor Networks and Power Management Design deep sleep strategies and transmission buffering for battery-powered sensor nodes
Sensor Applications Sensor Applications Implement real-world IoT systems with MQTT, servo control, and hysteresis logic
Hands-On Lab Sensor Calibration Lab Practice two-point calibration, filtering, and EEPROM storage in a Wokwi simulation
Sensor Fundamentals Sensor Fundamentals and Types Review core sensor types, characteristics, and selection criteria