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[] = {

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.


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.


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

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

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?

Oscar 5th February 2017 - 4:04 pm

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