Skip to content

Instantly share code, notes, and snippets.

@dreilly369
Created December 3, 2018 02:12
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 dreilly369/52ee1b79b188de56e6707dbc566ac0c6 to your computer and use it in GitHub Desktop.
Save dreilly369/52ee1b79b188de56e6707dbc566ac0c6 to your computer and use it in GitHub Desktop.
Simple Python 3 test of the HC-SR04 module on Raspberry Pi
import RPi.GPIO as GPIO
from time import sleep, time
# RPi Setup stuff
GPIO.setmode(GPIO.BCM)
trig = 23
echo = 24
GPIO.setup(trig, GPIO.OUT)
GPIO.setup(echo, GPIO.IN)
GPIO.output(trig, False)
sleep(1) # let the system and sensor settle
while True: # Loop forever
GPIO.output(trig, True)
sleep(0.00001) # keep pin high for 10 uS
GPIO.output(trig, False)
# Wait for the incoming pulse
while GPIO.input(echo) == 0:
pulse_start = time()
# Wait for the end ofthe pulse
while GPIO.input(echo) == 1:
pulse_end = time()
# Measure the width of the pulse base on python's timing
pulse_duration = pulse_end - pulse_start
dist_cm = pulse_duration / 58
dist_in = pulse_duration / 148
print(("Distance in centimeters: ", dist_cm))
print(("Distance in inches: ", dist_in))
sleep(0.05) # Let the sound dissipate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment