Project 5: IoT Sensor Hub (Pico W)

Build a Wi-Fi sensor hub that reads multiple sensors, publishes data over MQTT/HTTP, and survives real-world network failures.

Quick Reference

Attribute Value
Difficulty Level 2: Intermediate
Time Estimate 1-2 weeks
Main Programming Language C or MicroPython
Alternative Programming Languages C++
Coolness Level Level 3: Real IoT
Business Potential 4. The “Smart Home” Tier
Prerequisites GPIO, I2C/SPI basics, serial logging
Key Topics Wi-Fi stack, MQTT/HTTP, sensor sampling, power management

1. Learning Objectives

By completing this project, you will:

  1. Connect Pico W to Wi-Fi and manage reconnections.
  2. Read sensor data over I2C/SPI and calibrate values.
  3. Publish telemetry via MQTT or HTTP with retry logic.
  4. Implement a compact JSON payload schema.
  5. Design a watchdog and offline caching strategy.

2. All Theory Needed (Per-Concept Breakdown)

2.1 Pico W Wi-Fi Stack and Networking Basics

Fundamentals

The Pico W uses a CYW43439 Wi-Fi chip managed through a driver stack and lwIP. You must initialize the Wi-Fi firmware, connect to an access point, and manage IP configuration. Networking introduces latency, retries, and unpredictable failures, so your firmware must handle disconnects gracefully.

Deep Dive into the concept

On Pico W, the Wi-Fi chip runs its own firmware and is controlled by the RP2040 through a driver. The pico-sdk provides a Wi-Fi driver and integrates with lwIP to offer TCP/UDP sockets. The connection process includes scanning, association, authentication, and DHCP. Any step can fail, so your firmware must implement a retry policy and a backoff strategy. Once connected, you receive an IP address and can open TCP connections for HTTP or MQTT. lwIP uses callbacks or polling; you must call its service functions regularly to keep the stack alive. That means your main loop must avoid long blocking operations. Wi-Fi consumes significant power compared to bare-metal GPIO projects, so you should manage connection intervals or use periodic wake-ups. In this project, the hub can reconnect if the AP goes down and should buffer data locally until connectivity returns.

How this fits on projects

Networking fundamentals enable §3.2 requirements and §5.10 Phase 2 telemetry.

Definitions & key terms

  • DHCP -> automatic IP address assignment
  • lwIP -> lightweight TCP/IP stack
  • SSID -> Wi-Fi network name
  • Backoff -> wait strategy between retries

Mental model diagram (ASCII)

RP2040 -> Wi-Fi driver -> CYW43439 -> Access Point -> Internet

How it works (step-by-step)

  1. Initialize Wi-Fi firmware.
  2. Connect to SSID with credentials.
  3. Obtain IP via DHCP.
  4. Open TCP connection for MQTT/HTTP.

Minimal concrete example

cyw43_arch_init();
cyw43_arch_wifi_connect_timeout_ms(ssid, pass, CYW43_AUTH_WPA2, 30000);

Common misconceptions

  • “Wi-Fi is instant” -> association and DHCP take time.
  • “Once connected, it’s stable” -> real networks drop packets frequently.

Check-your-understanding questions

  1. Why must you service lwIP regularly?
  2. What happens if DHCP fails?
  3. Why use backoff when reconnecting?

Check-your-understanding answers

  1. To process network events and keep sockets alive.
  2. You have no IP address; network traffic fails.
  3. To avoid rapid retry loops and AP throttling.

Real-world applications

  • Smart home sensors, telemetry nodes, OTA updates.

Where you’ll apply it

References

  • Pico W Wi-Fi driver docs
  • lwIP documentation

Key insights

Networking makes firmware nondeterministic unless you design for failure and retries.

Summary

Wi-Fi on Pico W is a stack of drivers and lwIP that must be serviced and monitored.

Homework/Exercises to practice the concept

  1. Implement a reconnect loop with exponential backoff.
  2. Log connection time and DHCP latency over 10 boots.

Solutions to the homework/exercises

  1. Backoff doubles delay: 1s, 2s, 4s, 8s.
  2. Typical DHCP is 1-3 seconds on home networks.

2.2 Telemetry Protocols: MQTT vs HTTP

Fundamentals

IoT devices often publish data via MQTT (lightweight pub/sub) or HTTP (request/response). MQTT is efficient and built for unreliable networks; HTTP is simpler but more verbose. Choosing the protocol affects bandwidth, power, and reliability.

Deep Dive into the concept

