Project 3.9.60: Smart Water Ai Controller
Advanced Embedded Systems Project Using Raspberry Pi Pico 2 W and MicroPython
Overview
The Pico uses rule-based AI-style logic to close a relay-controlled water line when flow stays unusually high for too long.
A water controller should respond to sustained waste patterns, not just a single instant of high flow.
A Pico 2 W prototype with a pulse flow sensor, relay-controlled valve or test load, reset button, and status LED.
Rule-based AI-style water control, sustained-flow monitoring, and safe manual reset behavior.
Required Components
![]() Raspberry Pi Pico 2 W |
![]() Water level sensor |
![]() Breadboard |
![]() Jumper wires |
![]() Push button |
![]() Relay |
![]() LED |
![]() Resistor |
| --- |
Circuit Connections
| Component terminal | Connect to | Pico physical pin | Notes |
|---|---|---|---|
| Flow sensor pulse output | GPIO 14 | GPIO 14 / physical pin 19 | 3.3V-safe pulse signal |
| Relay IN | GPIO 15 | GPIO 15 / physical pin 20 | Valve or load control |
| Reset button leg 1 | GPIO 16 | GPIO 16 / physical pin 21 | Manual reset input |
| Reset button leg 2 | 3.3V output | Physical pin 36 | High when pressed |
| LED anode | 220 ohm resistor to GPIO 17 | GPIO 17 / physical pin 22 | Lockout LED |
| --- |
Wiring Diagram

Flow pulse output -> GPIO 14
GPIO 15 -> relay IN
Button -> GPIO 16 and 3.3V
GPIO 17 -> LED via 220 ohm
Step-by-Step Assembly
- Connect the flow pulse output to GPIO 14 and verify the signal is 3.3V-safe.
- Connect the relay control input to GPIO 15.
- Wire the reset button between GPIO 16 and 3.3V so it reads high when pressed.
- Connect the LED to GPIO 17 through a 220 ohm resistor.
- Attach only a safe low-voltage test load to the relay during validation.
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.
- Hardware setup: Assemble the Pico, sensor, indicator, and load wiring exactly as shown in the connection table before applying power.
- Test the input sensor: Test pulse counting from the flow sensor before any control action is enabled.
- Test the output device: Test the relay, LED, and reset button separately before running the control logic.
- Test the decision logic: Confirm that short normal flow does not trigger lockout but sustained high flow does.
- Run the full system: Run the full controller and compare the moving average with the relay state.
- Validate the prototype: Press the reset button after lockout and confirm the recovery behavior matches the rule set.
- 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 time
FLOW_PIN = 14
RELAY_PIN = 15
BUTTON_PIN = 16
LED_PIN = 17
SAMPLE_WINDOW_S = 5
HISTORY_LENGTH = 4
HIGH_USE_LPM = 3.5
pulse_count = 0
flow = Pin(FLOW_PIN, Pin.IN, Pin.PULL_UP)
relay = Pin(RELAY_PIN, Pin.OUT)
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_DOWN)
led = Pin(LED_PIN, Pin.OUT)
relay.on()
lockout = False
history = []
def count_pulse(pin):
global pulse_count
pulse_count += 1
def flow_lpm_from_pulses(pulses, seconds):
if seconds <= 0:
return 0.0
return (pulses / seconds) / 7.5
flow.irq(trigger=Pin.IRQ_FALLING, handler=count_pulse)
print('Smart water AI controller ready')
while True:
pulse_count = 0
start = time.ticks_ms()
while time.ticks_diff(time.ticks_ms(), start) < SAMPLE_WINDOW_S * 1000:
if lockout and button.value() == 1:
lockout = False
history = []
relay.on()
led.off()
print('Manual reset')
time.sleep_ms(100)
lpm = flow_lpm_from_pulses(pulse_count, SAMPLE_WINDOW_S)
if not lockout:
history.append(lpm)
history = history[-HISTORY_LENGTH:]
avg_lpm = sum(history) / len(history)
if len(history) == HISTORY_LENGTH and avg_lpm >= HIGH_USE_LPM:
lockout = True
relay.off()
led.on()
else:
avg_lpm = sum(history) / len(history) if history else 0
state = 'LOCKOUT' if lockout else 'OPEN'
print('Flow:{:.2f}L/min Avg:{:.2f} State:{}'.format(lpm, avg_lpm, state))
How the Code Works
| Code Section | What It Does | Why It Matters | What to Modify During Testing |
|---|---|---|---|
| Pulse-based flow measurement | Counts pulses and converts them into liters per minute | Flow control decisions should be based on real pulse measurement, not arbitrary ADC values | Verify the pulse-count conversion before changing the thresholds |
| Moving-average logic | Detects sustained high use instead of one short spike | This is the AI-style control logic behind the project | Adjust the window length or high-use threshold only after repeated tests |
| Lockout and reset path | Restricts the relay during sustained waste and allows manual recovery | Control systems need both an action and a safe way to recover | Test the relay with a safe low-voltage load before real hardware |
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 could be used in school, farm, or sanitation demonstrations with safe low-voltage loads
- Before deployment, the load wiring, enclosure, and power design need careful review
- Actuator systems need maintenance planning because relay wear and sensor drift affect reliability
Troubleshooting
| Problem | Possible Cause | Solution |
|---|---|---|
| Lockout happens too fast | The high-use threshold is too low or the history is too short | Raise HIGH_USE_LPM or increase HISTORY_LENGTH |
| The relay never closes | The relay polarity is different or the threshold is too high | Test the relay output separately and temporarily lower the threshold |
| Reset does nothing | The button wiring is wrong | Print the button state in a simple test and verify it goes high when pressed |
| Flow stays at zero | The pulse signal is not reaching GPIO 14 | Print the pulse count during a known flow event and recheck the sensor signal path |







