Skip to content

Instantly share code, notes, and snippets.

@abdul-rehman-2050
Created January 12, 2018 16:56
Show Gist options
  • Save abdul-rehman-2050/523f03a621c6d47d1ae28863a4490387 to your computer and use it in GitHub Desktop.
Save abdul-rehman-2050/523f03a621c6d47d1ae28863a4490387 to your computer and use it in GitHub Desktop.
Raspberry Pi Lesson: Ultrasonic HC-SR04
import RPi.GPIO as GPIO
import time
TRIG = 24
ECHO = 23
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
while 1:
time.sleep(1)
GPIO.output(TRIG,True)
time.sleep(0.00001)
GPIO.output(TRIG,False)
while GPIO.input(ECHO)==0:
pulse_start = time.time()
while GPIO.input(ECHO)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance,2)
print "Distance = " + str(distance) + "cm"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment