Programming the Arduino
Part 6: Speakers


Speakers create sound from electrical signals by moving back and forth thousands of times per second and causing the air to vibrate. The Arduino can generate simple beeping sounds by quickly turning an I/O pin on and off. As the speed increases, so does the pitch of the sound.

DO THIS: Hooking up a speaker

Assemble the following circuit and upload the program to your Arduino:

void setup()
    pinMode(2, OUTPUT);

void loop()
    // Play a 554 Hz (C#) tone for 250 ms:
    tone(2, 554);

    // Play a 440 Hz (A) tone for 250 ms:
    tone(2, 440);

    // Silence the buzzer for 500 ms:

You should hear the piezo buzzer repeatedly play two tones (C# and A) with a delay between repetitions.

Using pins to make tones

When the tone() function is called the Arduino will begin turning the specified pin on and off at the specified frequency. In our example above, tone(2, 440) tells the Arduino to turn pin 2 on and off at 440 hertz. The tone() function is similar to digitalWrite() in that it expects the pin to be configured as an OUTPUT pin, which we do using pinMode() in setup() above.

To change the tone being played on a pin you can simply call tone() again with the same pin and a different frequency. There is no need to stop it first. To silence the tone being played on a pin you should call the noTone() function as shown in the example above.

The tone() function can only be used to play a single note at a time. If you start playing a note it will stop any previously playing notes, even if they are on a different pin.

DO THIS: Songs and sounds

Create a program that either:

  • Plays a recognizable song with the correct notes and timing
  • Makes interesting sounds in response to input from at least two input devices (buttons, switches, or potentiometers)

When you finish and are signed off for one, do the other.

If you play a song you will need to convert the musical notes into tone() frequencies and delay() durations. This diagram shows the frequency of every note on a piano keyboard:

Doubling a note’s frequency moves it up exactly one octave, while halving the frequency moves it down an octave. There are many mathematical relationships found in music theory.