#include <Adafruit_NeoPixel.h>
// 定义WS2812的引脚和灯珠数量
#define LED_PIN 9
#define LED_COUNT 16
// 定义按钮引脚
#define BUTTON_PIN 2
// 创建NeoPixel对象
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
// 定义变量
unsigned long previousMillis = 0;
const long interval = 100; // 流水灯更新间隔(毫秒)
int currentPixel = 0;
// 按钮状态变量
int buttonState = 0;
int lastButtonState = HIGH; // 记录上一次按钮状态
int colorIndex = 0; // 当前颜色索引
// 定义几种颜色
const uint32_t colors[] = {
strip.Color(255, 0, 0), // 红色
strip.Color(0, 255, 0), // 绿色
strip.Color(0, 0, 255), // 蓝色
strip.Color(255, 255, 0), // 黄色
strip.Color(255, 0, 255), // 紫色
strip.Color(0, 255, 255) // 青色
};
void setup() {
// 初始化串口通信
Serial.begin(9600);
// 初始化WS2812灯带
strip.begin();
strip.show(); // 初始化所有灯珠为关闭状态
// 设置按钮引脚为输入模式
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void loop() {
// 读取按钮状态
buttonState = digitalRead(BUTTON_PIN);
// 检测按钮是否从高电平变为低电平(按下)
if (lastButtonState == HIGH && buttonState == LOW) {
Serial.println("Button pressed!");
// 切换到下一种颜色
colorIndex = (colorIndex + 1) % (sizeof(colors) / sizeof(colors[0]));
// 设置所有灯珠为新颜色
for (int i = 0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, colors[colorIndex]);
}
strip.show();
}
// 更新上一次按钮状态
lastButtonState = buttonState;
// 获取当前时间
unsigned long currentMillis = millis();
// 检查是否到了更新流水灯的时间
if (currentMillis - previousMillis >= interval) {
// 保存上一次更新的时间
previousMillis = currentMillis;
// 清除之前的灯珠颜色
strip.clear();
// 设置当前灯珠颜色为当前选择的颜色
strip.setPixelColor(currentPixel, colors[colorIndex]);
// 显示更新后的灯珠颜色
strip.show();
// 移动到下一个灯珠
currentPixel++;
if (currentPixel >= strip.numPixels()) {
currentPixel = 0;
}
}
}