Help setting PWM registers

I've been reading up about setting PWM registers and I think I understand which registers need to be set but very confused about how to do it. I've seen lots of different methods but don't really understand what they're doing.

If I want to set pin 3 (on my Uno R3) to non inverted phase corrected with a prescaler value of 8 I need:


I think that's correct but not sure. Can I just set the two registers directly to those bits?

And if that is correct can I use analogWrite to set the OCR2A (is that the TOP that determines the duty cycle?) or do I need to set it manually?

Or is OCR2A the number that the counter counts to? And if so how is the duty cycle set?

TCCR2A = B00100001;  // or 0x21
TCCR2B = B00001010;  // or 0x0A

It is that simple then? B meaning binary I assume and the other the hex value of the byte.

If I set them that way can I just use analogWrite on the pin?

If I set them that way can I just use analogWrite on the pin?

I don't think so. I think you have to set the other registers. The PWM value would be in one of the Output Compare Registers (like OCR2A or OCR2B). Look in the datasheet for how to set up and manipulate PWM outputs.

Ok, thanks. I thought that might be the case. I'll have another look at the datasheet and see if I can work it out.

Well I tried it bit values and they didn't work. Found a website which gave other values and set the prescaler to 8.

Surprisingly analogWrite did work after that so just needs the PWM mode set, which is nice.

If you look at the code of analogWrite you'll see what it does... It enables PWM
on the relevant pins if not already enabled and sets the relevant output compare register.

I will have a look at what's going on behind the scenes with that, might help me understand the OCR registers.


I think I've (almost) got it now. Not quite sure which bits I set wrong originally although I'm sure I could work that out.

As I expectsd though, OCR2A is the duty cycle for pin OC2A (pin 11) and OCR2B is the duty cycle for pin 3.

Thanks. That site looks very helpful.