/*
Diplomova prace : Palubni pocitac

timer - systemovy casovac

Atmega128A 10 MHz XTAL

Autor: Ondrej Lutera

2011/2012

*/
#include "timer.h"
#include "keys.h"
#include "pwrctrl.h"

volatile uint8_t timer=0;
volatile uint8_t tim = 0;
volatile uint8_t tim2=0;

uint8_t sleepMode=0;

/* preruseni vykonavane 32x za 1s.. je rizene hodinami RTC obvodu pcf8563 */
INT_ISR()
{
    if(sleepMode){

        if(bit_is_clear(KEY_PIN,KEY_OK)){

            CheckWakeUp();

        }


    }else{

    tim++;
    timer++;
    tim2++;

    if(tim2==8){

        tim2=0;
        // zde ziskame udaj rpm pro aktualni vypocet
        RpmPoll();      // inline

    }

    if(tim==32)   // kazdou 1s odber dat
    {

        CMeasPoll();        //fce je inline
        tim=0;

    }

    }

}

void InitTimer(uint8_t clk)
{

    INT_DDR &=~_BV(INT);
    INT_PULL|=_BV(INT);
    setFrekOutPCF(clk);
    INT_EICR |= INT_EICR_INIT;
    INT_EIMSK |=INT_EIMSK_INIT;

}

void DisTimer(void)
{

    INT_EICR&=~(INT_EICR_INIT);
    INT_PULL&=~_BV(INT);
    INT_EIMSK &=~INT_EIMSK_INIT;
    setFrekOutPCF(PCF_CLK_NONE);

}

inline uint8_t RetTimer(void)
{

    return timer;

}


uint8_t CompTimer(uint8_t TimState,uint8_t delay)
{

    uint8_t ActTimer = RetTimer();

    if(TimState > ActTimer && (255 - TimState + ActTimer) > delay) return 1;

    if(TimState < ActTimer && (ActTimer - TimState) > delay) return 1;


    return 0;
}
