I am trying to use Timer2 in an Uno in fast PWM mode. Can someone explain how to set up the TCCR2A & B registers?

Currently I have:

  TCCR2A |= _BV(WGM21) | _BV(WGM20);
  TCCR2B &= ~_BV(WGM22);

  TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
  TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
  TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

I would like to have the inverted value on TCCR2B, but I think it can be inverted using OCR2B ^= 255, correct? This is to have a varying signal on Pin11 and its inverse on Pin3, the signal is generated by varying the OCR2B value.


  • I realized a mistake, what I need to do is set up pins 11 and 3 (TCCR2 A & B?) to fast pwm mode. Then I will set OCR2A to a value, and OCR2B to the value's inverse. Should this work? – perigalacticon Jul 5 '16 at 7:56
  • I also tried: TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0); TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0)); TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10); But I'm still not getting output on pin 3. Thanks. Sorry for the excessive posts. – perigalacticon Jul 5 '16 at 8:14

If you want to get two complementary PWM signals, you have to set the same value to both output compare registers. This is necessary to have the two signals in phase. You also have to configure one PWM in non-inverting mode and the other in inverting mode. For example:

TCCR2A = _BV(COM2A1)  // non-inverting PWM on OC2A
       | _BV(COM2B0)  // PWM on OC2B:
       | _BV(COM2B1)  //    inverting mode
       | _BV(WGM20)   // fast PWM
       | _BV(WGM21);  // ditto
TCCR2B = _BV(CS10);   // clock at F_CPU / 1
OCR2A  = 84;          // duty cycle ~ 1/3
OCR2B  = 84;          // same signal, complemented

Checked on the scope: when pin 3 goes high pin 11 goes low and vice-versa.

  • Thank you. What I need is both PWM signals in non-inverting mode. Then I need to invert the duty cycle OCR2B w.r.t. OCR2A. So as OCR2A increases, OCR2B will decrease the same. The actual PWM signals are to be in-phase, but complementary duty cycle. Sorry for the confusion. – perigalacticon Jul 5 '16 at 11:27
  • Thanks Edgar, I was able to sort through the 328p datasheet and get the registers figured out. First time I have worked with registers and bit values and bit math so it took me some time to understand this but it works really well now. Thanks again. – perigalacticon Jul 6 '16 at 4:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.