/*
 * timer.c
 *
 * Created: 20.02.2019 20:56:18
 *  Author: jens
 */ 

#include <avr/io.h>
#include <avr/interrupt.h>
#include "timer.h"
#include "message.h"

static uint16_t timer_reload = 0;
static Timer_t user_timer[16];
static Fifo *g_pFifo = NULL;

ISR (TIMER1_OVF_vect)    // Timer1 ISR
{
	TCNT1 = timer_reload;

	for (int i=0; i < 16; i++)
	{
		if (user_timer[i].isRunning)
		{
			if (user_timer[i].count > 0)
			{
				user_timer[i].count--;
			}
			else
			{
				Msg_t msg = {Timer, i};
				if (fifo_push(g_pFifo, &msg))
				{
					user_timer[i].isRunning = 0;
				}
			}
		}
	}
}

void timer_init(Fifo *pFifo, uint16_t TIMER_RELOAD, TimerClockSel clockSel)
{
	g_pFifo = pFifo;
	timer_reload = TIMER_RELOAD;
	TCNT1 = TIMER_RELOAD;

	TCCR1A = 0x00;
	TCCR1B = (TCCR1B & TimerClockSel_mask) | clockSel;
	TIMSK1 = (1 << TOIE1) ; // Enable timer1 overflow interrupt(TOIE1)
}

void timer_start(TimerId timerId, uint16_t count)
{
	enterCritical();
	user_timer[timerId].count = count;
	user_timer[timerId].isRunning = 1;
	exitCritial();
}

