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 Arduino board of my robotic teapot with a piezo sounder](https://blog.chapelierfou.org/images/IMG_20170420_143033-small.jpg)
The Arduino board of my robotic teapot with a piezo sounder
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:
- 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)
- The note name in English notation as an uppercase letter, or lowercase if sharp (R has a special meaning and indicates a rest)
- 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:
4E52B42C54D52C52B44A42A42C54E52D52C56B42C54D54E54C54A42A42A42B42C56D52F54A52G52F56E52C54E52D52C54B42B42C54D54E54C54A44A44R0
In this example, a piezo passive sounder is connected on pin 3 …