Time for some music! In this lesson, you’ll use your potentiometer and the piezo buzzer to create continuously variable tones within a specific range.
Once again, you’ll use the map()
function that you already know. Additionally, you’ll use another new function: tone()
What are Tones?
First, we need to take a quick look at what tones actually are. In principle, they are vibrations with a specific frequency. More precisely, they are pressure fluctuations whose speed produces different pitches.
The higher the frequency of the fluctuations, the higher the tone. If you have a landline telephone, you can listen to the dial tone. This is often the so-called concert pitch A, which sounds at a frequency of 440 Hertz (Hz).
To produce an A one octave lower, you need to create a vibration that is half as large: 220 Hz. All other notes in the scale also have fixed frequencies. You can view a fairly extensive list of notes and corresponding frequencies on Github.
Generating Tones
As briefly mentioned at the beginning, there’s a practical function that can generate tones with your piezo: tone()
___STEADY_PAYWALL___
This function expects at least two parameters: the pin to which your piezo is connected and the frequency. An optional third parameter is the tone duration.
tone(piezoPin, frequency, duration);
So if you want to generate the concert pitch A with your piezo on pin 10 – without limiting the tone duration – the code looks like this:
tone(10, 440);
Pretty simple, right? However, you want a variable pitch that you determine using your potentiometer. Therefore, you first read the potentiometer signal and “map” it to a specific range.
potiValue = analogRead(potiPin);
piezoValue = map(potiValue, 0, 1023, 262, 523);
This time, this range is between 262 Hz and 523 Hz. These are the two C notes in two different octaves.
You then assign the frequency found with the map()
function to the variable piezoValue
. Then comes the tone()
function:
tone(piezoPin, piezoValue);
Here, you output the frequency through the piezo buzzer on the pin piezoPin
. However: While the tone range is limited by a low and a high C, the tones in between are “continuous,” which means they don’t necessarily correspond to a D, E, or F, etc.
Upload the sketch from the Exercise Files to your Arduino. Can you hear the tones and can you change them by turning the potentiometer? Sounds a bit like science fiction, doesn’t it? In the next lesson, you’ll build a kind of music box that plays a classic: Beethoven’s “Für Elise.”