from machine import Pin
import utime
trigger = Pin(20, Pin.OUT)
echo = Pin(21, Pin.IN)
buzzer = Pin(22, Pin.OUT) # Assuming you're using GPIO pin 22 for the buzzer
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
print("The distance from object is ", distance, "cm")
if distance < 10: # Example threshold, adjust as needed
activate_buzzer()
def activate_buzzer():
buzzer.on() # Turns on the buzzer
utime.sleep(0.1) # Keep it on for a short duration (adjust as needed)
buzzer.off() # Turns off the buzzer
while True:
ultra()
utime.sleep(1)