Created Tue, 11 Feb 2014 02:30:22 +0000 by WanaGo
Tue, 11 Feb 2014 02:30:22 +0000
Is anyone else having this problem, that this will work:
tone(Pin_D5, 120); delay(1000); noTone(Pin_D5); tone(Pin_D5, 220); delay(1000); noTone(Pin_D5);
But this will not play anything at all
tone(Pin_D5, 120, 1000); tone(Pin_D5, 220, 1000); noTone(Pin_D5);
I have seen some old posts on the tone() function, which made me try the first version above, but I don't see why the 2nd version with duration shouldn't work.
Tue, 11 Feb 2014 08:29:38 +0000
The problem here is that tone() is a non-blocking command. That means than when you start a tone playing the command doesn't wait for that tone to finish playing before continuing. All it does is start the tone, which is timer driver, and when its time expores it silences it. While it's playing that tone you can be doing other things.
In the second version of the program the commands are generating a tone, but are being overridden by the next command in the list so fast you can't hear the tone. It plays two tones so rapidly, followed by silence, that the sound doesn't get a chance to leave the speaker. Without the delay() calls in there you'll never hear anything.
You could create a little macro to combine the tone() and delay() calls:
#define tone_with_delay(P,T,D) tone(P,T,D); delay(D);
or better would be:
#define tone_with_delay(P,T,D) tone(P,T,(D+2)); delay(D);
The +2 will make the tones run into each other better and sound smoother and less stuttery (it's still playing the last tone while it's preparing to play the next tone. Adjust the +2 to suit.