//---------------------------------------------------
// ที่มาของโค้ด
// https://youtu.be/YX4HR5XUMhQ?si=NFe4lgsHegDXUXuM
//---------------------------------------------------
const int speakerPin = 9;
// ------------------------------------------------------------------------
byte beat = 120;
unsigned int speed = (60000 / beat) / 4;
// ------------------------------------------------------------------------
char noteNames[] = { 'g', 'a', 'b', 'C', 'D', 'E', 'F', 'G', 'A', 'B', ' ' };
unsigned int frequencies[] = { 196, 220, 246, 262, 294, 330, 349, 392, 440, 494, 0 };
const byte noteCount = sizeof(noteNames);
//-------------------------------------------------------------------------
// Cherry Pink And Apple Blossom White
char score[] =
"gCEGFEF" "EDFF"
"GABAGFE" "G"
"gCEGFEF" "EDAA"
"GEDC"
;
const byte scorelength = sizeof(score);
byte beats[scorelength] = {
2, 2, 2, 2, 2, 2, 2, 4, 2, 2, 8,
2, 2, 2, 2, 2, 2, 2, 8,
2, 2, 2, 2, 2, 2, 2, 4, 2, 2, 8,
4, 4, 4, 8
};
// ------------------------------------------------------------------------
void setup() {
pinMode(speakerPin, OUTPUT);
delay(100);
}
// ------------------------------------------------------------------------
void loop() {
for (int i = 0; i < scorelength; i++) {
int duration = beats[i] * speed;
playNote(score[i], duration);
}
delay(4000);
}
// ------------------------------------------------------------------------
void playNote(char note, int duration) {
// ฟังก์ชันสำหรับเล่นโน้ตตัวเดียว
for (int i = 0; i < noteCount; i++) {
if (noteNames[i] == note) {
if (frequencies[i] > 0) {
tone(speakerPin, frequencies[i], duration);
}
}
}
delay(duration);
}