/*
Diplomova prace : Palubni pocitac

backlight.c

Atmega128A 10 MHz XTAL

Autor: Ondrej Lutera

2011/2012

*/
#include "backlight.h"

uint8_t actOpto=0;
uint8_t actPwm=0;

uint8_t initOpto(odat_t * opto)
{

    pca_t pca;
    uint8_t ret=0;

    if(opto!=NULL)
    {
        if(opto->isSet != OPTO_SET)
        {
            uint8_t i;

            opto->isSet = OPTO_SET;

            for(i=0; i<OPTO_CNT; i++)
            {

                opto->data[i].opto = (100/OPTO_CNT)*(i+1) ;
                opto->data[i].pwm = 255;

            }

            ret = 1;
        }



        pca.pwm1 = opto->data[OPTO_CNT-1].pwm;
        pca.frek1 = 152;
        pca.ls =  CH1_PWM1;


    }
    else
    {

        pca.pwm1 = 50;
        pca.frek1 = 152;
        pca.ls =  CH1_PWM1;

    }
    initPCA();

    setPCA(&pca);

    return ret;
}

uint8_t optoPoll(uint8_t oldPwm,odat_t * opto)
{

    static uint8_t light[AVG_SAMPLES];
    static uint8_t index = 0;
    static uint8_t full = 0;
    static uint16_t oldAvg = 0;
    static uint8_t tim = 0;

    if(CompTimer(tim,OPTO_DELAY))
    {

        tim = RetTimer();

        uint8_t max;
        uint8_t i;
        uint16_t l=0;
        pca_t pcaData;

        if(StartAD(OPTO)!=OPTO) return l;

        ReadAD(OPTO)    ;

        StartAD(OPTO);


        uint16_t ad =ReadAD(OPTO)/5;

        if(ad > oldAvg && ad-oldAvg < 10) ad = oldAvg;
        else if(ad < oldAvg && oldAvg-ad < 10) ad = oldAvg;

        light[index++]=(ad);

        if(index==AVG_SAMPLES)
        {

            index = 0;
            full = 1;

        }

        if(full==1)max=AVG_SAMPLES;
        else max=index;

        for(i=0; i<max; i++) l+=light[i];

        l/=max;

        oldAvg = l;

        if(l>100) l = 100;

        i=OPTO_CNT-1;

        while(i > 0 && opto->data[i].opto > l)i--;

        pcaData.pwm1 = opto->data[i].pwm;

        actPwm=pcaData.pwm1;
        actOpto=opto->data[i].opto;

        pcaData.frek1 = 152;
        pcaData.ls =  CH1_PWM1;

        setPCA(&pcaData);

        return  l;


    }

    return oldPwm;

}

uint8_t getActOptoPwm(void)
{

    return actPwm;

}

uint8_t getActOptoIx(void)
{

    return actOpto;

}
