19 Nov 2011

No. 4 - Using potentiometer to control Piezo speaker for various pitch

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. 

Here is the circuit:

Same as last tutorial, we need to include the "pitches.h" file.
Here is the code:

  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.