I am trying to control the volume of a piezo speaker using two potentiometers. The first one will control the volume of the speaker from minimum to maximum volume. After the value of the first potentiometer is chosen, the second potentiometer will actuate the volume between the volume set by the first potentiometer and max volume. Here is my code so far:
#include "pitches.h"
const int speakerPin = 9;
const int pot1Pin = A0;
const int pot2Pin = A1;
// An array of notes for the melody
int melody[] = {NOTE_E4, NOTE_D4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_E4, NOTE_E4,
NOTE_D4, NOTE_D4, NOTE_D4, NOTE_E4, NOTE_G4, NOTE_G4,
NOTE_E4, NOTE_D4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_E4, NOTE_E4,
NOTE_E4, NOTE_D4, NOTE_D4, NOTE_E4, NOTE_D4, NOTE_C4};
// The duration of each note in the melody
int noteDurations[] = {4, 4, 4, 4, 4, 4, 2,
4, 4, 4, 4, 4, 2,
4, 4, 4, 4, 4, 4, 2,
4, 4, 4, 4, 4, 2};
int tempo = 100; // The tempo of the melody
void setup() {
pinMode(speakerPin, OUTPUT); // Set the speaker pin as an output
}
void loop() {
int desiredVolume = analogRead(pot1Pin); // Read the value from the first potentiometer
int actuationVolume = analogRead(pot2Pin); // Read the value from the second potentiometer
// Scale the actuation volume so that it falls between the desired volume and the maximum volume
actuationVolume = map(actuationVolume, 0, 1023, desiredVolume, 1023);
// Play the melody
for (int i = 0; i < 25; i++) {
int note = melody[i];
int duration = noteDurations[i];
// Play the note at the desired volume
tone(speakerPin, note, duration * 500 / tempo);
delay(duration * 500 / tempo);
}
}
The speaker plays a bunch of notes really fast and the potentiometers have no effect on the volume. Also, the song is supposed to be Mary Had a Little Lamb.