三个按键控制八个流水灯亮灭的程序
时间: 2024-09-23 17:13:13 浏览: 38
4按键控制16LED流水灯基于51
要编写一个简单的程序,使用三个按键控制八个流水灯(LED)的亮灭,我们可以假设每个按键对应两个相邻的灯泡,通过轮流点亮和熄灭这两个灯泡来实现。这里是一个基本的Python示例,我们使用GPIO库在Raspberry Pi上实现:
```python
import RPi.GPIO as GPIO
import time
# 定义灯泡列表和按键
lights = [7, 8, 9, 10, 11, 12, 13, 15] # GPIO pin numbers for lights
buttons = [4, 17, 27] # GPIO pins for buttons
GPIO.setmode(GPIO.BCM)
def setup():
GPIO.setup(lights, GPIO.OUT)
GPIO.setup(buttons, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def light_cycle(i):
GPIO.output(lights[i], GPIO.HIGH) # Turn on the light
time.sleep(0.5) # Short delay
GPIO.output(lights[i], GPIO.LOW) # Turn off the light
def button_handler(pin):
if GPIO.input(pin) == False: # Button is pressed
index = buttons.index(pin)
light_cycle(index * 2) # Switch on/off every two lights
light_cycle(index * 2 + 1)
def main():
setup()
while True:
for button in buttons:
button_handler(button)
time.sleep(0.1) # Small delay to debounce the buttons
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
GPIO.cleanup() # Clean up GPIO pins when interrupted
```
在这个程序中,`setup()`函数初始化GPIO,并设置按键为输入模式、灯泡为输出。`light_cycle(i)`函数负责开关指定位置的灯,`button_handler(pin)`则监听按键,当按下时切换相应范围内的灯。`main()`函数持续监控按键并响应。
阅读全文