#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) { // 开关按下 } 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; } } } } }请在开关按下那里添加第一条灯带从中间向两边亮起绿色,然后开始绿色呼吸,呼吸十秒之后变为红色呼吸
时间: 2024-03-22 07:37:23 浏览: 65
在开关按下那里添加以下代码可以实现第一条灯带从中间向两边亮起绿色,然后开始绿色呼吸,呼吸十秒之后变为红色呼吸:
```
// 第一条灯带从中间向两边亮起绿色
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);
}
// 绿色呼吸灯
for (int i = 0; i < 100; i++) {
int brightness = (exp(sin(i / 50.0 * PI)) - 0.36787944) * 255.0;
for (int j = 0; j < LED_COUNT_1; j++) {
leds_1[j].setRGB(0, brightness, 0);
}
FastLED.show();
delay(10);
}
// 红色呼吸灯
for (int i = 0; i < 100; i++) {
int brightness = (exp(sin(i / 50.0 * PI)) - 0.36787944) * 255.0;
for (int j = 0; j < LED_COUNT_1; j++) {
leds_1[j].setRGB(brightness, 0, 0);
}
FastLED.show();
delay(10);
}
```
注意,这段代码应该放在开关按下的 if 语句中,以确保只在开关按下时执行。同时,为了实现绿色和红色呼吸灯的切换,我在两段呼吸灯的代码中使用了不同的颜色值。
阅读全文