#include #include #include // 主灯组设置(8块×4颗 = 32颗) #define NUM_MAIN_LEDS 32 #define MAIN_DATA_PIN 2 // 灯带设置 #define NUM_STRIP_LEDS 8 #define STRIP_DATA_PIN 11 #define BRIGHTNESS 100 const int hallPins[8] = {3, 4, 5, 6, 7, 8, 9, 10}; bool hallLastState[8] = {HIGH}; CRGB mainLeds[NUM_MAIN_LEDS]; CRGB stripLeds[NUM_STRIP_LEDS]; // 灯带控制 bool stripFlashing = false; unsigned long stripStartTime = 0; const unsigned long stripDuration = 30000; // 30秒 unsigned long lastFlashToggleTime = 0; bool stripOn = false; uint8_t colorIndex = 0; CRGB colorList[7] = {CRGB::Red, CRGB::Orange, CRGB::Yellow, CRGB::Green, CRGB::Blue, CRGB::Indigo, CRGB::Violet}; // DFPlayer 相关 SoftwareSerial mySerial(12, 13); // RX, TX DFRobotDFPlayerMini myDFPlayer; bool musicPlaying = false; unsigned long musicStartTime = 0; const unsigned long musicPlayDuration = 30000; // 音乐播放30秒 unsigned long lastMusicTime = 0; const unsigned long musicCooldown = 5000; void setup() { FastLED.addLeds(mainLeds, NUM_MAIN_LEDS); FastLED.addLeds(stripLeds, NUM_STRIP_LEDS); FastLED.setBrightness(BRIGHTNESS); for (int i = 0; i < 8; i++) { pinMode(hallPins[i], INPUT); } Serial.begin(115200); mySerial.begin(9600); if (!myDFPlayer.begin(mySerial)) { Serial.println("无法初始化 DFPlayer Mini!"); while (true); } Serial.println("DFPlayer Mini 初始化成功"); myDFPlayer.volume(20); } void loop() { bool anyNewTriggered = false; unsigned long now = millis(); // 主灯组控制:四个不同颜色 for (int i = 0; i < 8; i++) { int state = digitalRead(hallPins[i]); int startIndex = i * 4; if (hallLastState[i] == HIGH && state == LOW) { anyNewTriggered = true; } if (state == LOW) { mainLeds[startIndex + 0] = CRGB::Red; mainLeds[startIndex + 1] = CRGB::Green; mainLeds[startIndex + 2] = CRGB::Blue; mainLeds[startIndex + 3] = CRGB::Yellow; } else { for (int j = 0; j < 4; j++) { mainLeds[startIndex + j] = CRGB::Black; } } hallLastState[i] = state; } // 音效播放逻辑(每次触发时启动一次30秒播放) if (anyNewTriggered) { if (!musicPlaying && (now - lastMusicTime >= musicCooldown)) { myDFPlayer.play(1); // 播放 001.mp3 musicPlaying = true; musicStartTime = now; lastMusicTime = now; } // 启动灯带闪烁 if (!stripFlashing) { stripFlashing = true; stripStartTime = now; lastFlashToggleTime = 0; colorIndex = 0; } } // 音乐播放停止判断 if (musicPlaying && (now - musicStartTime >= musicPlayDuration)) { myDFPlayer.stop(); musicPlaying = false; } // 灯带闪烁逻辑(7种颜色循环) if (stripFlashing) { if (now - stripStartTime < stripDuration) { if (now - lastFlashToggleTime >= 300) { stripOn = !stripOn; for (int i = 0; i < NUM_STRIP_LEDS; i++) { stripLeds[i] = stripOn ? colorList[colorIndex] : CRGB::Black; } if (stripOn) { colorIndex = (colorIndex + 1) % 7; } lastFlashToggleTime = now; } } else { stripFlashing = false; for (int i = 0; i < NUM_STRIP_LEDS; i++) { stripLeds[i] = CRGB::Black; } } } FastLED.show(); delay(20); }