Using potentiometer to vary pitch of a Piezo speaker

by Oscar

In this project, we will be using potentiometer to vary the pitch of the sound. This is basically the same as controlling the LED, the only difference is we need to calculate a corresponding pitch in the pitch array. Don’t worry if you don’t understand, let’s jump to the code and you will see. 

Some of the links on this page are affiliate links. I receive a commission (at no extra cost to you) if you make a purchase after clicking on one of these affiliate links. This helps support the free content for the community on this website. Please read our Affiliate Link Policy for more information.
Here is the circuit:
Same as last tutorial, we need to include the “pitches.h” file.
Here is the code:

[sourcecode language=”cpp”]
/*
as we vary the potentiometer, the pitch varies too. Oscar’s project.
*/

#include "pitches.h"
// notes to play, corresponding to the 3 sensors:
// 21 pitches
int notes[] = {
NOTE_B0,NOTE_C1,NOTE_D1,NOTE_E1,NOTE_F1,NOTE_G1,NOTE_A1,
NOTE_B1,NOTE_C2,NOTE_D2,NOTE_E2,NOTE_F2,NOTE_G2,NOTE_A2,
NOTE_B2,NOTE_C3,NOTE_D3,NOTE_E3,NOTE_F3,NOTE_G3,NOTE_A3};

int Tone = 0;
int speakerPin = 2;

void setup() {
// do nothing
}

void loop() {

// get potentiometer input
int sensorValue = analogRead(A0); // 0 – 1023

// calculate corresponding, divide by 49 as we have 21 pitches. 1023/13 ~ 21
int pitch = sensorValue/49;

tone(speakerPin, notes[pitch], 100);

// delay to let it finish ‘tone’ instruction.
delay(100);

}
[/sourcecode]

Leave a Comment

By using this form, you agree with the storage and handling of your data by this website. Note that all comments are held for moderation before appearing.

3 comments

Jordan G. 17th February 2021 - 6:53 pm

How would you use a potentiometer to vary the pitch of audio coming through a microphone?

Reply
Daryl 2nd February 2017 - 3:02 pm

Is it possible to add an LED that fades and brightens as you adjust the potentiometer in the experiment with the buzzer?

Reply
Oscar 5th February 2017 - 4:04 pm

yes simply hook up the LED to the output of the potentiometer with resistor?

Reply