Hardware Reference
In-Depth Information
Usingtone()toMakeSounds
The Arduino IDE includes a built-in function for easily making sounds of arbi-
trary frequencies. The tone() function generates a square wave of the selected
frequency on the output pin of your choice. The tone() function accepts three
arguments, though the last one is optional:
The first argument sets the pin to generate the tone on.
The second argument sets the frequency of the tone.
The third (optional) argument sets the duration of the tone. If the third
argument is not set, the tone continues playing until you call noTone() .
Because tone() uses one of the ATMega's hardware timers, you can start a
tone and do other things with your Arduino while it continues to play sound
in the background.
In the following sections, you learn how to play arbitrary sound sequences.
Once you've gotten that working, you can use tone() as a response to various
inputs (buttons, distance sensors, accelerometers, etc.). At the end of the chapter,
you build a simple five-button piano that you can play.
IncludingaDeinitionFile
When it comes to playing music, a definition file that maps frequencies to note
names proves useful. This makes it more intuitive to play simple musical clips.
For those familiar with reading sheet music, you know that notes are denoted
with letters representing their pitch. The Arduino IDE includes a header file
that correlates each of these notes with its respective frequency. Instead of dig-
ging through the Arduino install directory to find it, just visit the Exploring
Arduino Chapter 5 webpage, and download the pitch file to your desktop
( www.exploringarduino.com/content/ch5 ). You'll place it in your sketch direc-
tory after you've created it.
Next, open your Arduino IDE and save the blank sketch that is automatically
created when you open the IDE. As you've probably already noticed, when you
save a sketch, it actually saves a folder with that name and places an .ino file
inside of that folder. By adding other files to that folder, you can include them in
your program, all while keeping your code better organized. Copy the pitches.h
file you saved to the desktop into the folder created by the IDE; then close the
Arduino IDE. Open your .ino file in the Arduino IDE and notice the two tabs
that now appear (see Figure 5-3).
 
Search WWH ::




Custom Search