#MUHAMMAD AFIQ BIN MOHD AZHARI
#51221124217
#L05
from machine import Pin, ADC, I2C, PWM
from time import sleep
import ssd1306
import hcsr04
# --- Sensor Inputs ---
ph_sensor = ADC(Pin(32)) # Potentiometer for pH
tds_sensor = ADC(Pin(33)) # Potentiometer for TDS
# --- Outputs ---
dirty_led = Pin(14, Pin.OUT) # Red LED (dirty indicator)
valve_led = Pin(26, Pin.OUT) # Yellow LED (valve simulation)
pump_led = Pin(25, Pin.OUT) # Blue LED (pump simulation)
# --- Real buzzer using PWM ---
buzzer = PWM(Pin(27), freq=1000, duty=0) # 1kHz tone initially off
# --- Button ---
button = Pin(4, Pin.IN, Pin.PULL_UP) # Refill trigger
# --- Ultrasonic Sensor (HC-SR04) ---
ultrasonic = hcsr04.HCSR04(trigger_pin=18, echo_pin=19)
# --- OLED Display ---
i2c = I2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# --- Constants ---
PH_THRESHOLD = 2000
TDS_THRESHOLD = 2000
WATER_LEVEL_FULL_CM = 5 # Adjust as needed
refill_mode = False
def read_quality():
ph = ph_sensor.read()
tds = tds_sensor.read()
return ph, tds
def display_status(condition, level):
oled.fill(0)
oled.text("Smart Aquarium", 0, 0)
oled.text("Condition: " + condition, 0, 20)
oled.text("Level: " + level, 0, 40)
oled.show()
while True:
ph_val, tds_val = read_quality()
water_is_dirty = ph_val > PH_THRESHOLD or tds_val > TDS_THRESHOLD
if water_is_dirty and not refill_mode:
dirty_led.on()
buzzer.duty(512) # ON with tone
display_status("DIRTY", "-")
print("Status: DIRTY")
elif not refill_mode:
dirty_led.off()
buzzer.duty(0) # OFF
display_status("CLEAN", "-")
print("Status: CLEAN")
# Check for button press to refill
if not button.value() and water_is_dirty and not refill_mode:
print("Button pressed - starting refill")
refill_mode = True
buzzer.duty(0)
dirty_led.off()
valve_led.on()
pump_led.on()
display_status("CLEAN", "FILLING")
sleep(1)
# During refill, monitor water level
if refill_mode:
try:
distance = ultrasonic.distance_cm()
print(f"Water level: {distance:.1f} cm")
if distance <= WATER_LEVEL_FULL_CM:
valve_led.off()
pump_led.off()
display_status("CLEAN", "FULL")
print("Water is FULL")
refill_mode = False
sleep(150)
except OSError:
print("Ultrasonic read error")
sleep(0.5)