from machine import Pin, PWM
import utime
# Pin setup
Trig = Pin(15, Pin.OUT)
Echo = Pin(14, Pin.IN, Pin.PULL_DOWN)
Buzzer = PWM(Pin(6))
def measure_distance():
SpeedOfSoundInCM = 0.034
Trig.low()
utime.sleep_us(2)
Trig.high()
utime.sleep_us(10)
Trig.low()
# Measure the time taken for the sound wave to return
timeout = 3000
loopcount = 0
while Echo.value() == 0 and loopcount < timeout:
delaytime = utime.ticks_us()
loopcount += 1
loopcount = 0
while Echo.value() == 1 and loopcount < timeout:
receivetime = utime.ticks_us()
loopcount += 1
if loopcount >= timeout:
return 0
else:
# Calculate distance in cm
distance = ((receivetime - delaytime) * SpeedOfSoundInCM) / 2
return distance
while True:
distance = measure_distance()
print(distance)
if distance < 10:
# Activate buzzer for a short duration
Buzzer.duty_u16(3000)
Buzzer.freq(1700)
utime.sleep(0.05)
Buzzer.duty_u16(0)
utime.sleep(distance / 1000)