1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| int buzzerPin=D5; // 蜂鸣器引脚 const int songLength = 18; char notes[] = "cdfda ag cdfdg gf "; int beats[] = {1,1,1,1,1,1,4,4,2,1,1,1,1,1,1,4,4,2}; int tempo = 150; void setup() { pinMode(buzzerPin, OUTPUT); } void loop() { int i, duration; for (i = 0; i < songLength; i++) // step through the song arrays { duration = beats[i] \* tempo; // length of note/rest in ms if (notes[i] == ' ') // is this a rest? { delay(duration); // then pause for a moment } else // otherwise, play the note { tone(buzzerPin, frequency(notes[i]), duration); delay(duration); // wait for tone to finish } delay(tempo/10); // brief pause between notes } while(true){} } int frequency(char note) { int i; const int numNotes = 8; // number of notes we're storing char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' }; int frequencies[] = {262, 294, 330, 349, 392, 440, 494, 523}; for (i = 0; i < numNotes; i++) // Step through the notes { if (names[i] == note) // Is this the one? { return(frequencies[i]); // Yes! Return the frequency } } return(0); }
|