推荐一些聚拢流水灯的代码示例
时间: 2024-12-23 22:19:26 浏览: 2
聚拢流水灯通常指的是LED灯带效果,它是一种通过编程控制灯光逐个亮起、熄灭,形成流动动画的效果。这里提供一个简单的Python库`RPi.GPIO`和`threading`结合的示例,适用于Raspberry Pi平台:
```python
import RPi.GPIO as GPIO
import time
# 假设灯带使用了16个GPIO Pin,从GPIO 17到GPIO 32
LED_PINS = [17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 31, 32]
def light_up(pin):
GPIO.output(pin, True)
print(f"LED {pin} turned on")
def light_down(pin):
GPIO.output(pin, False)
print(f"LED {pin} turned off")
def ripple_effect():
for i in LED_PINS:
light_up(i) # 先点亮
time.sleep(0.1) # 等待一段时间
light_down(i) # 再关闭
try:
GPIO.setmode(GPIO.BCM) # 使用BCM模式
for pin in LED_PINS:
GPIO.setup(pin, GPIO.OUT) # 初始化为输出
# 创建一个线程来运行流光效果
thread = threading.Thread(target=ripple_effect)
thread.start()
# 主函数等待线程完成
thread.join()
except KeyboardInterrupt:
print("Caught keyboard interrupt, cleaning up...")
finally:
GPIO.cleanup() # 清理GPIO资源
```
阅读全文