Why another tone library?
I'd already written a highly optimized toneAC library because I needed higher volume, volume control, higher frequency, and better quality. However, toneAC uses fixed timer 1 PWM pins so it's not as flexible. Making toneAC work like tone was simple and there would be several advantages over the tone library, so I spent an hour and made NewTone from the toneAC library.
What does it do better/differently?
- About 1,200 bytes smaller code size than the Tone library.
- Faster execution time.
- Exclusive use of port registers for fastest and smallest code.
- Higher quality sound output than tone library.
- Uses timer 1 which may free up conflicts with the tone library.
How do I use it?
It's a plug-in replacement for the standard tone library. Add the include, use NewTone() instead of tone() and noNewTone() instead of noTone() to enjoy the benefits. If you're running out of program space or have a timer conflict with the tone library, this is the library for you. See the sketch below for an example.
Download: NewTone v1.0
If you're looking to save even more space and more features like almost twice as loud output and volume control, check out my toneAC library as well.
Example sketch
#include <NewTone.h>
#define TONE_PIN 2 // Pin you have speaker/piezo connected to (be sure to include a 100 ohm resistor).
// Melody (liberated from the toneMelody Arduino example sketch by Tom Igoe).
int melody[] = { 262, 196, 196, 220, 196, 0, 247, 262 };
int noteDurations[] = { 4, 8, 8, 4, 4, 4, 4, 4 };
void setup() {} // Nothing to setup, just start playing!
void loop() {
for (unsigned long freq = 125; freq <= 15000; freq += 10) {
NewTone(TONE_PIN, freq); // Play the frequency (125 Hz to 15 kHz sweep in 10 Hz steps).
delay(1); // Wait 1 ms so you can hear it.
}
noNewTone(TONE_PIN); // Turn off the tone.
delay(1000); // Wait a second.
for (int thisNote = 0; thisNote < 8; thisNote++) { // Loop through the notes in the array.
int noteDuration = 1000/noteDurations[thisNote];
NewTone(TONE_PIN, melody[thisNote], noteDuration); // Play thisNote for noteDuration.
delay(noteDuration * 4 / 3); // Wait while the tone plays in the background, plus another 33% delay between notes.
}
while(1); // Stop (so it doesn't repeat forever driving you crazy--you're welcome).
}
Tim