Search code examples
cmicrocontrolleratmega16

ATMEGA 328P varying frequency


I am trying to generate a 16kHz pwm... this is the code i am working with right now. `

int main(void){
DDRD |= (1 << DDD6);
// PD6 is now an output

OCR0A = 128;
// set PWM for 50% duty cycle


TCCR0A |= (1 << COM0A1);
// set none-inverting mode

TCCR0A |= (1 << WGM01) | (1 << WGM00);
// set fast PWM Mode

TCCR0B |= (1 << CS01);
// set prescaler to 8 and starts PWM


while (1);
{
    // we have a working Fast PWM
}}`

The default frequency is set to 64kHz... is there any way i can change the default frequency ? Because changing the prescalars does not help me get a frequency of 16kHz...


Solution

  • If you can use CTC mode instead of fast PWM (which means, you don't need to vary the pulse-pause-width ratio), you can use CTC mode to accomplish that:

    DDRD |= (1 << DDD6);
    // PD6 is now an output
    
    OCR0A = 32;
    // set PWM for 12.5% duty cycle
    
    
    TCCR0A |= (1 << COM0A0);
    // set toggle mode
    
    TCCR0A |= (1 << WGM01);
    // set CTC Mode
    
    TCCR0B |= (1 << CS01);
    // set prescaler to 8 and start PWM