4.1.4 Smart Water Sustainability Framework
Overview
Build and prototype a smart water sustainability framework using the Raspberry Pi Pico 2 W and MicroPython.
This expert project is designed as an open-ended research and prototype challenge. Learners should use the concept, suggested components, and starter code as a guide, then conduct further research, improve the design, and build a working prototype.
The final result should demonstrate a working embedded system prototype with clear documentation, testing evidence, and a short presentation of design decisions.
Required Components
![]() Raspberry Pi Pico 2 W |
![]() Flow Sensor |
![]() Water-quality sensor |
![]() Breadboard |
![]() Jumper wires |
Circuit Connections
| Component Pin | Connects To | Pico GPIO / Physical Pin Number | Notes |
|---|---|---|---|
| VCC | 3.3V | See source design notes | Verify pin compatibility and voltage level |
| GND | GND | See source design notes | Verify pin compatibility and voltage level |
| OUT | GPIO14 (Pin 19) | See source design notes | Verify pin compatibility and voltage level |
| Output | ADC0 (Pin 26) | See source design notes | Verify pin compatibility and voltage level |
Step-by-Step Assembly
Hardware Setup
Step 1: Connect Flow Sensor Power
- VCC → 3.3V
- GND → GND
Step 2: Connect Flow Sensor Signal
- OUT → GPIO14 (Pin 19)
Step 3: Connect Water Quality Sensor
- Output → ADC0 (Pin 26)
Step 4: Verify All Connections
Check that:
- Flow sensor VCC is connected to 3.3V
- Flow sensor GND is connected to GND
- Flow sensor OUT is connected to GPIO14
- Water quality sensor output is connected to ADC0
Testing Individual Components
Before running the full project, test each subsystem separately. This makes it easier to find wiring, code, or logic problems.
- Test each sensor reading in the Thonny Shell.
- Test each actuator using a safe low-power test.
- Verify communication between system layers.
- Record results and adjust the prototype before final integration.
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.
Starter Code
# Smart Water Sustainability Framework - Project 355
# Interrupt-based Flow Measurement
from machine import Pin, ADC
import time
# Layer 1: Water Monitoring Node
flow_pin = Pin(14, Pin.IN)
water_sensor = ADC(Pin(26))
# Flow counting variables
flow_count = 0
last_flow_time = 0
def flow_interrupt_handler(pin):
"""Interrupt handler for flow sensor pulses"""
global flow_count, last_flow_time
flow_count += 1
last_flow_time = time.time()
# Attach interrupt
flow_pin.irq(trigger=Pin.IRQ_RISING, handler=flow_interrupt_handler)
# Flow measurement window
MEASUREMENT_WINDOW = 60 # seconds
def reset_flow_count():
global flow_count
flow_count = 0
def read_water_data():
"""Read flow and quality"""
quality_raw = water_sensor.read_u16()
water_quality = int(((65535 - quality_raw) / 65535) * 100)
return {
"flow_count": flow_count,
"water_quality": water_quality,
"timestamp": time.time()
}
def calculate_sustainability_score(data):
flow = data["flow_count"]
quality = data["water_quality"]
liters = flow / 1000
if liters < 50:
usage_score = 100
elif liters < 100:
usage_score = 75
elif liters < 200:
usage_score = 50
else:
usage_score = 25
quality_score = quality
sustainability = (usage_score * 0.6) + (quality_score * 0.4)
if sustainability >= 80:
return "EXCELLENT", sustainability
elif sustainability >= 60:
return "GOOD", sustainability
elif sustainability >= 40:
return "FAIR", sustainability
else:
return "POOR", sustainability
def generate_framework_output(community_id, data, sustainability, score):
status, _ = sustainability
return {
"community_id": community_id,
"sustainability_status": status,
"sustainability_score": score,
"flow_rate": data["flow_count"],
"water_quality": data["water_quality"],
"recommendations": get_recommendations(status),
"policy_inputs": get_policy_inputs(status)
}
def get_recommendations(status):
recs = {
"EXCELLENT": ["Maintain current practices", "Share best practices"],
"GOOD": ["Continue monitoring", "Minor improvements"],
"FAIR": ["Implement conservation measures", "Review usage patterns"],
"POOR": ["Urgent conservation required", "Infrastructure review needed"]
}
return recs.get(status, [])
def get_policy_inputs(status):
inputs = {
"EXCELLENT": ["Recognize community achievement"],
"GOOD": ["Standard monitoring continue"],
"FAIR": ["Consider incentive program"],
"POOR": ["Emergency conservation policy"]
}
return inputs.get(status, [])
def start_sustainability_framework():
community_id = "COMMUNITY_001"
while True:
reset_flow_count()
time.sleep(MEASUREMENT_WINDOW)
data = read_water_data()
sustainability = calculate_sustainability_score(data)
output = generate_framework_output(
community_id,
data,
sustainability[0],
sustainability[1]
)
print(f"\n{'='*50}")
print("WATER SUSTAINABILITY FRAMEWORK")
print(f"{'='*50}")
print(f"Community: {output['community_id']}")
print(f"Score: {output['sustainability_score']:.1f}/100")
print(f"Status: {output['sustainability_status']}")
print("\nMetrics:")
print(f" Flow: {output['flow_rate']} pulses/{MEASUREMENT_WINDOW}s")
print(f" Quality: {output['water_quality']}%")
print("\nRecommendations:")
for r in output['recommendations']:
print(f" - {r}")
print("\nPolicy Inputs:")
for p in output['policy_inputs']:
print(f" - {p}")
print(f"{'='*50}")
start_sustainability_framework()
How the Code Works
| Code Section | What It Does | Why It Matters |
|---|---|---|
| Starter Code | Implements one layer or subsystem of the prototype | Separating the project into parts makes expert systems easier to test and improve |
Expected Result
The system should collect data, process it, control the required outputs, and show clear evidence that the prototype solves the intended problem.
Troubleshooting
| Problem | Possible Cause | Solution |
|---|---|---|
| No readings appear in Thonny | Incorrect wiring, wrong pins, or missing library | Recheck the circuit, confirm pin numbers, and test each module separately |
| Import error appears | Library file is missing or saved in the wrong location | Check the Pico file structure and save libraries exactly as instructed |
| Actuator does not respond | Relay/driver wiring or external power issue | Verify driver input, external power, and shared ground where required |
| Results are unstable | Sensor noise, loose wiring, or poor calibration | Secure the wiring and add calibration or averaging in code |
| Prototype works only sometimes | System is too complex to test all at once | Return to subsystem testing and integrate one part at a time |



