IR-Signal 38Khz PWM problem on AtMega2560

The information is overwhelming when searching this forum, but I still have a PWM problem.

I want to transmit IR signals. I have written two routines, one for setting up a PWM signal (38Khz) and an other for modulating this signal. I worked fine on an Arduino Uno, but there is a problem on the Mega 2560.

First setting up the PWM:

static void IR_PWM_INIT(void)  
  {
  // Freq.=38Khz. Pulse is 26uSec. ATMega 16 ClockCyclesPerMicrosec. Period = (16 * 26)/2
  #define top  207; 
  #define prescaler 1; // Clock niet laten delen door de prescaler. Dit is nit nodig voor deze frequentie
  
  // PWM output OC2B (PMW-9 defined as output)
  
  TCCR2A=0;
  TCCR2B=0;
  TCNT2=0;             // Set counter to zero, fresh start.
  ASSR&=~_BV(AS2);     // clock is input for prescaler input:
  OCR2B=top;           // Set Output Compare register. 
  
  TCCR2A=_BV(WGM21);   // CTC-mode: 010 = clear timer on compare match. 
  TCCR2B=prescaler;    // 001 = No prescaling
  }

Later I quickly turn on/of the PWM output to modulate the 38Khz signal

for(y=0; y<S.TransmitRepeat; y++) // herhaal verzenden IR code
    {
    x=1;
    while(x<=RawSignal[0])
      {
      TCCR2B|=_BV(COM2B0); // turn PWM on
      delayMicroseconds(RawSignal[x++]); 
      TCCR2B&=~_BV(COM2B0); // turn PWM off
      delayMicroseconds(RawSignal[x++]); 
      }
    }

It worked fine on a ATMega328, but no response on the ATMega2560.

Does anyone have an idea?

Note that the timer output pins are different between Arduino Uno and Arduino Mega. You are using Timer2.

Timer2A is Pin 11 on the Uno and Pin 10 on the Mega
Timer2B is Pin 3 on the Uno and Pin 9 on the Mega

For pin mapping, see:

I noticed that de pin assignment was changed. But I have found the problem! I tried to turn on the PWM with:

 TCCR2B|=_BV(COM2B0);

but TCCR2B is the wrong register, this must be TCCR2A. ]:smiley:

Anyway, thanks!

screenshot.png