怎么用按键控制WS2812灯带
灯带的功能目前都正常,但是想用一个按钮按下灯带亮工作一次,然后熄灭。现在用while和if都试过了,按钮总是无效的。后面用红字注释的位置。
#include <FastLED.h>
#define WS_NUM_LEDS 47
//D1到D5分别5组LED
#define WS_DATA_PIN1 D1
#define WS_DATA_PIN2 D2
#define WS_DATA_PIN3 D3
#define WS_DATA_PIN4 D4
#define WS_DATA_PIN5 D5
#define WS_COLOR GRB
int duration = 20;
CRGB ws_leds;
void selectLED(int pin) {
for(int i=0;i<WS_NUM_LEDS;i++){
FastLED.delay(duration<50 ? duration=duration+20 : duration);
ws_leds = CRGB::Red;
//ws_leds = rgb;
ws_leds =CRGB::Blue;
//ws_leds = rgb;
}
FastLED.show();
delay(100);
FastLED.clear();
// 选择5个不重复的随机LED让它们长亮
int selectedLeds;
for (int i = 0; i < 5; i++) {
int index;
bool duplicate;
do {
index = random(0,35);
duplicate = false;
for (int j = 0; j < i; j++) {
if (selectedLeds == index) {
duplicate = true;
break;
}
}
} while (duplicate);
selectedLeds = index;
ws_leds = CRGB::Blue;
}
// 选择2个不重复的随机LED让它们长亮
int SelectedLeds;
randomSeed(analogRead(0));
for (int x = 0; x < 2; x++) {
int index;
bool duplicate;
do {
index = random(35,47);
duplicate = false;
for (int y = 0; y < x; y++) {
if (SelectedLeds == index) {
duplicate = true;
break;
}
}
} while (duplicate);
SelectedLeds = index;
ws_leds = CRGB::Red;
}
FastLED.show();
delay(3000);
fill_solid(ws_leds, WS_NUM_LEDS, CRGB::Black);
FastLED.show();
delay(1000);
}
void setup() {
FastLED.setBrightness(10);
randomSeed(analogRead(A0));
pinMode(D7,INPUT_PULLUP); //D7设为上拉输入模式
}
int Val = digitalRead(D7);//将开关状态数值读取到变量中
void loop() {
while(Val == HIGH) { //现在是while(Val == HIGH) 灯带循环,while(Val==LOW)灯带就一直不亮,按键也没用
//设置芯片型号,和信号引脚,以及RGB灯珠的顺序(GRB 表示绿红蓝)
FastLED.addLeds<WS2812B, WS_DATA_PIN1, WS_COLOR>(ws_leds, WS_NUM_LEDS);
selectLED(D1);
FastLED.addLeds<WS2812B, WS_DATA_PIN2, WS_COLOR>(ws_leds, WS_NUM_LEDS);
selectLED(D2);
FastLED.addLeds<WS2812B, WS_DATA_PIN3, WS_COLOR>(ws_leds, WS_NUM_LEDS);
selectLED(D3);
FastLED.addLeds<WS2812B, WS_DATA_PIN4, WS_COLOR>(ws_leds, WS_NUM_LEDS);
selectLED(D4);
FastLED.addLeds<WS2812B, WS_DATA_PIN5, WS_COLOR>(ws_leds, WS_NUM_LEDS);
selectLED(D5);
}
}
把while改成用if实现,再把第72行int Val = digitalRead(D7);放在loop里面
帅猫 发表于 2023-12-23 22:02
把while改成用if实现,再把第72行int Val = digitalRead(D7);放在loop里面
{:6_204:}非常靠谱
页:
[1]