Ardunio Song

posted on March 12, 2023, 6:23 a.m.


I got all my components with this this kit. It includes a speaker to play the song! As I no longer have a picture of the setup, I cannot guide on the specific pin connections used, however, everything is self-explanatory in the code below.


const int buzzerPin = 9;
const int songLength = 18;
char notes[] = "cdfda ag cdfdg gf "; // a space represents a rest
int beats[] = {1,1,1,1,1,1,4,4,2,1,1,1,1,1,1,4,4,2};
int tempo = 150;
const int button1Pin = 2;
const int ledPin = 3; // LED pin
void setup()
{
pinMode(button1Pin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
}

void loop()
{
int button1State;
button1State = digitalRead(button1Pin);
int i, duration;

if (((button1State == LOW))) // if we're pushing button 1
{

digitalWrite(buzzerPin, HIGH);
for (i = 0; i < songLength; i++) // step through the song arrays
{
digitalWrite(ledPin, HIGH);
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
digitalWrite(ledPin, LOW);
}
}




}

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); // We looked through everything and didn't find it,
// but we still need to return a value, so return 0.
}


File
SHA256
Download