Electrical – atmega32u4 generate clock using timer4

atmegaavrclocktimer

I have a atmega32u4 with 8Mhz and try to generate a clock signal with 1,2 or 4 MHz using timer 4 and output it on PD6 (!OC4D)

For timer 1 and on PB5 (OC1A) I used CTC mode:

TCNT1=0;

// Toggle OC1A on Compare Match
TCCR1A = 0x00;
bitSet(TCCR1A, COM1A0);

// Clear Timer on Compare Match
TCCR1B = 0x00;
bitSet(TCCR1B, WGM12);


//8Mhz
// Set frequency (0 = 4Mhz, 1 = 2MHz, 3 = 1MHz)
OCR1A = <value>;

// No prescaling
bitSet(TCCR1B, CS10);

but timer4 does not have this CTC für OC4D (or have I got that wrong from datasheet?)

Is there another way to create that output?

Best Answer

I found the following solution for the problem:

// reset timer4
OCR4C = 0;
OCR4D = 0;

TCCR4A = 0x00;
TCCR4B = 0x00;
TCCR4C = 0x00;
TCCR4D = 0x00;

TCNT4=0;

// Toggle OC4D on Compare Match | enable PWM
TCCR4C = _BV(COM4D0) | _BV(PWM4D);


// Clear Timer on Compare Match
TCCR4D = _BV(WGM41);

// set lock bit for sync update
TCCR4E = _BV(TLOCK4);

// Set compare value
OCR4C = CLOCKCYCLE*2;
OCR4D = CLOCKCYCLE;

// No prescaling
TCCR4B = _BV(CS10);