I've already written 3 alternative tone libraries (toneAC, toneAC2 & NewTone). However, a user asked for a way to create tones without using any timers as he had conflicts with both timer 1 and timer 2. This seemed like a perfect opportunity to confuse people further by creating a 4th library that did essentially the same thing, generate sound. So, I wrote up sample code that evolved into the TimerFreeTone library. As a bonus, it works with all ATmega/ATtiny AVR microcontrollers as well as the Arduino Due, Teensy 3.x and other ARM-based microcontrollers equally well. As a second bonus, it allows you to set a volume level per note.
v1.5 - Fixed problem with latest release of the Arduino IDE which caused the library to totally stop functioning. Adjusted note duration to not fail on timer rollover. Now delays for note duration when frequency or volume are zero.
v1.4 Added optional volume parameter.
v1.3 Fixed problem with long tone play durations. Changed the way the note duration is calculated from a suggestion by Paul Stoffregen.
v1.2 calculates duration differently for higher tone accuracy and smaller code size.
v1.1 added a few small changes (after I got around to actually tested the library first-hand with an Arduino).
#include <TimerFreeTone.h>
#define TONE_PIN 10 // Pin you have speaker/piezo connected to (be sure to include a 100 ohm resistor).
int melody[] = { 262, 196, 196, 220, 196, 0, 247, 262 };
int duration[] = { 250, 125, 125, 250, 250, 250, 250, 250 };
void setup() {
for (int thisNote = 0; thisNote < 8; thisNote++) { // Loop through the notes in the array.
TimerFreeTone(TONE_PIN, melody[thisNote], duration[thisNote]); // Play thisNote for duration.
delay(50); // Short delay between notes.
}
}
void loop() {}
TimerFreeTone Library home page
Tim