Project 3.9.51: Smart Sanitation Iot Platform
Advanced Embedded Systems Project Using Raspberry Pi Pico 2 W and MicroPython
Overview
The Pico creates structured sanitation records locally and can optionally upload them to a local network endpoint.
A monitoring platform is not trustworthy if it cannot show where its data came from or continue working when the network fails.
A Pico 2 W prototype with a PIR sensor, MQ-135 gas sensor, status LED, local log file, and optional Wi-Fi upload.
Structured local records, optional network communication, and honest platform-prototype wording.
Required Components
![]() Raspberry Pi Pico 2 W |
![]() Gas sensor |
![]() Breadboard |
![]() Jumper wires |
![]() PIR Sensor |
![]() LED |
![]() Resistor |
|
| --- |
Circuit Connections
| Component terminal | Connect to | Pico physical pin | Notes |
|---|---|---|---|
| PIR OUT | GPIO 14 | GPIO 14 / physical pin 19 | Occupancy 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

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
- Connect the PIR output to GPIO 14 and allow warm-up before trusting occupancy records.
- Connect the MQ-135 analog output to GPIO 26 through a safe ADC path.
- Wire the LED to GPIO 16 through a 220 ohm resistor and connect the LED cathode to ground.
- Enter Wi-Fi credentials and local server details only after the local log file is working correctly.
- Warm up the MQ-135 and capture a room baseline before choosing the odor alert threshold.
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.
- Hardware setup: Assemble the Pico, sensor, indicator, and load wiring exactly as shown in the connection table before applying power.
- Test the input sensor: Test the PIR and gas sensor separately so you trust the occupancy and odor fields before creating records.
- Test the output device: Blink the LED and test local file writing before enabling optional upload.
- Test the decision logic: Confirm that one loop produces one sanitation record and that the odor flag changes logically with the threshold.
- Run the full system: Run the full node and compare local-only behavior with upload behavior to a local server.
- Validate the prototype: Disable Wi-Fi and confirm the node still produces useful local records for later review.
- 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_322.jsonl'
UPLOAD_ENABLED = False
UPLOAD_INTERVAL_S = 60
WIFI_SSID = 'YOUR_WIFI'
WIFI_PASSWORD = 'YOUR_PASSWORD'
SERVER_HOST = '192.168.1.50'
SERVER_PORT = 8000
SERVER_PATH = '/sanitation'
ODOR_ALERT = 22000
pir = Pin(PIR_PIN, Pin.IN, Pin.PULL_DOWN)
gas = ADC(GAS_PIN)
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_local(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 IoT platform prototype ready')
while True:
odor_raw = gas.read_u16()
record = {
'schema_version': 1,
'device_id': 'sanitation_322',
'uptime_s': time.ticks_ms() // 1000,
'occupancy_active': pir.value(),
'odor_raw': odor_raw,
'odor_flag': odor_raw >= ODOR_ALERT,
}
append_local(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(UPLOAD_INTERVAL_S)
How the Code Works
| Code Section | What It Does | Why It Matters | What to Modify During Testing |
|---|---|---|---|
| Structured sanitation record | Creates one documented record shape with occupancy and odor fields. | A platform claim is only meaningful if the raw node record is clear and consistent. | Add fields only when you can also explain how they will be validated. |
| append_local | Stores each record locally in JSON-lines format. | Local logging gives the system useful behavior even without the network. | Inspect the file contents before assuming the network is the problem. |
| upload_record | Optionally sends the same record to a local HTTP endpoint. | This demonstrates platform-ready communication without overclaiming a real deployment. | Enable upload only after local logging works correctly. |
| LED feedback | Shows visible activity whenever a record is processed. | A simple hardware cue helps students confirm the loop is alive during testing. | Use a different blink pattern later if you want separate local-only and uploaded states. |
Expected Result
The serial monitor prints one sanitation record each interval.
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 verified against a local server copy.
Validation Checks
- Normal condition test: confirm that one record is created and stored locally during each interval.
- Occupancy validation test: move through the PIR zone and confirm the occupancy_active field changes as expected.
- Odor validation test: warm up the MQ-135 and confirm the odor_flag changes when the threshold is crossed.
- Communication validation test: enable upload and compare the uploaded payload with the local file record.
- Fallback test: disconnect Wi-Fi or stop the server and confirm the node still stores records locally.
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 local file is empty | The file write failed or the loop is not running | Test a simple file write and confirm the Pico file system is writable. |
| Uploads never succeed | UPLOAD_ENABLED is false or the endpoint is wrong | Check the Wi-Fi credentials, server host, port, and path. |
| The odor flag is always true | The threshold is too low for the warmed-up baseline | Record the baseline after warm-up and raise ODOR_ALERT if needed. |
| The PIR state looks wrong | The sensor has not warmed up or is wired incorrectly | Wait for warm-up and print the PIR value directly during a simple test. |






