/*
 * ADC_drv.h
 *
 * Created: 19.4.2016 15:47:17
 *  Author: Chenda
 */ 


#ifndef ADC_DRV_H_
#define ADC_DRV_H_

// voltage reference definition
#define ADC_VREF_AREF			0b00
#define ADC_VREF_AVCC			0b01
#define ADC_VREF_INT_1_1V		0b11

// channels
#define ADC_CH_0				0b0000
#define ADC_CH_1				0b0001
#define ADC_CH_2				0b0010
#define ADC_CH_3				0b0011
#define ADC_CH_4				0b0100
#define ADC_CH_5				0b0101
#define ADC_CH_6				0b0110
#define ADC_CH_7				0b0111
#define ADC_CH_TEMP_SNS			0b1000
#define ADC_CH_1_1V				0b1110
#define ADC_CH_0V_GND			0b1111

// prescaler
#define ADC_PRESC_2				0b001
#define ADC_PRESC_4				0b010
#define ADC_PRESC_8				0b011
#define ADC_PRESC_16			0b100
#define ADC_PRESC_32			0b101
#define ADC_PRESC_64			0b110
#define ADC_PRESC_128			0b111

// auto trigger sources
#define ADC_ATRGSRC_FRUN		0b000
#define ADC_ATRGSRC_ACOMP		0b001
#define ADC_ATRGSRC_EINT0		0b010
#define ADC_ATRGSRC_TC0_CM_A	0b011
#define ADC_ATRGSRC_TC0_OVF		0b100
#define ADC_ATRGSRC_TC1_CM_B	0b101
#define ADC_ATRGSRC_TC1_OVF		0b110
#define ADC_ATRGSRC_TC1_CEVE	0b111

// macros
#define mADC_SelChannel(x)		ADMUX&=~(0b1111);ADMUX|=(x&0b1111)
#define mADC_SelReference(x)	ADMUX&=~(0b11<<6);ADMUX|=((x&0b11)<<6)
#define mADC_LeftAdjustedRes()	ADMUX|=(1<<ADLAR)
#define mADC_RightAdjustedRes()	ADMUX&=~(1<<ADLAR)
#define mADC_Enable()			ADCSRA|=(1<<ADEN)
#define mADC_Disable()			ADCSRA&=~(1<<ADEN)
#define mADC_StartConversion()	ADCSRA|=(1<<ADSC)
#define mADC_AutoTrigger_Enab()	ADCSRA|=(1<<ADATE)
#define mADC_AutoTrigger_Dis()	ADCSRA&=~(1<<ADATE)
#define mADC_IsConvDone()		ADCSRA&(1<<ADIF)
#define mADC_ClrConvDoneFlag()	ADCSRA|=(1<<ADIF)
#define mADC_Interr_Enab()		ADCSRA|=(1<<ADIE)
#define mADC_Interr_Dis()		ADCSRA&=~(1<<ADIE)
#define mADC_SelPrescaler(x)	ADCSRA&=~(0b111);ADCSRA|=(x&0b111)
#define mADC_SelAutoTrigSrc(x)	ADCSRB&=~(0b111);ADCSRB|=(x&0b111)
#define mADC_DigInp_Dis(x)		DIDR0|=(x)
#define mADC_DigInp_Enab(x)		DIDR0&=~(x)
#define mADC_ReadConvVal_Low()	ADCL			// have to be read before ADCH
#define mADC_ReadConvVal_High()	(ADCH&0b11)			//&0b11

// advanced macros
#define mADC_SetTempMeasure()	mADC_SelReference(ADC_VREF_INT_1_1V);mADC_SelChannel(ADC_CH_TEMP_SNS)
#define mADC_SetFreeRun()		mADC_AutoTrigger_Enab();mADC_SelAutoTrigSrc(ADC_ATRGSRC_FRUN)
#define mADC_SetSingleRun()		mADC_AutoTrigger_Dis()

#endif /* ADC_DRV_H_ */