I managed to work with timer 0 and 1 but am unable to generate a PWM with timer 2 in my atmega328p.

This is the code:

#include <avr/io.h>

int main(void)
    /* PD6 output */
    DDRD |= (1 << DDD6);

    /* 50% duty cycle */
    OCR2A = 128;

    /* fast PWM  */
    TCCR2A |= (1 << WGM21) | (1 << WGM20);

    /* prescaler = 8 */
    TCCR2B |= (1 << CS21);

    while (1);


Could someone explain what the issue is and why I am not seeing a pwm signal on pin 6 of my arduino uno board?


  • 2
    The post is definitely on topic. I don't understand why it has attracted a vote to be closed.
    – MichaelT
    Commented Apr 6, 2019 at 23:45
  • I am the one who up-voted the question, one of the three up-votes for the answer, and just up-voted your comment :)
    – VE7JRO
    Commented Apr 7, 2019 at 0:12
  • It's a shame that multitudes of "leave open" votes don't cancel our erroneous "off-topic" votes. Clearly on-topic. And timers are always such fun! :)
    – Madivad
    Commented Apr 9, 2019 at 15:14

1 Answer 1


The output compare unit of timer 2 is connected to pins PB3 (OC2A) and PD3 (OC2B). So you have to configure those as outputs. Keep in mind that you can't choose any pin when using hardware pwm, this hardware feature is linked to specific pins.

You also have to set COM2A1 in TCCR2A. Otherwise OC2A is disconnected from the output compare unit (ref: Table 17-3 in datasheet). The effect of COM2A0/1 depends on the configuration in WGM20-WGM22. The same applies to OC2B respectively.

  • I tried what you suggested, but that doesn't seem to work: paste.ubuntu.com/p/K8KmKnqyvV Any suggestions?
    – traducerad
    Commented Apr 6, 2019 at 19:40
  • I compiled/flashed your code and I found that in TCCR2A you have to set COM2A1 (see my edit).
    – Sim Son
    Commented Apr 6, 2019 at 20:37
  • @traducerad: The comment // enable timer 2 in your code is wrong. It should be // disable timer 2 in order to be consistent with what the following line actually does. Commented Apr 7, 2019 at 10:34

Your Answer

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

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