# MicroPython Program for Raspberry Pi Pico
# Project: Water Quality Monitoring & Auto Filtration System
from machine import Pin, ADC, I2C
from time import sleep
from ssd1306 import SSD1306_I2C
import hcsr04
# --- OLED Setup (SSD1306) ---
i2c = I2C(0, scl=Pin(5), sda=Pin(4)) # GP5 = SCL, GP4 = SDA
oled = SSD1306_I2C(128, 64, i2c)
# --- Potentiometers as Analog Inputs ---
ph_sensor = ADC(Pin(26)) # ADC0
tds_sensor = ADC(Pin(27)) # ADC1
# --- Ultrasonic Sensor Setup ---
trig = Pin(2, Pin.OUT)
echo = Pin(3, Pin.IN)
# --- LED Output ---
led = Pin(15, Pin.OUT)
# --- Function: Read Ultrasonic ---
def read_distance():
trig.low()
sleep(0.002)
trig.high()
sleep(0.01)
trig.low()
while echo.value() == 0:
start = time.ticks_us()
while echo.value() == 1:
end = time.ticks_us()
duration = time.ticks_diff(end, start)
distance_cm = (duration / 2) / 29.1
return distance_cm
# --- Main Loop ---
while True:
# Read analog values (0 - 65535, scaled to 0 - 100 for simplicity)
ph_val = ph_sensor.read_u16() * 100 / 65535
tds_val = tds_sensor.read_u16() * 100 / 65535
# Read ultrasonic sensor
try:
level_cm = read_distance()
except:
level_cm = 0 # fallback if sensor reading fails
# Display on OLED
oled.fill(0)
oled.text("pH : {:.1f}".format(ph_val), 0, 0)
oled.text("TDS: {:.1f}".format(tds_val), 0, 10)
oled.text("Level: {:.1f}cm".format(level_cm), 0, 20)
oled.show()
# Actuator logic: turn on LED if pH or TDS out of bounds
if ph_val < 20 or ph_val > 80 or tds_val > 70:
led.value(1)
else:
led.value(0)
sleep(1)