PWM signal Generation in Arduino Mega 2560

hi , I have tried to generate PWM signal using timers with Arduin Mega 2560 but I couldn't able to generate it

pin No 11 OCR2A , i want to generate Fast Pulse width modulation & waveform generation mode, with frequency scaling 1024
output frequency is 1KHz and duty cycle is 50%

void setup()
{

 TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20)  ; // non-Inverting PWM,      Wave Genaration Mode
  OCR2A = 500;
  TCCR2B =  _BV(WGM22) | _BV(CS22) | _BV(CS21) | _BV(CS20);  // Fast PWM and  prescaling 1024
  OCR2B = 1000;
}

void loop()
{

}

pin No 11 OCR2A

That's on an uno. On the mega OC2A is pin 10 and OC2B is pin 9.

Furthermore, Timer2 is an 8 bit timer and your values for OCR2A and OCR2B are too large.

The mode 7 you are using is Fast PWM to OCR2A. OCR2B can not be larger than the top value.

You are clearly trying to do this without proper documentation. Get a mega pinout and an ATmega data sheet for your processor in front of you.

I can able to generate PWM on pin no 9 (OCR2A) with 2 kHz , but OCR2A register is 8 bit which can take 256 is max value , but in code I have given 500 I dought how it is working ?

void setup()
{
 pinMode(9, OUTPUT);  // on 2A 
 pinMode(10, OUTPUT); // on 2B

 TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20) ; // non-Inverting PWM, 
 OCR2A = 500;
 TCCR2B =  _BV(WGM22) | _BV(CS21) | _BV(CS20);  // Fast PWM and NO prescaling 16M/1024
 OCR2B = 100;
 
 }

void loop() {}

If you write more then 8 bits into 8 bit's then all bits bigger then 8 are just dropped

500 = 0x1F4 =(into 8 bit)=> 0xF4 = 244

OCR2A = 244.

244 * .0625 * 32 = 488 microseconds for the timer cycle 2.049 KHz.

I can able to generate PWM on pin no 9 (OCR2A) with 2 kHz ,

Pin 9 on the Mega is OCR2B. OCR2B = 100 should be about 50% duty cycle on pin 9.

You should not leave incorrect comments in your code?

void setup()
{
pinMode(9, OUTPUT); // on 2A //Pin 9 is 2B on the mega
pinMode(10, OUTPUT); // on 2B //pin 10 is 2A on the mega

TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20) ; // non-Inverting PWM,
OCR2A = 500;
// Fast PWM and NO prescaling 16M/1024 // your CS20/CS21 settings are a prescaler of 32.
OCR2B = 100;
TCCR2B = _BV(WGM22) | _BV(CS21) | _BV(CS20); // Fast PWM and NO prescaling 16M/1024
OCR2B = 100;

}

void loop() {}

yup, i would not do that again thank you :slight_smile: