/*
 * i2c_test_attiny85.c
 *
 * Created: 12/11/2021 15:26:38
 * Author : 40008304
 */

#if __GNUC__
#include <avr/io.h>
#include <avr/interrupt.h>
#else
#include <inavr.h>
#include <ioavr.h>
#endif

#include "led_gen.h"
#include "led_receptor.h"
#include "usiTwiSlave.h"

#define NOM_CONSTRUC	0x08
#define NOM_CAPTEUR		0x10
#define VALEUR_DEMAN	0x49
#define BASIC_MODE		0x42

unsigned char adcled1;
unsigned char adcled2;
double moyLed1=0;
double moyLed2=0;
int iMoy=0;
volatile unsigned char recVal1=0;
volatile unsigned char recVal2=0;
volatile unsigned char recVal=0;

ISR (ADC_vect){
	adcled1=measureLed1();
	adcled2=measureLed2();
	moyLed1=moyLed1 + adcled1;
	moyLed2=moyLed2 + adcled2;
	iMoy++;
	if(iMoy >= 2000)
	{
		moyLed1=moyLed1/iMoy;
		moyLed2=moyLed2/iMoy;
		recVal1=(int)moyLed1;
		recVal2=(int)moyLed2;
		recVal=compareLed(recVal1,recVal2);
		moyLed1=0;
		moyLed2=0;
		iMoy=0;
	}
	ADCSRA |= (1<<ADSC);
}

ISR (TIMER0_OVF_vect)							//Interrupt vector for Timer0
{
	if (intr_count==5)							//waiting for 63 because to get 1 sec delay
	{
		timer_flag=1-timer_flag;
		intr_count=0;							//making intr_count=0 to repeat the count
	}
	else  intr_count++;							//incrementing c upto 63
}

int main( void )
{
    unsigned char cmd,i=0;
    unsigned char nom_capteur[8]= {'C','a','t','c','h','E','y','e'};
    unsigned char sensor_type[8]= {'I','R','O','b','s','t','a','c'};
	uint8_t slaveAdress;//data = 0x45;
    slaveAdress = 0x01;
	MCUCR |= (1<<PUD);
	
	usiTwiSlaveInit(slaveAdress);
	
	sei();
	ADC_init();
	ADC_start_conversion();
	timer0_init();
	
    while(1)
    {
        if( usiTwiDataInTransmitBuffer() )
        {
            cmd = usiTwiReceiveByte();
            switch(cmd)
            {
            case NOM_CONSTRUC :
                for (i=0; i<8; i++)
                {
                    usiTwiTransmitByte(nom_capteur[i]);
                }
                break;

            case NOM_CAPTEUR :
                for (i=0; i<8; i++)
                {
                    usiTwiTransmitByte(sensor_type[i]);
                }
                break;

            case VALEUR_DEMAN :
                usiTwiTransmitByte(recVal/*recVal*/);
                break;

            case BASIC_MODE :
                usiTwiTransmitByte(recVal);
                break;
            }
        }
    }
    return 0;
}
