Skip to content

Project 3.9.43: Smart Sanitation Analytics Cloud

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

Overview

The Pico collects sanitation readings, calculates simple trend metrics locally, and can optionally upload those records to a local analytics endpoint.

Cloud analytics claims are not believable when the device cannot show how the records were created or what happens when the network fails.

A Pico 2 W prototype with a PIR sensor, MQ-135 gas sensor, status LED, local JSON-lines log, and optional Wi-Fi upload.

Local analytics-ready records, occupancy and odor trend logic, and honest cloud-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
LDR
PIR Sensor
---

Circuit Connections

Component terminal Connect to Pico physical pin Notes
PIR OUT GPIO 14 GPIO 14 / physical pin 19 Usage event input
MQ-135 AO GPIO 26 ADC0 GPIO 26 / physical pin 31 Odor proxy input
LED anode 220 ohm resistor to GPIO 16 GPIO 16 / physical pin 21 Activity LED
---

Wiring Diagram

Circuit Diagram

PIR OUT -> GPIO 14
MQ-135 AO -> GPIO 26
GPIO 16 -> 220 ohm resistor -> LED anode
Common GND -> PIR, MQ-135, and LED

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 counting events.
  2. Connect the MQ-135 analog output to GPIO 26 through a safe ADC path.
  3. Wire the LED to GPIO 16 through a 220 ohm resistor and connect the LED cathode to ground.
  4. Enter Wi-Fi credentials and local endpoint settings only after the local record loop works correctly.
  5. Warm up the MQ-135 and record a room baseline before choosing any trend thresholds.

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 event counting and odor reading separately so the analytics 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 clear PIR events and odor changes and confirm the visit count, average odor, and status all update logically.
  5. Run the full system: Run the full cloud-ready node and compare local-only behavior with optional upload behavior.
  6. Validate the prototype: Disable Wi-Fi and confirm the node still stores useful records locally for later analysis.
  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 network
import socket
import time
import ujson as json
from machine import ADC, Pin

PIR_PIN = 14
GAS_PIN = 26
LED_PIN = 16
LOG_FILE = 'sanitation_334.jsonl'
UPLOAD_ENABLED = False
WIFI_SSID = 'YOUR_WIFI'
WIFI_PASSWORD = 'YOUR_PASSWORD'
SERVER_HOST = '192.168.1.50'
SERVER_PORT = 8000
SERVER_PATH = '/sanitation'
HISTORY_LENGTH = 6

pir = Pin(PIR_PIN, Pin.IN, Pin.PULL_DOWN)
gas = ADC(GAS_PIN)
led = Pin(LED_PIN, Pin.OUT)
last_pir = 0
visit_count = 0
odor_history = []


def average(values):
    return int(sum(values) / len(values)) if values else 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 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 analytics cloud prototype ready')

while True:
    occupancy = pir.value()
    if occupancy == 1 and last_pir == 0:
        visit_count += 1
    last_pir = occupancy

    odor = gas.read_u16()
    odor_history.append(odor)
    odor_history = odor_history[-HISTORY_LENGTH:]
    avg_odor = average(odor_history)

    if visit_count >= 8 and avg_odor >= 24000:
        status = 'HIGH'
    elif visit_count >= 3 or avg_odor >= 18000:
        status = 'WATCH'
    else:
        status = 'LOW'

    record = {
        'schema_version': 1,
        'device_id': 'sanitation_334',
        'uptime_s': time.ticks_ms() // 1000,
        'visit_count': visit_count,
        'odor_raw': odor,
        'odor_avg': avg_odor,
        '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(10)

How the Code Works

Code Section What It Does Why It Matters What to Modify During Testing
Visit counting Counts a new usage event only when the PIR changes from low to high. Edge-based counting is more reliable than counting every loop while motion is present. Compare the count with direct observation before trusting placement or logic.
Rolling odor average Summarizes recent odor values into one trend field. Trend fields are more useful for analytics than one noisy raw reading alone. Adjust HISTORY_LENGTH after you see how noisy the room conditions are.
Cloud-ready record flow Writes one structured record locally and optionally uploads the same record. This is the honest cloud-ready pattern for the project title. Enable upload only after local record quality is verified.

Expected Result

The serial monitor prints one sanitation analytics record with visit count, raw odor, average odor, and status fields.

The Pico stores the record locally even if Wi-Fi or the endpoint is unavailable.

When upload is enabled and working, the same record can be compared with the server copy for validation.

Validation Checks

  • Normal condition test: leave the room quiet and confirm the record remains low after warm-up.
  • Event-count test: walk through the PIR zone and compare the visit count with direct observation.
  • Trend test: create moderate and stronger odor conditions and confirm odor_avg rises appropriately.
  • Communication validation test: enable upload and compare the uploaded payload with the local file record.
  • Fallback test: disable Wi-Fi and confirm the node still stores local records without crashing.

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 visit count rises too fast The PIR is retriggering from one person or poor placement Reposition the PIR and compare the count with manual observation.
The average odor barely changes The MQ-135 is not warmed up or the room conditions are too stable Allow more warm-up time and create clearer test conditions.
Uploads always fail The credentials or endpoint settings are wrong Check UPLOAD_ENABLED, the Wi-Fi details, and the server host, port, and path.
The status feels unrealistic The thresholds do not match your room behavior Observe several real records and adjust the thresholds after repeated trials.