from machine import Pin
import time
print("Hello, ESP32!")
trig = Pin(5, Pin.OUT)
echo = Pin(14, Pin.IN)
buzzer = Pin(13, Pin.OUT)
def get_distance():
trig.off()
time.sleep_us(2)
trig.on()
time.sleep_us(10)
trig.off()
while echo.value() == 0:
pulse_start = time.ticks_us()
while echo.value() == 1:
pulse_end = time.ticks_us()
pulse_duration = time.ticks_diff(pulse_end, pulse_start)
distance = (pulse_duration * 0.0343) / 2
return distance
def buzz():
buzzer.on()
time.sleep(0.1)
buzzer.off()
time.sleep(0.1)
while True:
distance = get_distance()
print("Distance:", distance, "cm")
if distance < 50:
buzz()
time.sleep(1)