Skip to content

Project 2.1.30: Water Usage Monitoring

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


Overview

This project estimates how much water an irrigation system uses by combining pump runtime with a measured flow rate.

Students will build an automatic watering system, measure a pump flow rate, count watering cycles, and calculate cumulative water usage.

The final system should water when needed, estimate litres used in each cycle, and print regular usage reports showing total runtime, number of cycles, and estimated water use.

Required Components

Soil moisture sensor
Soil moisture sensor
LED and 220 Ω resistor
LED and 220 Ω resistor
Raspberry Pi Pico 2 W
Raspberry Pi Pico 2 W
1-channel relay module
1-channel relay module
Small DC water pump
Small DC water pump
External power supply
External power supply
Measuring container
Measuring container
Breadboard, jumper wires, tubing, and water container
Breadboard, jumper wires, tubing, and water container

Circuit Connections

Component terminal Connect to Pico physical pin Notes
Soil sensor AOUT GPIO 26 GPIO 26 / physical pin 31 ADC moisture input
Relay IN GPIO 15 GPIO 15 / physical pin 20 Pump control
Status LED anode GPIO 16 through 220 Ω resistor GPIO 16 / physical pin 21 Pump indicator
Status LED cathode GND Any GND pin LED return
Pump supply path Relay COM to NO contacts Not a Pico GPIO External power only

Wiring Diagram

Circuit Diagram

  Raspberry Pi Pico 2 W
  ┌─────────────────────┐
  │                     │
  │  GPIO 26 ───────────┤──── Soil Sensor AOUT
  │                     │
  │  GPIO 15 ───────────┤──── Relay IN
  │                     │
  │  GPIO 16 ────220Ω───┤──── Status LED (+)
  │                     │
  │  3.3V    ───────────┤──── Soil Sensor VCC
  │                     │
  │  GND     ───────────┤──── Soil Sensor GND
  │  GND     ───────────┤──── Status LED (-)
  │  GND     ───────────┤──── Relay GND
  │                     │
  └─────────────────────┘

  Relay Module            External Supply
  ┌──────────┐            ┌────────────┐
  │  COM ────┼────────────┤ (+)        │
  │  NO  ────┼──┐         │            │
  │  VCC ────┼──┼─────────┤ (+) (if    │
  │  GND ────┼──┼──┐      │   needed)  │
  └──────────┘  │  │      │            │
                │  │      └────────────┘
                │  │           │
                │  └───────────┘
                │         Pump (+)
                │
                └────────────── Pump (-) ──── External Supply (-)

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 Soil Moisture Sensor

Place the soil moisture probe so the sensing end can enter the soil sample. Identify VCC, GND, and AOUT / AO / Signal before wiring.

Step 3: Connect the Soil Sensor

Connect soil sensor VCC to 3.3V. Connect soil sensor GND to GND. Connect soil sensor AOUT, AO, or Signal to GPIO 26 (ADC0).

Step 4: Place and Wire the Relay Module

Identify relay VCC, GND, IN, COM, NO, and NC. Connect relay IN to GPIO 15. Power the relay module from the supply required by its label. Connect relay GND to Pico GND and to the external pump supply GND where shared grounding is required.

Step 5: Place the Status LED

Place the status LED on the breadboard. Connect its long leg through a 220Ω resistor to GPIO 16. Connect its short leg to GND.

Step 6: Wire the Pump Through the Relay

Connect the external pump supply positive wire to relay COM. Connect relay NO to the pump positive lead. Connect the pump negative lead to the external pump supply negative wire.

Step 7: Prepare the Measuring Container

Place the pump outlet into a measuring container for flow-rate testing. Keep the water container and tubing away from the Pico, breadboard, USB cable, and jumper wires.

Wiring Check

  • [x] Pico 2W is placed correctly across the breadboard center gap
  • [x] Soil sensor AOUT / AO / Signal connects to GPIO 26
  • [x] Relay IN connects to GPIO 15
  • [x] Status LED long leg connects through a 220Ω resistor to GPIO 16
  • [x] Status LED short leg connects to GND
  • [x] Pump positive path uses relay COM and NO
  • [x] Pump negative connects to external pump supply negative
  • [x] Measuring container is positioned before pump testing
  • [x] No loose jumper wires

Intermediate Note Measure the pump flow rate with a container and timer, then update FLOW_RATE_LPS in the code before trusting the litre calculation.

Safety Note Do not power the pump from the Pico. Use short supervised pump cycles, keep electronics away from water, and never run the pump just to collect statistics.


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 soil sensor, LED, and relay stage before any live pump test
  • Prepare a measuring container so the flow-rate calibration can be done safely

Test the Input Sensor

  • Calibrate the soil sensor with dry and wet references
  • Confirm that the moisture percentage changes before using it to trigger watering cycles

