cmicrocontrolleratmega16

ATmega328P varying frequency


I am trying to generate a 16 kHz PWM signal... 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 a 50% duty cycle

    TCCR0A |= (1 << COM0A1);
    // Set noninverting 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 64 kHz. Is there a way I can change the default frequency? Because changing the prescalers does not help me get a frequency of 16 kHz.


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