Skip to content

Project 3.3.3: Drainage Iot Dashboard

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


Overview

The Pico measures water level with an ultrasonic sensor and prepares a local network payload for a future dashboard or monitoring server.

Drainage and flood measurements are less useful when they are not stored in a consistent, reusable data format.

A Pico 2 W prototype with an HC-SR04 ultrasonic sensor, status LED, and Wi-Fi connection.

Ultrasonic level measurement, local-first Wi-Fi communication, and realistic dashboard-ready reporting.

Required Components

Raspberry Pi Pico 2 W
Raspberry Pi Pico 2 W
Ultrasonic sensor
Ultrasonic sensor
Breadboard
Breadboard
Jumper wires
Jumper wires
LED
LED
Resistor
Resistor

Circuit Connections

Component terminal Connect to Pico physical pin Notes
HC-SR04 TRIG GPIO 14 GPIO 14 / physical pin 19 Trigger output
HC-SR04 ECHO GPIO 13 through a voltage divider GPIO 13 / physical pin 17 3.3V-safe echo input
LED anode 220 ohm resistor to GPIO 16 GPIO 16 / physical pin 21 Communication status LED

Wiring Diagram

Circuit Diagram

  HC-SR04 TRIG                 -> GPIO 14
  HC-SR04 ECHO                 -> voltage divider -> GPIO 13
  GPIO 16 -> 220 ohm resistor  -> LED anode
  Common GND                   -> ultrasonic sensor and LED

Step-by-Step Assembly

  1. Connect the TRIG line to GPIO 14 and the protected ECHO line to GPIO 13.
  2. Wire the status LED to GPIO 16 through a 220 ohm resistor.
  3. Enter the Wi-Fi and local server settings in the code before upload testing.
  4. Validate the distance reading at known target positions before enabling reporting.

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 ultrasonic measurement locally at known distances before trying network communication.
  3. Test the output device: Test the LED output and Wi-Fi connection separately.
  4. Test the decision logic: Move the target through normal and warning distances to confirm the payload label changes logically.
  5. Run the full system: Run the full node and confirm whether reports are sent or buffered locally.
  6. Validate the prototype: Disconnect the network intentionally and verify that the buffer file captures the unsent records.
  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.

from machine import Pin
import network
import socket
import time
import ujson

TRIG_PIN = 14
ECHO_PIN = 13
LED_PIN = 16
WARNING_CM = 20
CRITICAL_CM = 10
WIFI_SSID = 'YOUR_WIFI'
WIFI_PASSWORD = 'YOUR_PASSWORD'
SERVER_HOST = '192.168.1.10'
SERVER_PORT = 8000
SERVER_PATH = '/drainage'
BUFFER_FILE = 'drainage_buffer.log'
NODE_ID = 'DRAIN_01'

trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
led = Pin(LED_PIN, Pin.OUT)

def measure_distance_cm():
    trig.value(0)
    time.sleep_us(2)
    trig.value(1)
    time.sleep_us(10)
    trig.value(0)
    timeout = 30000
    start = time.ticks_us()
    while echo.value() == 0:
        if time.ticks_diff(time.ticks_us(), start) > timeout:
            return None
    pulse_start = time.ticks_us()
    while echo.value() == 1:
        if time.ticks_diff(time.ticks_us(), pulse_start) > timeout:
            return None
    pulse_end = time.ticks_us()
    return (time.ticks_diff(pulse_end, pulse_start) * 0.0343) / 2

def connect_wifi(timeout_seconds=12):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if wlan.isconnected():
        return wlan
    wlan.connect(WIFI_SSID, WIFI_PASSWORD)
    start = time.time()
    while not wlan.isconnected() and time.time() - start < timeout_seconds:
        time.sleep(1)
    return wlan if wlan.isconnected() else None

def send_payload(payload):
    body = ujson.dumps(payload)
    try:
        addr = socket.getaddrinfo(SERVER_HOST, SERVER_PORT)[0][-1]
        client = socket.socket()
        client.settimeout(5)
        client.connect(addr)
        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)
        client.send(request.encode())
        client.close()
        return True
    except OSError:
        return False

def buffer_payload(payload):
    with open(BUFFER_FILE, 'a') as handle:
        handle.write(ujson.dumps(payload) + '\n')

print('Ultrasonic Wi-Fi node ready')

while True:
    distance = measure_distance_cm()
    if distance is None:
        label = 'NO_ECHO'
    elif distance <= CRITICAL_CM:
        label = 'CRITICAL'
    elif distance <= WARNING_CM:
        label = 'WARNING'
    else:
        label = 'NORMAL'

    payload = {'node': NODE_ID, 'timestamp': time.time(), 'distance_cm': distance, 'label': label}
    wlan = connect_wifi()
    sent = False
    if wlan:
        sent = send_payload(payload)

    if sent:
        led.value(1)
        print('Sent {}'.format(payload))
    else:
        led.value(0)
        buffer_payload(payload)
        print('Buffered {}'.format(payload))

    time.sleep(5)

How the Code Works

Code Section What It Does Why It Matters What to Modify During Testing
Distance labeling Converts the ultrasonic reading into a warning label The dashboard or report needs a clear status, not just raw distance Tune the distance bands after measuring real installation geometry
Payload upload Formats and sends a local JSON payload A clean payload structure makes later dashboard work easier Keep the endpoint local and simple during classroom testing
Buffer fallback Stores unsent records locally when the network is unavailable A realistic node should fail safely without losing data silently Inspect the buffer file after a forced network outage

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
All records show NO_ECHO The sensor aim or Echo wiring is wrong Check the voltage divider and validate the distance locally first
Records never send The Wi-Fi or server settings are wrong Verify the local endpoint and 2.4 GHz network settings
The LED never turns on No successful send is occurring or the LED wiring is wrong Test the network path first and then test GPIO 16 separately
Distance is unstable The target or sensor mount is poor Use a flatter target and mount the sensor more firmly