// This code is for ATmega1284p.

ISR(TIMER2_OVF_vect)
{
	// This routine will run once per second.
}

#define TCCR2B_DIV_BY_1		0x01
#define TCCR2B_DIV_BY_8		0x02
#define TCCR2B_DIV_BY_32	0x03
#define TCCR2B_DIV_BY_64	0x04
#define TCCR2B_DIV_BY_128	0x05
#define TCCR2B_DIV_BY_256	0x06
#define TCCR2B_DIV_BY_1024	0x07

#define ASSR_EXCLK		0x40
#define ASSR_AS2		0x20
#define ASSR_TCN2UB		0x10
#define ASSR_OCR2AUB		0x08
#define ASSR_OCR2BUB		0x04
#define ASSR_TCR2AUB		0x02
#define ASSR_TCR2BUB		0x01
#define ASSR_BUSY		(ASSR_TCN2UB | ASSR_OCR2AUB | ASSR_OCR2BUB | ASSR_TCR2AUB | ASSR_TCR2BUB)

#define GTCCR_TSM		0x80
#define GTCCR_PSRASY		0x02
#define GTCCR_PSRSYNC		0x01

#define TIFR2_OCF2B		0x04
#define TIFR2_OCF2A		0x02
#define TIFR2_TOV2		0x01
#define TIFR2_CLEAR		(TIFR2_OCF2B | TIFR2_OCF2A | TIFR2_TOV2)

#define PRR0_PRTIM2		0x40

#define TIMSK_OCIE2B		0x04
#define TIMSK_OCIE2A		0x02
#define TIMSK_TOIE2		0x01

static void
setupT2()
{
	// Switch clocks.
	TIMSK2 = 0;			// Disable all timer 2 interrupts.
	ASSR = ASSR_AS2;		// Select the TOSC crystal.
	
	// Set registers.
	GTCCR = GTCCR_PSRASY;		// Clear the prescaler.
	TCNT2 = 0;			// Clear the counter.
	OCR2A = 0;			// Compare register A.
	OCR2B = 0;			// Compare register B.
	TCCR2A = 0;			// Control register A.
	TCCR2B = TCCR2B_DIV_BY_128;	// Control register B.

	// Wait for the changes to propagate.
	while(((ASSR & ASSR_BUSY) != 0) || ((GTCCR & GTCCR_PSRASY) != 0)) {
		;
	}

	// Clear any previous interrupts.
	TIFR2 = TIFR2_CLEAR;

	// Enable interrupts.
	TIMSK2 = TIMSK_TOIE2;
}
