以下是一个简单的Arduino Uno驱动WS2812(也称为NeoPixel)LED的例程。这个例子使用了Adafruit NeoPixel库来简化操作。
所需硬件:
Arduino Uno
WS2812 LED条(例如Adafruit NeoPixel)
电源(建议使用外部电源,WS2812功耗较大)
电阻(如果需要限流)
所需软件:
Arduino IDE
Adafruit NeoPixel库
安装Adafruit NeoPixel库:
1. 打开Arduino IDE。
2. 进入 `工具` -> `库管理器`。
3. 搜索 `Adafruit NeoPixel`,然后点击 `安装`。
连接方式:
将WS2812的 `DIN` 引脚连接到Arduino的数字引脚(例如D6)。
将WS2812的 `VCC` 和 `GND` 分别连接到Arduino的5V和GND。
如果使用多个LED或长条,建议使用外部电源为WS2812供电。
示例代码:
```cpp
#include <Adafruit_NeoPixel.h>
#define PIN 6 // WS2812数据引脚连接到Arduino的数字引脚6
#define NUMPIXELS 8 // WS2812 LED的数量
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
void setup() {
strip.begin(); // 初始化NeoPixel库
strip.show(); // 将所有像素设置为“关闭”
}
void loop() {
// 设置第一个LED为红色
strip.setPixelColor(0, strip.Color(255, 0, 0));
strip.show();
delay(500);
// 设置第二个LED为绿色
strip.setPixelColor(1, strip.Color(0, 255, 0));
strip.show();
delay(500);
// 设置第三个LED为蓝色
strip.setPixelColor(2, strip.Color(0, 0, 255));
strip.show();
delay(500);
// 设置所有LED为白色
for(int i=0; i<NUMPIXELS; i++) {
strip.setPixelColor(i, strip.Color(255, 255, 255));
}
strip.show();
delay(500);
// 关闭所有LED
strip.clear();
strip.show();
delay(500);
}
```
代码说明:
1. 库的引入:`Adafruit_NeoPixel.h` 是控制WS2812 LED的库。
2. 定义引脚和LED数量:`PIN` 是连接WS2812的数据引脚,`NUMPIXELS` 是LED的数量。
3. 初始化:在 `setup()` 函数中,调用 `strip.begin()` 初始化库,并调用 `strip.show()` 将所有LED关闭。
4. 控制LED:在 `loop()` 函数中,使用 `strip.setPixelColor()` 设置特定LED的颜色,然后调用 `strip.show()` 更新显示。
注意事项:
电源:WS2812 LED的功耗较大,尤其是当使用多个LED时。建议使用外部电源为LED供电,而不是直接从Arduino获取电源。
电阻:如果需要限流,可以在数据引脚上串联一个电阻(例如220Ω)。
地线:确保Arduino和WS2812的地线(GND)连接在一起。
扩展:
你可以根据需要修改代码,实现更复杂的效果,例如彩虹、渐变、闪烁等。Adafruit NeoPixel库提供了丰富的功能,可以参考其官方文档和示例。 |