Playing music on Arduino

Provided you connect a piezo speaker to your Arduino board, the tone Arduino function allows to play tones given their frequencies. Let’s use it to play entire melodies!

The melody encoding format I’ll use is compact and pretty straightforward, but I admit it isn’t the easiest one to read. The melody is represented as a null-terminated string of chars, in which each note is described by 3 consecutive characters:

  1. The note duration in sixteenth notes as an hexadecimal digit between 0 and F (0 has a special meaning and is interpreted as a whole note)
  2. The note name in English notation as an uppercase letter, or lowercase if sharp (R has a special meaning and indicates a rest)
  3. The octave number as a decimal digit, between 0 and 8 (for a rest, the value is ignored)

So for instance, a quarter-note C from the 5th octave is 4C5, and a eighth-note D sharp from the 4th octave is 2d4.

With this notation, the Tetris theme is:

In this example, a piezo passive sounder is connected on pin 3 of the Arduino board. The code to play a melody stored in the format defined previously can be written as follows:

After setting the melody, the function syncMelody() must be called on each quarter of a beat to play it at the chosen tempo. It does not wait by itself to allow some other processing between calls.

The helper function pitch(unsigned int octave, unsigned char note) returns the frequency given an octave number and a note name. Lowercase note name is interpreted as sharp, and 0 is returned on a rest or on error. Note A from the 4th octave returns 440 Hz.

For instance, here is a simple example playing the Tetris theme!

I can now upgrade my dancing teapot to have it play a melody while dancing!

The Arduino board of the robotic teapot with a piezo sounder
The Arduino board of the robotic teapot with a piezo sounder

After adding the piezo speaker and including the previous code, I simply modified the main functions as follows:

As a result, the teapot now dances and sings!

You can find the upgraded source code under GPLv3 on my repository on GitHub.

4 thoughts on “Playing music on Arduino”

Leave a Reply

Your email address will not be published. Required fields are marked *