Songs on an Arduino

What you need:

To begin this tutorial, please download the generic song creator file above. Open the file and scroll down to the part of the loop that says “// Song goes here”. This is where all notes and rests should go. You can see an example of this in the comments.

To fully understand how to do this, we need a little bit of key information. When programming a song, you will likely need multiple octaves. To allow for this, I have named each note by its respective octave. Where NOTE_C4 is middle C and the note below NOTE_C4 is NOTE_B3. To sharp a note, simply place an S after the note, ie NOTE_CS4 refers to the sharped middle C.

The next bit of information we need is the note lengths. The normal note lengths have been defined and can be operated on as if they are numbers, ie HALFNOTE = QUARTERNOTE * 2 and a 32nd note = EIGHTHNOTE/2.

Now, we need to know how to use the notes and note lengths. We can use them in one of the three functions, note, rest, and spacedNote (which creates a tiny delay after a note). The note and spacedNote functions appear in this form, “note(NOTE_NAME, LENGTH);” and the rest function appears in the form “rest(LENGTH);”.

Lastly, we need to know what settings we can use. There are 4 main settings to be aware of. The first setting is the speakerPin, which is the pin connected to one of the piezoelectric speaker wires (with the other end connected through a resistor to ground). This pin must be a PWM pin. The tempo is obviously for setting the speed of the song. The continuePlaying option allows the program to repeat, and the continueDelay sets how long to wait (in ms) before replaying.

Once you understand what all the functions do and what all the variables mean, you can begin creating a song. Simply add the notes and rests in the indicated sections and manipulate the settings above the loop and you are ready to play music using your Arduino.

Here is an example file with which a rough version of Fur Elise is constructed (Same file as the video). As you may see in the file, it can be very useful to number your measures using comments. Numbering measures can allow for easier bug fixing and copy and pasting.

I hope you enjoyed this tutorial. Please feel free to leave comments and suggestions. Enjoy!

One comment on “Songs on an Arduino

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s