#include <FastLED.h> #define LED_PIN_1 3 #define LED_PIN_2 6 #define LED_COUNT_1 53 #define LED_COUNT_2 7 #define BRIGHTNESS 255 #define LED_TYPE WS2812B #define COLOR_ORDER GRB CRGB leds_1[LED_COUNT_1]; CRGB leds_2[LED_COUNT_2]; int pin_switch = 10; // 定义数字输入口pin10接收开关状态 int switch_state = 0; // 定义开关状态变量 void setup() { FastLED.addLeds<LED_TYPE, LED_PIN_1, COLOR_ORDER>(leds_1, LED_COUNT_1); FastLED.addLeds<LED_TYPE, LED_PIN_2, COLOR_ORDER>(leds_2, LED_COUNT_2); FastLED.setBrightness(BRIGHTNESS); Serial.begin(9600);//设置串口波特率为9600kbps pinMode(pin_switch, INPUT); // 初始化数字输入口 } void loop() { switch_state = digitalRead(pin_switch); // 读取开关状态 // 开关按下 if (switch_state == LOW) { // 第一条灯带从中间向两边亮起绿色 for (int i = 0; i < LED_COUNT_1 / 2; i++) { leds_1[LED_COUNT_1 / 2 - i - 1].setRGB(0, 255, 0); leds_1[LED_COUNT_1 / 2 + i].setRGB(0, 255, 0); FastLED.show(); delay(50); } //5秒延时 delay(5000); } else { // 开关未按下,灯带状态为白色呼吸灯 bool breathing = true; // 定义一个变量用于记录呼吸灯状态 while (breathing) { // 当呼吸灯状态为true时,执行循环 int brightness = 0; for (int i = 0; i < 7680; i++) { brightness = (exp(sin(i / 50.0 * PI)) - 0.36787944) * 108.0; for (int j = 0; j < LED_COUNT_1; j++) { leds_1[j].setRGB(brightness, brightness, brightness); } FastLED.show(); delay(10); switch_state = digitalRead(pin_switch); if (switch_state == LOW) { // 如果开关被按下,退出循环 breathing = false; break; } } } } }在5秒延时之后添加慢慢熄灭灯带
时间: 2024-03-22 14:38:02 浏览: 56
LED_board:将Arduino连接到LED板!
你可以在开关未按下的情况下,在循环之后添加一个慢慢熄灭灯带的代码段,例如:
```
// 开关未按下,灯带状态为白色呼吸灯
bool breathing = true; // 定义一个变量用于记录呼吸灯状态
while (breathing) { // 当呼吸灯状态为true时,执行循环
int brightness = 0;
for (int i = 0; i < 7680; i++) {
brightness = (exp(sin(i / 50.0 * PI)) - 0.36787944) * 108.0;
for (int j = 0; j < LED_COUNT_1; j++) {
leds_1[j].setRGB(brightness, brightness, brightness);
}
FastLED.show();
delay(10);
switch_state = digitalRead(pin_switch);
if (switch_state == LOW) { // 如果开关被按下,退出循环
breathing = false;
break;
}
}
}
// 慢慢熄灭灯带
for (int i = 255; i >= 0; i--) {
for (int j = 0; j < LED_COUNT_1; j++) {
leds_1[j].setRGB(i, i, i);
}
FastLED.show();
delay(10);
}
```
这段代码首先在呼吸灯循环结束后,进入到一个新的循环,用于慢慢熄灭灯带。在这个循环中,我们从亮度最高的白色开始,慢慢降低亮度,最终将灯带熄灭。
阅读全文