from machine import Pin
import utime
trigger = Pin(7, Pin.OUT)
echo = Pin(2, Pin.IN)
# Define water level thresholds
WATER_LEVEL_LOW = 100 # Adjust this value based on your setup
WATER_LEVEL_HIGH = 400 # Adjust this value based on your setup
# Define buzzer pin and configure it as an output
buzzer_pin = Pin(6, Pin.OUT)
# Define the watering pin and configure it as an output
watering_pin = Pin(8, Pin.OUT)
def ultra():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(5)
trigger.low()
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
distance = (timepassed * 0.0343) / 2
return distance
def activate_buzzer():
# Function to activate the buzzer
buzzer_pin.on()
utime.sleep(1) # Buzzer on for 1 second
buzzer_pin.off()
def start_watering():
# Function to start watering
watering_pin.on()
print("\nWatering started.")
activate_buzzer() # Activate the buzzer when watering starts
def stop_watering():
# Function to stop watering
watering_pin.off()
print("\nWatering stopped.")
activate_buzzer() # Activate the buzzer when watering stops
def check_water_level():
distance = ultra()
print("\nThe distance from the object is", distance, "cm")
# Check the water level
if distance < WATER_LEVEL_LOW:
print("\nWater level is low. Refill the tank.")
start_watering() # Start watering when water level is low
elif distance > WATER_LEVEL_HIGH:
print("\nWater level is high. Tank is full.")
stop_watering() # Stop watering when water level is high
else:
print("\nWater level is within the acceptable range.")
while True:
check_water_level()
utime.sleep(1)