0

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...

  • No way in fast PWM, but if you can use CTC Mode, it would work – Psi Mar 24 '17 at 21:25
  • But can i use the USART/UART to send bits of data to another microcontroller (F38x) via a wire in this mode? I need to vary the duty cycle and keep the frequency constant.. any hints on how i can achieve that? – Redwan Mahmud Mar 26 '17 at 22:34
  • I recommend using the built-in uart-interface. your atmega has 4 different timers, if i'm not mistaken. you don't change the actual clock cycle of the mc, you only vary the timer speed – Psi Mar 27 '17 at 01:00

1 Answers1

0

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
Psi
  • 6,387
  • 3
  • 16
  • 26
  • Hi can I use two pins to output the 16kHz wave ? I am currently outputting it from DDRD6 but want to output the same wave from 7 as well. I have added in this line " DDRD |= (1 << DDD7);" but that doesn't seem to work – Redwan Mahmud Apr 01 '17 at 22:50
  • This won't work this way. You should read the datasheet. Timer0 is _fix_ connected to PIND6. – Psi Apr 01 '17 at 22:59