#include <FastLED.h>
#define C_0 -1
#define C_1 262
#define C_2 294
#define C_3 330
#define C_4 350
#define C_5 393
#define C_6 441
#define C_7 495
// 灯带定义
#define LED_PIN 8
#define NUM_LEDS 16
CRGB leds[NUM_LEDS];
int yinfu[] = {C_1,C_2,C_3,C_1,C_1,C_2,C_3,C_1,C_3,C_4,C_5,
C_3,C_4,C_5,C_5,C_6,C_5,C_4,C_3,C_1,C_5,C_6,C_5,C_4,C_3,
C_1,C_1,C_5,C_1,C_1,C_5,C_1};
float yinpai[] = {1,1,1,1,1,1,1,1,1,1,2,1,1,2,0.75,0.25,0.75,0.25,1,1,
0.75,0.25,0.75,0.25,1,1,1,1,2,1,1,2};
int length;
int tonepin = 2;
// 根据音符频率计算亮灯个数
int getLedCount(int note) {
if (note == C_0) return 0;
else if (note <= C_2) return 2;
else if (note <= C_4) return 5;
else if (note <= C_6) return 9;
else return NUM_LEDS;
}
void setup() {
pinMode(tonepin, OUTPUT);
FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(50);
length = sizeof(yinfu) / sizeof(yinfu[0]);
}
void loop() {
for (int i = 0; i < length; i++) {
int note = yinfu[i];
int ledCount = getLedCount(note);
// 更新灯带:前ledCount个灯亮,其余熄灭
fill_solid(leds, NUM_LEDS, CRGB::Black);
for (int j = 0; j < ledCount; j++) {
leds[j] = CRGB::White;
}
FastLED.show();
// 播放音符
if (note != C_0) {
tone(tonepin, note);
}
delay(400 * yinpai[i]);
noTone(tonepin);
}
fill_solid(leds, NUM_LEDS, CRGB::Black);
FastLED.show();
delay(1000);
}