After thinking about it, I realized you don’t need a delay or millis() for the ToneAC code because it already
has a duration value. The processor will execute that for the given duration and move on to the next line of code. No delay necessary.
Look at this :
ToneAC library
Look at the example given. See the :
toneAC(0); // Turn off toneAC, can also use noToneAC().
?
#include <toneAC.h>
void setup() {} // Nothing to setup, just start playing!
void loop() {
for (unsigned long freq = 150; freq <= 15000; freq += 10){
toneAC(freq); // Play the frequency (150 Hz to 15 kHz).
delay(1); // Wait 1 ms so you can hear it.
}
toneAC(0); // Turn off toneAC, can also use noToneAC().
while(1); // Stop.
Now look at this example I wrote:
// ---------------------------------------------------------------------------
// Connect your piezo buzzer (without internal oscillator) or speaker to these pins:
// Pins 9 & 10 - ATmega328, ATmega128, ATmega640, ATmega8, Uno, Leonardo, etc.
// Pins 11 & 12 - ATmega2560/2561, ATmega1280/1281, Mega
// Pins 12 & 13 - ATmega1284P, ATmega644
// Pins 14 & 15 - Teensy 2.0
// Pins 25 & 26 - Teensy++ 2.0
// Be sure to include an inline 100 ohm resistor on one pin as you normally do when connecting a piezo or speaker.
// ---------------------------------------------------------------------------
#include <toneAC.h>
unsigned long freq = 250;
unsigned long time;
unsigned long update;
void setup()
{
Serial.begin(9600);
}
void loop()
{
time = millis();
Serial.print("Time: ");
Serial.println(time);
update = millis();
Serial.println("Start tone ");
while (update - time < 1000)
{
update = millis();
toneAC(freq); // Play the frequency (125 Hz to 15 kHz sw
}
Serial.print("Update: ");
Serial.println(update);
Serial.println("Stop tone ");
toneAC(0); // Turn off toneAC, can also use noToneAC().
while(1); // Stop (so it doesn't repeat forever driving you crazy--you're welcome).
}
It turns out that if you don’t have something to tell the processor to stop playing the tone it just keeps playing it and if you don’t have a delay it stops playing it as soon as it executes the
toneAC(0);
code.
You need something to keep it playing the tone until the desired time has elapsed so I added the “while”
loop. It works perfectly.
Note; In YOUR program , the tone will be executed by a conditional, so the:
while(1)
at the end of the program won’t be necessary. It was necessary for this example
because I don’t have a conditional to decide whether to play it or not.
Note the :
Pins 9 & 10 - ATmega328, ATmega128, ATmega640, ATmega8, Uno, Leonardo, etc.
Are these pins available ?