O'Reilly logo

Mastering Arduino by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using the tone function

For the first few examples in this chapter, we will be using the Arduino tone() function. This function comes in two varieties. The first variety takes two arguments, where the first is the pin number that the buzzer or speaker is connected to and the second is the frequency in hertz to play the sound at. The function looks like this:

tone(pinNumber, frequency);

When this function is used with only two parameters, the sound is played indefinitely. The following code shows how we could use this function to play a note using the previous circuit diagram:

#define PIEZOPIN 7
#define SPEAKERPIN 8

int soundPin = PIEZOPIN;

void setup() {
  tone(soundPin, 1000);
}

With this code, the tone() function is used within the setup() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required