Using the Arduino
Rather than generate your own square wave to turn an Arduino pin
ON/OFF repeatedly, you could use Arduino’s built-in
Advantages of using
Your sketch is simpler and easier to write.
Get “better” sound, because
tone()uses a built-in “Timer” on the
microcontroller chip to produce accurate square waves which
turn on and off at precise times.
Disadvantages of using
The particular timer used by
tone()(“Timer 2”) might not be available on
your microcontroller board.
You might need Timer 2 for other functions, depending on your application.
For example, the so-called “PWM” functions, which are widely used to control
servo-motors, also use Timer 2, thus conflicting with the
⚠Alert! Any time you use code or invoke a library that uses one of the microcontroller’s
timers, be sure to check whether that code conflicts with some other timing-sensitive
aspect of your program!
tone() to make a sound forever
When it is invoked with only 2 arguments,
tone() generates the sound
specified by the second argument on the pin specified by the first argument:
For example, make “Middle C” (262 Hz):
This sound goes on forever. To turn if off, invoke another function,
notone(), with one argument:
tone() for a specified period of time
tone() is invoked with 3 arguments, the last one limits the duration
of the tone in milliseconds. For example, this invocation
generates Middle A (440 Hz) on pin 6 for 3 seconds:
tone(6, 440, 3000);
In this case, it is not necessary to call
Other Tone Libraries
Arduino fans around the world have written a number of alternatives to the
tone() library, including
(i.e., collection of functions), which produces louder sounds and
offers some volume control.
which produces smaller, more efficient code, and uses Timer1 rather than Timer 2
- the TimerFreeTone library which
has the benefit that it doesn’t use any timers at all.