使用树莓派控制led灯板ws2812

推荐一个库 Adafruit_NeoPixel

这里是地址:https://github.com/adafruit/Adafruit_NeoPixel

这个原本是在Arduino上控制led的库

github上的介绍:

Arduino library for controlling single-wire-based LED pixels and strip such as the Adafruit 60 LED/meter Digital LED strip, the Adafruit FLORA RGB Smart Pixel, the Adafruit Breadboard-friendly RGB Smart Pixel, the Adafruit NeoPixel Stick, and the Adafruit NeoPixel Shield.

After downloading, rename folder to ‘Adafruit_NeoPixel’ and install in Arduino Libraries folder. Restart Arduino IDE, then open File->Sketchbook->Library->Adafruit_NeoPixel->strandtest sketch.

Compatibility notes: Port A is not supported on any AVR processors at this time

Supported chipsets

We have included code for the following chips - sometimes these break for exciting reasons that we can’t control in which case please open an issue!

AVR ATmega and ATtiny (any 8-bit) - 8 MHz, 12 MHz and 16 MHz

Teensy 3.x and LC

Arduino Due

Arduino 101

ATSAMD21 (Arduino Zero/M0 and other SAMD21 boards) @ 48 MHz

ATSAMD51 @ 120 MHz

Adafruit STM32 Feather @ 120 MHz

ESP8266 any speed

ESP32 any speed

Nordic nRF52 (Adafruit Feather nRF52), nRF51 (micro:bit)

Check forks for other architectures not listed here!

用在树莓派(python)上面也是一样的:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-skmaMHBm-1603779810385)(https://cdn-learn.adafruit.com/assets/assets/000/063/650/medium800/leds_NeoPixel_Single_LED_Red.jpg?1539811956)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-peSFGw36-1603779810398)(https://cdn-learn.adafruit.com/assets/assets/000/063/651/medium800/leds_NeoPixel_All_LEDs_Green.jpg?1539811967)]

下面是我做的成品地址:https://www.bilibili.com/video/av47393296

欢迎来讨论

下面是代码哦:

import time
import board
import neopixel

pixel_pin = board.D18 #定义针脚
num_pixels = 30 #定义LED个数
ORDER = neopixel.GRB

pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.2, auto_write=False,
pixel_order=ORDER)


def wheel(pos):
# Input a value 0 to 255 to get a color value.
# The colours are a transition r - g - b - back to r.
if pos < 0 or pos > 255:
r = g = b = 0
elif pos < 85:
r = int(pos * 3)
g = int(255 - pos*3)
b = 0
elif pos < 170:
pos -= 85
r = int(255 - pos*3)
g = 0
b = int(pos*3)
else:
pos -= 170
r = 0
g = int(pos*3)
b = int(255 - pos*3)
return (r, g, b) if ORDER == neopixel.RGB or ORDER == neopixel.GRB else (r, g, b, 0)


def rainbow_cycle(wait):
for j in range(255):
for i in range(num_pixels):
pixel_index = (i * 256 // num_pixels) + j
pixels[i] = wheel(pixel_index & 255)
pixels.show()
time.sleep(wait)


while True:

pixels.fill((255, 0, 0))
pixels.show()
time.sleep(1)
pixels.fill((0, 255, 0))
pixels.show()
time.sleep(1)
pixels.fill((0, 0, 255))
pixels.show()
time.sleep(1)
rainbow_cycle(0.001)