Project 2.1.19: Public Restroom Usage Monitor
Intermediate Embedded Systems Project Using Raspberry Pi Pico 2 W and MicroPython
Overview
This project builds a public restroom usage monitor that counts visits, tracks hourly usage patterns, and serves a local dashboard over Wi-Fi.
Students will combine a digital ultrasonic sensor, a cleaning-reset button, Wi-Fi time synchronisation, hourly usage storage, and a simple web page into one monitoring system.
The final system should connect to Wi-Fi, count restroom visits once per entry event, track the busiest hour, show when cleaning is recommended, and display the results in both the serial monitor and a browser.
Required Components
![]() Ultrasonic distance sensor |
![]() Breadboard and jumper wires |
![]() Raspberry Pi Pico 2 W |
![]() Push button |
![]() Built-in Pico LED |
![]() Service LED and 220 Ω resistor |
Circuit Connections
| Component terminal | Connect to | Pico physical pin | Notes |
|---|---|---|---|
| Ultrasonic VCC | 5V or module-rated VCC | External/module supply | Use a safe Echo level for the Pico |
| Ultrasonic GND | GND | Any GND pin | Common ground |
| Ultrasonic TRIG | GPIO 4 | GPIO 4 / physical pin 6 | Trigger output |
| Ultrasonic ECHO | GPIO 6 | GPIO 6 / physical pin 9 | Echo input; level-shift if needed |
| Cleaning reset button one side | GPIO 5 | GPIO 5 / physical pin 7 | Uses internal pull-up |
| Cleaning reset button other side | GND | Any GND pin | Pressing pulls the input low |
| Service LED anode | GPIO 16 through 220 Ω resistor | GPIO 16 / physical pin 21 | Service indicator |
Wiring Diagram

