2

I am trying to modify this code to move PWM from pin 3 to 11 (Arduino Nano v3), but have not had much success. How can it be done?

pinMode(3, OUTPUT);       // enable the PWM output
TCCR2A = B00100011;      // Fast PWM change at OCR2
TCCR2B = B11001;         // Timer running at full system clock
OCR2A = 21;              //  output frequency = 16,000,000/(OCR2A+1)
pinMode(3, OUTPUT);      // enable the PWM output 
OCR2B = 11;    // 50% duty cycle
bbglazer
  • 123
  • 3
  • 16

1 Answers1

3

Pin 11 is located on PB3, marked as OC2A - it means it is bound to OCR2A register, therefore this register can't be used as counters TOP value.

And because there is no mode without using OCR2A as TOP (except for using 0xFF as top value) you just can't use it in this case.

However if you need 50% only, you can use CTC mode with toggling OC2A on overflow.

According to comment something like this should handle it (Fast PWM mode):

  pinMode(11, OUTPUT);
  OCR2A = 7; // 19 -> 400kHz, 7 -> 1MHz, 10 -> 727.72kHz 
  TCCR2A = _BV(COM2A0) | _BV(WGM21) | _BV(WGM20); // Fast PWM mode, OC2A toggle on compare match + =TOP
  TCCR2B = _BV(WGM22) | 1; // start timer
KIIV
  • 3,534
  • 2
  • 18
  • 23
  • Thanks for explaining that. I do need a square wave at 50% duty cycle to generate a clock for another device. I need to set it to around 700kHz and would like to be able to vary it aprox +/- 300kHz. Is there a way I can set this up and have some decent control over that range, say at least 50 levels? – bbglazer Jul 25 '16 at 20:25
  • @bbglazer: if 13 steps are enough, see my updated answer – KIIV Jul 25 '16 at 21:33