Created
May 12, 2018 04:38
-
-
Save scriptpapi/662637dd33b2d647dfdf0269fe3f7086 to your computer and use it in GitHub Desktop.
Python code that reads in distance from HC-SR04 sensor on RasparryPi3
This file contains hidden or 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
# Modified from https://pimylifeup.com/raspberry-pi-distance-sensor | |
import RPi.GPIO as GPIO | |
import time | |
try: | |
GPIO.setmode(GPIO.BOARD) | |
PIN_TRIGGER = 7 | |
PIN_ECHO = 11 | |
GPIO.setup(PIN_TRIGGER, GPIO.OUT) | |
GPIO.setup(PIN_ECHO, GPIO.IN) | |
GPIO.output(PIN_TRIGGER, GPIO.LOW) | |
print "Waiting for sensor to settle" | |
time.sleep(2) | |
print "Calculating distance" | |
while True: | |
GPIO.output(PIN_TRIGGER, GPIO.HIGH) | |
time.sleep(1) | |
GPIO.output(PIN_TRIGGER, GPIO.LOW) | |
while GPIO.input(PIN_ECHO)==0: | |
pulse_start_time = time.time() | |
while GPIO.input(PIN_ECHO)==1: | |
pulse_end_time = time.time() | |
pulse_duration = pulse_end_time - pulse_start_time | |
distance = round(pulse_duration * 17150, 2) | |
print "Distance:",distance,"cm" | |
finally: | |
GPIO.cleanup() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment