from machine import Pin, PWM import utime Trig = Pin(27, Pin.OUT) Echo = Pin(26, Pin.IN, Pin.PULL_DOWN) Buzzer = PWM(Pin(18)) def CheckDistance(): SpeedOfSoundInCM = 0.034 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 > 3000 : exitLoop == True while Echo.value() == 1 and exitLoop == False: loopcount = loopcount + 1 receivetime = utime.ticks_us() if loopcount > 3000 : 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() < 10: Buzzer.duty_u16(3000) Buzzer.freq(1700) utime.sleep(0.05) Buzzer.duty_u16(0) utime.sleep(CheckDistance() / 1000)