Skip to content

Instantly share code, notes, and snippets.

@MarcScott
Last active March 5, 2021 18:50
Show Gist options
  • Save MarcScott/f9b2ebb37b32156eb5ebf2cb76bfef9d to your computer and use it in GitHub Desktop.
Save MarcScott/f9b2ebb37b32156eb5ebf2cb76bfef9d to your computer and use it in GitHub Desktop.
Pico Parking Sensor
from machine import Pin
from utime import sleep_us, ticks_us, sleep
trig=Pin(17, Pin.OUT)
echo=Pin(16, Pin.IN)
buzzer=Pin(27, Pin.OUT)
buzzer.value(1)
sleep(0.5)
buzzer.value(0)
def calc_cm(echo, trig):
## a 10 us signal to trig starts the internal ranging program of the sensor.
trig.low()
sleep_us(2)
trig.high()
sleep_us(10)
trig.low()
## echo pin is set high when the first pulses are sent out, so wait for the echo to go high
while echo.value() == 0:
pass
## Now record the time, then wait until the echo pin goes low, which means the echo has been received.
t1 = ticks_us()
while echo.value() == 1:
pass
# Record the time again, as the echo has been received
t2 = ticks_us()
## Calulate time difference.
## Speed of sound is approx 340m/s, which is 0.034 cm/us
## But the sound has traveled twice the distance, so need to / 2
## s = t * v
## s = (t2-t1) * 0.034 / 2
## s = (t2-t1) * 0.017 which is approximately
cm = (t2 - t1) / 58.0
return cm
while True:
cm = calc_cm(echo, trig)
print(cm)
if cm < 60:
buzzer.value(1)
sleep(0.01 * cm)
buzzer.value(0)
sleep(0.01 * cm)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment