2

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.

Thanks

2
  • 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? Jul 5, 2016 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. Jul 5, 2016 at 8:14

1 Answer 1

2

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.

2
  • 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. Jul 5, 2016 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. Jul 6, 2016 at 4:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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