This code plays a song on a buzzer connected to pin 13 by sending tone signals of varying frequencies and durations. It defines constants for the buzzer pin, song length, and tempo. Arrays store the note durations and character notes. In setup, the buzzer pin is set as output. The main loop plays each note by generating a tone signal for its duration before a delay. A frequency function maps character notes to frequencies.
This code plays a song on a buzzer connected to pin 13 by sending tone signals of varying frequencies and durations. It defines constants for the buzzer pin, song length, and tempo. Arrays store the note durations and character notes. In setup, the buzzer pin is set as output. The main loop plays each note by generating a tone signal for its duration before a delay. A frequency function maps character notes to frequencies.
//length of song in notes. const int songLength = 89; //time in ms between beats int tempo = 180 ; //duration of each note and space between int beats[] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,4}; //actual notes of song grouped together as it would be played char notes[] = "e bcd cba ace dcb cd e c a a d fA Gfe ce dcb cd e c a a E C D B C X g B E C D B C E a a G ";
void setup() { // put your setup code here, to run once: pinMode(buzzerPin, OUTPUT);
//sets buzzer pin to output mode.
}
//main function that runs code.
void loop() { // put your main code here, to run repeatedly: //variable that helps to know the space between notes.
int i, duration; //loop that goes all the way through the song. for (i = 0; i < songLength; i++) {
duration = beats[i] * tempo
//if there is space, have a space between notes. if (notes[i] == ' ' ) { delay(duration); } else { //otherwise, play sound. tone(buzzerPin, frequency(notes[i]), duration); delay(duration); } delay(tempo / 10); //space between notes } }
int frequency(char note) {
int i; const int numNotes = 14; //number of different note variables // array stores character of each note variable. char names[] = {'e', 'b', 'c', 'd', 'a', 'f', 'A', 'E', 'C', 'D', 'B', 'X', 'g', 'G'}; // frequencies that coincide with certain note char int frequencies[] = {659, 493, 523, 587, 440, 698, 880, 329, 261, 293, 246, 220, 207, 415}; for (i = 0; i < numNotes; i++) { // checks note type through different types, then checks if it is a actual note, // then, it returns frequency assigned to that note. if (names[i] == note) { return (frequencies[i]); } } return (0); }