Skip to content

Instantly share code, notes, and snippets.

@furkanbakkal
Created March 8, 2022 21:39
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 furkanbakkal/b3f01b296e7c1a0dc69b60e0fec01a03 to your computer and use it in GitHub Desktop.
Save furkanbakkal/b3f01b296e7c1a0dc69b60e0fec01a03 to your computer and use it in GitHub Desktop.
import RPi.GPIO as GPIO
import time
#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM) #GPIO mode
#set GPIO Pins
GPIO_TRIGGER = 4
GPIO_ECHO = 17
led=14
#setup GPIO pin (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
GPIO.setup(led, GPIO.OUT)
def distance():
# set Trigger to HIGH
GPIO.output(GPIO_TRIGGER, True)
# set Trigger after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
StartTime = time.time()
StopTime = time.time()
# save StartTime
while GPIO.input(GPIO_ECHO) == 0:
StartTime = time.time()
# save time of arrival
while GPIO.input(GPIO_ECHO) == 1:
StopTime = time.time()
# time difference between start and arrival
TimeElapsed = StopTime - StartTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2
return distance
try:
while True:
dist = distance()
print ("Measured Distance = %.1f cm" % dist)
time.sleep(0.5)
if dist<10: #if distance < 10 cm
GPIO.output(led, GPIO.HIGH) #led on
else :
GPIO.output(led, GPIO.LOW) #led off
except KeyboardInterrupt:
print("stopped by user")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment