Nou*_*Dev 1 python python-3.x raspberry-pi raspberry-pi3
我正在使用Raspberry Pi 3并使用Python控制三个LED.我可以说我对Python很好.这是我的代码:
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)
Run Code Online (Sandbox Code Playgroud)
我有一个调用函数led(),它接受两个参数,color(g,y或r)和state(on或off).在while循环中,leds_col询问控制台中的颜色和leds_stat状态.现在我想要实现的不是要求在另一条线上的颜色和另一条线中的led的状态,而是将它们合二为一.例如,我在控制台上写道:
g, on
Run Code Online (Sandbox Code Playgroud)
它会打开绿色LED.我知道我可以使用if语句:
if led_input == "g, on": GPIO.output(27,GPIO.HIGH)
但我确信有更好的方法可以做到这一点.
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)
Run Code Online (Sandbox Code Playgroud)
如果给出无效输入,则continue在输入有效之前询问.请参阅询问用户输入,直到他们对输入验证的更多想法给出有效响应.
不相关 - 但你可以优化你的led功能:
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)
Run Code Online (Sandbox Code Playgroud)
通过使用查找字典:请参阅dict()
| 归档时间: |
|
| 查看次数: |
322 次 |
| 最近记录: |