//
// 16-bit timer with interrupt
// By PEK '2005
//
// Compiler: GCC
// MCU: ATMega88
// Clock: 32 kHz
//

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/signal.h>
#include <avr/sleep.h>

register unsigned char counter asm("r16");	// Counter

// Timer Compare Match ISR
SIGNAL(SIG_OUTPUT_COMPARE1A)
{
	counter++;
	PORTD = counter;
}

int main(void)
{	
	// Initiate Ports
	PORTD = 0x00;
	DDRD = 0xFF;	// PortD as output

	// Initiate Timer
	PRR = ~_BV(PRTIM1);	// Only enable Timer/Counter 1
	TCCR1B = _BV(WGM12) | _BV(CS12) | _BV(CS10);	// clk/1024 and Clear on match
	OCR1A = 64;	// Compare register, 2 sec at 8 MHz
	
	TIMSK1 = _BV(OCIE1A);	// Enable Compare match interrupt
	
	counter = 0;	// Initialize counter

	set_sleep_mode(SLEEP_MODE_IDLE);	// IDLE mode enabled during sleep

	sei();	// Enable global interrupts
	
	while(1)
	{
		sleep_mode();
	}
	
	return 1;
}

