from machine import Pin, SoftI2C
import utime
from time import ticks_us, ticks_diff
from i2c_lcd import I2cLcd
sda = Pin(21)
scl = Pin(22)
i2c = SoftI2C(sda=sda, scl=scl, freq=400000)
I2C_ADDR = 0x27
lcd = I2cLcd(i2c, I2C_ADDR, 4, 20)
trigger = Pin(14, Pin.OUT)
echo = Pin(27, Pin.IN)
motor = Pin(25, Pin.OUT)
switch = Pin(26, Pin.IN, Pin.PULL_UP)
motor_status = False
tank_height = 400
tank_capacity = 1000
def measure_distance():
trigger.value(0)
utime.sleep(0.002)
trigger.value(1)
utime.sleep_us(10)
trigger.value(0)
while echo.value() == 0:
pass
signaloff = ticks_us()
while echo.value() == 1:
pass
signalon = ticks_us()
time_pulse = ticks_diff(signalon, signaloff)
distance = (time_pulse * 0.0343) / 2
return distance
def update_lcd(distance, motor_status):
water_level = tank_height - distance
if water_level < 0:
water_level = 0
fill_percentage = (water_level / tank_height) * 100
if fill_percentage > 100:
fill_percentage = 100
current_capacity = (fill_percentage / 100) * tank_capacity
motor_status_str = "ON" if motor_status else "OFF"
lcd.move_to(0, 0)
lcd.putstr(f"Filled: {fill_percentage:.2f}% ")
lcd.move_to(0, 1)
lcd.putstr(f"Motor: {motor_status_str:<4} ")
lcd.move_to(0, 2)
lcd.putstr(f"Capacity: 400L ")
lcd.move_to(0, 3)
lcd.putstr(f"Tank Height: {tank_height} cm")
lcd.clear()
lcd.putstr("HydroMeter Pro")
utime.sleep(2)
while True:
distance = measure_distance()
if switch.value() == 0:
utime.sleep(0.2)
motor_status = not motor_status
motor.value(motor_status)
update_lcd(distance, motor_status)
utime.sleep(1)