Welcome, Guest. Please Login or Register
YaBB - Yet another Bulletin Board
09.02.2010 at 19:52:44
News: Server upgrade went fine, you are now at the new system


Pages: 1
pwm sound revisited, pitch and volume control (Read 902 times)
dcb
Senior Member
****
Offline



Posts: 421

pwm sound revisited, pitch and volume control
31.05.2008 at 20:00:11
 
I needed something to send tones to a piezo on pin 10, with out bit banging (desperately need the cpu cycles for other things).  Borrowing from the servo threads, this is what I came up with.  I believe this is a different approach that what is currently in the playground.  
Code:
//pin 10 pwm sound with pitch and volume control
#define piezoPin 10 //pin 9 works too
#define minVol 0
#define maxVol 13  //rough guess, any more uses more power but not much louder
#define minPitch 0x0FFF
#define maxPitch 0x01FF
//add some defines for specific notes and play a song without bitbanging

void setup(){
  pinMode(piezoPin,OUTPUT);
  TCCR1A = 0x00; // sets timer control bits to PWM Phase and Frequency Correct mode
  TCCR1B = 0x12; // sets timer control bits to Prescaler N = 8
  analogWrite(piezoPin, 3); //something less than full volume
}

void loop(){
  //control the pitch
  for(int j=0;j<3;j++){ //control pitch
    for(int x = minPitch; x > maxPitch;x-=10){ //
      ICR1 = x;
      delay(10);
    }
  }
  
  //control the volume
  ICR1 = (minPitch +  maxPitch)/2;
  for(int j=0;j<3;j++){
    for(int x = minVol; x < maxVol;x++){ //
      analogWrite(piezoPin, x);
      delay(500);
    }
  }
}
 

Back to top
 
 
View Profile   IP Logged
Pages: 1