# How to get 38 Khz clock from Timer 0/2 in Arduino Mega 2560?

I have been trying to generate a PWM wave of 38 Khz (13 microsec= ON period , 13 microsec= OFF period). Currently I am using Timer 0 to generate the PWM wave , however i am confused as to how to prescale the 16Mhz input clock frequency so that i can get 38 Khz from it .

The code is as follows -

``````#include<avr/io.h>
#include<util/delay.h>

uint8_t  dutycycle;
void pwm_init()
{
// Configure PB.7 as output pin
DDRB |= (1<<PB7);
DDRG |= (1<<PG5);

// Clear o/p on Match and Fast PWM Mode
TCCR0A |=(1<<COM0A1) | (1<<WGM01) | (1<<WGM00) | (1<<COM0B1);// COM0A1/0b1 are the ouput ports , and WGM01 and WGM02 are used for fast PWM mode
TCCR0B |=(1<<WGM02) | (1<<CS01);//WGM02 is used to set the fast pwm mode with max value stored in OCRA. CS01 is used to prescale the clock frequency to 16Mhz % 8 .
OCR0A = 52;

}
void dutycycleA(uint8_t dutycycle)
{
OCR0B = (dutycycle * 52)/100 ;
}
int main()
{
pwm_init();

while(1)
{
dutycycle=50;
dutycycleA(dutycycle);
_delay_ms(1000);
}
}
``````

So , the code is supposed to keep checking the value of OCR0B with the timer value and if it is less than that , then the output is logic HIGH , and if it is same as the timer value , then it'll be logic LOW . the duty cycle is given as 50 so that a pulse waveform of 50% duty cycle is reached .

However I am unable to obtain 38Khz output .

Please help me figure out where I have gone wrong and also suggest corrections to my approach , if wrong .

Thank you .

PS - I am using Eclipse Neon platform.

38 KHz is generally used as the carrier frequency for IR communication. If that is what you are trying to do {a} why not tell us and {b} this IR Thread may help

...R

Robin2:
38 KHz is generally used as the carrier frequency for IR communication. If that is what you are trying to do {a} why not tell us and {b} this IR Thread may help

...R

Yup tha'ts the objective .

Actually I am trying to generate PWM wave of 38 Khz to communicate with my TV via IR transmitter . However , I am not sure about the correctness of my code , especially the OCR0A register content in Fast PWM mode .

So ... Did you study the link I gave you before you replied?

It's generally not a good idea to muck about with Timer0 as it is used for millis() an micros()

...R

Nick Gammon's timer tutorial has a section on generating and modulating 38KHz pulses.
https://www.gammon.com.au/timers