/*
 * led_receptor.c
 *
 * Created: 03/12/2021 14:29:43
 *  Author: 40008304
 */ 

#include "led_receptor.h"

volatile unsigned char intr_count;
volatile unsigned char timer_flag=0;
volatile unsigned char seconde=0;

volatile unsigned char ledresult1=0;
volatile unsigned char ledresult2=0;

void ADC_init(void)
{
	DDRB &=~(1<<PB3);										//Pin B3 en entree
	ADMUX |= (1<<MUX1)|(1<<MUX0)|(1<<ADLAR);				//MUX = 0010 donc sortie PB4 et ADLAR a 1 pour avoir les bits de poids fort en premier
	ADCSRA|= (1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0)|(1<<ADIE);		//ADEN conversion autorisee
															//On divise 16Mhz par 128 (125 KHz) < 200 KHz
															//Interruptions autorisees
	ADCSRB &= ~(0b111<<ADTS0);								//free-running mode
	sei();
};

void ADC_start_conversion(void)
{
	ADCSRA|=(1<<ADEN)|(1<<ADIE)|(1<<ADSC);
};

char ADC_read_value(void)
{
	ADCSRA|=(1<<ADSC);
	while(ADCSRA & (1<<ADSC));
	return ADCH;
};

float ADC_averaging(unsigned char val_ana)
{
	float valeur_finale=0;
	char precision;
	for(precision = 75; precision > 0 ; precision --)
	{
		valeur_finale = valeur_finale +(((val_ana * 0.01961) - valeur_finale) / 15);
	}
	return valeur_finale;
};

char measureLed1(void)
{
	if(timer_flag == 1)
	{
		if(led1_state==0)
		{
			led1_init();
			ledresult1=ADCH;
		}
		else
		{
			led1_stop();
		}
	}
	return ledresult1;
};

char measureLed2(void)
{
	if(timer_flag == 1)
	{
		if(led2_state==0)
		{
			led2_init();
			ledresult2=ADCH;
		}
		else
		{
			led2_stop();
		}
		timer_flag=0;
	}
	return ledresult2;
};

unsigned char compareLed(int led1,int led2)
{
	int adcCompare = led1 - led2;
    if(adcCompare < 1)
    {
	    if(led1 > 204)
	    {
		    return NOTHING;
	    }
	    else
	    {
		    return FRONT;
	    }
    }
    if (led1 > led2)	// adcLed2 > adcLed1
    {
	    return LEFT;
    }
    else
    {
	    return RIGHT;
    }
};
