12  Sensor Application Labs

Hands-On Exercises and Knowledge Checks

12.1 Learning Objectives

By the end of this chapter, you will be able to:

  • Design Sensor Deployments: Plan complete IoT sensor systems for real-world scenarios
  • Calculate Total Cost of Ownership: Budget hardware, installation, maintenance, and operational costs
  • Optimize Multi-Sensor Systems: Balance coverage, redundancy, and cost constraints
  • Estimate Data Requirements: Calculate storage, bandwidth, and cloud costs
  • Integrate Cross-Domain Sensors: Combine sensors from multiple domains for comprehensive solutions
In 60 Seconds

These hands-on labs build complete end-to-end sensor applications: wiring sensors to ESP32, writing firmware to collect and transmit data via MQTT, ingesting into a time-series database, and visualizing on a live dashboard. Labs progress from single-sensor data logging to multi-sensor monitoring systems with anomaly detection and alerting. Each lab produces a working deployable application, not just a breadboard prototype.

Key Concepts
  • End-to-End Lab Architecture: ESP32 sensor node → Wi-Fi → MQTT broker → Node-RED or Python subscriber → InfluxDB → Grafana dashboard; each component can be run locally or replaced with cloud equivalents for production deployment
  • MQTT Topic Hierarchy Design: Organizing sensor topics as home/room/sensor_type (e.g., factory/line1/vibration) enables subscribing to subsets (factory/#) or specific sensors (factory/line1/temperature); plan the hierarchy before deployment — changing it requires updating all publishers and subscribers
  • InfluxDB Line Protocol: The native InfluxDB data format: measurement,tag_key=tag_value field_key=field_value timestamp; tags are indexed strings (device_id, location), fields are the measured values; correct tag/field classification is critical for query performance
  • Grafana Panel Types: Time series (trends over time), gauge (current value vs. range), stat (single metric highlight), table (multi-sensor comparison), and alert list (triggered thresholds); choose panel types based on whether the audience needs trend, current state, or comparative information
  • ESP32 Wi-Fi Reconnection Logic: Production firmware must handle Wi-Fi disconnection and automatic reconnection without requiring a device reset; use the WiFi.onEvent() callback to detect disconnection and trigger reconnection, with exponential backoff to avoid overwhelming the access point
  • QoS Levels in MQTT: QoS 0 (at most once, no acknowledgment), QoS 1 (at least once, acknowledged), QoS 2 (exactly once, two-phase acknowledge); use QoS 1 for sensor data to ensure delivery despite brief connectivity interruptions, at the cost of potential duplicate delivery
  • Dashboard Alert Rules: Grafana and similar tools support alert rules: evaluate a query over a time window, trigger if a threshold is exceeded for a minimum duration; minimum duration prevents false alerts from brief spikes; notification channels include email, Slack, PagerDuty
  • Lab Verification Protocol: Each lab module should be verified at each stage: verify sensor wiring (multimeter/serial), verify MQTT publishing (MQTT Explorer), verify database ingestion (InfluxDB query), verify dashboard display (Grafana); verify each layer before proceeding to the next

12.2 MVU: Minimum Viable Understanding

Core concept: Successful IoT deployments require systematic planning across technical, operational, and financial dimensions. Why it matters: Projects fail not from sensor selection, but from underestimating installation costs, maintenance burden, and operational complexity. Key takeaway: Always prototype with 5-10% of planned sensors, validate assumptions, then scale.

These labs let you practice planning real IoT projects from start to finish – like designing a sensor network for a smart city or a factory. You will learn to estimate costs, calculate how many sensors you need, and figure out how to power them. Think of it as a simulation game where you plan an IoT deployment on paper before spending any money on real hardware.

In This Series:

Hands-On Resources:

12.3 Hands-On Labs

Time: ~30 min | Advanced | P06.C03.U17

12.3.1 Lab 1: Sensor Application Selection for Smart City

Objective: Select and plan sensor deployments for a smart city initiative.

Scenario: You are tasked with implementing IoT solutions for a mid-sized city (population 200,000, area 50 km2) with a $2 million budget over 5 years.

City Priorities:

  1. Reduce traffic congestion
  2. Improve air quality monitoring
  3. Optimize waste collection
  4. Enhance public safety

Tasks:

  1. Identify Applications: From the overview catalog, select 4 applications (one per priority)

  2. Calculate Deployment Costs: For each application, determine:

    • Number of sensors needed for adequate coverage
    • Total cost over 5 years
    • Cost per citizen per year
  3. Budget Allocation: Distribute the $2M budget across the 4 applications considering:

    • Impact on citizens
    • Coverage requirements
    • Operating costs
  4. Network Requirements: Calculate data requirements:

    • Total daily data generated
    • Monthly cloud storage costs (assume $0.02/GB)
    • Network bandwidth needs
  5. ROI Analysis: Estimate benefits:

    • Traffic: Reduced congestion ($X saved in productivity)
    • Air Quality: Health improvements
    • Waste: Collection efficiency gains
    • Safety: Incident response time reduction

Deliverables:

  • Sensor deployment plan with coverage maps
  • 5-year cost breakdown
  • Network architecture diagram
  • ROI justification

12.3.2 Lab 2: Multi-Sensor Deployment Optimization

Objective: Optimize sensor deployment under multiple constraints.

Scenario: Deploy environmental monitoring for a 10 km2 industrial park.

Requirements:

  • Monitor: Air quality (CO, CO2, NOx), Temperature, Humidity
  • Coverage: Complete park coverage
  • Budget: $150,000 (5 years)
  • Power: Solar-powered sensors (20 mW average)

Tasks:

  1. Sensor Selection: Choose appropriate sensors for each parameter

  2. Coverage Analysis: Calculate:

    • Effective range of each sensor type
    • Minimum sensors for complete coverage
    • Overlap factor for redundancy
  3. Cost Optimization:

    • Find maximum sensors within budget
    • Calculate coverage vs. cost trade-offs
    • Identify optimal sensor placement
  4. Power Budget: For solar deployment:

    • Calculate daily energy consumption
    • Size solar panels (assume 4 hours effective sunlight)
    • Determine battery capacity for 3-day autonomy
  1. Data Management: Estimate:
    • Sampling rates for each sensor
    • Total data generated daily
    • Storage requirements for 1-year retention
    • Network connectivity options (cellular vs. LoRaWAN)

Deliverables:

  • Optimized deployment plan
  • Coverage heat map
  • Power system design
  • Data management architecture

12.3.3 Lab 3: Sensor Data Rate Planning

Objective: Design network infrastructure for high-data-rate sensor applications.

Scenario: Industrial vibration monitoring system for a manufacturing plant with 100 machines.

Requirements:

  • Vibration sampling: 1000 Hz per machine
  • Temperature monitoring: 1 Hz per machine
  • Real-time anomaly detection
  • Historical data for 90 days

Tasks:

  1. Data Rate Calculation: For each sensor type:
    • Bytes per sample
    • Samples per second
    • Total data rate (Mbps)
  1. Network Design: Determine:
    • Can Wi-Fi handle the load?
    • Need for edge processing?
    • Data aggregation strategy
  2. Storage Sizing: Calculate:
    • Raw data storage (90 days)
    • Compressed storage (assume 3:1 compression)
    • Database sizing recommendations
  3. Edge Processing: Design edge analytics:
    • FFT analysis at edge (reduce data by 100x)
    • Alert generation rules
    • Cloud upload strategy (alerts vs. raw data)
  4. Cost Analysis: Compare:
    • Option A: Send all data to cloud
    • Option B: Edge processing + alert-only cloud
    • Calculate cloud costs, network costs, edge hardware

Deliverables:

  • Network architecture diagram
  • Data flow design
  • Storage sizing spreadsheet
  • Cost comparison matrix

12.3.4 Lab 4: Cross-Domain Sensor Integration

Objective: Integrate sensors across multiple domains for smart building management.

Scenario: Design IoT system for a 20-floor commercial building.

Requirements:

  • Energy management (Smart Metering)
  • Security (Access control, intrusion detection)
  • Environmental quality (HVAC optimization)
  • Occupancy tracking (Space utilization)

Tasks:

  1. Sensor Inventory: List all required sensors:
    • Energy: Current/voltage, power meters
    • Security: PIR, door sensors, cameras
    • Environment: Temp, humidity, CO2
    • Occupancy: PIR, desk sensors, Wi-Fi tracking
  2. Integration Architecture: Design:
    • Sensor bus topology (I2C, SPI, or wireless)
    • Edge gateways per floor
    • Central management system
    • Cloud integration
  3. Data Fusion: Create multi-sensor analytics:
    • Correlate occupancy with HVAC
    • Link access control with space usage
    • Combine for energy optimization
  4. Implementation Plan: Create:
    • Phased rollout schedule
    • Testing and validation plan
    • Maintenance procedures
    • Operator training requirements
  5. Business Case: Calculate:
    • Total system cost
    • Energy savings (estimated 20% reduction)
    • Security improvements
    • ROI timeline

Deliverables:

  • Complete sensor specification
  • System integration diagram
  • Implementation timeline
  • Business case presentation

When planning a sensor deployment, network connectivity is often the most expensive ongoing cost. Use this framework to select the optimal technology based on your requirements:

Criterion Wi-Fi (2.4 GHz) LoRaWAN Cellular (NB-IoT/LTE-M)
Range 50-100m indoor 2-15km urban/rural Nationwide (carrier coverage)
Data Rate 1-600 Mbps 0.3-50 kbps 200 kbps (NB-IoT), 1 Mbps (LTE-M)
Power (per transmission) 240-360mA 20-120mA 100-300mA
Battery Life (2xAA, 15min intervals) 20-40 days 3-7 years 6-18 months
Cost per Device $3-8 (module) $10-25 (module) $15-40 (module)
Monthly Fees $0 (self-hosted) $1-3/device (public network) $2-10/device (carrier)
Latency <10ms 1-5 seconds 1-10 seconds
Infrastructure Requires local AP/router Gateway needed (1 per 2-10km²) Uses carrier towers (no setup)

Decision Tree:

  1. Is mains power available? → YES: Wi-Fi is viable. NO: Continue to step 2.
  2. Is data transmission time-critical (<100ms latency)? → YES: Wi-Fi or cellular only. NO: Continue to step 3.
  3. Are sensors spread over >500m with no existing network? → YES: LoRaWAN or cellular. NO: Wi-Fi may work if you add access points.
  4. Do you control the deployment site (farm, factory, campus)? → YES: LoRaWAN (no monthly fees after gateway). NO: Cellular (no infrastructure needed).
  5. Is battery replacement acceptable every 6-18 months? → YES: Cellular works. NO: LoRaWAN required for multi-year battery life.

Example 1: Smart Agriculture (500-acre farm, 200 soil sensors)

  • Range: Sensors spread 1-3km apart → Wi-Fi ruled out
  • Power: Solar not practical for all locations → Battery-powered, need 5+ years
  • Site Control: Own the land → Can install LoRaWAN gateways
  • Choice: LoRaWAN with 8 gateways ($200 each). Cost: $1,600 infrastructure + $0 monthly vs $400-2,000/month for cellular

Example 2: Fleet Vehicle Tracking (50 delivery trucks, national coverage)

  • Range: Vehicles move across state/country → LoRaWAN ruled out (limited to gateway range)
  • Power: Vehicles have 12V power → Power not a constraint
  • Infrastructure: Cannot install gateways along routes → Need carrier network
  • Choice: Cellular (LTE-M) for mobility and nationwide coverage. Cost: $250-500/month for 50 devices

Example 3: Office Building HVAC (30 zones, temperature monitoring)

  • Range: All within 100m of router → Wi-Fi sufficient
  • Power: Mains power in ceiling → No battery concern
  • Latency: HVAC adjustments need <30s response → Wi-Fi provides instant response
  • Choice: Wi-Fi with existing office network. Cost: $0 monthly, $90-240 hardware (30 × $3-8/device)

Cost Breakeven Analysis (5-year total cost for 100 devices):

  • Wi-Fi: $500 hardware + $0 monthly = $500 total
  • LoRaWAN: $2,000 hardware + $15,000 monthly fees (if using public network at $2.50/device/month) = $17,000 total
  • Cellular: $2,500 hardware + $30,000 monthly fees ($5/device/month average) = $32,500 total

Total Cost of Ownership: Connectivity Comparison

For 100 sensors over 5 years (60 months):

LoRaWAN private network:

  • Gateway hardware: 5 gateways × $200 = $1,000
  • Sensor modules: 100 × $15 = $1,500
  • Installation: 100 × $20 = $2,000
  • Monthly: $0 (self-hosted)
  • Total: $4,500 ($0.75/sensor/month)

Cellular NB-IoT:

  • Sensor modules: 100 × $25 = $2,500
  • SIM cards: 100 × $5 = $500
  • Installation: 100 × $20 = $2,000
  • Monthly: 100 × $3 × 60 = $18,000
  • Total: $23,000 ($3.83/sensor/month)

Breakeven calculation: LoRaWAN pays back gateway cost after: \[\frac{\$1,000}{100 \times (\$3-\$0)/\text{month}} = \frac{1000}{300} = 3.3\text{ months}\]

This math shows LoRaWAN wins economically for fixed deployments beyond 4 months, while cellular suits mobile/dispersed scenarios where gateway infrastructure is impractical.

Key Insight: For fixed deployments you control (agriculture, campus, factory), LoRaWAN’s upfront gateway cost is recovered within 6-12 months compared to cellular’s monthly fees. For mobile or geographically dispersed deployments (fleet tracking, vending machines), cellular’s “no infrastructure” advantage outweighs higher ongoing costs.

12.4 Common Pitfalls

Pitfall: Over-Deploying Sensors Without Strategic Planning

The mistake: Deploying maximum sensor density assuming “more data is better,” then discovering network congestion, maintenance nightmares, and redundant data that increases costs without improving insights.

Why it happens: It feels safer to over-instrument. Proposals emphasizing “comprehensive coverage” win approval easier than “optimized sparse deployment.” Teams underestimate ongoing maintenance costs ($15-30/sensor/year) and network capacity requirements.

The fix: Start with minimum viable deployment based on spatial correlation analysis. For air quality, pollution diffuses over 1-2 km, so 1 sensor/km2 often suffices. For parking, you need 1:1 coverage. Pilot with 10-20% of planned sensors, analyze data to identify redundancy, then expand strategically. Total cost of ownership includes hardware, installation, connectivity, maintenance, and data storage.

Pitfall: Choosing Sensors Based on Lab Specs for Field Deployment

The mistake: Selecting sensors based on datasheet specifications measured under ideal lab conditions (25C, 50% humidity, no interference), then experiencing failures or drift in real-world conditions.

Why it happens: Datasheets present best-case performance. Outdoor deployments face temperature extremes (-20 to +50C), condensation, dust ingress, vibration, and electromagnetic interference. Indoor industrial environments add chemical exposure and mechanical stress.

The fix: Always check operating ranges, not just accuracy specs. For outdoor deployment, require IP65+ ratings and -40 to +85C operating range. Request field performance data or case studies from vendors. Budget for environmental protection (enclosures, sun shields, desiccants) and plan for more frequent calibration than lab-based intervals suggest.

Pitfall: Ignoring Power Budget for Battery-Powered Deployments

The mistake: Designing a sensor node that works perfectly when plugged in, then discovering batteries last weeks instead of years when deployed remotely.

Why it happens: Developers test with USB power and only consider power after the design is complete. Transmission power (Wi-Fi: 100-200mA, LoRa: 20-40mA) often dominates the budget, but sensor warm-up power and microcontroller sleep current are overlooked. Duty cycle calculations use best-case numbers.

The fix: Calculate power budget before selecting hardware. Use the formula: Battery life = Battery capacity / Average current. For 5-year life on 2xAA batteries (3000mAh), average current must be under 70 microamps. Choose LoRa/BLE over Wi-Fi, implement deep sleep (1-10 microamps), minimize transmission frequency, and use sensors with fast wake-up times. Always prototype and measure actual consumption.

12.5 Knowledge Check

Test your knowledge of sensor applications across IoT domains with these questions.

Question 1: Which sensor type is most commonly used across IoT applications?

Answer: B) Temperature

