【花雕动手做】有趣好玩的音乐可视化系列小项目(10)---WS2812硬板屏
项目之十:Arduino 和 FastLED多彩音乐灯
- /*
- 【花雕动手做】有趣好玩的音乐可视化系列小项目(10)---WS2812硬板屏
- 项目之十:Arduino 和 FastLED多彩音乐灯
- */
-
- #include <FastLED.h>
- #define SAMPLEPERIODUS 200
- #define MIC_PIN A0
- #define LED_DT 6
- #define COLOR_ORDER GRB
- #define LED_TYPE WS2812
- #define NUM_LEDS 256
- uint8_t max_bright = 33;
- struct CRGB leds[NUM_LEDS];
- CRGBPalette16 currentPalette = RainbowColors_p;
- CRGBPalette16 targetPalette;
-
- void setup() {
- pinMode(LED_BUILTIN, OUTPUT);
- LEDS.addLeds<LED_TYPE, LED_DT, COLOR_ORDER>(leds, NUM_LEDS);
- FastLED.setBrightness(max_bright);
- }
-
- float bassFilter(float sample) {
- static float xv[3] = {0, 0, 0}, yv[3] = {0, 0, 0};
- xv[0] = xv[1]; xv[1] = xv[2];
- xv[2] = sample / 9.1f;
- yv[0] = yv[1]; yv[1] = yv[2];
- yv[2] = (xv[2] - xv[0]) + (-0.7960060012f * yv[0]) + (1.7903124146f * yv[1]);
- return yv[2];
- }
-
- float envelopeFilter(float sample) {
- static float xv[2] = {0, 0}, yv[2] = {0, 0};
- xv[0] = xv[1];
- xv[1] = sample / 160.f;
- yv[0] = yv[1];
- yv[1] = (xv[0] + xv[1]) + (0.9875119299f * yv[0]);
- return yv[1];
- }
-
- float beatFilter(float sample) {
- static float xv[3] = {0, 0, 0}, yv[3] = {0, 0, 0};
- xv[0] = xv[1]; xv[1] = xv[2];
- xv[2] = sample / 7.015f;
- yv[0] = yv[1]; yv[1] = yv[2];
- yv[2] = (xv[2] - xv[0]) + (-0.7169861741f * yv[0]) + (1.4453653501f * yv[1]);
- return yv[2];
- }
-
- void loop() {
- unsigned long time = micros();
- float sample, value, envelope, beat, thresh, micLev;
- for (uint8_t i = 0; ; ++i) {
- sample = (float)analogRead(MIC_PIN);
- micLev = ((micLev * 67) + sample) / 68;
- sample -= micLev;
- value = bassFilter(sample);
- value = abs(value);
- envelope = envelopeFilter(value);
- if (i == 200) {
- beat = beatFilter(envelope);
- thresh = 0.02f * 75.;
-
- if (beat > thresh) {
- digitalWrite(LED_BUILTIN, LOW);
-
- int strt = random8(NUM_LEDS / 2);
- int ende = strt + random8(NUM_LEDS / 2);
- for (int i = strt; i < ende; i++) {
- uint8_t index = inoise8(i * 30, millis() + i * 30);
- leds[i] = ColorFromPalette(currentPalette, index, 255, LINEARBLEND);
- }
- } else {
- digitalWrite(LED_BUILTIN, HIGH);
- }
- i = 0;
- }
-
- EVERY_N_SECONDS(5) {
- uint8_t baseC = random8();
- targetPalette = CRGBPalette16(CHSV(baseC + random8(32), 255, random8(128, 255)),
- CHSV(baseC + random8(64), 255, random8(128, 255)),
- CHSV(baseC + random8(64), 192, random8(128, 255)),
- CHSV(baseC + random8(), 255, random8(128, 255)));
- }
-
- EVERY_N_MILLISECONDS(50) {
- uint8_t maxChanges = 24;
- nblendPaletteTowardPalette(currentPalette, targetPalette, maxChanges);
- }
-
- EVERY_N_MILLIS(50) {
- fadeToBlackBy(leds, NUM_LEDS, 64);
- FastLED.show();
- }
-
- for (unsigned long up = time + SAMPLEPERIODUS; time > 20 && time < up; time = micros()) { }
-
- } // for i
- } // loop()
复制代码
|