# Project objectives:
# Detect water level using ultrasonic sensor, display results on the console,
# and trigger a buzzer if water level is 10 cm or less.
#
# Hardware connections used:
# Ultrasonic sensor VCC to 5V, GND to GND, Trig to GPIO 16, Echo to GPIO 17
# Buzzer Signal to GPIO 18
from machine import Pin, I2C
from time import sleep, ticks_us
# Ultrasonic sensor setup
trigger = Pin(16, Pin.OUT)
echo = Pin(17, Pin.IN)
# Buzzer setup
buzzer = Pin(18, Pin.OUT)
# function to measure distance using ultrasonic sensor
def get_distance():
# trigger pulse
trigger.low()
sleep(0.02)
trigger.high()
sleep(0.00001) # 10 microseconds pulse
trigger.low()
# wait for echo response
while echo.value() == 0:
signal_off = ticks_us()
while echo.value() == 1:
signal_on = ticks_us()
# calculate pulse duration and distance
time_passed = signal_on - signal_off
distance = (time_passed * 0.0343) / 2 # convert time to distance (cm)
return distance
# function to control the buzzer
def trigger_buzzer(state):
buzzer.value(state) # state is 1 for ON and 0 for OFF
# continuously get sensor readings while the board has power
while True:
# Measure distance dynamically using the ultrasonic sensor
distance = get_distance()
# check if water level is 10 cm or less
if distance <= 10:
print(f"Water level: {distance:.1f} cm - ALERT!")
trigger_buzzer(1) # turn the buzzer ON
else:
print(f"Water level: {distance:.1f} cm")
trigger_buzzer(0) # turn the buzzer OFF
# delay of 1 second between readings
sleep(1)