from machine import Pin
import time
# Define pin numbers
PIN_TRIG = 26
PIN_ECHO = 25
LOW_LED = 18
MID_LED = 19
HIGH_LED = 21
MOTOR = 27
# Setup pins
trig = Pin(PIN_TRIG, Pin.OUT)
echo = Pin(PIN_ECHO, Pin.IN)
low_led = Pin(LOW_LED, Pin.OUT)
mid_led = Pin(MID_LED, Pin.OUT)
high_led = Pin(HIGH_LED, Pin.OUT)
motor = Pin(MOTOR, Pin.OUT)
# Initialize pin states
low_led.value(1) # LED OFF (Active LOW)
mid_led.value(1) # LED OFF
high_led.value(1) # LED OFF
motor.value(0) # Motor OFF (Active HIGH)
def measure_distance():
# Send a 10-microsecond pulse to trigger pin
trig.value(1)
time.sleep_us(10)
trig.value(0)
# Measure the pulse duration on the echo pin
while echo.value() == 0:
pass
start_time = time.ticks_us()
while echo.value() == 1:
pass
end_time = time.ticks_us()
# Calculate distance (duration in microseconds -> distance in cm)
duration = time.ticks_diff(end_time, start_time)
distance_cm = duration / 58
return distance_cm
while True:
distance = measure_distance()
print("Distance in CM:", distance)
print("Distance in inches:", distance / 2.54)
# Control LEDs and motor based on distance
if distance < 100: # Low water level
low_led.value(0) # Turn ON LOW_LED
mid_led.value(1) # Turn OFF MID_LED
high_led.value(1) # Turn OFF HIGH_LED
motor.value(1) # Turn ON MOTOR
elif 100 <= distance < 400: # Medium water level
low_led.value(1) # Turn OFF LOW_LED
mid_led.value(0) # Turn ON MID_LED
high_led.value(1) # Turn OFF HIGH_LED
elif distance >= 400: # High water level
low_led.value(1) # Turn OFF LOW_LED
mid_led.value(1) # Turn OFF MID_LED
high_led.value(0) # Turn ON HIGH_LED
motor.value(0) # Turn OFF MOTOR
time.sleep(1) # Wait 1 second before next measurement