Skip to content

Project 3.9.48: Smart Sanitation Global Prototype

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

Overview

The Pico creates a standardized sanitation record and local status score that could be replicated in many locations, while keeping the build honest and local-first.

Global-prototype claims are misleading when the local sensing node is not clearly defined, validated, or reproducible on its own.

A Pico 2 W prototype with a PIR sensor, MQ-5 Liquefied Petroleum/Methane Gas Sensor, BME280, status LED, local JSON-lines log, and optional Wi-Fi upload.

Standardized local records, reproducible prototype structure, and honest global-prototype framing.

Required Components

Raspberry Pi Pico 2 W
Raspberry Pi Pico 2 W
Gas sensor
Gas sensor
Breadboard
Breadboard
Jumper wires
Jumper wires
PIR Sensor
PIR Sensor
LED
LED
Resistor
Resistor
BME Sensor
BME Sensor
---

Circuit Connections

Component terminal Connect to Pico physical pin Notes
PIR OUT GPIO 14 GPIO 14 / physical pin 19 Occupancy input
MQ-5 AO GPIO 26 ADC0 GPIO 26 / physical pin 31 LPG/methane gas proxy input
BME280 SDA GPIO 20 GPIO 20 / physical pin 26 I2C0 SDA
BME280 SCL GPIO 21 GPIO 21 / physical pin 27 I2C0 SCL
LED anode 220 ohm resistor to GPIO 16 GPIO 16 / physical pin 21 Activity LED
---

Wiring Diagram

Circuit Diagram

PIR OUT -> GPIO 14
MQ-5 AO -> GPIO 26
BME280 SDA -> GPIO 20
BME280 SCL -> GPIO 21
GPIO 16 -> 220 ohm resistor -> LED anode
Common GND -> PIR, MQ-5, BME280, and LED
BME280 VCC -> 3.3V
BME280 GND -> GND

Diagram Placeholder [Insert wiring diagram or breadboard image here]


Step-by-Step Assembly

  1. Connect the PIR output to GPIO 14 and allow it to warm up before trusting occupancy values.
  2. Connect the MQ-5 analog output to GPIO 26 through a safe ADC path.
  3. Connect the BME280 to Pico 3.3V, GND, GPIO 20 (SDA), and GPIO 21 (SCL).
  4. Wire the LED to GPIO 16 through a 220 ohm resistor and connect the LED cathode to ground.
  5. Enter Wi-Fi and endpoint details only after the standardized local record loop is working correctly.

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 PIR, MQ-5, and BME280 separately so the prototype record is built from trusted inputs.
  3. Test the output device: Blink the LED and test local file writing before enabling upload.
  4. Test the decision logic: Create occupancy and odor changes and confirm the standardized score changes in an explainable way.
  5. Run the full system: Run the full prototype and compare local-only behavior with optional upload behavior.
  6. Validate the prototype: Discuss what parts of the node design could stay standard globally and what parts would need local adaptation.
  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.

Upload and run this code after the individual tests work correctly.

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

PIR_PIN = 14
GAS_PIN = 26
BME_SDA_PIN = 20
BME_SCL_PIN = 21
LED_PIN = 16
LOG_FILE = 'global_proto_350.jsonl'
UPLOAD_ENABLED = False
WIFI_SSID = 'YOUR_WIFI'
WIFI_PASSWORD = 'YOUR_PASSWORD'
SERVER_HOST = '192.168.1.50'
SERVER_PORT = 8000
SERVER_PATH = '/sanitation_proto'
ODOR_WARN = 18000
ODOR_HIGH = 28000

pir = Pin(PIR_PIN, Pin.IN, Pin.PULL_DOWN)
gas = 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)


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_record(record):
    try:
        with open(LOG_FILE, 'a') as handle:
            handle.write(json.dumps(record) + '\n')
    except OSError:
        print('Could not write local record')


def upload_record(record):
    if not UPLOAD_ENABLED:
        return False
    wlan = connect_wifi()
    if wlan is None:
        return False
    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('Smart sanitation global prototype ready')

while True:
    occupancy = pir.value()
    odor_raw = gas.read_u16()
    try:
        values = climate.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

    score = 0
    if occupancy == 1:
        score += 1
    if odor_raw >= ODOR_WARN:
        score += 2
    if odor_raw >= ODOR_HIGH:
        score += 2
    if temperature >= 32:
        score += 1
    if humidity >= 80:
        score += 1

    if score >= 5:
        status = 'CRITICAL'
    elif score >= 2:
        status = 'WATCH'
    else:
        status = 'NORMAL'

    record = {
        'schema_version': 1,
        'prototype_id': 'sanitation_350',
        'uptime_s': time.ticks_ms() // 1000,
        'occupancy_active': occupancy,
        'odor_raw': odor_raw,
        'temperature_c': temperature,
        'humidity_pct': humidity,
        'sanitation_score': score,
        'status': status,
    }

    append_record(record)
    uploaded = upload_record(record)
    led.value(1)
    time.sleep_ms(120)
    led.value(0)
    print(record, 'uploaded' if uploaded else 'local_only')
    time.sleep(15)

How the Code Works

Code Section What It Does Why It Matters What to Modify During Testing
Standardized local schema Creates one documented prototype record with a schema version and prototype ID. A replicable prototype begins with a clear and repeatable local record format. Update the schema only when you also update the documentation and validation plan.
Sanitation score Combines occupancy, odor, and climate into one prototype score. The score helps users compare conditions quickly while keeping the contributing fields visible. Adjust the score weights only after repeated tests in one local setting.
Local-first replication path Stores each record locally and optionally uploads it for integration testing. This keeps the prototype useful even before any larger system exists. Enable upload only after the local records are stable and understandable.

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
The score is always high The odor thresholds are too low or the MQ-5 is still warming up Allow more warm-up time and raise the thresholds after observing the local baseline.
Climate values stay at zero The BME280 read failed Test the BME280 separately and shorten the I2C wires if needed.
Uploads always fail The Wi-Fi details or endpoint settings are wrong Check UPLOAD_ENABLED, the credentials, and the server host, port, and path.
The local file stays empty Local file writing failed Test a short text write and confirm the Pico file system is writable.