MQTT uses a broker that routes messages by topics. Clients connect, publish data, and can set QoS levels. QoS 0 is “fire and forget,” QoS 1 ensures at-least-once delivery, and QoS 2 ensures exactly-once but with more overhead. For sensor hubs, QoS 1 is often a good balance. HTTP is stateless: you send a POST with JSON and wait for a response. It is simpler to debug but uses more overhead (headers, TLS). On constrained devices, MQTT is often more efficient. However, HTTP might be easier if you are pushing data to a REST API. This project should include both options or at least a clear choice with documented reasoning. You also need to design a retry policy and decide whether to buffer data locally when the network is down.

How this fits on projects

Telemetry design is part of §3.2 requirements and §3.5 data schema.

Definitions & key terms

  • MQTT broker -> server routing messages by topic
  • QoS -> quality of service for delivery guarantees
  • HTTP POST -> sending data to a server endpoint

Mental model diagram (ASCII)

Sensors -> JSON -> MQTT/HTTP -> Server -> Dashboard

How it works (step-by-step)

  1. Serialize sensor data to JSON.
  2. Connect to broker or server.
  3. Publish (MQTT) or POST (HTTP).
  4. Handle success or retry on failure.

Minimal concrete example

{"temp_c": 23.4, "humidity": 41.2, "ts": 1735689600}

Common misconceptions

  • “MQTT is always better” -> HTTP may fit your backend better.
  • “QoS 2 is safest” -> it adds latency and complexity.

Check-your-understanding questions

  1. What does QoS 1 guarantee?
  2. Why is HTTP more bandwidth heavy?
  3. When would you choose MQTT over HTTP?

Check-your-understanding answers

  1. At-least-once delivery; duplicates are possible.
  2. Headers and stateless requests add overhead.
  3. When you need lightweight, continuous telemetry or pub/sub.

Real-world applications

  • Smart home sensors, fleet telemetry, industrial monitoring.

Where you’ll apply it

References

  • MQTT 3.1.1 spec
  • REST API design guides

Key insights

Protocol choice shapes bandwidth, reliability, and backend integration.

Summary

MQTT is efficient for telemetry; HTTP is simple and ubiquitous.

Homework/Exercises to practice the concept

  1. Measure payload size for MQTT vs HTTP for the same JSON.
  2. Implement a retry loop with a max queue depth of 10.

Solutions to the homework/exercises

  1. MQTT payload is only the JSON; HTTP includes headers (~300 bytes).
  2. When queue full, drop oldest data and log a warning.

2.3 Sensor Sampling, Calibration, and Power Budget

Fundamentals

Sensors rarely output perfect values. You must sample at a suitable rate, apply calibration, and convert raw counts into physical units. Power consumption matters in Wi-Fi devices; sensors and radio can dominate the power budget.

Deep Dive into the concept

Sampling too fast wastes power and generates unnecessary data; too slow misses events. Choose a sampling interval based on the physical process (temperature changes slowly, motion changes quickly). Calibration involves offsets and scaling. For example, a temperature sensor might require an offset correction, and a humidity sensor might need a slope adjustment. For analog sensors, you may need to filter noise. Power budgeting requires understanding duty cycle: if Wi-Fi transmission takes 200 ms and you send every 10 seconds, your radio is only active 2% of the time, which saves energy. You can also put sensors or the MCU into low-power states between samples. In this project, you should measure the current draw during idle, sampling, and transmission and document it. Even if you power via USB, designing with power efficiency ensures reliability.

How this fits on projects

Sampling and calibration affect §3.2 requirements and §3.7 demo accuracy.

Definitions & key terms

  • Calibration -> mapping raw sensor data to accurate units
  • Duty cycle -> percentage of time a subsystem is active
  • Power budget -> total average current draw

Mental model diagram (ASCII)

Sample -> Calibrate -> Filter -> Package -> Transmit -> Sleep

How it works (step-by-step)

  1. Read sensor raw values.
  2. Apply calibration constants.
  3. Filter noise if needed.
  4. Package into JSON and transmit.

Minimal concrete example

float temp_c = raw * slope + offset;

Common misconceptions

  • “Faster sampling is always better” -> it wastes power and bandwidth.
  • “Calibration isn’t necessary” -> sensor offsets can be significant.

Check-your-understanding questions

  1. Why is duty cycle important for Wi-Fi power?
  2. How do you decide a sampling interval?
  3. What is the impact of calibration on long-term accuracy?

Check-your-understanding answers

  1. Wi-Fi peaks are high; reducing active time lowers average power.
  2. Match it to the dynamics of the physical phenomenon.
  3. It corrects offsets and scale errors that accumulate over time.

Real-world applications

  • Battery-powered sensors, environmental monitors, wearables.

Where you’ll apply it

References

  • Sensor datasheets for calibration guidance
  • “Making Embedded Systems” Ch. 8

Key insights

Sensor accuracy is as much about calibration and sampling strategy as hardware.

Summary

