I'm doing a project that requires a lot of PWM's and I've gotten 6 of the 9 PWM capable pins to work, but I'm struggling to get the last 3 running.

To get the OC1A-C Pins running a PWM, I did this:

DDRB = 0xE0 //Pins B7,B6 & B5 to output
TCCR1A |= (1 << COM1A1) | (1 << COM1A0) |(1 << COM1B1) | (1 << COM1B0) | (1 << COM1C1) | (1 << COM1C0) | (1 << WGM10);
TCCR1B |=  (1 << WGM12) | (1 << CS11);

//Test PWM Values
OCR1A = 0x10;
OCR1B = 0x20;
OCR1C = 0x30;

However, when I try to do the the same for OC2A and OC2B, nothing happens:

DDRB = 0x10 //B4 to output
DDRD = 0x02 //D1 to output
TCCR2A |= (1 << COM2A1) | (1 << COM2A0) |(1 << COM2B1) | (1 << COM2B0) | (1 << WGM20);
TCCR2B |=  (1 << WGM22) | (1 << CS21);

//Test PWM Values
OCR2A = 0x40;
OCR2B = 0x50;

So what else do I need to set to get the PWM on those pins working?

  • \$\begingroup\$ What the datasheet say about those ports? Are you sure they are exactly the same as the other ports? \$\endgroup\$ – MathieuL Jul 17 '15 at 16:14
  • \$\begingroup\$ @MathieuL the only difference is Timer 2 is an 8 bit timer, but the docs say the configurations are the same for both :atmel.com/images/doc7593.pdf \$\endgroup\$ – Dom Jul 17 '15 at 16:19

You've select waveform mode 5 (WGM22=1, WGM21=0, WGM20=1). This means: "Phase Correct PWM where OCR2A is the TOP value".

This means that the timer will count up to the value in OCR2A and then count back down to zero. The OC2A pin won't have an output in this mode, and the OC2B pin will be set when counting up on a compare match between OCR2B and TCNT2 and cleared when the compare match occurs when counting back down. As you have set the OCR2B value to be higher than OCR2A, then a compare match will never happen because the counter starts counting back down before it happens. This means you will not get any output on OC2B either. This mode is designed for if you want a specific PWM frequency at the expense of a PWM output and you set OCR2B<=OCR2A.

I believe what you want is either waveform mode 3 (WGM22=0, WGM21=1, WGM20=1) or waveform mode 1 (WGM22=0, WGM21=0, WGM20=1). These are "Fast PWM" and "Phase Correct PWM" respectively, but which use 0xFF as the TOP value. In this mode, both outputs can be used to generate a PWM signal with a fixed frequency but independent duty cycle (the frequency depends on the prescaler settings and clock frequency).

Just for reference, the above is based on Table 16-7 on page 158 of the datasheet.

| improve this answer | |
  • 1
    \$\begingroup\$ Yeah... That was it. WGM2 = 5 and WGM1 = 5 map to two different operations. \$\endgroup\$ – Dom Jul 17 '15 at 18:15

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.