Autonomous clock generation with Mega 2560

Greetings,
This should be a pretty simple and ubiquitous task on the MEGA2560, and I'm looking for some prior art somebody on forum might contribute. I would like to use a timer in the MEGA 2560 to generate a 1MHz clock at an I/O pin. The criteria for this clock generator are simply.

  1. 50% duty cycle
    2)To run autonomously in background
  2. To perform unperturbed by any other CPU activities being performed, ext interrupts, etc.

Basically, I'd like a clean 1MHz clock derived from the 16MHz MEGA's CPU clock for driving external hardware. There are probably many ways to do this, but I'm looking for the cleanest and most straight forward to implement.
Regards, Mark

You will want to use a timer.

Here is an example:

void setup( void )
{
    //TIMER1
    //  100 kHz on 8 MHz atmega
    // 200 kHz on 16 MHz atmega
    //Timer1 16-bit
    //set waveform generator mode WGM3..0: 0100 (mode 4; CTC, OCR1A compare)   
    TCCR1A = 0;  //DO THIS FIRST (clear previous timer modes)
    //set prescaler CS12..0: 001 (clkio/1)
    TCCR1B = (1<<WGM12) | (1<<CS10);
    //set compare register
    OCR1A = 39; //toggle is zero relative!
    //on Mega2560, OC1A function is tied to pin 11 (9 on ATmega328)
    pinMode( 9, OUTPUT );
    //state pin will assume when disconnected from OC1A
    digitalWrite( 9, LOW );   
    TCCR1A = (1<<COM1A0); //connect to output pin (toggle).
       
}//setup

void loop( void){}

Similar to jremington's solution: This will give a 1MHz 50% DC output on pin 12:

/*
 * Sketch:  mega_1mhz
 * Target:  Mega2560
 */

const uint8_t pinCKOUT = 12;  //PB6 OC1B

void setup( void ) 
{
    pinMode( pinCKOUT, OUTPUT );
    
    //WGM=15 Fast PWM, TOP=OCR1A, BOTTOM=0
    //prescaler = /1 (16MHz clock rate)
    TCCR1A = _BV(COM1B1) | _BV(WGM11) | _BV(WGM10);
    TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS10);
    OCR1A = 15;
    OCR1B = 7; 

}//setup

void loop( void ) 
{

}//loop

Thanks folks! That did the trick! :slight_smile:

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.