Skip to content

Project 3.1.24: River Level Monitor

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


Overview

The Pico measures the distance to the water surface and translates it into a clear level label on a local dashboard.

Flood or river conditions are harder to communicate when only a raw distance value is shown.

A Pico 2 W prototype with an HC-SR04 ultrasonic sensor, OLED display, and warning LED.

Water-level interpretation, calibration at known distances, and local dashboard 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
OLED
OLED

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
OLED SDA GPIO 20 GPIO 20 / physical pin 26 I2C0 SDA
OLED SCL GPIO 21 GPIO 21 / physical pin 27 I2C0 SCL
LED anode 220 ohm resistor to GPIO 16 GPIO 16 / physical pin 21 Warning LED

Wiring Diagram

Circuit Diagram

  HC-SR04 TRIG                 -> GPIO 14
  HC-SR04 ECHO                 -> voltage divider -> GPIO 13
  GPIO 20                      -> OLED SDA
  GPIO 21                      -> OLED SCL
  GPIO 16 -> 220 ohm resistor  -> LED anode
  Common GND                   -> ultrasonic sensor, OLED, and LED

Step-by-Step Assembly

  1. Connect the ultrasonic TRIG pin to GPIO 14.
  2. Connect the ECHO pin to GPIO 13 through a voltage divider or use a 3.3V-safe module.
  3. Connect the OLED to Pico 3.3V, GND, GPIO 20, and GPIO 21.
  4. Wire the LED to GPIO 16 through a 220 ohm resistor and connect its cathode to ground.
  5. Mount the ultrasonic sensor securely above the target surface before taking measurements.

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: Measure known distances such as 5 cm, 10 cm, 20 cm, and 30 cm to validate the ultrasonic reading.
  3. Test the output device: Test the OLED and LED outputs separately before running the level monitor.
  4. Test the decision logic: Move a flat target under the sensor and confirm the level label changes at the chosen thresholds.
  5. Run the full system: Run the full system and compare the printed distance with the OLED display.
  6. Validate the prototype: Record the measurement error at several distances and decide whether the thresholds need adjustment.
  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 I2C, Pin
import time

try:
    from ssd1306 import SSD1306_I2C
    HAS_OLED = True
except ImportError:
    HAS_OLED = False

TRIG_PIN = 14
ECHO_PIN = 13
LED_PIN = 16
I2C_SDA_PIN = 20
I2C_SCL_PIN = 21
WARNING_CM = 20
CRITICAL_CM = 10

trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
led = Pin(LED_PIN, Pin.OUT)
i2c = I2C(0, sda=Pin(I2C_SDA_PIN), scl=Pin(I2C_SCL_PIN), freq=400000)
if HAS_OLED:
    oled = SSD1306_I2C(128, 64, i2c)

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()
    pulse = time.ticks_diff(pulse_end, pulse_start)
    return (pulse * 0.0343) / 2

print('Flood display ready')

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

    led.value(1 if status in ('WARNING', 'CRITICAL') else 0)
    text_distance = '---' if distance is None else '{:.1f}'.format(distance)
    print('Distance:{}cm Status:{}'.format(text_distance, status))

    if HAS_OLED:
        oled.fill(0)
        oled.text('Water Level', 0, 0)
        oled.text('Dist:{}cm'.format(text_distance), 0, 20)
        oled.text(status, 0, 44)
        oled.show()

    time.sleep(1)

How the Code Works

Code Section What It Does Why It Matters What to Modify During Testing
Ultrasonic timing Measures the echo pulse width to estimate distance Distance measurement is the main data source in this prototype Validate the reading at several known distances before trusting the thresholds
Level mapping Converts distance into NORMAL, WARNING, or CRITICAL A status label is easier to explain than raw distance alone Tune the warning levels after testing the actual installation geometry
OLED and LED outputs Shows the status locally and lights the warning LED when needed Local visibility matters even without a network connection If the OLED is blank, confirm the display library and I2C wiring

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 works well for classroom demonstrations and local monitoring pilots
  • Before deployment, it needs calibration records, protective mounting, and regular validation checks
  • Display-only systems still depend on correct sensor placement and trained users

Troubleshooting

Problem Possible Cause Solution
Distance never changes The ultrasonic sensor is aimed badly or the echo pin is not wired correctly Reposition the sensor and verify the Echo voltage divider
OLED stays blank The display library is missing or the I2C pins are wrong Confirm ssd1306.py is on the Pico and use GPIO 20 and GPIO 21
Measurements are inaccurate The target surface is uneven or too angled Use a flatter target for calibration and mount the sensor more securely
The LED is always on The thresholds are too high or the measured distance is smaller than expected Check the empty-distance baseline and lower the warning sensitivity if needed