# 硬件器材
* 樹莓派3B+
* [古德微樹莓派擴展板]([https://item.taobao.com/item.htm?spm=a1z10.3-c.w4002-22298106374.9.158170c90MOfva&id=578376338324](https://item.taobao.com/item.htm?spm=a1z10.3-c.w4002-22298106374.9.158170c90MOfva&id=578376338324))
* [柔性ws2812貼片led燈帶]([https://item.taobao.com/item.htm?spm=a1z10.3-c.w4002-22298106374.9.4cbc70c9a29bu7&id=584515172003](https://item.taobao.com/item.htm?spm=a1z10.3-c.w4002-22298106374.9.4cbc70c9a29bu7&id=584515172003))
鏈接方式如下圖。

>當然采用古德微擴展板只是為了方便,直接插到板子上就好了,其實只要有樹莓派和燈帶,燈帶正確的連接到樹莓派就可以使用本教程。
# 安裝燈帶相關的python庫
樹莓派控制led燈帶需要用到[rpi-ws281x-python](https://github.com/rpi-ws281x/rpi-ws281x-python)庫,具體安裝方法如下。
```
sudo pip install rpi-ws281x
```
# 用法簡介
控制燈帶主要用的是`PixelStrip`類,這個類的方法和屬性如下:
```
>>> dir(rpi_ws281x.PixelStrip)
[..., 'begin', 'getBrightness', 'getPixelColor', 'getPixelColorRGB', 'getPixels', 'numPixels', 'setBrightness', 'setGamma', 'setPixelColor', 'setPixelColorRGB', 'show']
```
## 初始化燈帶
初始化燈帶主要用到如下代碼:
```
strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
```
參數中大寫的變量是在測試代碼中定義了的,含義如下:
```python
# LED 配置:
LED_COUNT = 10 # 要控制LED的數量.
LED_PIN = 18 # GPIO接口 (PWM編碼).
LED_BRIGHTNESS = 255 # 設置LED亮度 (0-255)
#以下LED配置無需修改
LED_FREQ_HZ = 800000 # LED信號頻率(以赫茲為單位)(通常為800khz)
LED_DMA = 10 # 用于生成信號的DMA通道(嘗試10)
LED_INVERT = False # 反轉信號(使用NPN晶體管電平移位時)
```
所以你會看到古德微的平臺中只需要你設定燈帶LED燈的數量,引腳和亮度了。

圖片中的這個積木塊與`strip = PixelStrip(18 10, 800000, 10, False, 50, 0)`是完全等效的。其中**LED信號頻率、DMA通道(不明白沒關系)、翻轉信號以及信道等參數無需配置**,所以這個庫其實還可以繼續簡化的。
## 顏色設置
`rip_ws281x`庫中顏色的設置是通過`Color`類實現的,等效于下列積木塊:

幫助信息如下:
```
Color(red, green, blue, white=0)
根據參數指定的紅綠藍顏色的值合成24位的顏色.。
每種顏色的范圍是0到255,最小值是0,最大值255。
```
所以上面積木塊等效的代碼就是`Color(50, 30, 10)`。
## 設定LED顏色

設定顏色是通過`setPixelColor()`方法實現的,上述積木塊的等效代碼是`strip.setPixelColor(1, Color(50, 30, 10))`
## 其他

實際上每種積木塊都有對應的方法,而且代碼相比來說更加靈活,比如設定顏色:
```
setPixelColorRGB(self, n, red, green, blue, white=0) unbound rpi_ws281x.rpi_ws281x.PixelStrip method
Set LED at position n to the provided red, green, and blue color.
Each color component should be a value from 0 to 255 (where 0 is the
lowest intensity and 255 is the highest intensity).
```
直接通過顏色指定單個LED燈的顏色,比如`setPixelColorRGB(1, 50, 30, 10)`,也可以根據自己的使用習慣定義自己的函數。
同時`'getBrightness', 'getPixelColor', 'getPixelColorRGB', 'getPixels', 'numPixels'`等用來獲取燈帶信息的函數,是積木塊有待實現的。
# 燈帶特效
## 顏色刷新

開始的時候燈帶沒有顏色,一共60個LED燈,從0開始,每隔0.05秒,點亮一共LED燈,這樣整個燈帶就從不亮,到全亮,顏色可以指定,比如原來是全綠色,就可以用紅色依次替代原來的綠色。

# 測試案例代碼
測試案例提供了多種特效,代碼也寫的很有參考價值。復制下面的代碼,并保存為strandtest.py,按照圖中的命令執行就可以了。

```
#!/usr/bin/env python3
# NeoPixel library strandtest example
# Author: Tony DiCola (tony@tonydicola.com)
#
# Direct port of the Arduino NeoPixel library strandtest example. Showcases
# various animations on a strip of NeoPixels.
import time
from rpi_ws281x import PixelStrip, Color
import argparse
# LED strip configuration:
LED_COUNT = 16 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).
# LED_PIN = 10 # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10 # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest
LED_INVERT = False # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53
# Define functions which animate LEDs in various ways.
def colorWipe(strip, color, wait_ms=50):
"""Wipe color across display a pixel at a time."""
for i in range(strip.numPixels()):
strip.setPixelColor(i, color)
strip.show()
time.sleep(wait_ms / 1000.0)
def theaterChase(strip, color, wait_ms=50, iterations=10):
"""Movie theater light style chaser animation."""
for j in range(iterations):
for q in range(3):
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i + q, color)
strip.show()
time.sleep(wait_ms / 1000.0)
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i + q, 0)
def wheel(pos):
"""Generate rainbow colors across 0-255 positions."""
if pos < 85:
return Color(pos * 3, 255 - pos * 3, 0)
elif pos < 170:
pos -= 85
return Color(255 - pos * 3, 0, pos * 3)
else:
pos -= 170
return Color(0, pos * 3, 255 - pos * 3)
def rainbow(strip, wait_ms=20, iterations=1):
"""Draw rainbow that fades across all pixels at once."""
for j in range(256 * iterations):
for i in range(strip.numPixels()):
strip.setPixelColor(i, wheel((i + j) & 255))
strip.show()
time.sleep(wait_ms / 1000.0)
def rainbowCycle(strip, wait_ms=20, iterations=5):
"""Draw rainbow that uniformly distributes itself across all pixels."""
for j in range(256 * iterations):
for i in range(strip.numPixels()):
strip.setPixelColor(i, wheel(
(int(i * 256 / strip.numPixels()) + j) & 255))
strip.show()
time.sleep(wait_ms / 1000.0)
def theaterChaseRainbow(strip, wait_ms=50):
"""Rainbow movie theater light style chaser animation."""
for j in range(256):
for q in range(3):
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i + q, wheel((i + j) % 255))
strip.show()
time.sleep(wait_ms / 1000.0)
for i in range(0, strip.numPixels(), 3):
strip.setPixelColor(i + q, 0)
# Main program logic follows:
if __name__ == '__main__':
# Process arguments
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit')
args = parser.parse_args()
# Create NeoPixel object with appropriate configuration.
strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
# Intialize the library (must be called once before other functions).
strip.begin()
print('Press Ctrl-C to quit.')
if not args.clear:
print('Use "-c" argument to clear LEDs on exit')
try:
while True:
print('Color wipe animations.')
colorWipe(strip, Color(255, 0, 0)) # Red wipe
colorWipe(strip, Color(0, 255, 0)) # Blue wipe
colorWipe(strip, Color(0, 0, 255)) # Green wipe
print('Theater chase animations.')
theaterChase(strip, Color(127, 127, 127)) # White theater chase
theaterChase(strip, Color(127, 0, 0)) # Red theater chase
theaterChase(strip, Color(0, 0, 127)) # Blue theater chase
print('Rainbow animations.')
rainbow(strip)
rainbowCycle(strip)
theaterChaseRainbow(strip)
except KeyboardInterrupt:
if args.clear:
colorWipe(strip, Color(0, 0, 0), 10)
```
參考資料
1. 樂鷹計算機工作室[樹莓派控制WS2812B燈帶 - Python](https://www.dellts.cn/article/88.html)
- 簡介
- 更新樹莓派源
- GPIO Zero基礎案例
- 導入GPIO Zero庫
- 引腳編碼
- 樹莓派代碼編輯器
- LED
- 電磁繼電器
- 呼吸燈
- LED條形圖
- led條
- 交通燈
- 按鈕
- 按鈕控制LED燈
- 用按鈕控制攝像頭
- 舵機
- 關機按鈕
- 按鈕拍照
- 反應速度游戲
- 音樂盒子
- 單個按鈕控制多個元件
- 全彩燈
- 人體紅外傳感器
- 亮度傳感器
- 距離傳感器
- 馬達控制
- 機器人
- 按鈕控制機器人
- 鍵盤控制機器人
- 紅外感應機器人
- 電位器
- 用數模轉換器測量溫度
- 通過3個電位器控制全彩燈
- 時控加熱燈
- 聯網狀態指示
- CPU溫度條形圖
- 更多
- OLED屏幕
- GPIO Zero基礎案例2
- 古德微樹莓派案例
- ws2812燈帶python案例
- ads1115
- 高級秘籍
- 4 配置遠程GPIO
- 5 遠程GPIO案例
- 5.1 LED和按鈕
- 6 樹莓派Zero OTG USB數據線
- 7.數據源和值
- 微信發送疫情
- 8. 命令行工具
- 9. 常見問題
- 10. 從RPi.GPIO庫遷移到GPIO Zero
- 公眾號文章
- Python繪制疫情圖表
- 百度人工智能案例
- vscode配置樹莓派遠程開發環境
- Jupyter Notebook相關
- 樹莓派拍攝定格動畫
- oled
- 創客與音樂
- 如何入門Python
- 交通標志