Temperature sensors are used in approximately 15 different application types across smart cities, smart environment, smart water, smart industrial, smart agriculture, smart animal farming, and smart health domains. They’re versatile, low-cost ($2-10), and essential for environmental monitoring, HVAC control, equipment monitoring, and health applications.

Question 2: For smart parking applications, what is the primary sensor used?

    1. Ultrasound
    1. Camera
    1. Magnetic field
    1. Pressure

Answer: C) Magnetic field

Magnetic field sensors detect the presence of large metal objects (vehicles) by measuring disruptions in the Earth’s magnetic field. They’re buried in or mounted under parking spaces, are weather-resistant, low-power, and cost-effective for large-scale deployments. While cameras and ultrasound can work, magnetic sensors are the industry standard due to their reliability and low maintenance.

Question 3: Which application domain typically has the highest sensor data rates?

    1. Smart Agriculture
    1. Smart Health (vital signs)
    1. Smart Parking
    1. Smart Retail

Answer: B) Smart Health (vital signs)

Smart Health vital signs monitoring (ECG, pulse, respiration) requires 100+ Hz sampling rates for accurate waveform capture and medical diagnosis. ECG typically samples at 250-500 Hz. In contrast, smart agriculture might sample every few minutes, smart parking every 10 seconds, and retail inventory on-demand.

