python-3.x - 缩短用于按顺序点亮 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)
解决方案
首先,我会将您的代码分成一个设置函数,您可以在其中设置所有引脚。
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)
推荐阅读
- python - 如何在python中传递文件路径?
- r - 填充地图上 geom_point 的 ggplot2 图例
- reactjs - ReactJS react-step-wizard 在动画后关注输入
- flutter - 如何使用 Flutter bloc 构建一个文本字段,在用户键入时将其值更新为另一个小部件?
- apache - 使用 .htaccess 强制 SSL + www + 子目录
- sql - 连接 Google Big Query 中的重复记录
- sql - 从 SQL Server 表的查询中提取外键约束和引用列
- python - 将列从一个数据帧映射到另一个具有多个 id 和日期的数据帧
- textarea - 如何实现多行输出
- css - 仅在显示引导模式后才应用 CSS 动画