首页 > 解决方案 > 缩短用于按顺序点亮 LED 的 python 代码

问题描述

我正在编写 python 3.7 代码以在一段时间内一次打开一个 LED。8 个 LED 通过电路连接到 Raspberry Pi 2 Model B V1.1。我希望用户能够按照他们定义的顺序和持续时间点亮 LED。我已经定义了 8 个函数来点亮每种颜色的 LED,这里只显示一个。这是我的第一次编码经验,我想知道是否有办法不对所有可能的序列组合进行手动编码,如下例所示。我只显示其中一个 LED 的树的开头。

import RPi.GPIO as GPIO
import time

q_colour = 'What LED colour would you like?'
q_duration = 'How many seconds should I turn it on for?'
q_another = 'Would you like to add another colour? yes/no'

def red_led(duration): 
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(18, GPIO.OUT)
    GPIO.output(18, HIGH)
    time.sleep(duration)
    GPIO.output(18, LOW)
    GPIO.cleanup()

while True:
    colour = input(q_colour)

    if colour == 'quit':
        break
    if colour == 'red':
        another_colour = input('q_another')
    if another_colour == 'no':
        duration = input(q_duration)
        red_led(duration)
    else:
        colour = input(q_colour)

标签: python-3.xraspberry-pi2led

解决方案


首先,我会将您的代码分成一个设置函数,您可以在其中设置所有引脚。

int red = 18
int green = 19
int blue = 20

def setup():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(red, GPIO.OUT)
    GPIO.setup(green, GPIO.OUT)
    GPIO.setup(blue, GPIO.OUT)

然后,您可以将函数概括为参数。

def turn_on_led(led):
    GPIO.output(led, HIGH)

def turn_off_led(led):
    GPIO.output(led, LOW)

# Initialize
setup()

# Example for a sequence should go into a function
turn_on_led(red)
turn_on_led(green)
time.sleep(5)
turn_off_led(red)
turn_off_led(green)

推荐阅读