Test the Output Device

  • Test the relay and LED before connecting the real pump
  • Measure the real pump flow rate and update FLOW_RATE_LPS so the water-use report is meaningful

Run the Full System

  • Use TEST_MODE first so reports appear in a short classroom period
  • Run at least one dry-soil watering cycle and confirm that the reported litres increase
  • Compare the estimated litres with the actual amount collected in the measuring container

Save the Project

  • Save the final code and record the calibrated flow rate used in your calculation
  • Note the number of cycles and the total estimated litres from your final test run

Additional Testing and Calibration Checks

Calibration and tuning notes

  • Calibrate FLOW_RATE_LPS using a real container test before trusting the litre output
  • Use TEST_MODE so a report appears quickly in class
  • If the estimated litres look wrong, recalculate the flow rate from a longer measurement run
  • Keep the water path stable during tests so flow-rate calibration is repeatable

Quick testing checklist

  • [ ] Soil moisture values change correctly
  • [ ] Pump and LED run during each watering cycle
  • [ ] Cycle count increases after watering
  • [ ] Total estimated litres increase after each cycle
  • [ ] Usage reports print at the chosen interval

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.

from machine import ADC, Pin
import time

TEST_MODE = True
RELAY_ON = 0
RELAY_OFF = 1
PUMP_RUN_S = 5
MIN_REST_S = 30
REPORT_INTERVAL_S = 120 if TEST_MODE else 3600
FLOW_RATE_LPS = 0.08

soil = ADC(26)
relay = Pin(15, Pin.OUT)
status_led = Pin(16, Pin.OUT)

dry_reading = 52000
wet_reading = 22000
dry_threshold = 35
recovery_threshold = 45

ready_to_water = True
last_cycle = time.time() - MIN_REST_S
total_runtime_s = 0
total_liters = 0.0
cycle_count = 0
session_start = time.time()
last_report = session_start

relay.value(RELAY_OFF)
status_led.value(0)


def clamp(value, low, high):
    if value < low:
        return low
    if value > high:
        return high
    return value


def moisture_percent():
    raw = soil.read_u16()
    span = dry_reading - wet_reading
    if span == 0:
        return 0
    percent = int(((dry_reading - raw) * 100) / span)
    return clamp(percent, 0, 100)


def run_cycle():
    global total_runtime_s, total_liters, cycle_count, last_cycle, ready_to_water
    relay.value(RELAY_ON)
    status_led.value(1)
    print("Pump ON: watering cycle started")
    time.sleep(PUMP_RUN_S)
    relay.value(RELAY_OFF)
    status_led.value(0)
    total_runtime_s += PUMP_RUN_S
    cycle_count += 1
    total_liters += PUMP_RUN_S * FLOW_RATE_LPS
    last_cycle = time.time()
    ready_to_water = False
    print("Pump OFF: cycle complete")


def print_report():
    session_hours = max((time.time() - session_start) / 3600, 0.001)
    print("=== Water Usage Report ===")
    print("Cycles:{} Runtime:{}s Water:{:.2f}L Rate:{:.2f}L/h".format(
        cycle_count,
        total_runtime_s,
        total_liters,
        total_liters / session_hours,
    ))


print("Water usage monitoring ready")

while True:
    now = time.time()
    moisture = moisture_percent()

    if moisture >= recovery_threshold:
        ready_to_water = True

    if ready_to_water and moisture <= dry_threshold and (now - last_cycle) >= MIN_REST_S:
        run_cycle()
    else:
        print("Moisture:{}% Cycles:{} Water:{:.2f}L".format(moisture, cycle_count, total_liters))

    if now - last_report >= REPORT_INTERVAL_S:
        print_report()
        last_report = now

    time.sleep(5)

How the Code Works

Code Section What It Does Why It Matters
FLOW_RATE_LPS Stores the calibrated litres-per-second value of the pump The water-use estimate is only as good as this calibration
run_cycle() Runs the pump and updates statistics after each cycle Usage tracking must be tied directly to the actuator event
cycle_count, total_runtime_s, and total_liters Store the main usage statistics These values turn a watering system into a monitoring system
print_report() Summarises the session data at intervals Periodic reports help students compare water use over time

Expected Result

When the soil is dry enough, the pump should run for one timed cycle and the status LED should light. After each watering event, the system should update the total runtime, cycle count, and estimated water used. At the report interval, the Shell should print a summary showing cumulative litres and usage rate.


Troubleshooting

Problem Possible cause Solution
The litre total is unrealistic FLOW_RATE_LPS was guessed instead of measured Re-measure the pump flow with a timed container test
The report never appears TEST_MODE is off or the report interval is too long Enable TEST_MODE or shorten REPORT_INTERVAL_S for testing
Cycles are counted but no water moves The pump intake is dry or tubing is blocked Stop the test, refill the water source, and inspect the tubing
The system waters too often Thresholds or re-arm timing are too aggressive Increase the recovery threshold or the minimum rest time