import RPi.GPIO as GPIO
import lcd1602
import time
# Ultrasonic sensor pins
TRIG_PIN = 5
ECHO_PIN = 6
# Buzzer pin
BUZZER_PIN = 13
# LCD display initialization
lcd = lcd1602.LCD1602()
lcd.init(0x27, 1) # LCD address and number of lines
# Setup GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(TRIG_PIN, GPIO.OUT)
GPIO.setup(ECHO_PIN, GPIO.IN)
GPIO.setup(BUZZER_PIN, GPIO.OUT)
# Function to measure distance using the ultrasonic sensor
def get_distance():
GPIO.output(TRIG_PIN, True)
time.sleep(0.00001)
GPIO.output(TRIG_PIN, False)
pulse_start = time.time()
pulse_end = time.time()
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
distance = pulse_duration * 17150 # Speed of sound in cm/s
return round(distance, 2)
try:
while True:
distance = get_distance()
lcd.clear()
lcd.write_string("Water Level:")
lcd.setCursor(0, 1)
lcd.write_string(f"{distance} cm")
if distance < 70: # Adjust this threshold as needed
GPIO.output(BUZZER_PIN, GPIO.HIGH)
else:
GPIO.output(BUZZER_PIN, GPIO.LOW)
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()