Question 4: What is the primary cost component for water quality sensors?

    1. Installation
    1. Energy consumption
    1. Hardware (sensor cost)
    1. Maintenance

Answer: C) Hardware (sensor cost)

Water quality sensors (pH, Dissolved Oxygen, conductivity, nitrates) are expensive, typically $250+ per unit compared to $5-10 for temperature sensors. They require specialized electrodes, calibration, and periodic replacement. This makes deployment planning critical to balance coverage with budget constraints.

Question 5: For a city-wide air quality monitoring network with 1000 sensors sampling at 0.1 Hz and 50 bytes per sample, what is the approximate daily data volume?

    1. ~50 MB
    1. ~250 MB
    1. ~430 MB
    1. ~860 MB

Answer: C) ~430 MB

Calculation: Daily data = 1000 sensors × 0.1 samples/s × 50 bytes/sample × 86,400 seconds/day = 1000 × 0.1 × 50 × 86,400 = 432,000,000 bytes = 432 MB

With protocol overhead (headers, metadata, retransmissions), expect ~430-500 MB/day.

This calculation is essential for network bandwidth planning, cloud storage costs estimation, and edge processing decisions in large-scale IoT deployments.

Question 6: Which sensor application typically requires GPS?

    1. Smart lighting
    1. Fleet tracking
    1. Waste management
    1. Indoor air quality

