Skip to content

Project 3.1.33: Wi-fi Multi-node Iot Sensor Network

Advanced Embedded Systems Project Using Raspberry Pi Pico 2 W and MicroPython


Overview

The Pico acts as one environmental sensor node that labels its readings with a node ID and sends them to a local network endpoint.

Distributed monitoring becomes difficult when nodes have no identity, no communication fallback, and no way to validate what was really sent.

A Pico 2 W prototype node with a BME280, LDR, status LED, and Wi-Fi upload to a local test server.

Node identity, local buffering, honest prototype networking, and subsystem-by-subsystem validation.

Required Components

Raspberry Pi Pico 2 W
Raspberry Pi Pico 2 W
BME280
BME280
Breadboard
Breadboard
Jumper wires
Jumper wires
LED
LED
Resistor
Resistor
LDR
LDR

Circuit Connections

Component terminal Connect to Pico physical pin Notes
BME280 VCC 3.3V output Physical pin 36 Sensor power
BME280 GND GND Physical pin 38 Common ground
BME280 SDA GPIO 20 GPIO 20 / physical pin 26 I2C0 SDA
BME280 SCL GPIO 21 GPIO 21 / physical pin 27 I2C0 SCL
LDR divider midpoint GPIO 26 ADC0 GPIO 26 / physical pin 31 Ambient light input
LED anode 220 ohm resistor to GPIO 15 GPIO 15 / physical pin 20 Communication status LED

Wiring Diagram

Wi-fi Multi-node Iot Sensor Network wiring diagram

  BME280 SDA -> GPIO 20
  BME280 SCL -> GPIO 21
  BME280 VCC -> 3.3V
  BME280 GND -> GND
  LDR divider midpoint -> GPIO 26
  GPIO 15 -> 220 ohm resistor -> LED anode
  Wi-Fi uses the Pico 2 W radio and needs no extra wiring

Step-by-Step Assembly

  1. Connect the BME280 to Pico 3.3V, GND, GPIO 20 (SDA), and GPIO 21 (SCL).
  2. Build the LDR voltage divider and connect the midpoint to GPIO 26.
  3. Connect the LED to GPIO 15 through a 220 ohm resistor and connect the LED cathode to GND.
  4. Enter your 2.4 GHz Wi-Fi credentials and local server address in the code after local sensor testing is complete.
  5. Give each copy of this node a unique NODE_ID before expanding to a larger network.

Testing Individual Components

Before running the full project, test each subsystem separately. This makes it easier to find wiring, library, or logic problems before full integration.

  1. Hardware setup: Assemble the Pico, sensor, indicator, and load wiring exactly as shown in the connection table before applying power.
  2. Test the input sensor: Test the BME280 and LDR separately so each local reading is believable before any upload attempt.
  3. Test the output device: Blink the LED from a short script so the local status feedback is verified.
  4. Test the decision logic: Confirm that the node sequence number increases correctly and that the buffer file is used when upload fails.
  5. Run the full system: Run the full system with a local test server and compare the sent payload with the local serial output.
  6. Validate the prototype: Turn off the router or change the server address and confirm the node still stores its data locally.
  7. Save the project: Save the validated program on the Pico as main.py and keep a copy on the computer for future edits.

Full Project Code

After completing and checking the circuit connections, open Thonny IDE, copy and paste this code into a new file or upload the project file to the Raspberry Pi Pico 2 W, then run it from Thonny.

import bme280
import network
import socket
import time
import ujson as json
from machine import ADC, Pin

NODE_ID = 'node_282_a'
BME_SDA_PIN = 20
BME_SCL_PIN = 21
LIGHT_PIN = 26
LED_PIN = 15
WIFI_SSID = 'YOUR_WIFI'
WIFI_PASSWORD = 'YOUR_PASSWORD'
SERVER_HOST = '192.168.1.50'
SERVER_PORT = 8000
SERVER_PATH = '/nodes'
UPLOAD_INTERVAL_S = 60
BUFFER_FILE = 'node_282_buffer.jsonl'

i2c = I2C(0, sda=Pin(BME_SDA_PIN), scl=Pin(BME_SCL_PIN), freq=400000)
sensor = bme280.BME280(i2c=i2c)
light = ADC(LIGHT_PIN)
led = Pin(LED_PIN, Pin.OUT)
sequence = 0


def blink(times, duration_ms=120):
    for _ in range(times):
        led.on()
        time.sleep_ms(duration_ms)
        led.off()
        time.sleep_ms(duration_ms)


def connect_wifi(timeout_s=15):
    wlan = network.WLAN(network.STA_IF)
    if wlan.isconnected():
        return wlan

    wlan.active(True)
    wlan.connect(WIFI_SSID, WIFI_PASSWORD)
    for _ in range(timeout_s):
        if wlan.isconnected():
            return wlan
        time.sleep(1)
    return None


def append_buffer(record):
    try:
        with open(BUFFER_FILE, 'a') as handle:
            handle.write(json.dumps(record) + '\n')
    except OSError:
        print('Could not write local buffer')


def post_record(record):
    address = socket.getaddrinfo(SERVER_HOST, SERVER_PORT)[0][-1]
    body = json.dumps(record)
    request = 'POST {} HTTP/1.1\r\nHost: {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}'.format(
        SERVER_PATH,
        SERVER_HOST,
        len(body),
        body,
    )

    sock = socket.socket()
    try:
        sock.connect(address)
        sock.send(request.encode())
        sock.recv(128)
        return True
    finally:
        sock.close()


print('IoT node prototype ready')

while True:
    try:
        values = sensor.values
        temperature = float(values[0].replace('C', ''))
        pressure = float(values[1].replace('hPa', ''))
        humidity = float(values[2].replace('%', ''))
    except Exception:
        temperature = 0
        pressure = 0
        humidity = 0

    sequence += 1
    record = {
        'node_id': NODE_ID,
        'sequence': sequence,
        'uptime_s': time.ticks_ms() // 1000,
        'temperature_c': temperature,
        'pressure_hpa': pressure,
        'humidity_pct': humidity,
        'light_raw': light.read_u16(),
    }

    wlan = connect_wifi()
    if wlan is not None:
        try:
            sent = post_record(record)
        except OSError:
            sent = False
    else:
        sent = False

    if sent:
        blink(1)
        print('sent', record)
    else:
        append_buffer(record)
        blink(3)
        print('buffered', record)

    time.sleep(UPLOAD_INTERVAL_S)

How the Code Works

Code Section What It Does Why It Matters What to Modify During Testing
Sensor setup Builds one climate and light sensing node A network is only useful when each node has trustworthy local inputs Fix any sensor wiring issue before changing the network code
connect_wifi Connects the Pico W to the local wireless network Communication must be tested separately from sensing Adjust the timeout only after confirming the credentials are correct
post_record Sends one structured JSON payload to the local server A clear payload shape makes multi-node analysis possible later Change the host, port, and path to match your local endpoint
append_buffer Stores records locally when sending fails A good node shows failure honestly instead of silently losing data Inspect the buffer file after failures so you know whether recovery worked

Expected Result

The serial monitor prints one structured node record at each interval.

A short LED blink shows successful transmission, while three blinks show local buffering after failure.

The record includes a node ID and sequence number so repeated nodes can later be distinguished on the server.

Validation Checks

  • Normal condition test: confirm one record is created with sensible temperature, humidity, and light values
  • Communication validation: run a local HTTP test server and confirm the payload received by the server matches the serial output
  • Fallback test: disable the server or Wi-Fi and confirm that records are appended to the local buffer file
  • Calibration test: compare the BME280 reading with a known thermometer and observe how the LDR changes between bright and dim conditions
  • False trigger test: restart the board and confirm the node still sends one record per interval instead of flooding the server
  • Limitation test: discuss what would still be required before duplicating this node into a full network

Deployment and Limitations

  • This prototype is useful as a pilot node for classrooms, farm sheds, or local environmental studies
  • Before deployment, you would need a more reliable enclosure, network recovery strategy, and maintenance plan for the sensors
  • A real multi-node rollout would also need consistent node labeling, time synchronization, and secure endpoint design

Troubleshooting

Problem Possible Cause Solution
The node never connects to Wi-Fi The credentials or 2.4 GHz network are wrong Verify the SSID, password, and that the router allows 2.4 GHz clients
The server receives nothing The host, port, or path is wrong Test the same endpoint with a simple local client and then retry from the Pico
The buffer file stays empty during failures The file write is failing or post_record is still succeeding Force a bad server address and confirm the board can write a simple test file
Sensor values look unrealistic The BME280 or LDR divider is wired incorrectly Validate each input locally before using the network path