This guide is derived from the earlier outline (edition not confirmed) for CACS460 (Internet of Things). All units and topics follow the outlined sequence; wording and examples are original student study material, not official TU text.
How to use this guide
Internet of Things integrates sensors, connectivity, platforms, cloud, and security into functional systems. The exam tests your ability to design IoT systems, select appropriate technologies, understand data analytics, and address security challenges. Practice designing simple IoT architectures, writing node firmware, and evaluating trade-offs between protocols and platforms. Marks are awarded for correct block diagram description, explaining sensor selection criteria, and describing security best practices.
Learning Outcomes
By the end of this course, a student should be able to:
- Describe the fundamental components of an IoT system and their interactions.
- Select appropriate sensors and actuators for given application domains.
- Design IoT systems using appropriate platform architectures and communication protocols.
- Implement basic IoT node programming (e.g., Arduino/Raspberry Pi) for sensor data acquisition and actuation.
- Evaluate IoT security challenges and propose mitigation strategies.
- Explain data analytics, edge computing, and cloud offerings for IoT data.
Unit 1: Introduction to IoT
Teaching hours: 8
Topics in outline order
-
Definition and Characteristics of IoT. The Internet of Things (IoT) refers to a network of physical devices, vehicles, home appliances, and other items embedded with electronics, software, sensors, actuators, and connectivity which enables these objects to collect and exchange data. Key characteristics:
- Things: Physical objects with embedded systems, ranging from simple sensors to complex machines.
- Connectivity: Network communication using various protocols and technologies, enabling data exchange.
- Data: Collected from the environment, processed, and transmitted for analysis.
- Sensing: Capturing environmental changes through sensors.
- Actuation: Performing actions in the physical world based on decisions.
- Intelligence: Data processing, analytics, and decision-making, often using cloud or edge computing.
- Heterogeneity: Diverse devices, platforms, and protocols coexisting.
IoT ecosystem: Things/sensors → communication network → data processing/storage (cloud/edge) → application layer (user-facing services).
IoT dimensions:
- Things perspective: Device-centric view focusing on sensors, actuators, and connectivity.
- Data perspective: Information-centric view focusing on data generation, processing, and value extraction.
- Services perspective: Value-centric view focusing on business models, applications, and services.
Benefits: Improved efficiency (automated monitoring and control), cost savings (reduced waste, predictive maintenance), enhanced comfort (smart home automation), new business models (data-as-a-service, remote monitoring), and improved quality of life (health monitoring, smart cities).
-
Physical and Logical Design of IoT. Physical design encompasses the core IoT architecture:
- Sensors/actuators: Detect environmental changes and perform actions (temperature, light, motion, etc.).
- Communication modules: Wireless chips/modules for network connectivity (Wi-Fi, BLE, LoRa, Cellular).
- Microcontrollers/processors: Embedded computing units (Arduino ATmega2560, ESP32, Raspberry Pi compute modules).
- Power sources: Batteries, energy harvesting, wired power.
Logical design defines functionality and protocols:
- Application layer: CoAP, MQTT, HTTP, AMQP for messaging.
- Network layer: IP-based networking, IPv4/IPv6, routing.
- Transport layer: TCP/UDP for reliable/unreliable delivery.
- Perception layer: Sensors and actuators.
- Business layer: Applications, services, and value generation.
IoT architecture models:
- Three-layer architecture: Perception layer, network layer, application layer.
- Five-layer architecture: Adds middleware layer (between network and application) and business layer.
- Six-layer architecture: Adds edge computing, security, and analytics layers.
Design considerations: Scalability (supporting thousands/millions of devices), interoperability (different devices/communicating), energy efficiency (long battery life), reliability (fault tolerance), and latency (real-time response requirements).
-
IoT Enabled Technologies. Wireless technologies:
- Wi-Fi: High bandwidth, limited range, high power, suitable for home/office.
- Bluetooth/BLE: Short range, low power, suitable for peripheral devices.
- Zigbee: Mesh networking, low power, 2.4 GHz, suitable for home automation.
- LoRaWAN: Long range, very low power, sub-GHz, suitable for wide-area IoT.
- Cellular (LTE-M, NB-IoT): Carrier-grade, wide area, moderate power, supports voice and data.
- Z-Wave: Home automation, sub-GHz, mesh networking.
Edge computing: Processes data near the source (reduces latency, bandwidth usage). Fog computing: Intermediate layer between edge and cloud. Cloud platforms: AWS IoT Core, Microsoft Azure IoT Hub, Google Cloud IoT Core. Data analytics: Real-time streaming analytics, batch processing, and machine learning on IoT data.
-
IoT and M2M. Machine-to-Machine (M2M) refers to direct communication between devices using any technology, while IoT extends M2M by adding internet connectivity, cloud integration, and advanced data analytics.
M2M characteristics: Point-to-point communication, proprietary protocols, often localized (single factory or building), focused on specific tasks (telemetry, remote monitoring).
IoT differences: Internet-scale connectivity, standard protocols (MQTT, CoAP), cloud integration, data analytics, ecosystem openness.
Convergence: Modern IoT incorporates M2M concepts, and M2M implementations increasingly use IoT architectures.
Example: Industrial M2M for machine telemetry vs. consumer IoT for smart home control.
-
Domain Specific IoTs.
- Home Automation: Smart lighting, thermostats, security systems, voice assistants, appliance control; protocols: Zigbee, Z-Wave, Wi-Fi.
- Smart Cities: Intelligent traffic management, environmental monitoring, smart lighting, waste management, public safety sensors; protocols: LoRaWAN, cellular, Wi-Fi.
- Environment: Air quality monitoring, water level sensing, weather stations, disaster warning systems; protocols: LoRaWAN, cellular.
- Energy: Smart grid components, solar panel monitoring, wind turbine sensors, energy consumption tracking; protocols: M-Bus, cellular, Zigbee.
- Retail: Inventory tracking, smart fitting rooms, customer behavior analysis, proximity marketing; protocols: BLE, Wi-Fi, NFC.
- Logistics: Fleet tracking, condition monitoring (temperature, humidity for perishables), warehouse automation, shipment visibility; protocols: cellular, satellite, LoRaWAN.
- Agriculture: Precision farming, soil moisture sensors, irrigation control, livestock monitoring, greenhouse automation; protocols: LoRaWAN, cellular, Zigbee.
- Industry: Industrial IoT (IIoT) for predictive maintenance, quality control, robot control, supply chain monitoring; protocols: OPC UA, MQTT, cellular.
- Health and Lifestyle: Wearable vital sign monitors, fall detection, smart medication dispensers, fitness trackers; protocols: BLE, NFC, cellular.
Explanation
-
Definition and Characteristics of IoT. The Internet of Things (IoT) bridges the physical and digital worlds by equipping everyday objects with sensing, actuation, and connectivity. The thing represents any physical object with embedded intelligence—from a simple temperature sensor to a complex industrial robot. Connectivity enables these objects to send data over networks using diverse protocols (Wi-Fi, cellular, LoRa, etc.). Data is the lifeblood of IoT; raw sensor readings are meaningless without processing, context, and analysis. Sensing captures environmental changes (temperature, light, motion) through various sensor types. Actuation converts control signals into physical actions (motor movement, valve opening, alarm triggering). Intelligence involves data processing, analytics, and often machine learning to derive insights and automate decisions. Heterogeneity reflects the reality that IoT deployments mix devices from different manufacturers, running different OS versions, using different communication protocols. The IoT ecosystem comprises four layers: things/sensors (field devices), communication network (wireless or wired), data processing/storage (cloud platforms like AWS IoT Core, edge servers), and application layer (user-facing services like dashboards, mobile apps). The three IoT dimensions provide different perspectives: the things perspective focuses on device capabilities and limitations, the data perspective on data generation, velocity, variety, and value, and the services perspective on business models, applications, and delivered value. Benefits span improved operational efficiency (automated monitoring reduces manual checks), cost savings (predictive maintenance avoids unplanned downtime), enhanced comfort (smart home automation), new business models (selling sensor data or offering data-as-a-service), and improved quality of life (remote health monitoring, smart cities).
-
Physical and Logical Design of IoT. The physical design specifies the tangible components: sensors detect environmental changes (temperature, light, motion), communication modules (wireless chips) enable data transmission, microcontrollers/processors (e.g., Arduino, ESP32, Raspberry Pi) provide computing power, and power sources (batteries, energy harvesting) ensure operation. The logical design abstracts functionality into layers: the perception layer (sensors/actuators), network layer (IP-based routing, IPv4/IPv6), transport layer (TCP/UDP for reliable or unreliable delivery), application layer (CoAP for constrained devices, MQTT for publish/subscribe, HTTP/HTTPS for web integration), and business layer (applications, services, value generation). IoT architecture models range from the simple three-layer (perception, network, application) to the more comprehensive five-layer (adding middleware for data processing and business) and six-layer (adding edge computing, security, analytics). Design considerations are critical for successful deployments: scalability ensures the system supports growth from dozens to millions of devices; interoperability enables diverse devices to communicate using standard protocols; energy efficiency extends battery life through low-power designs and duty cycling; reliability provides fault tolerance and graceful degradation; and latency meets real-time response requirements for applications like industrial control or autonomous vehicles.
-
IoT Enabled Technologies. The choice of wireless technology depends on application requirements:
- Wi-Fi offers high data rates (up to several Gbps) but consumes more power and has limited range (typically 10-50 meters indoors). Suitable for home/office environments where devices have constant power.
- Bluetooth/BLE (Bluetooth Low Energy) is designed for short-range, low-power communication. Ideal for wearable devices, health monitors, and periodic data transmission. BLE supports advertising (one-way broadcasting) and connection modes.
- Zigbee operates on the 2.4 GHz band with mesh networking capability, allowing devices to relay messages through intermediate nodes. Ideal for home automation, building automation, and industrial sensor networks covering large areas.
- LoRaWAN (Long Range Wide Area Network) uses sub-GHz frequencies (e.g., 868 MHz in Europe, 915 MHz in US) for extremely long range (2-5 km urban, 15+ km rural) and very low power consumption. Devices can operate on batteries for 5-10 years. Suitable for wide-area IoT applications like smart cities, agriculture, and utility metering.
- Cellular (LTE-M, NB-IoT) provides carrier-grade connectivity over wide areas. Supports mobility, voice, and data. NB-IoT is optimized for massive IoT with narrow bandwidth and deep coverage. LTE-M supports higher data rates and mobility. Used in fleet tracking, remote asset monitoring, and cellular IoT applications.
- Z-Wave is a sub-GHz mesh networking protocol similar to Zigbee but certified for home interoperability. Ideal for smart home devices (lights, locks, sensors).
Edge computing processes data near the source (on the device or gateway) rather than sending all data to the cloud. Benefits include reduced latency (real-time response), reduced bandwidth (only send alerts/aggregated data), improved reliability (functional without connectivity), and privacy (sensitive data stays on-device). Fog computing extends edge computing to an intermediate layer between edge devices and cloud, providing additional processing, storage, and analytics capabilities.
Cloud platforms offer IoT-specific services: AWS IoT Core supports MQTT, HTTP, and LoRaWAN protocols, device shadows, and scales to billions of devices. Microsoft Azure IoT Hub provides device provisioning, routing, and integration with Azure services. Google Cloud IoT Core (now part of Cloud IoT Edge) offers device management and integration with AI/ML services.
Data analytics on IoT data handles the three V's: volume (massive data from thousands/millions of devices), velocity (real-time or near real-time streams requiring low-latency processing), and variety (heterogeneous data types: temperature, humidity, images, audio, vibration). Analytics types include descriptive (what happened), diagnostic (why it happened), predictive (what will happen), and prescriptive (what should we do).
-
IoT and M2M. While both involve machine communication, M2M is the foundation: direct device-to-device communication using proprietary protocols, often in localized settings (single factory, building). IoT builds on M2M by adding internet connectivity, cloud platforms, and advanced data analytics. The key distinctions:
- Scale: M2M is typically localized; IoT is internet-scale.
- Protocols: M2M uses proprietary protocols; IoT standardizes on MQTT, CoAP, HTTP.
- Cloud integration: M2M often lacks cloud integration; IoT integrates with cloud for storage, processing, and services.
- Data analytics: M2M may perform simple threshold monitoring; IoT incorporates machine learning, big data analytics.
- Ecosystem: M2M is vendor-specific; IoT is open and heterogeneous.
Convergence is evident: modern IoT deployments incorporate M2M concepts (point-to-point communication for specific tasks), and many M2M implementations now use IoT architectures (IP connectivity, cloud integration). For example, an industrial M2M system for machine telemetry in a factory may use IoT protocols (MQTT) and cloud platforms for remote monitoring and analytics, blurring the line between M2M and IoT.
-
Domain Specific IoTs. Each domain adapts IoT technology to specific requirements:
- Home Automation: Smart lighting (Philips Hue, Zigbee/Z-Wave), thermostats (Nest), security systems (cameras, door locks), voice assistants (Amazon Echo, Google Home). Protocols: Zigbee, Z-Wave, Wi-Fi, BLE.
- Smart Cities: Intelligent traffic management (smart traffic lights, occupancy sensors), environmental monitoring (air quality, noise), smart lighting (adjust based on presence), waste management (fill-level sensors in bins), public safety (gunshot detection, flood monitoring). Protocols: LoRaWAN, cellular (LTE-M, NB-IoT), Wi-Fi.
- Environment: Air quality monitoring (particulate matter, CO2 sensors), water level sensing (ultrasonic), weather stations (temperature, humidity, pressure, rain gauges), disaster warning systems (early warning for floods, earthquakes). Protocols: LoRaWAN, cellular.
- Energy: Smart grid components (smart meters, fault detectors), solar panel monitoring (irradiance, temperature sensors), wind turbine sensors (vibration, rotational speed), energy consumption tracking (sub-metering). Protocols: M-Bus, cellular, Zigbee.
- Retail: Inventory tracking (RFID, weight sensors), smart fitting rooms (virtual try-on), customer behavior analysis (heat maps, dwell time), proximity marketing (Bluetooth beacons sending offers). Protocols: BLE, Wi-Fi, NFC.
- Logistics: Fleet tracking (GPS trackers, temperature monitoring for refrigerated goods), condition monitoring (temperature, humidity for perishables), warehouse automation (conveyor systems, robotic arms), shipment visibility (real-time location, estimated arrival). Protocols: cellular, satellite, LoRaWAN.
- Agriculture: Precision farming (soil moisture sensors, variable rate irrigation), soil moisture monitoring, irrigation control (automatic valve opening/closing), livestock monitoring (collars with GPS and vital sign sensors), greenhouse automation (light, temperature, humidity control). Protocols: LoRaWAN, cellular, Zigbee.
- Industry (IIoT): Predictive maintenance (vibration analysis, thermal imaging), quality control (computer vision on production lines), robot control (safe human-robot collaboration), supply chain monitoring (track-and-trace). Protocols: OPC UA, MQTT, cellular.
- Health and Lifestyle: Wearable vital sign monitors (heart rate, SpO2, ECG), fall detection (accelerometer-based alerts), smart medication dispensers (scheduled dosing), fitness trackers (step count, sleep tracking). Protocols: BLE, NFC, cellular.
Worked Example 1: Defining IoT and Its Characteristics
Problem: Define IoT and explain its six key characteristics with an example for each.
Solution:
Definition: The Internet of Things (IoT) refers to a network of physical devices, vehicles, home appliances, and other items embedded with electronics, software, sensors, actuators, and connectivity which enables these objects to collect and exchange data.
Characteristics:
- Things: Physical objects with embedded systems. Example: A smart thermostat (e.g., Nest) contains temperature sensors, a microprocessor, and Wi-Fi connectivity.
- Connectivity: Network communication enabling data exchange. Example: The Nest thermostat uses Wi-Fi to connect to the home network and cloud.
- Data: Collected from the environment and processed. Example: The thermostat collects temperature readings every minute and sends them to the cloud.
- Sensing: Capturing environmental changes through sensors. Example: The thermostat's temperature sensor detects when the room temperature drops below the setpoint.
- Actuation: Performing actions based on decisions. Example: The thermostat turns on the heating system when the temperature is too low.
- Intelligence: Data processing and decision-making. Example: The Nest learns the schedule and preferences, then automatically adjusts temperature for comfort and energy savings.
IoT ecosystem diagram (Mermaid):
graph LR
A[Things/Sensors] -->|read data| B[Communication Network]
B -->|transmit data| C[Data Processing/Storage]
C -->|analyze insights| D[Application Layer]
D -->|user interaction| E[User/Frontend]
Accessible summary: IoT connects physical objects to the internet, enabling them to sense, communicate, and act. The six key characteristics (things, connectivity, data, sensing, actuation, intelligence) work together: things capture environmental data, connectivity transmits it, data is processed for insights, sensing monitors changes, actuation performs actions, and intelligence enables smart decisions. The ecosystem flows from things through communication to data processing and finally to applications that interact with users.
Worked Example 2: Comparing IoT Architecture Models
Problem: Compare the three-layer, five-layer, and six-layer IoT architecture models.
Solution:
| Layer | Three-Layer | Five-Layer | Six-Layer |
|---|---|---|---|
| Application | Application layer | Application layer | Application layer |
| Middleware | Not present | Data processing, analytics | Not present (combined with edge) |
| Business | Not present | Business layer | Business layer |
| Edge Computing | Not present | Not present | Edge computing layer |
| Security | Not present | Not present | Security layer |
| Analytics | Not present | Not present | Analytics layer |
Swipe to see all columns
Three-layer architecture: The simplest model with perception layer (sensors/actuators), network layer (communication, IP-based), and application layer (user-facing services). Quick to implement, suitable for small-scale deployments.
Five-layer architecture: Adds middleware layer between network and application for data processing, protocol conversion, and business logic. Adds business layer for value generation, service delivery, and business model management. Suitable for medium-scale deployments with moderate complexity.
Six-layer architecture: Adds edge computing layer for local data processing (reduces latency, bandwidth usage), security layer for authentication, authorization, encryption, and threat detection, and analytics layer for real-time and batch analytics at the edge or cloud. Suitable for large-scale, critical IoT deployments requiring low latency, strong security, and advanced analytics.
Design implication: Choose the architecture based on deployment scale and requirements. A home automation system may use three layers; a smart city may need five or six layers for scalability, middleware interoperability, and edge analytics.
Worked Example 3: M2M vs IoT Comparison
Problem: Differentiate between M2M and IoT with a concrete example.
Solution:
M2M (Machine-to-Machine):
- Communication: Point-to-point between two devices.
- Protocol: Proprietary (e.g., Modbus, DNP3).
- Scope: Localized (single factory floor).
- Task: Read temperature from a sensor and transmit to a PLC (Programmable Logic Controller).
- Example: An industrial sensor monitors motor temperature and sends the reading via Modbus to a PLC that controls the motor speed.
IoT (Internet of Things):
- Communication: Internet-scale, standard protocols (MQTT, CoAP).
- Scope: Global, cloud-integrated.
- Task: Monitor motor temperature, send to cloud, enable remote access, apply ML for predictive maintenance.
- Example: The same motor temperature sensor connects via Wi-Fi to an IoT platform (AWS IoT Core), stores data in a time-series database, dashboards are accessible via mobile app, and a machine learning model predicts bearing failure based on vibration trends.
Key differences table:
| Aspect | M2M | IoT |
|---|---|---|
| Connectivity | Point-to-point, localized | Internet-scale, global |
| Protocols | Proprietary | Standard (MQTT, CoAP, HTTP) |
| Cloud | Often absent | Integral |
| Data Analytics | Simple threshold monitoring | ML, big data analytics |
| Ecosystem | Vendor-specific | Open, heterogeneous |
Accessible summary: M2M is direct device communication, usually in a single location, using proprietary protocols for specific tasks. IoT extends M2M by adding internet connectivity, standard protocols, cloud platforms, and advanced analytics. The same temperature sensor can be used in both: M2M sends data to a local controller, while IoT sends it to the cloud for remote access and advanced analysis.
Worked Example 4: Domain Specific IoT - Smart Agriculture
Problem: Describe a smart agriculture IoT system for monitoring soil moisture and automating irrigation.
Solution:
System overview: A smart agriculture system consists of soil moisture sensors deployed across a field, a microcontroller (e.g., Arduino or ESP32) that reads sensor values, and an automated irrigation system (solenoid valve) that turns on/off based on moisture levels. The system connects to the cloud for remote monitoring and control.
Components:
- Sensors: Capacitive soil moisture sensors (e.g., FC-28) placed at multiple locations in the field. Output: analog voltage proportional to moisture content.
- Microcontroller: ESP32 (integrated Wi-Fi and Bluetooth). Reads sensor values via ADC (analog-to-digital conversion) every 5 minutes.
- Actuators: Solenoid valve controlled by a relay module connected to the ESP32 GPIO. Opens when soil moisture is below threshold, closes when above.
- Communication: ESP32 sends sensor data to AWS IoT Core via MQTT (
agriculture/field1/moisturetopic). Receives commands to open/close the valve. - Cloud: AWS IoT Core stores data in Timestream. Dashboard (Grafana) shows real-time moisture levels over time. Alerts trigger when moisture falls below a critical threshold.
- Power: Solar panel with battery backup for continuous operation in the field.
Data flow:
- Soil moisture sensor reads analog voltage → ESP32 ADC converts to digital value (0-4095).
- ESP32 publishes moisture percentage to MQTT topic
agriculture/field1/moisture. - AWS IoT Core receives and stores the data in Timestream.
- Grafana dashboard displays moisture level over time (daily, weekly views).
- If moisture < 30%, an alert is sent (SMS, email) and a Lambda function closes the valve.
Control logic:
# ESP32 MicroPython code snippet
import machine, time, umqtt.simple as mqtt
sensor = machine.ADC(0) # Soil moisture sensor on ADC0
valve = machine.Pin(2, machine.Pin.OUT) # Relay on GPIO2
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('SSID', 'PASSWORD')
# Wait for Wi-Fi connection
while not wlan.isconnected():
pass
client = mqtt.MQTTClient('esp32_01', 'broker.hivemq.com')
client.connect()
while True:
value = sensor.read()
moisture = 100 - (value / 4095) * 100 # Convert to percentage
# Publish moisture level
client.publish(b'agriculture/field1/moisture', f'{moisture:.1f}')
# Control valve based on threshold
if moisture < 30:
valve.on() # Irrigate
else:
valve.off() # Stop irrigation
time.sleep(300) # Wait 5 minutes
Expected result: The system continuously monitors soil moisture and automates irrigation, reducing water waste and improving crop yield. Remote farmers can check moisture levels via a dashboard and receive alerts when intervention is needed.
Accessible summary: Smart agriculture uses IoT to monitor soil conditions and automate watering. Sensors measure moisture, a microcontroller processes the data, and cloud connectivity enables remote monitoring. The system saves water by irrigating only when needed and provides farmers with actionable insights via dashboards.
Worked Example 5: Setting Up Arduino for IoT Sensor Reading
Problem: Set up an Arduino Uno to read temperature from a DHT11 sensor and publish the value via MQTT.
Solution:
Hardware setup:
- Arduino Uno
- DHT11 temperature and humidity sensor
- Breadboard and jumper wires
- USB cable for power and programming
Wiring:
- DHT11 VCC → Arduino 5V
- DHT11 GND → Arduino GND
- DHT11 Data → Arduino GPIO 2 (through 10kΩ pull-up resistor to 5V)
- The pull-up resistor ensures stable communication with the DHT11 sensor.
Software setup:
- Install Arduino IDE from arduino.cc.
- Connect Arduino via USB, select board (Arduino Uno) and port (e.g., /dev/tty.usbmodem1411).
- Install the
Adafruit DHT sensor libraryandAdafruit Unified Sensor libraryvia Library Manager. - Example sketch:
#include "Adafruit_DHT.h"
#define DHTPIN 2 // Digital pin connected to DHT11
#define DHTTYPE DHT11 // DHT 11 sensor type
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
// Read temperature and humidity
float h = dht.readHumidity();
float t = dht.readTemperature(); // Celsius
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print to Serial Monitor
Serial.print("Humidity: "); Serial.print(h);
Serial.print(" %\tTemperature: "); Serial.print(t); Serial.println(" *C");
// TODO: Add MQTT publishing code here
// client.publish("home/temperature", String(t).c_str());
delay(2000); // Wait 2 seconds between readings.
}
MQTT integration (additional code):
#include <PubSubClient.h>
#include <WiFiClient.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* mqtt_server = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
// ... (WiFi setup, DHT setup)
client.setServer(mqtt_server, 1883);
}
void loop() {
// ... (DHT reading code)
if (!client.connected()) {
reconnect();
}
client.loop();
// Publish temperature to MQTT topic
String tempMsg = String(t);
client.publish("home/temperature", tempMsg.c_str());
delay(2000);
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ArduinoClient")) {
Serial.println("MQTT connected");
} else {
delay(5000);
}
}
}
Expected result: The Arduino reads temperature and humidity from the DHT11 every 2 seconds, prints to the Serial Monitor, and publishes the temperature to the MQTT topic home/temperature. The value is available for subscribing clients (e.g., a dashboard, home automation system).
Verification:
- Open Arduino Serial Monitor (baud rate 9600) to see humidity and temperature readings.
- Use an MQTT client (e.g., MQTTX, Eclipse Paho) to subscribe to
home/temperatureand verify messages arrive every 2 seconds. - Check that the DHT11 readings are reasonable (temperature: -40°C to 80°C, humidity: 20% to 80%).
Accessible summary: Setting up an Arduino for IoT involves wiring a sensor (DHT11), installing libraries, and writing firmware that reads sensor data and optionally publishes it via MQTT. The example demonstrates the full cycle: sensor reading, data preparation, and MQTT communication. The 10kΩ pull-up resistor on the data pin is essential for reliable DHT11 communication.
Worked Example 6: Raspberry Pi GPIO Setup for Sensor Interfacing
Problem: Set up a Raspberry Pi to read a PIR motion sensor and control an LED based on motion detection.
Solution:
Hardware setup:
- Raspberry Pi 4 Model B
- PIR motion sensor (e.g., HC-SR501)
- LED + 220Ω current-limiting resistor
- Breadboard and jumper wires
- 5V power supply (official Raspberry Pi power supply)
Wiring:
- PIR VCC → Raspberry Pi 2 pin (5V)
- PIR GND → Raspberry Pi 6 pin (GND)
- PIR OUT → Raspberry Pi GPIO 17 (pin 11)
- LED anode (long leg) → resistor → GPIO 18 (pin 12)
- LED cathode (short leg) → Raspberry Pi GND (pin 6)
Software setup:
- Install Raspberry Pi OS on the SD card.
- Enable SSH and I2C/SPI if needed:
sudo raspi-config, Interface Options. - Update software:
sudo apt update && sudo apt upgrade. - Python script using
gpiozero:
from gpiozero import MotionSensor, LED
from signal import pause
# GPIO pin assignments
pir = MotionSensor(17) # PIR sensor connected to GPIO17
led = LED(18) # LED connected to GPIO18 with current-limiting resistor
# Motion detection callback
def motion_detected():
print("Motion detected!")
led.on() # Turn on LED when motion is detected
def motion_removed():
print("Motion ended")
led.off() # Turn off LED when motion stops
# Assign callbacks
pir.when_motion = motion_detected
pir.when_no_motion = motion_removed
# Keep the script running
print("Motion sensor active. Press Ctrl+C to exit.")
pause()
Alternative: Using RPi.GPIO library:
import RPi.GPIO as GPIO
import time
# GPIO setup
GPIO.setmode(GPIO.BCM)
PIR_PIN = 17
LED_PIN = 18
GPIO.setup(PIR_PIN, GPIO.IN) # PIR sensor as input
GPIO.setup(LED_PIN, GPIO.OUT) # LED as output
try:
while True:
if GPIO.input(PIR_PIN):
print("Motion detected!")
GPIO.output(LED_PIN, GPIO.HIGH) # Turn on LED
else:
print("No motion")
GPIO.output(LED_PIN, GPIO.LOW) # Turn off LED
time.sleep(0.1)
except KeyboardInterrupt:
GPIO.cleanup() # Reset GPIO settings on exit
Expected result: The PIR sensor detects motion in its field of view and triggers the LED to turn on. When motion stops, the LED turns off after the sensor's default timeout (typically 2-5 seconds). The Python script prints status messages to the console.
Verification:
- Wave hand in front of the PIR sensor; the LED should turn on.
- Remove hand; the LED should turn off after the sensor's timeout (typically 2-5 seconds).
- Check Python output for "Motion detected!" / "Motion ended" messages.
- Ensure no error messages related to GPIO pin numbering.
Accessible summary: Interfacing a PIR motion sensor with a Raspberry Pi involves connecting the sensor's VCC, GND, and OUT pins to power, ground, and a GPIO input pin. The gpiozero library simplifies Python programming with high-level classes (MotionSensor, LED) and automatic callback handling. The RPi.GPIO library provides lower-level control for advanced use cases. The system detects motion and provides visual feedback via an LED, suitable for security systems, automation, and interactive projects.
Explanation (Unit 1 continued)
The explanations above establish the foundational concepts that underpin the entire IoT course. Understanding the definition and characteristics of IoT is essential before designing or evaluating any system. The physical and logical design framework provides a structured approach to component selection and architecture design. IoT enabled technologies guide the choice of communication protocols and platforms based on application requirements. The M2M vs IoT comparison clarifies the evolution and distinctions between these related paradigms. Domain specific IoTs demonstrate how IoT technology adapts to diverse application areas, each with unique requirements, constraints, and suitable protocols. These foundational topics (Units 1-2) provide the knowledge base for the more advanced topics in Units 3-6, which cover platform design, data analytics, cloud offerings, and security.
Unit 2: Sensor, Actuators and Interfacing
Teaching hours: 18
Topics in outline order
- Roles of Sensors and actuators, Types of sensors: Active and passive, analog and digital, Contact and no-contact, Absolute and relative.
- Working of sensors: Position, occupancy and motion, velocity and acceleration, force, pressure, flow, Acoustic, Humidity, light, radiation, temperature, chemical, biosensor, camera.
- Development boards: Arduino and Raspberry PI installation, interfacing and programming using python.
Explanation
-
Roles of Sensors and Actuators. Sensors convert physical quantities (temperature, light, motion, pressure, etc.) into electrical signals (voltage, current, resistance changes) that can be measured and processed by electronic circuits. Actuators convert electrical signals into physical actions (movement, heat, sound, fluid flow). The distinction is fundamental: sensors input physical world data to the digital system; actuators output digital decisions to the physical world.
Sensor roles:
- Primary sensor: Directly measures the physical quantity. Example: A thermistor directly responds to temperature changes by varying its resistance.
- Secondary sensor: Converts the primary sensor's output to a standardized signal. Example: An ADC (Analog-to-Digital Converter) converts the thermistor's varying resistance into a digital number (0-1023) that a microcontroller can process.
- Active sensor: Requires external power to operate. Example: A capacitive touch sensor requires power to detect changes in capacitance. A piezoelectric sensor generates its own charge but requires circuitry to condition the output.
- Passive sensor: Does not require external power to operate (it may generate a signal). Example: A thermocouple generates a voltage proportional to temperature difference without external power. A photodiode in photovoltaic mode generates current from light without external power.
Sensor types by operation:
- Active sensors: Require power (capacitive touch, inductive proximity, ultrasonic range finder with internal oscillator).
- Passive sensors: No power needed (thermocouple, photodiode in photovoltaic mode, strain gauge with external bridge excitation).
Sensor selection criteria are critical for reliable operation:
- Sensitivity: Change in output per unit of measured quantity. High sensitivity detects small changes.
- Range: Minimum and maximum measurable values. The range must encompass the expected measurement values.
- Accuracy: Closeness of the measured value to the true value. Expressed as ±percentage of full scale.
- Resolution: Smallest detectable change. A 12-bit ADC has resolution of 1/4096 of full scale (~0.024%).
- Response time: Time for the sensor output to reflect a change in the measured quantity. Fast response is critical for dynamic systems.
- Linearity: Proportional relationship between input and output. Linear sensors have a straight-line response; nonlinear sensors require calibration curves.
- Hysteresis: Dependence on the history of measurements. The output value differs depending on whether the input is increasing or decreasing.
- Drift: Gradual change in zero reading over time. Regular calibration mitigates drift.
- Cost: Balance between performance and budget. Higher-performance sensors cost more.
- Environmental robustness: Ability to operate in the intended environment (temperature range, humidity, dust, vibration, electromagnetic interference). Sensors for harsh environments are more expensive but necessary for reliability.
-
Working of sensors. Each sensor type is designed for specific physical quantities:
-
Position:
- Potentiometer: Variable resistance based on knob position; used for user controls, joysticks.
- Encoder (optical or magnetic): Provides position and speed feedback; used in motor control, robotics. Optical encoders use a coded disk and photodetectors; magnetic encoders use Hall effect sensors.
- LVDT (Linear Variable Differential Transformer): Measures linear displacement; used in precision machinery, hydraulic systems. Produces differential AC voltage proportional to core position.
-
Occupancy and motion:
- PIR sensor (Passive Infrared): Detects heat/motion changes by comparing IR levels across two slots; used in security lights, automatic doors. Detects humans and large animals within ~10-15 feet.
- Microwave sensor: Uses Doppler effect to detect motion through walls; higher range than PIR, more prone to false triggers. Used in automotive presence detection.
- Ultrasonic sensor: Time-of-flight measurement using sound waves; measures distance and motion. Consists of TRIG (send ultrasound) and ECHO (receive reflected ultrasound). Distance = (time × speed of sound) / 2.
-
Velocity and acceleration:
- Accelerometer (MEMS): Measures acceleration vectors, e.g., MPU6050 gives 3-axis acceleration and gyroscope (angular velocity). Measures g-force (9.8 m/s² at rest). Used in smartphones (screen orientation), gaming, drones (flight stabilization).
- Gyroscope: Measures angular velocity (degrees/second). Often combined with accelerometer in an IMU (Inertial Measurement Unit) for 6-DOF or 9-DOF tracking.
- Tachometer: Measures rotational speed (RPM); used in engines, fans. Optical (interrupter) or magnetic (Hall effect).
-
Force:
- Load cell (strain gauge based): Measures force/weight; used in industrial scales, weighbridges. A strain gauge deforms under force, changing resistance; a Wheatstone bridge converts this to voltage.
- Strain gauge: Deformation-based; measures resistance change due to stretching/compression. Often used in structural health monitoring.
- Dynamometer: Direct force measurement; used in testing equipment, material testing.
-
Pressure:
- Pressure sensor (piezoelectric, capacitive, resistive): Measures gauge or absolute pressure; used in weather stations, altimeters, medical devices. Piezoelectric generates voltage under mechanical stress; capacitive varies plate separation; resistive changes conductive material resistance.
- Barometer: Atmospheric pressure measurement; used in weather forecasting, altitude determination. Bosch BME280 combines barometer with temperature and humidity.
- Touch sensor (capacitive/resistive): Touchscreen input; detects finger presence/location. Capacitive senses changes in capacitance; resistive measures resistance change when touching.
-
Flow:
- Flow meter (electromagnetic, ultrasonic, turbine): Measures liquid/gas flow rate; used in water supply, HVAC, industrial processes. Electromagnetic (Faraday's law) measures voltage induced by conductive fluid flow; ultrasonic uses time-of-flight of ultrasound through the fluid; turbine uses rotating blades proportional to flow rate.
- Venturi meter: Constriction-based pressure difference; measures flow rate from pressure drop across a narrowed pipe section.
-
Acoustic:
- Microphone: Converts sound waves to electrical signals; used in audio recording, voice commands, surveillance. Dynamic (electromagnetic), condenser (capacitance change), MEMS (miniature, integrated).
- Hydrophone: Underwater acoustic detection; similar to microphone but designed for water coupling. Used in submarine detection, sonar.
-
Humidity:
- Hygrometer: Measures relative humidity; used in weather stations, HVAC, incubators. Capacitive hygrometers (most common) use a polymer film that changes capacitance with humidity.
- DHT11/DHT22: Common digital humidity/temperature sensors; output is a digital signal with humidity and temperature values. DHT11 is basic (1 decimal place, 20-80% RH, 0-50°C); DHT22 is more precise (2 decimal places, 0-100% RH, -40-80°C).
-
Light:
- Photodiode: Current proportional to light intensity; used in light meters, automatic brightness control, solar panels. Silicon photodiodes respond to visible and near-infrared light.
- LDR (Light-Dependent Resistor): Resistance decreases with light intensity; used in street lights, garden lights. Simple, low-cost, but slow response and poor accuracy.
- CCD/CMOS: Image sensors for cameras; capture light intensity per pixel to form images. Used in digital cameras, smartphones, security cameras.
-
Radiation:
- Radiation sensor (Geiger-Müller tube): Measures ionizing radiation; used in nuclear monitoring, environmental safety. Detects alpha, beta, gamma radiation via ionization events in a gas-filled tube.
- Dosimeter: Cumulative exposure measurement; integrates radiation dose over time. Used by personnel working with radioactive materials.
-
Temperature:
- Thermistor (NTC/PTC): Resistance changes with temperature; NTC (Negative Temperature Coefficient) resistance decreases as temperature rises. Common in consumer electronics, 3D printers.
- RTD (Resistance Temperature Detector): Platinum-based, high accuracy; used in industrial processes, laboratories. PT100 (100Ω at 0°C) provides precise temperature measurement.
- Thermocouple: Voltage proportional to temperature difference between two dissimilar metals; wide range (-200°C to +1800°C). Used in furnace monitoring, engine exhaust, industrial processes. Requires cold-junction compensation.
-
Chemical:
- MQ-2, MQ-135: Common gas sensors; detect combustible gases, smoke, alcohol, NH3, CO, LPG. Analog output voltage varies with gas concentration. Not highly specific; affected by temperature, humidity, and other gases.
- Biosensor: Combines biological recognition element (enzyme, antibody) with transducer (electrochemical, optical); used in medical diagnostics, glucose monitoring.
-
Camera:
- CCD/CMOS image sensor: Captures visual images; used in security cameras, robot vision, documentation. Resolution measured in megapixels (e.g., 5 MP, 8 MP, 12 MP). Color filters (RGB Bayer pattern) enable color imaging.
Actuator types:
- Electrical: Motor (DC, Stepper, Servo), Solenoid, Relay (switches higher power circuits). Used in robotics, automation, home control.
- Thermal: Heater, Peltier (thermoelectric cooler). Used in 3D printers (melting filament), temperature control, thermal testing.
- Hydraulic: Cylinder, Motor. Used in heavy machinery, aircraft flight controls, industrial presses. Uses pressurized fluid to generate force.
- Pneumatic: Air cylinder, Motor. Used in factory automation, robotics, pneumatic tools. Uses compressed air for movement.
- Piezoelectric: Buzzer, Ultrasonic transducer. Generates sound or vibration from electrical voltage; used in buzzers, ultrasonic cleaning, ultrasonic ranging.
Actuator selection criteria:
- Force/torque output: Must meet the physical requirement (lift 10 kg, rotate 360°).
- Speed: Time to complete the action (motor rpm, valve opening time).
- Power consumption: Continuous draw and peak power (battery life, power supply sizing).
- Control precision: Position accuracy, repeatability (servo vs. stepper vs. DC motor with PID).
- Environmental ratings: Operating temperature, IP rating (water/dust resistance), corrosion resistance.
- Cost and availability: Balance between performance needs and budget constraints.
-
-
Development boards: Arduino and Raspberry PI installation, interfacing and programming using python.
Arduino (e.g., Arduino Uno, Mega):
-
Specifications:
- Arduino Uno: ATmega328P microcontroller, 14 digital I/O pins (6 PWM), 6 analog inputs, 16 MHz clock, 32 KB flash memory, 2 KB SRAM, 1 KB EEPROM, USB programming, 3.3V/5V power selection.
- Arduino Mega: ATmega2560, 54 digital I/O pins (15 PWM), 16 analog inputs, 256 KB flash, 8 KB SRAM, 4 KB EEPROM, more peripherals (UARTs, SPI, I2C).
-
Setup:
- Install Arduino IDE from arduino.cc.
- Connect board via USB cable to computer.
- Select board:
Tools → Board → Arduino Uno(or Mega). - Select port:
Tools → Port(e.g., /dev/tty.usbmodem1411 on Mac, COM3 on Windows). - Upload "Blink" test sketch: Built-in LED on pin 13 blinks on/off every second.
-
Python integration:
- pySerial library for serial communication:
import serial; ser = serial.Serial('/dev/ttyUSB0', 9600)opens the serial port at 9600 baud. Data can be sent/received usingser.write()andser.read(). - RPi.GPIO library for Raspberry Pi GPIO control (not on Arduino, but relevant for Pi-Arduino integration).
- Adafruit CircuitPython for simplified sensor interaction: Pre-built CircuitPython firmware for Arduino/ESP32/Raspberry Pi simplifies sensor interaction via imports (e.g.,
import board; import adafruit_dht; dht_device = adafruit_dht.dht.DHT11(board.D2)).
- pySerial library for serial communication:
-
Interfacing examples:
- Reading temperature from DHT11 connected to GPIO2.
- Blinking LED on GPIO17.
- Reading ultrasonic distance from TRIG/ECHO pins.
- Controlling a motor using PWM (Pulse Width Modulation).
-
Communication protocols:
- I2C (Inter-Integrated Circuit): Two-wire interface (SDA, SCL pins); multiple devices via different addresses; standard for sensors, EEPROMs, displays. Typical speed: 100 kHz, 400 kHz (fast mode), 3.4 MHz (high-speed).
- SPI (Serial Peripheral Interface): Four-wire interface (MOSI, MISO, SCK, CS); high-speed, full-duplex; multiple devices via CS (chip select) lines. Used for fast sensors, displays, SD cards.
- UART (Universal Asynchronous Receiver-Transmitter): Two-wire interface (TX, RX); serial communication; used for GPS, Bluetooth, debugging. Data format: start bit, data bits, optional parity bit, stop bit.
- 1-Wire: Single data line, multiple devices (each with unique ROM address); low-speed, long-distance; used for temperature sensors (DS18B20), EEPROMs.
-
Power considerations:
- Arduino: Powered via USB (5V from computer) or DC jack (7-12V recommended external power).
- Raspberry Pi: Requires 5V/2.5A minimum (official power supply); avoid USB power hubs for multiple sensors (voltage drop may cause instability). GPIO pins provide 3.3V (max 50 mA per pin, 150 mA total for all pins). Use level shifters for 5V sensors.
Raspberry Pi (e.g., Raspberry Pi 4 Model B):
-
Specifications:
- Quad-core ARM Cortex-A72 CPU, 1-8 GB RAM.
- 40 GPIO pins (27 general-purpose, plus special functions).
- Dual-band Wi-Fi (2.4 GHz and 5 GHz).
- Bluetooth 5.0.
- Ethernet (RJ45, 1 Gbps).
- HDMI (up to 4K at 60 Hz).
- 4 USB 3.0 ports.
-
Setup:
- Install Raspberry Pi OS (official OS from raspberrypi.com).
- First boot: expand filesystem, set locale, enable SSH/Wi-Fi.
- Connect peripherals: monitor, keyboard, mouse (or headless with SSH).
- Update software:
sudo apt update && sudo apt upgrade. - Enable SSH:
sudo systemctl enable sshor configure viaraspi-config. - Enable I2C/SPI if using sensors:
sudo raspi-config → Interfaces → I2C/SPI.
-
Python sensor examples:
adafruit-circuitpython-dhtfor DHT11/DHT22 temperature/humidity:import board; import adafruit_dht; dht_device = adafruit_dht.dht.DHT11(board.D2).smbus2for I2C sensors (e.g., BH1750 light sensor, MPU6050 IMU):import smbus2; bus = smbus2.SMBus(1); data = bus.read_i2c_block_data(0x40, 0x01).pigpiofor PWM control:import pigpio; pi = pigpio.pi(); pi.set_PWM_dutycycle(18, 128)sets PWM duty cycle on GPIO 18.
-
Interfacing examples:
- Reading temperature from DHT11 connected to GPIO4.
- Blinking LED on GPIO17 (software PWM).
- Reading ultrasonic distance from TRIG/ECHO pins (GPIO17 as output trigger, GPIO27 as input echo).
- Controlling a DC motor using L298N driver and PWM on GPIO12.
-
Communication protocols:
- I2C: SDA is GPIO 2 (pin 3), SCL is GPIO 3 (pin 5). Multiple devices at different addresses (0x48 for ADC, 0x5A for BMP180, etc.).
- SPI: MOSI GPIO 19 (pin 35), MISO GPIO 21 (pin 41), SCLK GPIO 23 (pin 16), CE0 GPIO 8 (pin 24), CE1 GPIO 7 (pin 26). Used for displays, SD card, sensors.
- UART: TX is GPIO 15 (pin 10), RX is GPIO 14 (pin 8). Used for debugging, GPS, serial communication with other devices.
- 1-Wire: GPIO 4 (pin 7) can be used with
w1-gpiooverlay for DS18B20 temperature sensors.
-
Power considerations:
- Raspberry Pi 4 requires 5V/3A (official power supply) for full operation with USB peripherals. The 40 GPIO pins provide 3.3V output (max 50 mA per pin, 150 mA total for all pins combined). Never apply 5V to a 3.3V GPIO pin (will damage the Pi). Use level shifters for 5V sensors. The Pi can be powered via USB-C (P4), GPIO header (2-3.3V), or the micro-USB port (P6, for older models).
-
Explanation (Unit 2 continued)
The detailed sensor and actuator descriptions provide the knowledge needed to select appropriate components for IoT designs. Sensors convert physical quantities to electrical signals, and the choice depends on the required physical quantity, sensitivity, range, accuracy, resolution, response time, linearity, hysteresis, drift, cost, and environmental robustness. Actuators convert electrical signals back to physical actions, and selection depends on force/torque output, speed, power consumption, control precision, environmental ratings, and cost. Development boards (Arduino, Raspberry Pi) provide accessible platforms for prototyping and education. The Arduino is ideal for simple, low-power, standalone projects with its easy-to-use IDE and extensive library support. The Raspberry Pi offers more computing power, connectivity (Wi-Fi, Ethernet), and GPIO flexibility, running a full OS (Linux) and supporting Python, C++, and other languages. Communication protocols (I2C, SPI, UART, 1-Wire) enable multiple device connectivity on the same bus, each with trade-offs in speed, complexity, and device count. Power considerations are critical: Arduino's 5V USB or 7-12V DC, and Raspberry Pi's 5V/2.5A-3A requirement. Improper power (undersized supply, excessive GPIO current) causes instability, crashes, or permanent damage.
Worked Example 1: Sensor Selection for a Temperature Monitoring System
Problem: Select a temperature sensor for a greenhouse monitoring system that operates in the range 0°C to 40°C, requires ±0.5°C accuracy, and runs on battery power for 6 months.
Solution:
Sensor options comparison:
| Sensor | Type | Range | Accuracy | Power | Cost | Suitability |
|---|---|---|---|---|---|---|
| Thermistor (NTC) | Passive | -40°C to +125°C | ±0.1°C to ±0.5°C | Very low (voltage divider) | $0.50 - $2.00 | Excellent: Meets accuracy, range, and low-power requirements. Self-heating effect must be considered. |
| Thermocouple | Active | -200°C to +1800°C | ±1°C to ±2°C (cold-junction comp.) | Moderate (requires amplification) | $1.00 - $5.00 | Overkill: Range far exceeds requirements; complexity and cost not justified. |
| RTD (PT100) | Active | -200°C to +850°C | ±0.1°C | High (excitation current) | $5.00 - $20.00 | Overkill: Range and cost exceed requirements; requires excitation circuitry. |
| DS18B20 (1-Wire) | Digital | -55°C to +125°C | ±0.5°C | Low (parasite mode possible) | $2.00 - $5.00 | Good: Meets accuracy and range; 1-Wire simplifies wiring; parasite mode reduces wire count. |
Swipe to see all columns
Selection: NTC thermistor with ±0.3°C accuracy in the 0-40°C range. A voltage divider circuit reads the resistance change, and an ADC (e.g., Arduino's 10-bit ADC) converts to temperature.
Circuit design:
- Thermistor (10 kΩ at 25°C) in voltage divider with fixed 10 kΩ resistor to VCC.
- ADC reads analog voltage:
value = analogRead(A0)(0-1023). - Temperature calculation:
float voltage = value * 5.0 / 1023; float resistance = 10000 * voltage / (5.0 - voltage); float temperature = 1 / (A + B * log(resistance) + C * pow(log(resistance), 3));(Steinhart-Hart equation, with A, B, C from thermistor datasheet).
Expected result: The system monitors greenhouse temperature within ±0.5°C accuracy across 0-40°C. Battery life exceeds 6 months due to low sensor power consumption (periodic readings every 30 seconds, deep sleep between readings).
Verification:
- Place thermistor in temperature bath at 0°C, 20°C, 40°C; verify measured values.
- Measure current draw; confirm battery life > 6 months with expected reading frequency.
- Compare with a calibrated reference thermometer.
Accessible summary: For the greenhouse system, an NTC thermistor is the best choice: it covers the required temperature range, offers the needed accuracy, and consumes minimal power for battery operation. The thermistor's resistance changes with temperature, and this change is read by an ADC on the microcontroller. The Steinhart-Hart equation converts resistance to temperature. The 1-Wire DS18B20 is a good alternative that simplifies wiring with a single data line.
Worked Example 2: ADC Conversion and Temperature Calculation
Problem: Read a thermistor value using Arduino's ADC and calculate temperature using the Steinhart-Hart equation.
Solution:
Circuit: NTC thermistor (10 kΩ at 25°C) in voltage divider with 10 kΩ resistor connected to VCC (5 V). ADC pin A0 reads the midpoint voltage.
Arduino code:
const int thermistorPin = A0;
const float VCC = 5.0;
const float R_SERIES = 10000.0;
// Steinhart-Hart coefficients for a specific NTC thermistor
const float A = 1.009129e-3;
const float B = 2.378405e-4;
const float C = 2.019202e-7;
void setup() {
Serial.begin(9600);
}
void loop() {
// Read ADC value (0-1023)
int adcValue = analogRead(thermistorPin);
// Convert ADC to voltage
float voltage = adcValue * VCC / 1023.0;
// Calculate thermistor resistance using voltage divider
// R_thermistor = R_series * (VCC / voltage - 1)
float R_therm = R_SERIES * (VCC / voltage - 1);
// Steinhart-Hart equation: 1/T = A + B * ln(R) + C * (ln(R))^3
float ln_R = log(R_therm);
float inv_T = A + B * ln_R + C * pow(ln_R, 3);
// Convert to Celsius
float temperatureC = 1.0 / inv_T - 273.15;
// Print results
Serial.print("Resistance: "); Serial.print(R_therm); Serial.println(" Ω");
Serial.print("Temperature: "); Serial.print(temperatureC); Serial.println(" °C");
delay(2000); // Read every 2 seconds
}
Intermediate steps:
analogRead(thermistorPin)reads the ADC value (0-1023 for 5 V reference).voltage = adcValue * VCC / 1023.0converts the ADC reading to voltage (e.g., 512 → 2.5 V).R_therm = R_SERIES * (VCC / voltage - 1)calculates the thermistor's resistance using the voltage divider formula. If voltage = 2.5 V, R_therm = 10000 * (5/2.5 - 1) = 10000 Ω (expected at 25°C).ln_R = log(R_therm)natural logarithm of resistance (e.g., ln(10000) ≈ 9.21).inv_T = A + B * ln_R + C * pow(ln_R, 3)applies the Steinhart-Hart equation (A, B, C are thermistor-specific coefficients).temperatureC = 1.0 / inv_T - 273.15converts from Kelvin to Celsius.
Expected result: The Serial Monitor displays the thermistor resistance (Ω) and calculated temperature (°C). At 25°C (room temperature), the resistance should be close to 10 kΩ. At 0°C, resistance is higher (~30-40 kΩ depending on the thermistor). At 40°C, resistance is lower (~3-5 kΩ).
Verification:
- Measure resistance with a multimeter at known temperatures (ice water 0°C, boiling water 100°C).
- Compare calculated temperature with a reference thermometer.
- Check that the ADC reading is stable (noise filtering: take multiple readings and average).
Accessible summary: The Arduino ADC converts the thermistor's analog voltage to a digital value (0-1023). The voltage divider circuit produces a voltage proportional to the thermistor's resistance. The Steinhart-Hart equation (with three coefficients specific to the thermistor) converts resistance to temperature in Kelvin, then Celsius. The example shows the full chain: sensor → voltage divider → ADC → calculation → temperature display.
Worked Example 3: PIR Motion Sensor Circuit and Python Reading
Problem: Connect a PIR motion sensor to a Raspberry Pi and read motion events using Python.
Solution:
Circuit: HC-SR501 PIR motion sensor connected to Raspberry Pi GPIO 17.
Wiring:
- PIR VCC → Pi 2 pin (5V)
- PIR GND → Pi 6 pin (GND)
- PIR OUT → Pi GPIO 17 (pin 11)
- No external resistor needed; PIR output is 3.3V when triggered.
Python code using gpiozero:
from gpiozero import MotionSensor
from signal import pause
# GPIO pin assignment
pir = MotionSensor(17) # PIR sensor connected to GPIO17
# Callback when motion is detected
def motion_detected():
print("--- Motion detected ---")
# Could trigger: send MQTT message, turn on light, record event
# Callback when motion stops (after sensor timeout)
def motion_removed():
print("--- Motion ended ---")
# Could trigger: turn off light, send alert, log event
# Assign callbacks
pir.when_motion = motion_detected
pir.when_no_motion = motion_removed
print("Motion sensor active. Wave your hand in front of the sensor.")
print("Press Ctrl+C to exit.")
# Keep the script running (pause handles signals)
pause()
Python code using RPi.GPIO:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
PIR_PIN = 17
GPIO.setup(PIR_PIN, GPIO.IN) # PIR sensor as input
try:
while True:
if GPIO.input(PIR_PIN):
print(f"{time.strftime('%Y-%m-%d %H:%M:%S')} - Motion detected!")
# Add: LED control, MQTT publish, logging
else:
# print(f"{time.strftime('%Y-%m-%d %H:%M:%S')} - No motion")
pass
time.sleep(0.1)
except KeyboardInterrupt:
GPIO.cleanup() # Reset GPIO settings on exit
Expected result: When motion is detected within the PIR sensor's field of view, the console prints "Motion detected!" (gpiozero) or a timestamped message (RPi.GPIO). After motion stops, the sensor automatically times out (typically 2-5 seconds) and prints "Motion ended" or returns to the low state. The LED on the PIR (if present) lights up when triggered.
Verification:
- Wave hand in front of the PIR sensor; console output shows motion detection.
- Remove hand; after the sensor's timeout, console shows motion ended.
- Test multiple triggers; verify consistent detection.
- Check that the sensor's timeout adjusts (some PIRs have potentiometers for sensitivity and timeout).
Accessible summary: The PIR motion sensor connects to a Raspberry Pi's GPIO input pin. When motion is detected, the script reacts (print message, turn on LED, send alert). The gpiozero library provides the simplest approach with automatic callback handling. The RPi.GPIO library offers more control for advanced scenarios. The PIR sensor's detection range is ~3-7 meters with a 110° field of view; the timeout (duration the output stays high) is adjustable via onboard potentiometers.
Worked Example 4: I2C LCD Display with Arduino
Problem: Connect a 16×2 I2C LCD display to an Arduino and display temperature readings.
Solution:
Components: Arduino Uno, I2C 16×2 LCD display (PCF8866 or similar), NTC thermistor circuit, jumper wires.
Wiring:
- LCD VCC → Arduino 5V
- LCD GND → Arduino GND
- LCD SDA → Arduino A4 (SDA line)
- LCD SCL → Arduino A5 (SCL line)
- Thermistor → A0 (analog input, as in Worked Example 2)
LiquidCrystal_I2C library installation:
- Open Arduino IDE.
Sketch → Include Library → Manage Libraries...- Search for
LiquidCrystal I2Cand installLiquidCrystal I2C by Frank de Brabander. - Alternatively, use the
liquidcrystal_I2Clibrary via Library Manager.
Arduino code:
#include <Wire.h> // I2C communication library (built-in)
#include <LiquidCrystal_I2C.h> // I2C LCD library
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set LCD address, cols, rows
const int thermistorPin = A0;
const float VCC = 5.0;
const float R_SERIES = 10000.0;
const float A = 1.009129e-3;
const float B = 2.378405e-4;
const float C = 2.019202e-7;
void setup() {
Serial.begin(9600);
// Initialize LCD
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on backlight
// Print static text
lcd.setCursor(0, 0); // Column 0, Row 0
lcd.print("Temp: ");
}
void loop() {
// Read thermistor (as in Worked Example 2)
int adcValue = analogRead(thermistorPin);
float voltage = adcValue * VCC / 1023.0;
float R_therm = R_SERIES * (VCC / voltage - 1);
float ln_R = log(R_therm);
float inv_T = A + B * ln_R + C * pow(ln_R, 3);
float temperatureC = 1.0 / inv_T - 273.15;
// Display on LCD
lcd.setCursor(6, 0); // Column 6, Row 0 (after "Temp: ")
lcd.print(temperatureC, 1); // Print with 1 decimal place
// Also print to Serial Monitor
Serial.print("Temp: "); Serial.print(temperatureC, 1); Serial.println(" *C");
delay(2000); // Update every 2 seconds
}
Expected result: The 16×2 LCD displays "Temp: 23.5°C" on the first line, updating every 2 seconds. The second line may remain blank or show additional information (e.g., humidity if a DHT sensor is also connected). The Serial Monitor also prints the temperature values.
Verification:
- Confirm the LCD addresses with
0x27(common) or0x3F(alternative). Use an I2C scanner sketch if the display is blank. - Adjust the contrast potentiometer on the LCD module if the text is barely visible.
- Compare LCD temperature readings with the Serial Monitor values; they should match.
- Test at known temperatures (ice water, room temperature, warm water) and verify the displayed values.
Accessible summary: The I2C LCD display reduces wiring (only 2 wires: SDA and SCL) compared to a parallel LCD (6+ wires). The LiquidCrystal_I2C library simplifies displaying text. The Arduino reads the thermistor, calculates temperature using the Steinhart-Hart equation, and shows it on the LCD. The I2C address (typically 0x27) must match the hardware jumper settings on the LCD module.
Worked Example 5: MQTT Publish/Subscribe Between Two Arduinos
Problem: Set up two Arduinos to communicate via MQTT: one publishes temperature, the other subscribes and lights an LED if temperature > 30°C.
Solution:
Hardware:
- Arduino Uno (×2)
- Breadboards, jumper wires
- USB cables for programming
- Computer with Arduino IDE and internet access
Network: Both Arduinos connect to the same Wi-Fi network. Use a public MQTT broker (e.g., broker.hivemq.com on port 1883) for testing.
Arduino 1 (Publisher) - Temperature sensor and MQTT publisher:
#include <WiFiN.h> // WiFi library (built-in on ESP8266/ESP32; use WiFi101 on MKR)
#include <PubSubClient.h> // PubSubClient library (install via Library Manager)
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* mqtt_server = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
// Set MQTT broker
client.setServer(mqtt_server, 1883);
}
void loop() {
// Ensure MQTT connection is maintained
if (!client.connected()) {
reconnect();
}
client.loop();
// Read temperature from DHT11
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Publish temperature to MQTT topic
String tempMsg = String(t, 1); // 1 decimal place
client.publish("home/temperature", tempMsg.c_str());
Serial.print("Published: "); Serial.println(tempMsg);
delay(5000); // Publish every 5 seconds
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ArduinoPublisher")) {
Serial.println("MQTT reconnected");
} else {
delay(5000);
}
}
}
Arduino 2 (Subscriber) - LED control based on temperature:
#include <WiFiN.h>
#include <PubSubClient.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* mqtt_server = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
#define LED_PIN 13 # Built-in LED on pin 13
void setup() {
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
Serial.println("WiFi connected");
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Check for MQTT messages on subscribed topic
if (client.subscribe("home/temperature")) {
Serial.println("Subscribed to home/temperature");
}
// Callback when a message arrives
client.setCallback([](char* topic, byte* payload, unsigned int length) {
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
float temp = message.toFloat();
Serial.print("Received: "); Serial.print(message);
// Turn on LED if temperature > 30°C
if (temp > 30.0) {
digitalWrite(LED_PIN, HIGH);
Serial.println(" - LED ON (temp > 30°C)");
} else {
digitalWrite(LED_PIN, LOW);
Serial.println(" - LED OFF");
}
});
}
Expected result: Arduino 1 publishes the temperature reading to home/temperature every 5 seconds. Arduino 2 subscribes to this topic and turns on the built-in LED (pin 13) when the temperature exceeds 30°C. The LED turns off when the temperature drops below 30°C. Both Arduinos print status to their Serial Monitors.
Verification:
- Upload Publisher code to Arduino 1; open Serial Monitor to see "Connected to WiFi" and "Published: 25.5" messages.
- Upload Subscriber code to Arduino 2; open Serial Monitor to see "Subscribed to home/temperature" and received messages.
- Trigger temperature changes (cover DHT11 with hand, blow warm air); observe LED turning on/off accordingly.
- Test network disconnection and reconnection; verify the
reconnect()function restores MQTT connectivity.
Accessible summary: Two Arduinos can communicate wirelessly via MQTT over Wi-Fi. One publishes sensor data (temperature) to a topic; the other subscribes and reacts (LED on/off based on threshold). The PubSubClient library handles MQTT connection, publishing, and subscription. A public broker (broker.hivemq.com) is suitable for testing; production systems should use private MQTT brokers (AWS IoT Core, Azure IoT Hub) with TLS encryption and authentication.
Worked Example 6: Raspberry Pi Sensor Data Logging to CSV
Problem: Log temperature and humidity readings from a DHT11 sensor to a CSV file on a Raspberry Pi.
Solution:
Hardware: Raspberry Pi 4, DHT11 sensor, breadboard, jumper wires, 5V power supply.
Wiring:
- DHT11 VCC → Pi 2 pin (5V)
- DHT11 GND → Pi 6 pin (GND)
- DHT11 Data → Pi GPIO 4 (pin 7) with 10 kΩ pull-up resistor to 5V
Python script (run as cron job or manually):
import time
import board
import adafruit_dht
import csv
import os
from datetime import datetime
# Initialize DHT device on GPIO 4
dht_device = adafruit_dht.dht.DHT11(board.D4)
CSV_FILE = "/home/pi/sensor_log.csv"
def read_sensor():
try:
# Read temperature and humidity
temperature = dht_device.temperature
humidity = dht_device.humidity
if temperature is None or humidity is None:
raise ValueError("Sensor returned None values")
return temperature, humidity
except Exception as e:
print(f"Error reading sensor: {e}")
return None, None
def log_data():
temp, hum = read_sensor()
if temp is not None and hum is not None:
# Prepare data row
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
row = [now, f"{temp:.1f}", f"{hum:.1f}"]
# Write to CSV (append mode, create if not exists)
file_exists = os.path.isfile(CSV_FILE)
with open(CSV_FILE, "a", newline="") as f:
writer = csv.writer(f)
if not file_exists:
writer.writerow(["Timestamp", "Temperature_C", "Humidity_%"]) # Header
writer.writerow(row)
print(f"Logged: {row}")
else:
print("Failed to read sensor data")
# Main loop: log every 30 seconds
if __name__ == "__main__":
while True:
log_data()
time.sleep(30) # Wait 30 seconds between readings
Expected result: The CSV file /home/pi/sensor_log.csv is created (if not existing) with a header row and data rows. Each row contains a timestamp, temperature in °C, and humidity in %. The script runs every 30 seconds, providing continuous logging. Example CSV content:
Timestamp,Temperature_C,Humidity_%
2026-01-15 10:00:00,23.5,45.2
2026-01-15 10:00:30,23.4,45.5
2026-01-15 10:01:00,23.6,45.1
Verification:
- Run the script manually; check that the CSV file is created/updated.
- Verify the CSV contains expected data (temperature between 0-50°C, humidity between 20-80%).
- Check for errors in the console (sensor read failures, file write errors).
- Ensure the script survives interruptions (try/except handles sensor errors; file closing is automatic with
withstatement).
Accessible summary: The Raspberry Pi logs DHT11 sensor readings to a CSV file for later analysis. The script uses the adafruit-circuitpython-dht library, reads temperature and humidity every 30 seconds, and appends data to a CSV file with a timestamp. The CSV can be opened in Excel, Google Sheets, or Python pandas for visualization (e.g., plotting temperature trends over time). Error handling ensures the script doesn't crash on sensor read failures.
Explanation (Unit 2 continued)
Unit 2 provides comprehensive coverage of sensors, actuators, and development board interfacing. The detailed sensor descriptions (position, motion, force, pressure, flow, acoustic, humidity, light, radiation, temperature, chemical, biosensor, camera) equip students with the knowledge to select appropriate sensors for specific applications. The actuator types (electrical, thermal, hydraulic, pneumatic, piezoelectric) and selection criteria ensure proper actuation in IoT systems. The development board sections (Arduino and Raspberry Pi) cover installation, Python integration, communication protocols (I2C, SPI, UART, 1-Wire), and power considerations. The worked examples demonstrate practical circuits and code for temperature sensing (thermistor with Steinhart-Hart equation), PIR motion detection, I2C LCD display, MQTT communication between Arduinos, and Raspberry Pi sensor data logging. These examples bridge the gap between theory and practice, enabling students to build functional IoT prototypes.
Unit 3: IoT Platform Design Methodology
Teaching hours: 6
Topics in outline order
- Case Study on IoT System for Weather Monitor
Explanation
-
Case Study on IoT System for Weather Monitor. This comprehensive case study illustrates the end-to-end IoT system design process from requirements specification to deployment and monitoring. The weather monitoring system is a classic IoT application that captures environmental data (temperature, humidity, pressure) and makes it accessible via a cloud dashboard.
System overview: The case study builds a complete IoT weather station that measures temperature, humidity, and atmospheric pressure. The system consists of sensors connected to a microcontroller, which transmits data over Wi-Fi to a cloud platform. The cloud platform stores the data and provides a web dashboard for real-time visualization, historical tracking, and alert configuration.
Sensors:
- DHT11 or DHT22 for temperature and humidity (most common, low cost, well-documented).
- BMP180 for atmospheric pressure (optional, provides additional weather data).
- BME280 for temperature, humidity, and pressure in a single package (more integrated, higher cost).
Microcontroller:
- Arduino Uno: Simple, well-documented, ideal for learning. No Wi-Fi natively; requires Ethernet shield or Wi-Fi module.
- ESP32: Integrated Wi-Fi and Bluetooth, more processing power, more GPIO pins, easier Wi-Fi setup. Ideal for production IoT projects.
- Raspberry Pi: Full computer running Linux, extensive connectivity (Wi-Fi, Ethernet, USB), suitable if local processing or other sensors are needed.
Data acquisition: Sensors are read at regular intervals (e.g., every 30 seconds). The DHT11 provides temperature and humidity every 1-2 seconds. The BMP180/BME280 provides pressure, temperature, and humidity with I2C interface. Data is formatted as JSON for easy transmission and parsing:
{"temperature": 24.5, "humidity": 60.2, "pressure": 1013.25}.Communication:
- Wi-Fi connection to local router. The microcontroller connects to the home/office Wi-Fi network using SSID and password. MQTT is used for publish/subscribe messaging.
- MQTT broker: The data is published to a topic (e.g.,
home/sensors/weather/temperature). Common brokers: Mosquitto (local), AWS IoT Core, Azure IoT Hub, Google Cloud IoT Hub, public broker (broker.hivemq.com). - Topic structure:
home/sensors/weather/temperature,home/sensors/weather/humidity,home/sensors/weather/pressure. Topic hierarchy enables granular subscriptions and filtering.
Cloud platform:
- AWS IoT Core: Device registration, certificate setup, MQTT topic mapping. Thing shadows represent current device state. Dashboard: AWS IoT Things Dashboard for real-time viewing. Integration with other AWS services (S3 for storage, Lambda for processing, CloudWatch for monitoring).
- Azure IoT Hub: Device provisioning, built-in IoT Hub explorer, message routing to Azure services (Storage, Event Hubs, Functions). Azure IoT Central is a SaaS solution for rapid IoT app development.
- Google Cloud IoT Core (now part of Cloud IoT Edge): Device management, integration with AI/ML APIs (Vision, Speech), dataflow into BigQuery for analytics.
Dashboard:
- AWS IoT Things Dashboard: Displays real-time readings, plots time-series graphs (temperature/humidity over time), supports custom widgets. Alerts can be configured (e.g., temperature > 30°C triggers notification via SNS).
- Azure IoT Central: Pre-built templates for weather monitoring. Drag-and-drop dashboard customization. Built-in rules and actions (send email, trigger webhook).
- Grafana: Open-source dashboard that can query data from InfluxDB, TimescaleDB, Prometheus. Highly customizable, supports many data sources. Great for self-hosted solutions.
Power:
- USB power: For prototyping and development.
- Battery: 2× AA batteries with holder for standalone operation. Battery life estimation: DHT11 + ESP32 active ~3-5 days; with deep sleep and hourly readings, 2-4 weeks.
- Solar: Small solar panel with LiPo battery charger for extended outdoor operation.
Lessons learned (from the case study):
- Power budgeting is critical for battery-operated devices. Sensors consume power only during readings; communication (Wi-Fi) is the biggest power consumer. Put the device into deep sleep between readings.
- Wi-Fi connection may drop and requires reconnection logic. Implement automatic reconnection in firmware.
- MQTT broker selection impacts latency and reliability. Public brokers are easy to start; private brokers (AWS IoT, Azure IoT) offer more control and security.
- Sensor calibration ensures accurate readings. Factory-calibrated sensors (BME280) are preferred; raw sensors (thermistor) require calibration curves.
- Dashboard design should show relevant data clearly. Avoid information overload; display key metrics (current temperature, min/max, trend arrow) and provide access to historical data.
Worked Example: Weather Monitor System Deployment
Problem: Deploy a weather monitoring system using ESP32, DHT22, and AWS IoT Core. The system reads sensor data every 60 seconds and publishes to AWS IoT Core. A Grafana dashboard displays the data.
Solution:
Step 1: Hardware setup
- ESP32 development board
- DHT22 temperature/humidity sensor
- Breadboard and jumper wires
- USB cable for power and programming
Wiring:
- DHT22 VCC → ESP32 5V
- DHT22 GND → ESP32 GND
- DHT22 DATA → ESP32 GPIO 4 (or any GPIO, with 10 kΩ pull-up resistor to 5V)
- The 10 kΩ pull-up resistor is essential for reliable DHT22 communication with ESP32.
Step 2: ESP32 firmware (Arduino IDE)
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
// DHT sensor
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// WiFi credentials
const char* ssid = "your_SSID";
const char* password = "your_password";
// MQTT broker
const char* mqtt broker = "broker.hivemq.com";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
// Sensor data
float temperature = 0;
float humidity = 0;
void setup() {
Serial.begin(115200);
dht.begin();
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
Serial.println("IP: " + WiFi.localIP());
// Set MQTT broker
client.setServer(mqtt_broker, mqtt_port);
}
void loop() {
// Ensure MQTT connection
if (!client.connected()) {
reconnect();
}
client.loop();
// Read sensor every 60 seconds
static unsigned long lastRead = 0;
if (millis() - lastRead >= 60000) {
lastRead = millis();
// Read temperature and humidity
float h = dht.readHumidity();
float t = dht.readTemperature(); // Celsius (use dht.readTemperature(true) for Fahrenheit)
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
temperature = t;
humidity = h;
// Publish to AWS IoT Core (or public broker)
String payload = "{\"temperature\":" + String(t, 1) +
",\"humidity\":" + String(h, 1) +
",\"timestamp\":" + String(millis()) + "}";
client.publish("home/weather/sensor", payload.c_str());
Serial.print("Published: "); Serial.println(payload);
}
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ESP32WeatherStation")) {
Serial.println("MQTT connected");
} else {
delay(5000);
}
}
}
Step 3: AWS IoT Core setup
- Create a thing: "weather-station" in the AWS IoT Core console.
- Attach a policy that allows MQTT publish/subscribe on the desired topics.
- Generate certificates and keys for the ESP32 (or use MQTT.fx for testing with public broker).
- Configure the ESP32 with the endpoint, thing name, and certificates (for production) or use a public broker for testing.
Step 4: Grafana dashboard setup
- Set up an InfluxDB or TimescaleDB database to store the MQTT data.
- Use MQTT Explorer or EMQX to bridge MQTT messages into the database.
- Create a Grafana dashboard with a time-series panel:
- Data source: InfluxDB
- Measurement:
weather_sensor - Field:
temperature,humidity - X-axis:
time - Y-axis:
value - Add thresholds, alerts, and annotations as needed.
Step 5: Expected results
- ESP32 publishes JSON messages to
home/weather/sensorevery 60 seconds. - MQTT bridge stores messages in InfluxDB.
- Grafana dashboard shows temperature and humidity trends over time.
- Alerts trigger when temperature > 30°C or humidity > 80%.
Step 6: Verification
- Check ESP32 Serial Monitor for "WiFi connected" and published messages.
- Use MQTT Explorer to verify messages arrive on the correct topic.
- Query InfluxDB:
SELECT * FROM "weather_sensor" WHERE time > now() - 1h; - Grafana dashboard displays live-updating charts.
Accessible summary: The weather monitoring case study demonstrates the full IoT design process: sensor selection, microcontroller firmware, wireless communication, cloud platform configuration, and dashboard visualization. The ESP32 provides integrated Wi-Fi for easy connectivity. AWS IoT Core offers scalable device management and security. Grafana provides interactive dashboards for data visualization. Key lessons include power budgeting (deep sleep between readings), reliable Wi-Fi reconnection, and sensor calibration for accuracy.
Unit 4: Data and Analytics for IoT
Teaching hours: 10
Topics in outline order
- An Introduction to Data Analytics for IoT
- Machine Learning
- Big Data Analytics Tools and Technology
- Edge Streaming Analytics
- Network Analytics
Explanation
-
An Introduction to Data Analytics for IoT. IoT generates massive data volumes from sensors deployed across physical environments. The five V's of IoT data define the analytical challenges:
- Volume: Millions/billions of sensors, each reading frequently (e.g., 1 reading/second × 10,000 sensors = 10,000 readings/second). Storing this volume requires scalable solutions.
- Velocity: Data arrives in real-time or near real-time. Latency requirements vary: some applications need sub-second response (industrial control), while others accept minutes-of-delay (environmental monitoring).
- Variety: Heterogeneous data types: numeric (temperature, humidity), textual (logs, events), visual (camera images, video), audio (voice commands, acoustic sensing), binary (firmware updates, configuration).
- Veracity: Data quality issues: sensor drift (gradual change in sensor accuracy), noise (random fluctuations), missing values (sensor malfunction, connectivity loss), outliers (extreme values from events). Data cleaning and imputation are essential.
- Value: The potential insights and business benefits derived from data. Value comes from predictive maintenance (reduce downtime), optimization (reduce resource waste), new business models (sell data, offer services), and improved decision-making.
Analytics types:
- Descriptive: What happened? Summaries, dashboards, historical trends. Example: "Average temperature over the last 24 hours."
- Diagnostic: Why did it happen? Root cause analysis, correlation. Example: "Temperature spiked because the HVAC system failed."
- Predictive: What will happen? Regression, classification, time-series forecasting. Example: "Temperature will rise to 35°C in the next hour based on current trends."
- Prescriptive: What should we do? Optimization, recommendation engines. Example: "Turn on the AC at 28°C to maintain comfort."
Data pipeline: Sensor → edge preprocessing → transmission (MQTT/HTTPS) → cloud storage (time-series DB like InfluxDB, PostgreSQL with TimescaleDB) → processing/analytics → visualization (Grafana, Tableau, PowerBI).
Common challenges: Data integration (different formats, protocols, schemas), data quality (cleaning, imputation, outlier detection), storage management (retention policies, compression, archiving), and real-time processing (low-latency requirements, stream processing).
-
Machine Learning. IoT + ML enables predictive maintenance, anomaly detection, and intelligent decision-making on edge or cloud.
Edge ML: Lightweight models on microcontrollers. TensorFlow Lite for MicroPython / TinyML models (< 100 KB). Example: Anomaly detection on vibration data for predictive maintenance on a motor. The model runs on the device (e.g., ESP32 with 512 KB RAM) and detects deviations from normal operation without sending data to the cloud.
Cloud ML: Scalable models on cloud platforms. AWS SageMaker, Azure ML, Google AI Platform. Example: Forecasting electricity demand from smart meter data using linear regression, decision trees, or neural networks.
Typical IoT ML tasks:
- Classification: Fault vs. normal operation from sensor data. Example: "Is this motor bearing failing? (Classify: normal, fault developing, fault imminent)."
- Regression: Remaining useful life prediction. Example: "The bearing will fail in 500 hours based on vibration trends."
- Time-series forecasting: Temperature prediction, demand forecasting. Example: "Next hour's temperature: 28°C; next day's electricity demand: 15 MWh."
- Anomaly detection: Abnormal machine behavior, fraud detection. Example: "Unusual vibration pattern indicates misalignment; raise alert."
Features: Sensor readings (temperature, vibration, voltage), derived features (statistics over windows: mean, standard deviation, minimum, maximum over last 5 minutes), and time features (hour, day of week, seasonality, holiday).
Model evaluation: Accuracy, precision, recall, F1-score (classification); RMSE, MAE, R² (regression). Cross-validation ensures model generalizability.
Example: Predicting motor bearing failure from vibration sensor data (accelerometer x/y/z axes) using a Random Forest classifier. The model is trained on labeled data (normal/fault) and achieves 95% accuracy on test data. Features include mean and std of x/y/z acceleration over 1-minute windows.
-
Big Data Analytics Tools and Technology. Popular frameworks for large-scale IoT data processing:
-
Apache Hadoop: Distributed storage (HDFS) and distributed processing (MapReduce). Good for batch processing of large datasets. Not suitable for real-time streaming.
-
Apache Spark: In-memory processing, much faster than Hadoop MapReduce. Supports Python (PyScola), Scala, Java, SQL. Structured Streaming for micro-batch and near real-time processing. Ideal for IoT data that needs faster than batch but doesn't require true low-latency.
-
Apache Kafka: Distributed streaming platform, high-throughput, fault-tolerant, topic-based. Acts as the messaging backbone for IoT data. Producers (sensors/devices) publish to Kafka topics; consumers (analytics, storage) subscribe. Guarantees order within a partition, supports replication for fault tolerance.
-
Apache Flink: True stream processing, event-time processing, exactly-once semantics. Lower latency than Spark Structured Streaming. Ideal for real-time anomaly detection, alert generation.
-
Time-series databases:
- InfluxDB: Popular, SQL-like query language (Flux), retention policies, continuous queries. Optimized for high-write throughput (millions of points/second). Supports downsampling and retention policies.
- TimescaleDB: PostgreSQL extension, hypertables, full SQL support. Leverages PostgreSQL's ecosystem (connections, tools, extensions). Good for relational + time-series data.
- Prometheus: Monitoring-focused, pull model (scrape metrics from endpoints), alerting (Alertmanager). Default storage; best for infrastructure monitoring, not general IoT data.
-
Stream processing:
- Apache Storm: Real-time computation, distributed, fault-tolerant. One of the first streaming frameworks; still used for simple topologies.
- Spark Structured Streaming: Micro-batch (default 1-second batch) and true streaming (continuous processing). Integrates with Spark SQL, MLlib.
- Kafka Streams: Java library, embedded in applications. Processes data from Kafka topics, supports windowing, joins, aggregations.
Example architecture: Sensors → MQTT → Kafka topics → Spark Structured Streaming → time-series DB (InfluxDB/TimescaleDB) → Grafana dashboard. This pipeline handles high-throughput sensor data, enables real-time analytics, and provides historical visualization.
-
-
Edge Streaming Analytics. Edge analytics processes data near the source (on the device or gateway) rather than sending all data to the cloud.
Benefits:
- Reduced latency: Real-time response (critical for industrial control, autonomous systems).
- Reduced bandwidth: Only send alerts/aggregated data; not raw sensor data. Saves costs on cellular/ satellite connections.
- Improved reliability: System functional without cloud connectivity. Edge device continues operating locally.
- Privacy: Sensitive data (camera images, audio) stays on-device; only metadata/alerts leave the device.
Techniques:
- Sliding window: Recent N readings (e.g., last 10 temperature readings); compute average, max, min over the window.
- Tumbling window: Non-overlapping fixed intervals (e.g., every 5 minutes); compute aggregate for each interval.
- Session window: Group events by user/device session (e.g., "active period" until 10 minutes of inactivity).
- Incremental aggregation: Running sum/average updated with each new reading (no need to recompute from scratch).
Edge ML models: TensorFlow Lite for MicroPython, ONNX Runtime, TinyML models (< 100 KB). A TinyML model for anomaly detection might be 20-50 KB, running on microcontrollers with 64 KB RAM.
Example: A gateway device processes sensor data from 50 IoT nodes. Instead of sending 50 temperature readings every minute (300 readings/minute), the gateway computes the average temperature every 5 minutes (12 readings/hour) and sends only the average (and max/min) to the cloud. If temperature exceeds 30°C, a local alarm triggers, and a high-resolution reading is sent.
-
Network Analytics. Network analytics monitors and optimizes IoT communication networks.
Key metrics:
- Throughput: Successful data deliveries per second. Measured in messages/sec or bytes/sec. Critical for high-frequency sensing (GPS, video).
- Latency: Time from sensor read to cloud receive. Measured in milliseconds/seconds. Critical for real-time control (should be < 100 ms for motor control, < 1 second for dashboard updates).
- Packet loss: Percentage of lost messages. Critical for reliable operation; > 5% may indicate network issues. QoS levels in MQTT help mitigate (QoS 1 = at least once, QoS 2 = exactly once).
- Jitter: Variation in latency. Important for real-time audio/video; jitter > 50 ms degrades quality.
- Connectivity: Percentage of online devices. Expected: 99%+ for critical deployments.
Protocols:
- MQTT (Message Queuing Telemetry Transport): Lightweight publish/subscribe, QoS 0 (at most once), QoS 1 (at least once), QoS 2 (exactly once). Header as small as 2 bytes. Good for unreliable networks, satellite links, cellular with poor coverage.
- CoAP (Constrained Application Representation): RESTful, UDP-based, small header (4 bytes). DNS-friendly. Supports observe/notify for resource monitoring. Good for very constrained devices (8-bit microcontrollers, limited power).
- HTTP/HTTPS: Widely supported, higher overhead (hundreds of bytes header). Good for occasional data upload, firmware updates, web-based device management.
- LoRaWAN: Class A (receive after transmit, ~2% duty cycle), Class B (scheduled receive windows), Class C (always listening). Adaptive data rate (ADR) adjusts transmission power and data rate per device. Good for wide-area IoT, low-power sensors.
Network optimization:
- Adaptive data rate (ADR): Network adjusts each device's transmission power and data rate based on link quality. Devices in good signal areas use higher data rate (more consumption, faster); devices in poor areas use lower data rate (less consumption, slower). Can reduce average power consumption by 50-80%.
- Mesh networking (Zigbee, Thread): Multi-hop routing improves reliability; if one node fails, messages reroute through other nodes. Self-healing network topology.
- SNMP (Simple Network Management Protocol): Monitor and alert on network status, device reachability, interface statistics. Standard for network management.
Example: A cellular IoT network with 1000 devices using NB-IoT. Without ADR, average device battery life is 2 years; with ADR, battery life extends to 5 years. Packet loss < 1% ensures reliable data delivery for environmental monitoring. Mesh networking (Zigbee) in a smart home with 50 devices provides redundancy; if one router fails, messages route through alternative paths.
Explanation (Unit 4 continued)
Unit 4 covers the critical domain of IoT data analytics, enabling students to transform raw sensor data into meaningful insights. The introduction to data analytics explains the five V's (volume, velocity, variety, veracity, value) and four analytics types (descriptive, diagnostic, predictive, prescriptive). Students learn the end-to-end data pipeline from sensor to visualization. The machine learning section covers edge and cloud ML, typical IoT tasks (classification, regression, time-series forecasting, anomaly detection), feature engineering, and model evaluation. The big data tools section introduces Hadoop, Spark, Kafka, Flink, and time-series databases (InfluxDB, TimescaleDB, Prometheus) for large-scale data processing. Edge streaming analytics demonstrates how to reduce latency and bandwidth by processing data locally. Network analytics covers key metrics (throughput, latency, packet loss, jitter) and protocol comparisons (MQTT, CoAP, HTTP, LoRaWAN) with optimization techniques (ADR, mesh networking, SNMP). The worked examples and practical code snippets prepare students to implement data pipelines, build ML models, and optimize IoT networks.
Unit 5: IoT Physical Servers and Cloud Offering
Teaching hours: 3
Topics in outline order
- Cloud storage models and Communication APIs of IoT Systems
Explanation
-
Cloud storage models and Communication APIs of IoT Systems. Cloud storage provides the backbone for IoT data persistence, analysis, and long-term retention. The choice of storage model depends on data type, access patterns, scalability requirements, and budget.
Cloud storage models:
- Object storage (AWS S3, Google Cloud Storage, Azure Blob Storage): Stores data as objects with metadata. Highly scalable (petabytes), durable (99.999999999% durability for S3), and suitable for unstructured data (sensor logs, images, audio, video). Pricing based on storage class: Standard (frequent access, $0.023/GB-month), Infrequent Access (less frequent, $0.0125/GB-month), Glacier (archive, $0.004/GB-month, retrieval time minutes-hours). Example: Store millions of temperature readings as JSON objects in S3.
- File storage (AWS EFS, Azure Files, Google Cloud NFS): Network-attached file system, mountable on instances. Suitable for shared access, legacy applications, and workloads requiring a file system interface. Pricing based on provisioned throughput and storage. Example: Mount EFS on EC2 instances to share sensor data across multiple servers.
- Database storage:
- Time-series DB (InfluxDB, TimescaleDB): Optimized for timestamped data, high-write throughput (millions of points/second), and range queries (last hour, last day). InfluxDB uses a purpose-built storage engine; TimescaleDB extends PostgreSQL with hypertables. Example: Store sensor data with
INSERT INTO sensor_readings (time, temperature, humidity) VALUES (now(), 23.5, 45.2). - Key-value store (DynamoDB, Redis): Simple device state, caching. DynamoDB offers on-demand or provisioned throughput; Redis is an in-memory data store for sub-millisecond latency. Example: Store current device status (
{"device_id": "ESP32-01", "status": "online"}). - Cloud-native relational (AWS RDS, Azure SQL): Structured business data, complex queries, joins. Good for relational data alongside IoT sensor data. Example: Store device metadata (device_id, location, firmware_version) in an RDS table.
- Time-series DB (InfluxDB, TimescaleDB): Optimized for timestamped data, high-write throughput (millions of points/second), and range queries (last hour, last day). InfluxDB uses a purpose-built storage engine; TimescaleDB extends PostgreSQL with hypertables. Example: Store sensor data with
Communication APIs:
- MQTT API: Publish/subscribe model.
client.publish(topic, payload)sends a message to a topic.client.subscribe(topic)receives messages on a topic. Used for real-time sensor data, event notification. QoS levels (0, 1, 2) provide different guarantee levels. Example:client.publish("home/temperature", "23.5"). - HTTP API: Standard REST operations.
GET(retrieve resource),POST(create resource),PUT(update resource),DELETE(remove resource). Widely supported across browsers, servers, clients. Higher overhead than MQTT due to HTTP headers. Example:GET /api/v1/devices/temperaturereturns current temperature. - CoAP API: RESTful over UDP.
GET,POST,PUT,DELETEoperations with minimal header (4 bytes). Supports observe/notify for resource monitoring (client observes a resource and receives notifications when it changes). DNS-friendly, good for constrained devices. Example:coap://lightsensor.local/valuereturns the current light level. - Thing shadow (AWS IoT Core): Represents the current state of a device.
client.shadow.update()updates the shadow;client.shadow.get()retrieves the current state. Useful for synchronizing device state with the cloud, even when the device is offline. Example: The shadow reports{"state": {"desired": {"led": "on"}, "reported": {"led": "on"}}}.
Example data flow: Sensor → ESP32 publishes
{"temp": 25}tohome/office/tempvia MQTT to AWS IoT Core → thing shadow updated → dashboard subscribed to shadow changes → user views current temperature on mobile app.API rate limits: Cloud providers impose per-second/minute limits. AWS IoT free tier: 1 M messages/day. Design with exponential backoff and queuing (e.g., if publish fails, retry after 1s, then 2s, 4s, 8s...). Use local buffering on the device (store readings when offline, send when connection restores).
Worked Example: Designing an IoT Data Storage Strategy
Problem: Design a storage strategy for a smart city air quality monitoring system with 50 sensor nodes, each reporting PM2.5, temperature, and humidity every 5 minutes. Data must be retained for 2 years for trend analysis.
Solution:
Requirements analysis:
- 50 sensors × 3 readings/ hour (every 5 min) × 24 hours × 365 days × 2 years = ~10.5 million readings.
- Data types: numeric (PM2.5, temperature, humidity), timestamps.
- Access patterns: ad-hoc queries (last hour, last day), trend analysis (monthly/yearly averages), real-time dashboard.
- Budget constraints: moderate; need cost-effective storage with query capabilities.
Storage model selection:
| Storage Option | Cost (2 years) | Write Throughput | Query Capabilities | Suitability |
|---|---|---|---|---|
| InfluxDB | ~$50-100 | Very high (point every 5 sec) | TSQL, range queries, aggregations | Excellent: Purpose-built for time-series; handles high write volume; built-in functions for time-based aggregations. |
| TimescaleDB | ~$100-200 | High (via PostgreSQL) | Full SQL, joins, complex analytics | Good: Leverages PostgreSQL ecosystem; supports relational data (device metadata) alongside time-series. |
| Amazon S3 | ~$20-50 | Very high | Limited (SELECT S3 object metadata, Athena queries) | Fair: Cost-effective for archival; query via Amazon Athena; not ideal for real-time or frequent ad-hoc queries. |
| Google Cloud Storage | ~$20-50 | Very high | Limited (same as S3) | Fair: Same as S3; integrated with BigQuery for analytics. |
Swipe to see all columns
Recommended: InfluxDB as the primary time-series database, with Amazon S3 as the long-term archive for raw sensor logs.
InfluxDB setup:
- Create an InfluxDB bucket (e.g.,
air_quality) with retention period 2 years. - Configure write API:
POST /api/v2/write?bucket=air_quality&org=myorg&token=MYTOKEN. - Write format:
sensor_id,temperature=23.5,humidity=45.2 1672531200(line protocol). - Query example:
from(bucket: "air_quality") |> range(start: -1h) |> filter(fn: (r) => r.sensor_id == "sensor-23") |> aggregateWindow(every: 1m, fn: mean, fn: max).
Example data flow: Sensors → MQTT → Kafka → InfluxDB → Grafana dashboard.
S3 archive strategy:
- Configure InfluxDB to export raw data to S3 daily/weekly.
- S3 bucket lifecycle: transition to Glacier after 365 days for cost-effective archival.
- Retrieve via Athena for occasional analysis:
SELECT * FROM air_quality_raw WHERE sensor_id = 'sensor-23' AND year = 2024;
Expected result: The system stores 10.5 million readings cost-effectively. InfluxDB enables real-time dashboards and ad-hoc queries. S3 provides cheap archival for the full 2-year history. The combined approach balances cost, performance, and retention requirements.
Verification:
- Write a sample point to InfluxDB and verify with
SELECT * FROM air_quality LIMIT 1; - Query the last hour's data:
from(bucket: "air_quality") |> range(start: -1h) - Check S3 bucket for archived objects after the lifecycle transition.
- Compare query response times between InfluxDB (seconds) and S3+Athena (minutes).
Accessible summary: For the smart city air quality system, InfluxDB is the recommended time-series database: it handles high write volumes (50 sensors × every 5 minutes), provides SQL-like queries and aggregations, and integrates with Grafana for dashboards. Amazon S3 serves as the cost-effective long-term archive. The data pipeline is: sensors → MQTT → Kafka → InfluxDB → Grafana, with daily/weekly exports to S3 for archival. This ensures real-time accessibility and long-term retention at moderate cost.
Unit 6: Securing IoT Systems
Teaching hours: 3
Topics in outline order
- IoT Security Challenges
- IoT System's Security Practices
Explanation
-
IoT Security Challenges. IoT devices introduce unique security challenges due to their constraints and deployment environments:
-
Device constraints: Limited computing power, memory, and battery life hinder implementation of strong security mechanisms. A typical ESP32 has 512 KB RAM and 4 MB flash; running TLS encryption may consume significant resources. Security features must be lightweight or hardware-accelerated.
-
Default credentials: Many devices ship with unchanged factory passwords (admin/admin, root/root). Botnets like Mirai scan the internet for devices with default credentials and compromise them en masse. Change default passwords immediately upon device deployment.
-
Unencrypted communication: Many IoT protocols (default MQTT without TLS, HTTP without HTTPS) transmit data in plaintext. Interceptors can read sensor data, inject false readings, or control devices. Always use TLS/SSL for communication (MQTT over TLS on port 8883, HTTPS for REST APIs).
-
Fragmented ecosystem: Diverse manufacturers, protocols, and update mechanisms create security gaps. A smart home may have devices from 10+ vendors, each with different security practices and update cycles. Standardization and integration layers are needed.
-
Lack of regular updates: Devices may never receive security patches. Some IoT devices have no mechanism for over-the-air (OTA) updates. Vendors may discontinue older models, leaving known vulnerabilities unpatched.
-
Network vulnerabilities: IoT devices expand the attack surface, often connected to insecure networks (public Wi-Fi, guest networks without segmentation). A compromised IoT device can be used as an entry point to other networked devices.
-
Physical tampering: Devices in accessible locations (outdoor, public) can be reset, modified, or extracted. An attacker can open a weather sensor, reset it to factory settings, or connect directly to the UART interface.
-
Botnet recruitment: Compromised IoT devices form botnets for DDoS attacks. The Mirai botnet (2016) exploited default credentials on cameras and DVRs, launching massive DDoS attacks that took down major websites (Twitter, Netflix, Reddit).
-
Data privacy: Continuous sensor collection (cameras, microphones, location) raises surveillance concerns. Smart speakers always listening, fitness trackers monitoring location, smart cameras in private spaces. Data minimization and anonymization are essential.
-
Firmware integrity: Unsigned or unverified firmware can be flashed, replacing legitimate firmware with malicious versions. Without firmware verification, an attacker can permanently compromise a device.
-
Industrial IoT (IIoT) risks: Compromised control systems can cause physical damage or safety incidents. A hacked industrial furnace controller could cause overheating; a compromised water treatment system could release contaminants.
Attack vectors:
- Botnets: Coordinated DDoS attacks (Mirai 2016 exploited default credentials on cameras/DVRs).
- Ransomware: Encrypt device functionality or data (e.g., smart lock ransomware, ransomware targeting IIoT PLCs).
- Man-in-the-middle: Intercept/modify unencrypted communications (e.g., ARP spoofing, rogue access point).
- Firmware flashing: Replace firmware with malicious version (via unsecured OTA update).
- Privacy invasion: Unauthorized access to cameras/microphones (e.g., hacked baby monitors, Ring doorbell breaches).
- Data exfiltration: Steal sensor data, credentials, or personal information (e.g., fitness app data leakage, health monitor data breach).
-
-
IoT System's Security Practices. Comprehensive security measures across device, network, data, and lifecycle layers:
Device-level security:
- Change default passwords to strong unique passwords (12+ characters, mixed case, numbers, symbols).
- Disable unused services (Telnet, SSH if not needed, default web server). Each open service is a potential entry point.
- Keep firmware updated (enable automatic updates if available; subscribe to vendor security notices). OTA (Over-the-Air) updates facilitate remote patching.
- Use hardware-based security (Trusted Platform Module TPM, secure enclave) where available. TPM provides hardware-rooted key storage, attestation, and secure boot.
- Secure boot: Ensures only signed firmware runs at startup; prevents rootkit installation.
Network-level security:
- Use TLS/SSL for all communications (MQTT over TLS on port 8883, HTTPS for REST APIs). TLS encrypts data in transit and provides server/client authentication.
- Network segmentation (VLAN or guest network for IoT, isolated from main PCs and servers). IoT devices should not share the same network as workstations, file servers, or critical infrastructure.
- Firewall rules (allow only necessary ports and IPs). Restrict inbound/outbound traffic to known endpoints (MQTT broker, cloud API endpoints).
- Intrusion detection (monitor for unusual traffic patterns). Analyze flow logs, detect unusual data volumes, failed login attempts, unusual connection patterns.
- VPN (Virtual Private Network) for remote access to IoT infrastructure. WireGuard, OpenVPN provide secure tunneling for administration.
Data-level security:
- Encrypt sensitive data at rest (AES-256 encryption, cloud storage encryption). Enable encryption on the storage service (S3 bucket encryption, DynamoDB encryption at rest).
- Encrypt data in transit (TLS, SSH, VPN). Never transmit sensitive sensor data (video, audio, location) in plaintext.
- Access control: Least privilege principle (devices/apps only access needed resources). Grant minimum permissions for the device to function.
- Authentication and authorization (certificates, tokens, OAuth 2.0). Use mutual TLS (mTLS) for device-to-cloud authentication. OAuth 2.0 for third-party app access.
- Privacy by design: Data minimization (collect only needed sensor data). Anonymization (remove personally identifiable information from sensor data). Consent management (user opts in/out of data collection).
Monitoring and response:
- Log security events (connection attempts, configuration changes, firmware updates). Centralized logging (ELK stack, Splunk) aids investigation.
- Intrusion detection systems (monitor for anomalous patterns). Rate of failed logins, unusual data transfers, unexpected device behavior.
- Incident response plan (steps if compromise detected). Isolate affected device, reset credentials, investigate logs, notify stakeholders, recover from backup.
Example security-hardened setup: ESP32 with MQTT over TLS, certificate-based authentication, unique per-device passwords, VLAN isolation, automatic firmware updates via OTA, and AWS IoT Core with thing shadows and thing groups for managed deployment.
Explanation (Unit 6 continued)
Unit 6 addresses the critical topic of IoT security, covering both challenges and practical mitigation strategies. The security challenges section highlights device constraints, default credentials, unencrypted communication, fragmented ecosystems, lack of updates, network vulnerabilities, physical tampering, botnet recruitment, data privacy, firmware integrity, and IIoT risks. The security practices section provides layered defense: device-level (change passwords, disable unused services, firmware updates, hardware security, TPM), network-level (TLS/SSL, segmentation, firewalls, IDS, VPN), data-level (AES-256 encryption, least privilege, authentication/authorization, privacy by design), and monitoring/response (logging, IDS, incident response plan). The example security-hardened setup demonstrates how to combine these practices into a coherent deployment using ESP32, MQTT over TLS, AWS IoT Core, and network segmentation. Understanding these security concepts is essential for protecting IoT deployments from evolving threats.
Key Terms (Comprehensive)
internet of things · IoT · things · connectivity · data · sensing · actuation · intelligence · heterogeneity · IoT ecosystem · perception layer · network layer · application layer · business layer · three-layer architecture · five-layer architecture · six-layer architecture · edge computing · fog computing · AWS IoT Core · Azure IoT Hub · Google Cloud IoT Core · MQTT · CoAP · HTTP · AMQP · LoRaWAN · Zigbee · Z-Wave · BLE · Bluetooth · LTE-M · NB-IoT · M2M · machine-to-machine · smart home · smart city · precision farming · industrial IoT · IIoT · wearable · wearable devices · wearable vital signs · firmware · over-the-air · OTA · botnet · Mirai · ransomware · man-in-the-middle · firmware flashing · data exfiltration · thing shadow · edge analytics · cloud analytics · time-series database · InfluxDB · TimescaleDB · Apache Hadoop · Apache Spark · Apache Kafka · Apache Flink · Stream processing · TensorFlow Lite · TinyML · Apache Storm · structured streaming · ThingSpeak · AWS IoT Core · Azure IoT Hub · Google Cloud IoT Core · DHT11 · DHT22 · BMP180 · BME280 · MQ-2 · MQ-135 · GPIO · Raspberry Pi · Arduino · pySerial · gpiozero · Adafruit CircuitPython · pigpio · I2C · SPI · UART · 1-Wire · ADR · adaptive data rate · mesh networking · SNMP · TLS · SSL · AES-256 · least privilege · OAuth 2.0 · data minimization · anonymization · consent management · logging · incident response
Key Terms (Comprehensive)
internet of things · IoT · things · connectivity · data · sensing · actuation · intelligence · heterogeneity · IoT ecosystem · perception layer · network layer · application layer · business layer · three-layer architecture · five-layer architecture · six-layer architecture · edge computing · fog computing · AWS IoT Core · Azure IoT Hub · Google Cloud IoT Core · MQTT · CoAP · HTTP · AMQP · LoRaWAN · Zigbee · Z-Wave · BLE · Bluetooth · LTE-M · NB-IoT · M2M · machine-to-machine · smart home · smart city · precision farming · industrial IoT · IIoT · wearable · wearable devices · wearable vital signs · firmware · over-the-air · OTA · botnet · Mirai · ransomware · man-in-the-middle · firmware flashing · data exfiltration · thing shadow · edge analytics · cloud analytics · time-series database · InfluxDB · TimescaleDB · Apache Hadoop · Apache Spark · Apache Kafka · Apache Flink · Stream processing · TensorFlow Lite · TinyML · Apache Storm · structured streaming · ThingSpeak · AWS IoT Core · Azure IoT Hub · Google Cloud IoT Core · DHT11 · DHT22 · BMP180 · BME280 · MQ-2 · MQ-135 · GPIO · Raspberry Pi · Arduino · pySerial · gpiozero · Adafruit CircuitPython · pigpio · I2C · SPI · UART · 1-Wire · ADR · adaptive data rate · mesh networking · SNMP · TLS · SSL · AES-256 · least privilege · OAuth 2.0 · data minimization · anonymization · consent management · logging · incident response
Detailed Practice Questions and Answer Keys
Question 1: Define IoT and explain its six key characteristics with an example for each.
Answer Key: See Unit 1, Worked Example 1 (Definition and Characteristics of IoT). The six characteristics are things, connectivity, data, sensing, actuation, and intelligence, with examples ranging from smart thermostats to cloud analytics.
Question 2: Compare the three-layer, five-layer, and six-layer IoT architecture models.
Answer Key: See Unit 1, Worked Example 2 (Comparing IoT Architecture Models). The comparison table shows layer additions: three-layer (perception, network, application), five-layer (adds middleware and business), six-layer (adds edge computing, security, analytics).
Question 3: Differentiate between M2M and IoT with a concrete example.
Answer Key: See Unit 1, Worked Example 3 (M2M vs IoT Comparison). M2M is point-to-point, proprietary, localized; IoT is internet-scale, standard protocols, cloud-integrated. Example: Industrial sensor → local PLC (M2M) vs. same sensor → cloud dashboard with ML analytics (IoT).
Question 4: Select appropriate sensors for a wearable vital signs monitoring system (heart rate, SpO2, temperature) with constraints: battery life > 1 week, cost < $10 per sensor, accuracy ±1°C for temperature, ±2 bpm for heart rate.
Answer Key: See the detailed answer in the guide under Question 4. The MAX30102 combines heart rate and SpO2 sensing via light absorption, while the DS18B20 provides accurate temperature via 1-Wire. Total cost ~$9, well within the $10 budget.
Question 5: Explain the difference between edge computing and fog computing in IoT contexts.
Answer Key:
- Edge computing: Processes data on the device or immediate gateway (milliseconds latency, very low bandwidth). Example: An ESP32 calculates average temperature locally and sends only the average to the cloud.
- Fog computing: Processes data on an intermediate node between edge and cloud (seconds latency, moderate bandwidth). Example: A local gateway server in a building pre-processes data from 100 floor sensors before sending summarized data to the cloud.
Question 6: Write a TinyML model inference code snippet for anomaly detection on sensor data.
Answer Key: See the TinyML code snippet in the guide under Question 5. Load a TFLite model, set sensor data as input, invoke inference, and check the anomaly score against a threshold.
Question 7: Compare MQTT and CoAP for IoT use cases.
Answer Key: See the MQTT vs CoAP comparison in the guide under Question 6. MQTT is publish/subscribe, TCP-based, QoS 0/1/2, header ~2 bytes; CoAP is RESTful, UDP-based, small header ~4 bytes, observe/notify support.
Question 8: Describe the data pipeline from sensor to dashboard in an IoT system.
Answer Key: See the data pipeline description in the guide under Question 7. Sensor → edge preprocessing → transmission (MQTT/HTTPS) → cloud storage (InfluxDB, S3) → processing/analytics (Spark, Flink, ML models) → visualization (Grafana, Tableau, PowerBI).
Question 9: What are the key security practices for an ESP32-based IoT deployment?
Answer Key: See the ESP32 security practices in the guide under Question 8. Use MQTT over TLS, unique per-device certificates, change default Wi-Fi/MQTT passwords, isolate IoT devices on a separate VLAN, implement OTA firmware updates with signed images, use AWS IoT Core thing shadows, enable AWS IoT Core logging and monitoring, configure firewall rules.
Question 10: Design a backup and recovery strategy for an IoT data pipeline.
Answer Key: See the backup and recovery strategy in the guide under Question 9. Use InfluxDB's built-in backup (export to line protocol, store in S3), configure S3 lifecycle to transition old data to Glacier, test recovery by restoring from S3 to a new InfluxDB instance, maintain separate copies of device configurations (certificates, keys, firmware versions) in a secure location.
Self-Check Questions (with Answers)
-
Question: What does IoT stand for and what does it refer to? Answer: IoT stands for Internet of Things. It refers to a network of physical devices, vehicles, home appliances, and other items embedded with electronics, software, sensors, actuators, and connectivity which enables these objects to collect and exchange data.
-
Question: What are the three IoT architecture models and how do they differ? Answer: The three architecture models are: three-layer (perception, network, application), five-layer (adds middleware and business), and six-layer (adds edge computing, security, analytics). Each additional layer increases complexity but improves scalability, interoperability, and functionality.
-
Question: Differentiate between M2M and IoT in three aspects. Answer: M2M is point-to-point, proprietary protocols, localized; IoT is internet-scale, standard protocols (MQTT, CoAP), cloud-integrated with data analytics and open ecosystem.
-
Question: What are the five V's of IoT data? Answer: The five V's are volume (massive data from many devices), velocity (real-time/near real-time streams), variety (heterogeneous data types: numeric, text, visual, audio), veracity (data quality issues: drift, noise, missing values), and value (business insights and benefits).
-
Question: Which sensor would you select for monitoring a temperature range of -20°C to +60°C with ±0.5°C accuracy, and why? Answer: An NTC thermistor suitable for -20°C to +60°C with ±0.3°C accuracy, or a DS18B20 1-Wire sensor (±0.5°C, -55°C to +125°C). The thermistor offers better accuracy in the specified range; the DS18B20 provides digital output and easier wiring via 1-Wire.
-
Question: What does edge computing enable in IoT systems? Answer: Edge computing enables data processing near the source, reducing latency (real-time response), reducing bandwidth (only send alerts/aggregated data), improving reliability (functional without connectivity), and enhancing privacy (sensitive data stays on-device).
-
Question: Compare InfluxDB and TimescaleDB for IoT time-series storage.
Answer Key: InfluxDB is purpose-built for high-write throughput (millions of points/second) with a SQL-like language (Flux) and time-focused functions. TimescaleDB is a PostgreSQL extension (hypertables) offering full SQL, joins, and relational data integration. Choose InfluxDB for pure time-series; choose TimescaleDB when combining time-series with relational data or leveraging PostgreSQL ecosystem.
-
Question: What does TLS/SSL provide for IoT communication? Answer: TLS/SSL encrypts data in transit and provides server/client authentication, preventing eavesdropping, tampering, and man-in-the-middle attacks on IoT communications.
-
Question: What are the three main IoT security practices at the device level? Answer: Change default passwords, disable unused services, and keep firmware updated (including OTA updates).
-
Question: Describe the principle of least privilege in the context of IoT security. Answer: The least privilege principle means devices and applications should only have access to the minimum resources necessary to function, limiting the impact of compromise if a device is breached.