Choose sampling intervals wisely, calibrate data, and track power impact.

Homework/Exercises to practice the concept

  1. Compute average current if Wi-Fi draws 120 mA for 0.2 s every 10 s.
  2. Create a 2-point calibration curve for a temperature sensor.

Solutions to the homework/exercises

  1. Average current = 120 mA * 0.02 = 2.4 mA plus baseline.
  2. Use known temperature points to solve for slope and offset.

3. Project Specification

3.1 What You Will Build

A Pico W sensor hub that reads temperature and humidity (and at least one more sensor), packages the data into JSON, and publishes to an MQTT broker or HTTP endpoint.

3.2 Functional Requirements

  1. Wi-Fi connectivity: connect and reconnect to SSID.
  2. Sensor sampling: read at least two sensors.
  3. Telemetry: publish JSON via MQTT or HTTP.
  4. Error handling: retry on network failure.
  5. Local status: LED or serial log for health.

3.3 Non-Functional Requirements

  • Reliability: reconnect within 30 seconds of network loss.
  • Performance: publish every 10 seconds without blocking.
  • Usability: clear logs and JSON schema.

3.4 Example Usage / Output

[WIFI] connected ip=192.168.1.42
[SENSOR] temp=23.4C hum=41.2%
[MQTT] publish topic=home/pico/sensor ok

3.5 Data Formats / Schemas / Protocols

{
  "device_id": "pico-hub-01",
  "ts": 1735689600,
  "temp_c": 23.4,
  "humidity": 41.2,
  "light_lux": 120
}

3.6 Edge Cases

  • Wi-Fi down -> queue data and retry.
  • Sensor read fails -> send error flag and last known value.
  • MQTT broker unreachable -> fallback to HTTP or local log.

3.7 Real World Outcome

Your hub reliably publishes data and recovers from network interruptions.

3.7.1 How to Run (Copy/Paste)

cmake .. && make -j4
picotool load -f pico_w_hub.uf2
minicom -b 115200 -o -D /dev/ttyACM0

3.7.2 Golden Path Demo (Deterministic)

  • Use a fixed JSON schema and publish every 10 seconds.
  • Verify three consecutive messages on the broker.

3.7.3 Failure Demo (Bad Input)

  • Scenario: wrong Wi-Fi password.
  • Expected result: retries with backoff and logs [ERROR] auth failed.

3.7.4 If API: example request/response

POST /ingest
200 OK
{"status":"ok"}

4. Solution Architecture

4.1 High-Level Design

Sensors -> Sampling -> JSON -> MQTT/HTTP -> Network -> Server
                      ^
                   Retry/Queue

4.2 Key Components

| Component | Responsibility | Key Decisions | |———–|—————-|—————| | Wi-Fi Manager | Connect + reconnect | Exponential backoff | | Sensor Driver | Read and calibrate | I2C/SPI per sensor | | Telemetry | Publish JSON | MQTT QoS1 | | Queue | Buffer offline data | Ring buffer in RAM | | Logger | Diagnostics | Serial + LED |

4.3 Data Structures (No Full Code)

typedef struct {
  float temp_c;
  float humidity;
  float light_lux;
  uint32_t ts;
} sensor_sample_t;

4.4 Algorithm Overview

Key Algorithm: Sample/Publish Loop

  1. Read sensors and calibrate.
  2. Serialize to JSON.
  3. If Wi-Fi connected, publish; else queue.
  4. Retry queued data when online.

Complexity Analysis:

  • Time: O(1) per sample
  • Space: O(N) for queued samples

5. Implementation Guide

5.1 Development Environment Setup

# Pico SDK + Wi-Fi
export PICO_SDK_PATH=/path/to/pico-sdk

5.2 Project Structure

iot-hub/
├── firmware/
│   ├── main.c
│   ├── wifi.c
│   ├── sensors.c
│   └── telemetry.c
└── README.md

5.3 The Core Question You’re Answering

“How do you build a reliable Wi-Fi sensor node that survives real network failures?”

5.4 Concepts You Must Understand First

  1. Wi-Fi connection and lwIP servicing
  2. MQTT/HTTP telemetry trade-offs
  3. Sensor calibration and power budgeting

5.5 Questions to Guide Your Design

  1. How will you store data when offline?
  2. How often will you sample and publish?
  3. What QoS level is appropriate?

5.6 Thinking Exercise

Estimate how long it takes to reconnect to Wi-Fi after a power loss.

5.7 The Interview Questions They’ll Ask

  1. How do you handle Wi-Fi reconnection in firmware?
  2. What is MQTT QoS and why choose QoS 1?
  3. How do you design for sensor calibration?

5.8 Hints in Layers

