代码:
#define musicpin 5 //喇叭引脚 int song[] = { //音乐音频 392, 392, 440, 392, 523, 493, 392, 392, 440, 392, 587, 523, 392, 392, 784, 659, 523, 493, 440, 698, 698, 659, 523, 587, 523 }; int noteDurations[] = { //音节长度 6, 6, 3, 3, 3, 2, 6, 6, 3, 3, 3, 2, 6, 6, 3, 3, 3, 3, 2, 6, 6, 3, 3, 3, 2 }; void play1() //音频播放函数 { for (int thisNote = 0; thisNote < 25; thisNote++) { int noteDuration = 1000 / noteDurations[thisNote]; // 计算每个节拍的时间,以一个节拍一秒为例,四分之一拍就是1000/4毫秒,八分之一拍就是1000/8毫秒 tone(musicpin, song[thisNote], noteDuration); int pauseBetweenNotes = noteDuration * 1.30; // 每个音符间的停顿间隔,以该音符的130%为佳 delay(pauseBetweenNotes); noTone(musicpin); } }; void setup() { pinMode(musicpin, OUTPUT);//初始化IO } void loop() { play1(); delay(2000); //等待2秒 }