Answer: B) Fleet tracking

Fleet tracking requires GPS to monitor vehicle locations in real-time for route optimization, delivery tracking, and driver behavior analysis. Smart lighting uses light sensors (LDR), waste management uses ultrasound distance sensors, and indoor air quality uses gas sensors (CO, CO2, VOCs). GPS provides outdoor location accuracy of 5-10 meters.

Question 7: What is the main advantage of edge processing in sensor networks?

    1. Lower hardware costs
    1. Reduced network bandwidth requirements
    1. Simpler software
    1. Better sensor accuracy

Answer: B) Reduced network bandwidth requirements

Edge processing analyzes data locally at or near the sensor, sending only aggregated results, alerts, or compressed data to the cloud. For example, vibration monitoring at 1 kHz generates massive raw data, but FFT analysis at the edge can reduce transmission by 100x, sending only frequency peaks and anomaly alerts. This dramatically reduces network bandwidth costs, cloud storage costs, and enables real-time responses.

Question 8: For industrial vibration monitoring at 1000 Hz sampling rate, which network technology is most suitable?

    1. LoRaWAN
    1. NB-IoT
    1. Wi-Fi or Ethernet
    1. Bluetooth LE

Answer: C) Wi-Fi or Ethernet

High-frequency vibration monitoring at 1000 Hz with 4 bytes per sample generates 4 KB/s per sensor (240 KB/min). Wi-Fi (54+ Mbps) or Ethernet (100+ Mbps) can handle this data rate with multiple sensors. LoRaWAN is limited to ~50 kbps with 1% duty cycle, NB-IoT to ~100 kbps, and BLE to ~1 Mbps. For industrial monitoring, wired Ethernet provides the most reliable high-bandwidth solution.

Question 9: In multi-sensor deployments, what does “sensor coverage” typically refer to?

    1. The physical size of the sensor
    1. The geographic area each sensor can monitor effectively
    1. The number of sensor types deployed
    1. The data transmission range

Answer: B) The geographic area each sensor can monitor effectively

Sensor coverage defines the geographic area or volume that one sensor can effectively monitor, determining how many sensors are needed for complete area coverage. For example, a temperature sensor might cover 100 m2 indoors, a gas sensor 50 m2 (due to diffusion), and a camera 500 m2 (depending on resolution and mounting height). Coverage planning ensures no blind spots while minimizing deployment costs.

Question 10: For a $500,000 budget over 5 years, approximately how many gas sensors can be deployed? (Assuming $45 hardware + $50 installation + $15/year maintenance each)

    1. ~2,500 sensors
    1. ~5,000 sensors
    1. ~7,500 sensors
    1. ~10,000 sensors

Answer: A) ~2,500 sensors

Calculation: Total cost per sensor = Hardware ($45) + Installation ($50) + Maintenance ($15 × 5 years) = $45 + $50 + $75 = $170 per sensor over 5 years.

Maximum sensors = $500,000 / $170 = 2,941 sensors.

Answer A (~2,500) is the closest practical estimate accounting for additional costs like gateways, network infrastructure, and contingency. This calculation is fundamental for IoT project budgeting and ROI analysis.

