Issue
I'm using the Raspberry Pi 3 and controlling three LEDs with Python. I could say I'm good with Python. Here's my code:
import RPi.GPIO as GPIO
import time
#GPIO Pins
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(17,GPIO.OUT)
GPIO.setup(27,GPIO.OUT)
GPIO.setup(22,GPIO.OUT)
def led(color,state):
if state == "on":
if color == "g": #green
GPIO.output(27,GPIO.HIGH)
elif color == "y": #yellow
GPIO.output(22,GPIO.HIGH)
elif color == "r": #red
GPIO.output(17,GPIO.HIGH)
print ("LED on")
elif state == "off":
if color == "g":
GPIO.output(27,GPIO.LOW)
elif color == "y":
GPIO.output(22,GPIO.LOW)
elif color == "r":
GPIO.output(17,GPIO.LOW)
print ("LED off")
while True:
leds_col = input("Color (r, g, y): ")
leds_stat = input("On or Off: ")
led(leds_col, leds_stat)
I have a function called led()
that takes two arguments, color
(g, y or r) and state
(on or off). In the while loop, leds_col
asks for the color in the console and leds_stat
for the status.
Now what I'm trying to achieve is rather than asking for the colour in a different line and the status of the led in another line, is to combine them two. So for example I'd write on the console:
g, on
And it would turn on the green LED.
I know i can just use an if statement like:
if led_input == "g, on": GPIO.output(27,GPIO.HIGH)
But I'm sure there's a better way to do this.
Solution
Use string.split():
while True:
what = input("Color [r,g,y] and state [on,off] (ex.: 'r on'): ").strip().lower().split()
if len(what)==2:
leds_col,leds_stat = what
# sort the color input to reduce possible values
leds_col = ''.join(sorted(leds_col))
if leds_col not in "r g y gr ry gy gry" or leds_stat not in "on off":
continue
else:
continue
led(leds_col, leds_stat)
If invalid input is given, this will continue
to ask until inputs are valid.
See Asking the user for input until they give a valid response for more ideas on input validation.
Unrelated - but you can optimize your led
-function:
def led(color,state):
d = {"on":GPIO.HIGH, "off":GPIO.LOW,
"g":27, "y":22, "r":17}
for c in color:
GPIO.output(d[c],d[state])
print("LED",color,state)
by using a lookup dictionary: see dict()
Answered By - Patrick Artner