How to set Timer2 frequency?

Hello, sorry I am kinda new to arduino. I have a two dc h-bridge motor drivers and one servo. well servo uses Timer1 and so it is connected to pin 10. so for motor drivers I have to use pin 3, 11 and 5, 6 as I know 5 and 6 uses Timer0 and 3 and 11 uses Timer2 and I want them to have same PWM frequency(980Hz). this is the code I wrote:

  uint32_t f_cpu = 16000000;
  uint16_t targetFrequency = 980;
  uint16_t prescaler = 8;
  uint8_t value = (f_cpu / (prescaler * targetFrequency)) - 1;
  value = (value > 255) * 255 + (value <= 255)*value;

  TCCR2A = 0;
  TCCR2B = 0;

  TCCR2B |= (1 << CS21);
  TCCR2A |= (1 << WGM20) | (1 << WGM21); 
  TCCR2A |= (1 << COM2A1) | (1 << COM2B1);

will this work? and am I even looking it right? like can I do it without having to do this? I am using a driver that just has each 2 pins for PWM input and it controls speed and direction based on which pin receives signal

will this work?

It will do something. You made a number of timer register setting choices without bothering to explain any of them. Why?

Careful study of the data sheet explains all the details, and there is this excellent tutorial:

And this one:
https://docs.arduino.cc/tutorials/generic/secrets-of-arduino-pwm/

In addition there are several web pages that help with the calculations, like this one: AVR Timer Calculator | Eleccelerator

TCCR2B |= (1 << CS21); // sets prescaler of 8 and I wonder if it is correct if I want to have 980Hz

TCCR2A |= (1 << WGM20) | (1 << WGM21); // sets fast PWM mode, the timer counter counts up and then drops down to zero again

TCCR2A |= (1 << COM2A1) | (1 << COM2B1); // for non-inverted PWM

is it correct?? and do I need to do it as I said in the question above?

No, which you will discover by studying the material in the links I posted.

Up to which value?
The counter TOP value can come from a number of sources

For timer0

and for timer2

You will get 977Hz

You can drag the dashed lines (e.g. OC2A, OC2B) up and down to see the phases shift.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.