12.6 Summary

This series on sensor applications covered:

  • Smart Cities: Air quality monitoring, traffic management, waste management, and street lighting optimization reduce costs and improve quality of life
  • Industrial IoT: Predictive maintenance, vibration monitoring, and asset tracking prevent downtime and optimize operations
  • Agriculture: Soil moisture sensing, weather monitoring, and livestock tracking increase yields while reducing water and resource usage
  • Healthcare: Remote patient monitoring, fall detection, and medication adherence improve patient outcomes and reduce hospital readmissions
  • Environmental Sensing: Climate monitoring, water quality tracking, and wildlife observation support conservation and research
  • Deployment Strategies: Sensor placement, network topology, and power management determine system reliability and longevity
  • Cost Analysis: Total cost of ownership includes hardware, installation, maintenance, connectivity, and data storage over the system lifetime

Fundamentals:

Processing:

Output:

  • Actuators - Converting sensor data to action

Architecture:

Data:

Learning:

Sammy the Sensor was working on the biggest lab exercise yet – planning sensors for an entire city!

“Okay team,” Sammy announced, “we have a $2 million budget to make our city smarter. Where do we start?”

Max the Microcontroller pulled up the city map. “First, let’s figure out what problems to solve. Traffic jams waste everyone’s time. Air pollution makes people sick. Garbage trucks drive to bins that are already empty!”

“I know!” said Lila the LED, lighting up. “We put magnetic sensors in parking spaces so people can find spots on their phone. Ultrasonic sensors in trash bins tell trucks which bins are full. And air quality sensors tell people when pollution is bad!”

Bella the Battery did some math: “Hmm, each sensor costs about $50-150, plus we need gateways and cloud storage. That’s $170 per sensor over 5 years when you count installation and maintenance. With $2 million, we can afford about 11,000 sensors!”

“But we don’t NEED 11,000!” Max said wisely. “Remember – more sensors isn’t always better. One air quality sensor covers a whole square kilometer because pollution spreads through the air. But parking needs one sensor per space because each car is different.”

Sammy nodded. “So the lesson is: plan smart, not big. Start with a small test of 100 sensors, see what works, then grow from there!”

“And always remember the TOTAL cost,” Bella added. “The sensor is just the beginning – you also pay for installation, batteries, internet connection, and fixing things when they break!”

“Now THAT’s a real-world IoT lesson!” everyone agreed.

12.7 What’s Next

If you want to… Read this
Understand the architecture behind sensor applications Sensor Application Architecture
Explore Python-based sensor data processing for post-lab analysis Sensor Applications with Python
Apply lab knowledge to choose sensors for specific domains Sensor Apps: Selection Wizard
Learn about the mobile phone as an alternative sensor platform Mobile Phone as a Sensor