P2 树莓派流水灯制作 Flow LED
Introduction
此章节我们将学习如何通过一个按钮打开或者关闭LED。
What you will need
树莓派×1
线路板×1
网络电缆×1
LED×8
电阻(220Ω)×8
跳线
What you will do
通过编程由上到下依次设置GPIO0至GPIO7,然后你会看到LED0至LED7被依次点亮。你可以通过控制它们的延迟时间和点亮顺序使得八个LED闪烁出不同的效果。
第一步:如下图所示连接电路
第二步:使用nano编辑和保存代码
这里主要运用for构建一个loop来依次点亮led,而闪烁的占空比我们通过time模块来实现。
def loop():
while True:
for pin in pins:
GPIO.output(pin, GPIO.LOW)
time.sleep(0.5)
GPIO.output(pin, GPIO.HIGH)
Python code
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
pins = [11, 12, 13, 15, 16, 18, 22, 7]
def setup():
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
for pin in pins:
GPIO.setup(pin, GPIO.OUT) # Set all pins' mode is output
GPIO.output(pin, GPIO.HIGH) # Set all pins to high(+3.3V) to off led
def loop():
while True:
for pin in pins:
GPIO.output(pin, GPIO.LOW)
time.sleep(0.5)
GPIO.output(pin, GPIO.HIGH)
def destroy():
for pin in pins:
GPIO.output(pin, GPIO.HIGH) # turn off all leds
GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
destroy()
领取专属 10元无门槛券
私享最新 技术干货