首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

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

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

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180324G0810500?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券