I'm doing an Arduino based project using the PWM hooked up to a 0.5W 8Ω speaker in order to make various sounds, I want to implement a digital volume control and I thought about using another PWM output and an Opto-Isolator....would this be possible?
And....if it is possible - could anyone recommend a suitable candidate?
Cheers Chiphackers - Let me know if this is too vague :)
Update - I've got the speaker connected directly to the PWM output without amplification - I'm using a couple of tactile switches to turn the volume up and down
Here's the circuit (In Theory) -
Here's some code too, I've got the PWM set to high speed and I'm using it to ramp the volume of the tones up and down -
/////////////////////////////////////////////////////////////////////////////////////
// Configure PWM on pins 3 and 11 to run at maximum speed, rather than the default //
/////////////////////////////////////////////////////////////////////////////////////
pinMode(3,OUTPUT); // speaker on pin 3
cli(); // disable interrupts while registers are configured
bitSet(TCCR2A, WGM20);
bitSet(TCCR2A, WGM21); // set Timer2 to fast PWM mode (doubles PWM frequency)
bitSet(TCCR2B, CS20);
bitClear(TCCR2B, CS21);
bitClear(TCCR2B, CS22);
sei(); // enable interrupts now that registers have been set
////////// Function for playing tones -
void playTone(long tone, int duration)
{
prevMicros = micros();
while (micros() - prevMicros < duration)
{
analogWrite(3, VOLUME);
delayMicroseconds(tone);
analogWrite(3, 0);
delayMicroseconds(tone);
}
}