Hi, I need help.. how to generate 25Khz PWM for Pin 3/9 , what is the code? Thanks
Which Arduino?
Sorry. . Arduino Uno and Arduino Mega
Here's a way to do it on an Uno. The Mega is similar except that pin 3 uses the OC3C output of TIMER3 and pin 9 uses the OC2B output of TIMER2.
const uint8_t pinNine = 9; //PB1, OC1A
const uint8_t pinThree = 3; //PD3, OC2B
void setup( void )
{
//set up pin 9 output
// TIMER1 16-bit
// /1 prescaler CLK = 16MHz T=62.5nS
// ICR1 = ((1/25000) / 62.5nS) - 1 = 639
// OCR1A = (ICR1+1)/2 = 320
// WGM14; ICR1 sets TOP
// OC sets on bottom, clears on compare
TCCR1A = _BV(COM1A1) | _BV(WGM11);
TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS10);
ICR1 = 639;
OCR1A = 320;
pinMode( pinNine, OUTPUT );
// TIMER2 8-bit
// /8 prescaler; CLK = 2MHz T=500nS
// OCR2A = ((1/25000) / 500nS) - 1 = 79
// OCR2B = (OCR2A+1)/2 = 40
// WGM7; OCR2A sets TOP
// OC sets on bottom, clears on compare
TCCR2A = _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(WGM22) | _BV(CS21);
OCR2A = 79;
OCR2B = 40;
pinMode( pinThree, OUTPUT );
}//setup
void loop( void )
{
}//loop
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.