import RPi.GPIO as GPIO
import time
TRIG_PIN = 2
ECHO_PIN = 4
BUZZER_PIN = 5
WATER_LEVEL_THRESHOLD = 30
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG_PIN, GPIO.OUT)
GPIO.setup(ECHO_PIN, GPIO.IN)
GPIO.setup(BUZZER_PIN, GPIO.OUT)
try:
while True:
# Trigger the ultrasonic sensor
GPIO.output(TRIG_PIN, False)
time.sleep(0.2) # Wait for sensor to settle
GPIO.output(TRIG_PIN, True)
time.sleep(0.00001)
GPIO.output(TRIG_PIN, False)
# Read the echo pulse duration
while GPIO.input(ECHO_PIN) == 0:
pulse_start = time.time()
while GPIO.input(ECHO_PIN) == 1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
# Convert the duration to distance (in centimeters)
distance = (pulse_duration * 34300) / 2 # Speed of sound is 343 m/s, and there and back journey
print("Distance: {:.2f} cm".format(distance))
# Check if the water level is below the threshold
if distance < WATER_LEVEL_THRESHOLD:
# Water level is below the threshold, sound the buzzer
GPIO.output(BUZZER_PIN, GPIO.HIGH)
else:
# Water level is above the threshold, turn off the buzzer
GPIO.output(BUZZER_PIN, GPIO.LOW)
time.sleep(1) # Delay to avoid continuous readings
except KeyboardInterrupt:
GPIO.cleanup()