What We’re DoingTo this point we have controlled light, motion, and electrons, Let’s tackle sound next. But sound is an analog phenomena, how will our digital Arduino cope? We will once again rely on its incredible speed which will let it mimic analog behavior. To do this, we will attach a piezo element to one of the Arduino’s digital pins. A piezo element makes a clicking sound each time it is pulsed with current. If we pulse it at the right frequency (for example 440 times a second to make the note middle A) these clicks will run together to produce notes. Let’s get to experimenting with it and get your Arduino playing ‘Twinkle Twinkle Little Star’.

No SoundGiven the size and shape of the piezo element it is easy to miss the right holes on the breadboard. Try double checking its placement.

Can’t Think While the Melody is Playing.Just pull up the piezo element whilst you think, upload your program then plug it back in.

Tired of Twinkle Twinkle Little Star?The code is written so you can easily add your own songs, check out the code below to get started.

Making it Better?

Playing with the speed:
The timing for each note is calculated based on variables, as such we can tweak the sound of each note or the timing. To change the speed of the melody you need to change only one line.
int tempo = 300; —> int tempo = (new #)
Change it to a larger number to slow the melody down, or a smaller number to speed it up.

Tuning the notes:
If you are worried about the notes being a little out of tune this can be fixed as well. The notes have been calculated based on a formula in the comment block at the top of the program. But to tune individual notes just adjust their values in the tones[] array up or down until they sound right. (each note is matched by its name in the names[] (array ie. c = 1915 )