Reputation: 15
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()
This code was given to me as part of this project:https://www.instructables.com/id/Raspberry-Pi-Park-Sensor/
when I plug everything in and set up my code properly indented I get "return distance" outside function. Can someone explain what is happening to me? sometimes the code doesn't even run. I tried indenting the return distance etc. but it still is not working. Can someone please show the proper way to display this code into python and I wonder if globalvariable can play apart of this as well
Upvotes: 0
Views: 45
Reputation: 37
like Klaus said the identation is important, I can't test it at the moment, but I purpose you to debug your file to see where the bug appears.
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, True)
GPIO.output(YELLOW, False)
GPIO.output(RED, False)
def yellow_light():
GPIO.output(GREEN, False)
GPIO.output(YELLOW, True)
GPIO.output(RED, False)
def red_light():
GPIO.output(GREEN, False)
GPIO.output(YELLOW, False)
GPIO.output(RED, True)
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()
Upvotes: 1