Using the Arduino tone() Function

Rather than generate your own square wave to turn an Arduino pin
ON/OFF repeatedly, you could use Arduino’s built-in tone() function.

Advantages of using tone():

  1. Your sketch is simpler and easier to write.

  2. 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 tone()

  1. The particular timer used by tone() (“Timer 2”) might not be available on
    your microcontroller board.

  2. 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 tone() function.

‚ö†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!

Calling 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):

tone(BUZZER,262);

This sound goes on forever. To turn if off, invoke another function,
notone(), with one argument:

notone(BUZZER);

Calling tone() for a specified period of time

When 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 notone().

Other Tone Libraries

Arduino fans around the world have written a number of alternatives to the
standard tone() library, including