I am trying to adjust the volume of a piezo speaker, via a potentiometer. I have researched a fair bit, and I have read that the volume can be changed by changing the voltage going through it. And to do this, I have read, you can alter the duty cycle of a PWM pin.
I am making noises through the piezo via the tone() function, and have encountered a few problems...
I have all of the materials provided in the Arduino Starter Kit: Arduino Starter Kit Multi-language — Arduino Official Store
Here is the code relating to the noise making:
int piezoPin = 9;
int volumePin = A0;
float volume = 0;
float voltage = 0;
void setup()
{
Serial.begin(9600);
pinMode(songChangePin,INPUT_PULLUP);
pinMode(piezoPin,OUTPUT);
}
void loop()
{
for (i = 0; i < notes[song]; i ++)
{
buttonCheck();
volumeCheck();
tone(piezoPin,note[song][i]*2,240000*fracNote[song][i]/tempo[song]*duration[song][i]);
delay(240000*fracNote[song][i]/tempo[song]);
}
}
void volumeCheck()
{
volume = analogRead(volumePin);
volume = map(volume,484,1023,0,5);
Serial.print("Volume - ");
Serial.print(volume);
Serial.print(" , ");
digitalWrite(piezoPin,volume);
}
Sorry I don't have a photo of the circuit, but I've lost the USB cable for my camera...
The piezo is connected to the ~9 pin (~ = PWM), the potentiometer 3rd leg is connected to A0, both have resistors in between.
The voltage readings in the serial window range from 0-5, however, the actual volume of the poezo doesn't seem to change.
I think the problem is that the tone function ignores anything to do with the set duty cycle of the pin, and chucks out whatever voltage it needs. Could be completely wrong, though. If that is the case, how can I combat this.
I have looked for alternatives to the tone() function, and have found this: http://michael.thegrebs.com/2009/03/23/playing-a-tone-through-an-arduino-connected-piezo/
Would this have the same problems, though?
Thanks for any help. If I've left any required information out, please let me know.