Skip to content

Instantly share code, notes, and snippets.

@SaraM92
Created July 10, 2024 19:37
Show Gist options
  • Save SaraM92/ebcb61c3402a24673d66b4d5aac19c31 to your computer and use it in GitHub Desktop.
Save SaraM92/ebcb61c3402a24673d66b4d5aac19c31 to your computer and use it in GitHub Desktop.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
trig = 23
echo = 24
led = 14
GPIO.setup(echo, GPIO.IN)
GPIO.setup(trig, GPIO.OUT)
GPIO.setup(led, GPIO.OUT)
while True:
GPIO.output(trig, True)
time.sleep(0.00001) # 10 microseconds
GPIO.output(trig, False)
while GPIO.input(echo) == 0:
pass
start = time.time()
while GPIO.input(echo) == 1:
pass
end = time.time()
distance = ((end - start) * 34300) / 2
print("distance:", distance, "cm")
time.sleep(1)
if distance < 20:
print("LED on")
GPIO.output(led, GPIO.HIGH)
time.sleep(1)
print("LED off")
GPIO.output(led, GPIO.LOW)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment