Skip to content

Project 3.9.30: Smart Environmental Monitoring Mesh

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

Overview

The Pico packages environmental readings into broadcast packets so one node can be tested as part of a future multi-node mesh-style monitoring system.

Large monitoring systems fail when individual nodes do not produce a clear, repeatable packet structure before scaling to many devices.

A Pico 2 W prototype with an MQ-5 Liquefied Petroleum/Methane Gas Sensor, BME280, status LED, and UDP broadcast packet output on a local network.

Node identity, packet design, local broadcast testing, and honest mesh-ready wording.

Required Components

Raspberry Pi Pico 2 W
Raspberry Pi Pico 2 W
Gas sensor
Gas sensor
Breadboard
Breadboard
Jumper wires
Jumper wires
LED
LED
Resistor
Resistor
BME280
BME280
---

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
MQ-5 AO GPIO 26 ADC0 GPIO 26 / physical pin 31 LPG/methane gas proxy input
LED anode 220 ohm resistor to GPIO 16 GPIO 16 / physical pin 21 Heartbeat LED
---

Wiring Diagram

Circuit Diagram

  MQ-5 AO -> GPIO 26
  BME280 SDA -> GPIO 20
  BME280 SCL -> GPIO 21
  GPIO 16 -> LED via 220 ohm
  BME280 VCC -> 3.3V
  BME280 GND -> GND
  Wi-Fi uses the Pico 2 W radio and needs no extra wiring

Step-by-Step Assembly

  1. Connect the MQ-5 analog output to GPIO 26 through a safe 3.3V ADC path.
  2. Connect the BME280 to Pico 3.3V, GND, GPIO 20 (SDA), and GPIO 21 (SCL).
  3. Connect the LED to GPIO 16 through a 220 ohm resistor.
  4. Enter the Wi-Fi credentials and confirm the local network supports UDP broadcast testing.
  5. Warm up the gas sensor fully before evaluating packet contents.

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 gas and temperature readings separately so the packet fields are based on believable data.
  3. Test the output device: Blink the LED from a short script so the heartbeat output is confirmed.
  4. Test the decision logic: Check that each loop increments the sequence number and produces one packet.
  5. Run the full system: Run the full node and inspect the broadcast packets from a local listener on the same network.
  6. Validate the prototype: Discuss what routing, acknowledgment, and retry behavior would still be needed for a real mesh.
  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, I2C, Pin

NODE_ID = 'mesh_301_a'
GAS_PIN = 26
BME_SDA_PIN = 20
BME_SCL_PIN = 21
LED_PIN = 16
WIFI_SSID = 'YOUR_WIFI'
WIFI_PASSWORD = 'YOUR_PASSWORD'
BROADCAST_IP = '255.255.255.255'
BROADCAST_PORT = 5005
INTERVAL_S = 30

mq5 = ADC(GAS_PIN)
i2c = I2C(0, sda=Pin(BME_SDA_PIN), scl=Pin(BME_SCL_PIN), freq=400000)
climate = bme280.BME280(i2c=i2c)
led = Pin(LED_PIN, Pin.OUT)
sequence = 0


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 blink():
    led.on()
    time.sleep_ms(120)
    led.off()


def broadcast_packet(packet):
    wlan = connect_wifi()
    if wlan is None:
        return False
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    try:
        sock.sendto(json.dumps(packet).encode(), (BROADCAST_IP, BROADCAST_PORT))
        return True
    finally:
        sock.close()


print('Environmental mesh-ready node ready')

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

    sequence += 1
    packet = {
        'node_id': NODE_ID,
        'sequence': sequence,
        'uptime_s': time.ticks_ms() // 1000,
        'gas_raw': mq5.read_u16(),
        'temperature_c': temperature,
    }

    success = broadcast_packet(packet)
    print(packet, 'broadcast' if success else 'local_only')
    blink()
    time.sleep(INTERVAL_S)

How the Code Works

Code Section What It Does Why It Matters What to Modify During Testing
Packet schema Creates one repeatable packet structure with node identity and sequence number A multi-node system needs node traceability from the start Do not change packet fields casually once several nodes depend on the same schema
broadcast_packet Sends the packet over UDP broadcast on the local network This is a useful stepping stone toward multi-node communication Change the IP and port only if your lab listener uses different settings
Wi-Fi connection Connects the Pico W to the local lab network The communication path must be validated separately from the sensing logic Test the network with a simpler example if broadcast fails
Heartbeat LED Blinks every packet cycle to show that the node is still active Local heartbeat feedback is helpful before packet listeners are working If the LED blinks but packets are missing, debug the network layer next

Expected Result

The serial monitor reports the current reading or state clearly.

The hardware output responds when the decision logic changes state.

Subsystem behavior matches the thresholds, timing, or rules described in the document.

Validation Checks

  • Normal condition test: confirm the system stays in its safe or idle state under baseline conditions
  • Warning condition test: move the input close to the chosen threshold and confirm the transition is sensible
  • Critical condition test: trigger the strongest alert or control state and confirm the output response is correct
  • Calibration test: compare the sensor or timing against a known reference or repeated trial
  • Limitation test: deliberately create an awkward or noisy condition and note how the prototype behaves

Deployment and Limitations

  • This prototype is suitable for local pilots where sensor data must be logged or transmitted over short periods
  • Before deployment, network reliability, power backup, and endpoint security need attention
  • The system should keep useful local behavior even when communication fails

Troubleshooting

Problem Possible Cause Solution
No packets are received The Wi-Fi did not connect or UDP broadcast is blocked Confirm the credentials, check the local listener, and verify the network allows broadcast
Sequence numbers do not increase The loop is restarting unexpectedly Check for power instability or runtime errors in the serial output
Gas values look unstable The MQ-5 is still warming up Allow more warm-up time and compare several packets before trusting the value
Temperature stays at zero The BME280 read failed Test the BME280 separately and fix the wiring before debugging the packet layer