您现在的位置是:
网站首页
> 程序设计 
> 树莓派 
树莓派点亮led
简介树莓派点亮led,实现跑马灯效果B站链接 https://www.bilibili.com/video/BV1EB4y1c7Jq
一、接线
4个led的负极共用一个ground,阳极分别接4个GPIO口。4个阳极引脚分别是32, 36, 38, 40
二、封装GPIO
直接调用GPIO库时比较繁琐,切容易错误,先封装一个自己的GPIO库
class MyGPIO():
init_count = 0
mode = GPIO.BOARD
def __init__(self, idx, init_with_high):
if MyGPIO.init_count == 0:
GPIO.setmode(MyGPIO.mode)
MyGPIO.init_count += 1
self.idx = idx
initial = GPIO.HIGH if init_with_high else GPIO.LOW
GPIO.setup(self.idx, GPIO.OUT, initial=initial)
def __del__(self):
MyGPIO.init_count -= 1
if MyGPIO.init_count == 0:
GPIO.cleanup()
def high(self):
GPIO.output(self.idx, GPIO.HIGH)
def low(self):
GPIO.output(self.idx, GPIO.LOW)
三、封装单个led
class Led():
def __init__(self, idx):
self.gpio = MyGPIO(idx, init_with_high=False)
def turn_on(self):
self.gpio.high()
def turn_off(self):
self.gpio.low()
四、封装多个led
class LedArray():
def __init__(self, idxs=list()):
self.leds = list()
for idx in idxs:
self.leds.append(Led(idx))
1. 闪烁效果
def flash(self, interval_seconds=1, time_seconds=10):
while time_seconds > 0:
for led in self.leds:
led.turn_on()
time.sleep(interval_seconds)
for led in self.leds:
led.turn_off()
time.sleep(interval_seconds)
time_seconds -= interval_seconds * 2
2. 跑马灯效果
def marquee(self, interval_seconds=1, time_seconds=10):
while time_seconds > 0:
for led in self.leds:
led.turn_on()
time.sleep(interval_seconds)
led.turn_off()
time_seconds -= interval_seconds