Created
December 3, 2018 02:12
-
-
Save dreilly369/52ee1b79b188de56e6707dbc566ac0c6 to your computer and use it in GitHub Desktop.
Simple Python 3 test of the HC-SR04 module on Raspberry Pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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