/******************************************************
	library for better time management
	timer_delay.c

	Author: Jakub Tiller
*******************************************************/

#include <stdio.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include "timer_delay_drv.h"
#include <util/delay.h>
#include <avr/pgmspace.h>
#include <stdlib.h>

volatile unsigned int time_counter=0;

/* ---------------------------------------------------------------------
**	function: timer_delay_init()
** initialization function of timer_delay
**
** inputs: 	BYTE data, RS rs
** outputs: none
** ---------------------------------------------------------------------
*/
#ifdef _TIMER0
void timer_delay_init(void)
{
	TCCR0 |= (1<<CS02) | (1<<CS00);
	TIMSK = (1 << TOIE0); // enable overflow interrupt
	TCNT0 = TIM_CONST;

	sei();
}
#endif

#ifdef _TIMER1
void timer_delay_init(void)
{
	TCCR1B |= (1<<CS12);
	TIMSK = (1 << TOIE1); // enable overflow interrupt
	TCNT1 = TIM_CONST;

	sei();
}
#endif

#ifdef _TIMER2
void timer_delay_init(void)
{
	TCCR2 |= (1<<CS22) | (1<<CS21) | (1<<CS20);
	TIMSK = (1 << TOIE2); // enable overflow interrupt
	TCNT2 = TIM_CONST;

	sei();
}
#endif


/* ---------------------------------------------------------------------
**	function: sys_time()
** it returns system time
**
** inputs: 	none
** outputs: unsigned int sys_time
** ---------------------------------------------------------------------
*/
unsigned int sys_time(void)
{
	return time_counter;	
}


/* ---------------------------------------------------------------------
**	function: AVR_interrupt
** interrupt handler
**
** inputs: 	BYTE data, RS rs
** outputs: none
** ---------------------------------------------------------------------
*/
#ifdef _TIMER0
ISR (TIMER1_OVF_vect)
{
	time_counter++;
	TCNT0 = TIM_CONST;
		
}
#endif

#ifdef _TIMER1
ISR (TIMER1_OVF_vect)
{
	time_counter++;
	TCNT1 = TIM_CONST;
}
#endif

#ifdef _TIMER2
ISR (TIMER1_OVF_vect)
{
	time_counter++;
	TCNT2 = TIM_CONST;	
}
#endif

