Skip to content

Instantly share code, notes, and snippets.

@schappim
Created March 29, 2020 21:30
Show Gist options
  • Select an option

  • Save schappim/cb5fb96feae46d767bdb94ace547a859 to your computer and use it in GitHub Desktop.

Select an option

Save schappim/cb5fb96feae46d767bdb94ace547a859 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# Written by pcmanbob
# https://www.raspberrypi.org/forums/memberlist.php?mode=viewprofile&u=71930&sid=78c72fd5d7f7c6d39cf3b3ddcc9a0ed5
# See: https://www.raspberrypi.org/forums/viewtopic.php?t=228207#p1399745
# Import required Python libraries
import time
import RPi.GPIO as GPIO
# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Define GPIO to use on Pi
GPIO_TRIGGER = 23
GPIO_ECHO = 24
# Set pins as output and input
GPIO.setup(GPIO_TRIGGER,GPIO.OUT) # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN) # Echo
# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER, False)
print "Ultrasonic Measurement"
# Allow module to settle
time.sleep(0.5)
# Send 10us pulse to trigger
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO)==0:
start = time.time()
while GPIO.input(GPIO_ECHO)==1:
stop = time.time()
# Calculate pulse length
elapsed = stop-start
# Distance pulse travelled in that time is time
# multiplied by the speed of sound (cm/s)
distancet = elapsed * 34300
# That was the distance there and back so halve the value
distance = distancet / 2
print "Distance :", distance
print "Elaspsed time :", elapsed
print "Total distance :", distancet
# Reset GPIO settings
GPIO.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment