from machine import Pin, time_pulse_us
import time
# Define pins
PIN_TRIG = Pin(26, Pin.OUT)
PIN_ECHO = Pin(25, Pin.IN)
LOWLED = Pin(18, Pin.OUT)
MIDLED = Pin(19, Pin.OUT)
EMPTY = Pin(21, Pin.OUT)
MOTOR = Pin(27, Pin.OUT)
# Initialize the pins
LOWLED.value(1)
MIDLED.value(1)
EMPTY.value(1)
MOTOR.value(0)
def measure_distance():
# Trigger the ultrasonic pulse
PIN_TRIG.value(1)
time.sleep_us(10)
PIN_TRIG.value(0)
# Measure the duration of the echo pulse
duration = time_pulse_us(PIN_ECHO, 1, 30000) # Timeout after 30ms
# Convert to distance in cm
distance_cm = duration / 58
return distance_cm
while True:
level = measure_distance()
print("Distance in CM:", level)
print("Water Level:", 400 - level)
if level <=100: # Tank is full
print("Water Level is Full.")
LOWLED.value(1)
MIDLED.value(1)
EMPTY.value(1) # Only set once
MOTOR.value(1)
print("MOTOR is turned off")
elif 200 <= level < 300: # Low water level
print("Water Level is Low.")
LOWLED.value(0) # Low LED on
MIDLED.value(1)
EMPTY.value(1)
MOTOR.value(0)
print("MOTOR is turned on")
elif 100 <= level < 200:
print("Water Level is Normal.")
LOWLED.value(1)
MIDLED.value(0) # Mid LED on
EMPTY.value(1)
MOTOR.value(0)
print("MOTOR is turned on")
elif level > 300 :
print("Tank is Empty.")
LOWLED.value(1)
MIDLED.value(1)
EMPTY.value(0) # Emmpty LED on
MOTOR.value(0)
print("MOTOR is turned on")
time.sleep(1)