Toggled pwm with timers in UNO

Hello everybody, I'm new at this forum. :blush:
Well, I wanna to do a toggled pwm, so when port A is 1 the port B is 0.... and, of course, with the same duty cycle and frequency.
I tried to do this configuration with the register of TIMER2 of AVR328p, but only port A (I/O 11 of Arduino) works with PWM, another is always on 0 :frowning:
void setup(){
TCCR2B= 5; //OB00000100; fast PWM mode, 64 prescaler
TCCR2A= 227; //Ob11100011; port A inverted and port B not inverted - this configuration does the toggle.

OCR2A= 127; //50%duty cycle
OCR2B= 127;
}
void loop(){
delay(30);
}
PS: I only simulated in proteus 8 because I don't have oscilloscope :frowning:

I need another configuration to it work??
PS2: I wanna to control a motor with this pwm.

Thanks people! :wink:

Have you set your pins as outputs?
Your prescaler for 64 is wrong. It should be TCCR2B = 4. TCCR2B =5 is 128.

I can see outputs on both pins (approx 1khz) with this code, which is equivalent to yours with reference to register values from the Atmega 328 data sheet. I can see outputs on both pins, but don't have a scope to see if they are inverted as they should be. Perhaps someone with a scope could verify this code.

void setup() {
  pinMode(3, OUTPUT); //OC2B
  pinMode(11, OUTPUT); //OC2A
  TCCR2A = 0; //initialize register
  TCCR2B = 0; //in itialize register
  TCCR2A = _BV(WGM20) | _BV(WGM21); //set fast PWM 255 top
  TCCR2A |= _BV(COM2A1) | _BV(COM2A0); //Set OC2A on Compare Match, clear OC2A at BOTTOM,(inverting mode).
  TCCR2A |= _BV(COM2B1); //Clear OC2B on Compare Match, set OC2B at BOTTOM,(non-inverting mode).
  //TCCR2A = B11100011 = 227
  TCCR2B = _BV(CS22); //prescaler 64
  //TCCR2B =B00000100 = 4 
  OCR2A = 127;
  OCR2B = 127;

}

void loop() {
}

OKay, I tested all codes poted here and I "do" this:

byte n=127;
int change= 4;
void setup(){
TCCR2B= 4; //OB00000100 - 256 prescaler
TCCR2A= 227; //Ob11100011 - Fast pwm mode with TOP in 0xFF, OC0A inverting mode, OC0B non-inverting mode
OCR2A= n; //starts with 50%duty cycle
OCR2B= n;

pinMode(11, OUTPUT);
pinMode(3, OUTPUT);
Serial.begin(9600);
}

void loop(){
OCR2A= n;
OCR2B= n;
if(n>=250) change=-change;
if(n<=5) change=-change;

n= n+change;
Serial.println(n);

delay(30);
}

All of them, with no exceptions, do this (attachment)

I tried with the Timer0 (pin 5 and 6) and works in same mode, I pin work like PWM and another no. With the timer 1 (16 bits), it works fine....

Thanks people :slight_smile:

I arranged to use a scope on the output of the sketch in my previous reply. It indeed showed the two traces, with opposed polarity as intended. Previously I could count outputs on both pins, but could not determine phasing.

I do not know why you can only see one pin output with Timer2, and what the issue might be with your Arduino or scope, but I'm pretty sure the issue is not the code.

SquareWaves.jpg