Arduino tone() Can Play Sparky Danger Organ

I got a spark plug to sing a song, but it was singing out of tune and I didn’t know why. I barely know enough about music to get this far. My friend Emily had more sheet music reading skill and offered to double-check my music translation. If her translation sounds good, then we’ll know the problem was my sheet music translation. If her translation also sounds odd, we’ll know the problem is with my timing code controlling spark frequency.

I replaced my version of the song with hers, and it sounded great! So that’s settled: Sparky’s first performance sounded bad because I didn’t know how to read sheet music. I also received feedback that the way I represented music in my Arduino code was peculiar. No argument from me, because I wrote it out of ignorance and it was what I could hack together at the time. Emily then asked if there was a reason why I’m not using tone() if I’m using an Arduino anyway. The answer was that I didn’t know it existed.

Prompted by this question, a bit of searching on “Arduino tone library” found a GitHub repository at https://github.com/bhagman/Tone, whose README explained it was a library to use AVR timers to generate 50% duty cycle square waves of a specified frequencies along with a list of #define that mapped musical notes to frequencies. It also said a single-timer version of the library has been incorporated into Arduino core, so for single-voice applications like Sparky we wouldn’t even need to install an additional library.

I thought the 50% duty cycle (half of time signal is on, half off) might be a problem, because I’ve been using 0.5ms signal pulses and leaving the pin off the rest of the time. I looked in the tone library but wasn’t familiar enough with AVR timer configuration registers to understand how I might convert it over. Then I remembered the always-useful mantra: check the easy thing first. Maybe Sparky doesn’t mind if the trigger pulse was longer.

Since the single-timer version of tone was now built into Arduino, I looked for Arduino built-in examples illustrating its use. I found “Examples/02.Digital/toneMelody” which was designed to work with a piezo buzzer. I pointed it to Sparky’s IGT pin and heard it play the little melody. Great! Sparky doesn’t mind longer IGT pulses and I can throw out all of my hacked-up music-hampering playback code and just use tone(). I don’t even need to struggle with sheet music or convert them to MIDI notes anymore, I can play songs other people have already translated for tone() playback. I found several collections and the first collection with its own take on Beethoven’s “Ode to Joy” is https://github.com/robsoncouto/arduino-songs. I gave to Sparky and yeah, way better than my version and a lot easier too. I wish I knew tone() existed a few days ago, but at least I know now.

Leave a comment