Skip to content

Instantly share code, notes, and snippets.

@suadanwar
Created June 16, 2021 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suadanwar/81ca2b83383310fa170a76bdf56771fb to your computer and use it in GitHub Desktop.
Save suadanwar/81ca2b83383310fa170a76bdf56771fb to your computer and use it in GitHub Desktop.
The sample code for ultrasonic sensor with Raspberry Pi Pico
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment