from machine import Pin, PWM
import utime
Trig = Pin(15, Pin.OUT)
Echo = Pin(14, Pin.IN, Pin.PULL_DOWN)
Buzzer = PWM(Pin(6))
def CheckDistance():
SpeedOfSoundInCM = 0.1
Trig.low()
utime.sleep_us(2)
Trig.high()
utime.sleep_us(10)
Trig.low()
exitLoop = False
loopcount = 0 #used as a failsafe if the signal doesn't return
while Echo.value() == 0 and exitLoop == False:
loopcount = loopcount + 1
delaytime = utime.ticks_us()
if loopcount > 200 : exitLoop == True
while Echo.value() == 1 and exitLoop == False:
loopcount = loopcount + 1
receivetime = utime.ticks_us()
if loopcount > 200: exitLoop == True
if exitLoop == True: #We failed somewhere
return 0
else:
distance = ((receivetime - delaytime) * SpeedOfSoundInCM) / 2
return distance
while True:
distance = CheckDistance()
print(distance)
if CheckDistance() < 20:
Buzzer.duty_u16(200)
Buzzer.freq(1700)
utime.sleep(0.8)
Buzzer.duty_u16(0)
utime.sleep(CheckDistance()/1000)