Skip to content

Project 3.5.1: Flood Early Warning

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


Overview

The Pico combines rainfall and water-level data to produce an early warning score for flood risk.

A single sensor can miss important flood signals, especially when rising water and heavy rain happen at different times.

A Pico 2 W prototype with a rain sensor, ultrasonic sensor, LED, and buzzer.

Multi-sensor scoring, warning levels, and prototype validation for early flood awareness.

Required Components

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

Circuit Connections

Component terminal Connect to Pico physical pin Notes
Rain sensor AO GPIO 26 ADC0 GPIO 26 / physical pin 31 Analog rain input
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 15 GPIO 15 / physical pin 20 Warning LED
Buzzer positive GPIO 16 GPIO 16 / physical pin 21 Critical alert

Wiring Diagram

Circuit Diagram

  Rain sensor AO        -> GPIO 26
  HC-SR04 TRIG          -> GPIO 14
  HC-SR04 ECHO          -> voltage divider -> GPIO 13
  GPIO 15               -> 220 ohm resistor -> LED anode
  GPIO 16               -> buzzer positive
  Common GND            -> all modules

Step-by-Step Assembly

  1. Connect the rain sensor analog output to GPIO 26.
  2. Connect the ultrasonic TRIG and protected ECHO lines to GPIO 14 and GPIO 13.
  3. Wire the LED and buzzer to GPIO 15 and GPIO 16.
  4. Keep the Pico dry and move only the rain plate or water target during testing.

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 rain sensor and ultrasonic distance reading separately before combining them.
  3. Test the output device: Test the LED and buzzer with simple scripts before enabling the scoring logic.
  4. Test the decision logic: Increase rainfall and water level one factor at a time to confirm the score changes as expected.
  5. Run the full system: Run the full system and compare the score with the final warning output.
  6. Validate the prototype: Discuss which false-trigger sources could affect rain, distance, or both sensors outdoors.
  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 ADC, Pin
import time

RAIN_PIN = 26
TRIG_PIN = 14
ECHO_PIN = 13
LED_PIN = 15
BUZZER_PIN = 16
RAIN_WARN = 30000
RAIN_HIGH = 45000
WATER_WARN_CM = 20
WATER_CRITICAL_CM = 10

rain_sensor = ADC(RAIN_PIN)
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
led = Pin(LED_PIN, Pin.OUT)
buzzer = Pin(BUZZER_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()
    pulse = time.ticks_diff(pulse_end, pulse_start)
    return (pulse * 0.0343) / 2

print('Multi-sensor flood warning ready')

while True:
    rain_value = rain_sensor.read_u16()
    distance = measure_distance_cm()
    score = 0

    if rain_value >= RAIN_WARN:
        score += 1
    if rain_value >= RAIN_HIGH:
        score += 1
    if distance is not None and distance <= WATER_WARN_CM:
        score += 2
    if distance is not None and distance <= WATER_CRITICAL_CM:
        score += 2

    if score >= 4:
        status = 'CRITICAL'
    elif score >= 2:
        status = 'WARNING'
    else:
        status = 'NORMAL'

    led.value(1 if status in ('WARNING', 'CRITICAL') else 0)
    buzzer.value(1 if status == 'CRITICAL' else 0)
    text_distance = '---' if distance is None else '{:.1f}'.format(distance)
    print('Rain:{} Dist:{}cm Score:{} Status:{}'.format(rain_value, text_distance, score, status))
    time.sleep(1)

How the Code Works

Code Section What It Does Why It Matters What to Modify During Testing
Sensor scoring Combines rainfall intensity and water level into one risk score Multi-factor scoring is more informative than a single threshold Tune each sensor threshold after measuring realistic test values
Status mapping Converts the score into NORMAL, WARNING, or CRITICAL A documented mapping makes the system explainable Keep the label mapping simple during initial validation
Alert outputs Uses LED and buzzer outputs to reflect the final status Outputs help users react without reading every raw value Test the LED and buzzer channels independently first

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 can be used for local warning demonstrations and early field trials
  • Before deployment, it needs enclosure protection, calibration records, and a clear response procedure
  • Alert systems should always be treated as decision-support tools unless they are certified for the application

Troubleshooting

Problem Possible Cause Solution
The score stays high Thresholds are too low or the rain sensor baseline is not understood Measure dry and wet rain-sensor values first and adjust thresholds
Distance reads as no echo often The ultrasonic target or alignment is poor Use a flatter target and verify the Echo line protection
The system never reaches warning The thresholds are too strict Use measured test values to tune the warning bands
Alerts do not match the printed score The outputs are wired incorrectly Test each output pin with a standalone script and compare against the code logic