P2 如何使用树莓派制作流水灯

Introduction

此章我们将会学习如何让八个LED产生你想要的多种闪烁效果,当然,还是在树莓派的基础上进行试验。

What you will need

  • 树莓派×1
  • 线路板×1
  • 网络电缆×1
  • LED×8
  • 电阻(220Ω)×8
  • 跳线

What you will do

通过编程由上到下依次设置GPIO0至GPIO7,然后你会看到LED0至LED7被依次点亮。你可以通过控制它们的延迟时间和点亮顺序使得八个LED闪烁出不同的效果。

第一步:如下图所示连接电路

第二步:使用nano编辑和保存代码

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()

 

发表评论