# How to set the duty cycle of CTC arduino timer (1MHZ Square Wave Pulse)

Hello..
my post is similar to this post Timer in CTC mode to generate 1MHz pulse - Programming Questions - Arduino Forum but after reading the whole answers i still haven't found the solution for my problem.
Well i want to generate 1Mhz square wave by using arduino (in this case im using Mega2560). At first what im trying to do is setting a pin high for 1us(by using delayMicroseconds() function) and then set it off again (my expectations is by using 1us periode, i'd get 1MHz square wave pulse) but what i got was a square wave with 56Khz of frequency and i couldn't set it higher any more.
Here is my code:

``````void setup() {
pinMode(11,OUTPUT);
}

void loop() {

digitalWrite(11,HIGH);
delayMicroseconds(0.5);
digitalWrite(11,LOW);
delayMicroseconds(0.5);

}
``````

So i guess there must be some calculations to generate this 1Mhz square wave. By using the code i got from the topic above i could successfully generate 1Mhz square wave, but i couldn't set the % of the duty cycle of the pulse. Here is the code:

``````#define myOutputPin 11

void setup ()
{
pinMode (myOutputPin, OUTPUT);
TCCR1A = 0;
TCCR1B = 0;
TCNT1  = 0;
OCR1A = 7;   // toggle after counting to 8
TCCR1A |= (1 << COM1A0);   // Toggle OC1A on Compare Match.
TCCR1B |= (1 << WGM12);    // CTC mode
TCCR1B |= (1 << CS10);     // clock on, no pre-scaler
}
void loop ()
{
}
``````

Since my understanding about avr timer is not really deep, i couldn't modify the code above in order to set the % of the duty cycle of the pulse. I have searched any reference about this in the internet but i still haven't found the right understandable method.
Im sorry if my post is too long to read, but i hope i can find the solution of my problem in this forum. Thank you so much for your time.

``````delayMicroseconds(0.5);
``````

You can't delay by half a microsecond, that function takes an unsigned int as an argument, not a float.

Also, the code itself takes time to execute.

The logical way to do this is to use the hardware timers. This outputs 1 MHz reliably:

``````#ifdef __AVR_ATmega2560__
const byte CLOCKOUT = 11;  // Mega 2560
#else
const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
#endif

void setup ()
{
// set up 1 MHz timer on CLOCKOUT (OC1A)
pinMode (CLOCKOUT, OUTPUT);
// set up Timer 1
TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
OCR1A =  7;       // output every 8 cycles
}  // end of setup

void loop ()
{
// whatever
}  // end of loop
``````