Hint 1: Start with Wi-Fi connect and a simple HTTP POST. Hint 2: Add a single sensor and JSON payload. Hint 3: Add MQTT and retries. Hint 4: Add offline queue and backoff.

5.9 Books That Will Help

| Topic | Book | Chapter | |——-|——|———| | Embedded design | “Making Embedded Systems” | Ch. 8-10 | | Networking basics | “TCP/IP Illustrated” | Vol. 1, Ch. 1-3 | | IoT patterns | “Designing Connected Products” | Ch. 6 |

5.10 Implementation Phases

Phase 1: Foundation (2-3 days)

  • Connect to Wi-Fi and log IP.
  • Read a single sensor. Checkpoint: logs show valid readings.

Phase 2: Core Functionality (4-6 days)

  • Implement JSON telemetry via MQTT/HTTP.
  • Add retry logic. Checkpoint: broker receives messages.

Phase 3: Resilience (3-5 days)

  • Add offline queue and backoff.
  • Add watchdog and error logs. Checkpoint: device recovers after router reset.

5.11 Key Implementation Decisions

| Decision | Options | Recommendation | Rationale | |———-|———|—————-|———–| | Protocol | MQTT vs HTTP | MQTT | Efficient for telemetry | | Retry | Fixed vs exponential | Exponential | Reduces network stress | | Queue | RAM vs flash | RAM for MVP | Simpler; flash optional |


6. Testing Strategy

6.1 Test Categories

| Category | Purpose | Examples | |———-|———|———-| | Unit Tests | JSON formatting | Known sample to JSON string | | Integration Tests | Wi-Fi + MQTT | Publish to local broker | | Edge Case Tests | Network loss | Router power cycle |

6.2 Critical Test Cases

  1. Normal publish: 3 consecutive messages arrive.
  2. Wi-Fi drop: reconnect within 30 seconds.
  3. Broker down: queue fills and logs warnings.

6.3 Test Data

Sample payload: {"temp_c":23.4,"humidity":41.2}

7. Common Pitfalls & Debugging

7.1 Frequent Mistakes

| Pitfall | Symptom | Solution | |———|———|———-| | Blocking network calls | Device freezes | Use timeouts and non-blocking loops | | JSON errors | Server rejects payload | Validate schema locally | | Power dips | Random resets | Add decoupling and stable supply |

7.2 Debugging Strategies

  • Log Wi-Fi state transitions.
  • Use a local MQTT broker for testing.

7.3 Performance Traps

  • Publishing too frequently increases power and network load.

8. Extensions & Challenges

8.1 Beginner Extensions

  • Add a status LED for Wi-Fi connectivity.
  • Add a simple web dashboard.

8.2 Intermediate Extensions

  • Add TLS support for secure MQTT.
  • Add sensor auto-discovery on I2C.

8.3 Advanced Extensions

  • Implement OTA firmware updates.
  • Store offline data in flash with wear leveling.

9. Real-World Connections

9.1 Industry Applications

  • Smart home: environmental sensors.
  • Industrial monitoring: remote telemetry nodes.
  • Home Assistant MQTT integrations
  • pico-examples Wi-Fi demos

9.3 Interview Relevance

  • IoT reliability and network failure handling are common topics.

10. Resources

10.1 Essential Reading

  • Pico W networking docs
  • MQTT specification

10.2 Video Resources

  • MQTT and IoT fundamentals courses

10.3 Tools & Documentation

  • mosquitto broker and clients
  • lwIP documentation

11. Self-Assessment Checklist

11.1 Understanding

  • I can explain how Pico W connects to Wi-Fi.
  • I can compare MQTT and HTTP for telemetry.
  • I can calibrate sensor data.

11.2 Implementation

  • Hub reconnects after Wi-Fi loss.
  • JSON payload matches schema.
  • Telemetry publishes at fixed interval.

11.3 Growth

  • I can add a new sensor easily.
  • I can explain retry and backoff strategy.

12. Submission / Completion Criteria

Minimum Viable Completion:

  • Wi-Fi connection and one sensor reading published.

Full Completion:

  • Multiple sensors + robust reconnect + JSON schema.

Excellence (Going Above & Beyond):

  • TLS + OTA updates + persistent queue.

13. Additional Content Rules

13.1 Determinism

Use fixed publish interval (e.g., 10 s) and fixed JSON schema. Log timestamps in UTC.

13.2 Outcome Completeness

  • Success demo: §3.7.2
  • Failure demo: §3.7.3
  • Error JSON shape: { "error": { "code": "NETWORK", "message": "..." } }
  • CLI exit codes: host test client returns 0 success, 2 connection failure, 4 JSON validation error.

13.3 Cross-Linking

Concept links in §2.x and related projects in §10.4.

13.4 No Placeholder Text

All sections are fully specified for this project.