Created
July 16, 2019 06:44
-
-
Save winhtut/b19e3ecb716a4478657f6d4fef839ce7 to your computer and use it in GitHub Desktop.
raspberrypi ultrasonic
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
import RPi.GPIO as GPIO | |
import time | |
GPIO.setwarnings(False) | |
GPIO.cleanup() | |
GPIO.setmode(GPIO.BCM) | |
TRIG = 4 | |
ECHO = 18 | |
GREEN = 17 | |
YELLOW = 27 | |
RED = 22 | |
GPIO.setup(TRIG,GPIO.OUT) | |
GPIO.setup(ECHO,GPIO.IN) | |
GPIO.setup(GREEN,GPIO.OUT) | |
GPIO.setup(YELLOW,GPIO.OUT) | |
GPIO.setup(RED,GPIO.OUT) | |
def green_light(): | |
GPIO.output(GREEN, GPIO.HIGH) | |
GPIO.output(YELLOW, GPIO.LOW) | |
GPIO.output(RED, GPIO.LOW) | |
def yellow_light(): | |
GPIO.output(GREEN, GPIO.LOW) | |
GPIO.output(YELLOW, GPIO.HIGH) | |
GPIO.output(RED, GPIO.LOW) | |
def red_light(): | |
GPIO.output(GREEN, GPIO.LOW) | |
GPIO.output(YELLOW, GPIO.LOW) | |
GPIO.output(RED, GPIO.HIGH) | |
def get_distance(): | |
GPIO.output(TRIG, True) | |
time.sleep(0.00001) | |
GPIO.output(TRIG, False) | |
while GPIO.input(ECHO) == False: | |
start = time.time() | |
while GPIO.input(ECHO) == True: | |
end = time.time() | |
signal_time = end-start | |
distance = signal_time / 0.000058 | |
return distance | |
while True: | |
distance = get_distance() | |
time.sleep(0.05) | |
print(distance) | |
if distance >= 25: | |
green_light() | |
elif 25 > distance > 10: | |
yellow_light() | |
elif distance <= 5: | |
red_light() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment