int buzzer = 8;
// 簡譜對應頻率(C 大調,低音 4 號鍵為 C4 = 262Hz)
int noteFreq[] = {
0, // 0 = 無音
262, // 1 = C
294, // 2 = D
330, // 3 = E
349, // 4 = F
392, // 5 = G
440, // 6 = A
494 // 7 = B
};
// 播放單一音符的函數
void playNote(int note, int duration) {
if (note == 0) {
noTone(buzzer); // 休止符
} else {
tone(buzzer, noteFreq[note], duration);
}
delay(duration * 1.3); // 加入間隔
noTone(buzzer);
}
// 播放簡譜陣列的函數
void playMelody(int melody[], int beats[], int length) {
for (int i = 0; i < length; i++) {
int duration = 1000 / beats[i]; // 四分音符為 250ms
playNote(melody[i], duration);
}
}
// 小星星簡譜(1~7 對應 C D E F G A B)
int twinkleMelody[] = {
1, 1, 5, 5, 6, 6, 5, 0,
4, 4, 3, 3, 2, 2, 1, 0,
5, 5, 4, 4, 3, 3, 2, 0,
5, 5, 4, 4, 3, 3, 2, 0,
1, 1, 5, 5, 6, 6, 5, 0,
4, 4, 3, 3, 2, 2, 1
};
int twinkleBeats[] = {
4, 4, 4, 4, 4, 4, 2, 4,
4, 4, 4, 4, 4, 4, 2, 4,
4, 4, 4, 4, 4, 4, 2, 4,
4, 4, 4, 4, 4, 4, 2, 4,
4, 4, 4, 4, 4, 4, 2, 4,
4, 4, 4, 4, 4, 4, 2
};
void setup() {
// 無需初始化
}
void loop() {
int length = sizeof(twinkleMelody) / sizeof(int);
playMelody(twinkleMelody, twinkleBeats, length);
}
留言
張貼留言