Ultrasonic sensor output -> GPIO 4
Cleaning reset button -> GPIO 5 and GND
GPIO 16 -> 220Ω -> Service LED anode
Service LED cathode -> GND
Built-in Pico LED -> used in code for Wi-Fi status
Step-by-Step Assembly
Step 1: Place the Raspberry Pi Pico 2W
Place the Raspberry Pi Pico 2W on the breadboard so it sits across the center gap. Keep the USB port facing outward so you can easily connect it to your computer.
Step 2: Position the Ultrasonic Distance Sensor
Place the entry or ultrasonic sensor where one restroom-use event creates one clean trigger instead of repeated rapid triggers. Identify VCC, GND, and output before wiring.
Step 3: Connect the Entry Sensor
Connect sensor VCC to the safe low-voltage supply required by the module label. Connect sensor GND to GND. Connect sensor output to GPIO 4.
Step 4: Place the Cleaning Reset Button
Place the cleaning reset push button across the breadboard center gap. Connect one side of the button to GPIO 5. Connect the opposite side of the button to GND.
Step 5: Place and Connect the Service LED
Place the service LED on the breadboard. Identify the long leg as the anode (+) and the short leg as the cathode (-). Connect the service LED long leg through a 220Ω resistor to GPIO 16. Connect the service LED short leg to GND.
Step 6: Prepare for Wi-Fi Dashboard Testing
The built-in Pico LED is used for Wi-Fi connection state, so no extra Wi-Fi LED is needed. Prepare your Wi-Fi credentials in your local code copy before running the dashboard. Open the IP address shown in the Thonny Shell from a browser on the same Wi-Fi network.
Wiring Check
- [x] Pico 2W is placed correctly across the breadboard center gap
- [x] Ultrasonic sensor output connects to GPIO 4
- [x] Ultrasonic sensor GND connects to GND
- [x] Cleaning reset button connects between GPIO 5 and GND
- [x] Service LED long leg connects through a 220Ω resistor to GPIO 16
- [x] Service LED short leg connects to GND
- [x] Pico built-in LED is used for Wi-Fi status
- [x] Pico 2W and viewing device are on the same Wi-Fi network for the dashboard
- [x] No loose jumper wires
Intermediate Note The dashboard uses Wi-Fi and ntptime. Keep real Wi-Fi credentials private, and tune the sensor position so one use event does not create many repeated counts.
Safety Note Keep electronics away from water and wet surfaces. This project monitors usage patterns, so avoid collecting personal identity data and keep the dashboard limited to classroom-safe information.
Testing Individual Components
Before running the full project, test each part separately. This makes it easier to find wiring, library, or code problems.
Hardware Setup
- Build the ultrasonic sensor, reset button, and service LED wiring first before testing Wi-Fi
- A stable input sensor is important because usage analysis is only as good as the event count
Test the Input Sensor
- Trigger one entry event and confirm the count increases only once because of the lockout rule
- Press the cleaning-reset button and confirm the service counter resets correctly
Test the Output Device
- Confirm the service LED turns on when the cleaning threshold is reached
- Check that the built-in LED blinks during Wi-Fi connection and stays on afterward
Test Communication
- Enter the Wi-Fi credentials, run the code, and wait for the IP address to appear in the Thonny Shell
- Open the dashboard in a browser on the same network and confirm the usage values update
Run the Full System
- Trigger several visit events and confirm the total count, current hour count, and peak-hour report all update correctly
- Press the cleaning-reset button and confirm only the service-needed count resets while the overall hourly usage history remains available
Save the Project
- Save the final code without exposing real credentials in any shared copy
- Record the service threshold and timezone offset used in your dashboard test
Additional Testing and Calibration Checks
- Entry-event test: trigger one clean entry event and confirm the count increases only once because of the lockout
- Hourly-slot test: confirm events are added to the current hour after time sync succeeds
- Service-threshold test: generate enough events to turn on the service LED
- Reset test: press the cleaning-reset button and confirm the visits-since-cleaning counter returns to zero while total visits remain stored
- Wi-Fi setup test: ensure the Pico and browser device are on the same 2.4 GHz network
- Dashboard test: open the IP address in a browser and confirm the displayed values update over time
Full Project Code
After completing and checking the circuit connections, open Thonny IDE. Copy and paste the code below into a new file, or upload the project file to the Raspberry Pi Pico 2 W, then run it from Thonny.
import network
import ntptime
import socket
import time
from machine import Pin, time_pulse_us
WIFI_SSID = 'YOUR_WIFI_NAME'
WIFI_PASSWORD = 'YOUR_WIFI_PASSWORD'
UTC_OFFSET_HOURS = 0
trig = Pin(4, Pin.OUT)
echo = Pin(6, Pin.IN)
reset_button = Pin(5, Pin.IN, Pin.PULL_UP)
service_led = Pin(16, Pin.OUT)
wifi_led = Pin('LED', Pin.OUT)
PRESENCE_CM = 80
VISIT_LOCKOUT_SECONDS = 8
SERVICE_THRESHOLD = 30
TIME_SYNC_INTERVAL = 3600
DEBOUNCE_MS = 250
hourly_usage = [0] * 24
total_visits = 0
visits_since_clean = 0
last_visit_time = 0
last_sync = 0
last_button_ms = 0
previous_present = False
def distance_cm():
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
pulse = time_pulse_us(echo, 1, 30000)
if pulse < 0:
return 999
return (pulse / 2) / 29.1
def person_present():
return distance_cm() <= PRESENCE_CM
def button_pressed():
global last_button_ms
now_ms = time.ticks_ms()
if reset_button.value() == 0 and time.ticks_diff(now_ms, last_button_ms) > DEBOUNCE_MS:
while reset_button.value() == 0:
time.sleep(0.02)
last_button_ms = now_ms
return True
return False
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to Wi-Fi...')
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
start = time.time()
while not wlan.isconnected():
wifi_led.value(1 - wifi_led.value())
if time.time() - start > 20:
raise RuntimeError('Wi-Fi connection timeout')
time.sleep(0.5)
wifi_led.value(1)
print('Wi-Fi connected:', wlan.ifconfig()[0])
return wlan
def sync_time():
global last_sync
ntptime.settime()
last_sync = time.time()
print('Clock synchronised from NTP.')
def local_now():
return time.localtime(time.time() + (UTC_OFFSET_HOURS * 3600))
def record_visit():
global total_visits, visits_since_clean, last_visit_time
now = time.time()
if now - last_visit_time < VISIT_LOCKOUT_SECONDS:
return
hour = local_now()[3]
hourly_usage[hour] += 1
total_visits += 1
visits_since_clean += 1
last_visit_time = now
print('Visit counted. Total:', total_visits)
print('=== Public Restroom Usage Monitor ===')
wlan = connect_wifi()
try:
sync_time()
except Exception as error:
print('Time sync failed:', error)
while True:
present = person_present()
if present and not previous_present:
record_visit()
previous_present = present
if button_pressed():
visits_since_clean = 0
print('Cleaning counter reset.')
service_led.value(1 if visits_since_clean >= SERVICE_THRESHOLD else 0)
print('Distance:{:.1f}cm Total:{} SinceClean:{}'.format(
distance_cm(), total_visits, visits_since_clean
))
time.sleep(1)
How the Code Works
| Code Section | What It Does | Why It Matters |
|---|---|---|
| Wi-Fi and NTP setup | Connect the Pico 2 W to the network and synchronise time | Hourly usage analysis needs a reliable clock |
| Visit lockout logic | Counts one visit only once within the lockout period | This avoids many duplicate counts from one entry event |
| Hourly usage array | Stores visit totals for each hour of the day | Students can identify patterns such as peak-use times |
| Dashboard page | Serves the totals and service status to a local browser | This turns the monitor into a usable maintenance dashboard |
Expected Result
After Wi-Fi connection, the built-in LED should stay on and the serial monitor should show the local IP address.
Each valid entry event should increase the total visit count and the current hour counter only once.
When the cleaning threshold is reached, the service LED should turn on and the browser dashboard should show the increased visits-since-cleaning value.
Troubleshooting
| Problem | Possible cause | Solution |
|---|---|---|
| The page never loads | The Pico did not connect to Wi-Fi or the browser is on a different network | Check the Shell for the IP address and confirm both devices are on the same 2.4 GHz network |
| The hourly counts go to the wrong slot | Time sync failed or the timezone offset is wrong | Check the NTP sync messages and adjust UTC_OFFSET_HOURS |
| One visit becomes many counts | The lockout is too short or the sensor is bouncing | Increase VISIT_LOCKOUT_SECONDS or improve sensor placement |
| The service LED never turns on | The service threshold is too high or visit events are not being counted | Lower SERVICE_THRESHOLD for testing and verify the input event logic |




