import RPi.GPIO as GPIO
import time

# Define GPIO pins
TRIG = 23  # GPIO pin for the ultrasonic sensor's trigger
ECHO = 24  # GPIO pin for the ultrasonic sensor's echo
BUZZER = 17  # GPIO pin for the buzzer

# Set GPIO mode and initialize pins
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
GPIO.setup(BUZZER, GPIO.OUT)

def distance_measurement():
    # Trigger ultrasonic sensor
    GPIO.output(TRIG, True)
    time.sleep(0.00001)
    GPIO.output(TRIG, False)

    # Wait for echo to be HIGH (start time)
    while GPIO.input(ECHO) == 0:
        pulse_start = time.time()

    # Wait for echo to be LOW (end time)
    while GPIO.input(ECHO) == 1:
        pulse_end = time.time()

    # Calculate distance
    pulse_duration = pulse_end - pulse_start
    distance = pulse_duration * 17150  # Speed of sound (343m/s) divided by 2

    return distance

try:
    while True:
        dist = distance_measurement()
        print(f"Distance: {dist:.2f} cm")

        # Check if the distance is less than a threshold (e.g., 10 cm)
        if dist < 10:
            # Turn on the buzzer
            GPIO.output(BUZZER, GPIO.HIGH)
        else:
            # Turn off the buzzer
            GPIO.output(BUZZER, GPIO.LOW)

except KeyboardInterrupt:
    pass

# Cleanup GPIO on exit
GPIO.cleanup()
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT