/* ------------------------------------------------------------------------- */
/* ------------------------ On Chip ADC code   ----------------------------- */
/* ------------------------------------------------------------------------- */
static uint16_t adc_lastval;	//last ATMega ADC value
static uint32_t adc_accum;		//ADC value accumulator
static uint16_t voltage;
static signed int 	adc_samps;	//ADC sample counter

#define A 1702	//with x=ADC reading, Voltage v [mV]:
#define B 712	//v=x*1000/A+B


/* ADC---------------------------------------------------------------------- */

static void ADC_Init(void) {	
	adc_lastval=0xffff;
	ADMUX  = 0xC2; /* Vref=1.1V, measure ADC2 */
	ADCSRA = 0x87; /* enable ADC, not free running, interrupt disable, rate = 1/128 */
}

static void ADC_Voltage(void) {
uint32_t x=adc_lastval;
x=x*1000;
x=x/A;
x=x+B;		//voltage in mV
x=x+50;		//round to 100mV
x=x/100;
voltage=x;	//voltage in 100mV units
}


static void ADC_Poll(void) {
	if(!(ADCSRA & _BV(ADSC))){
		if(adc_samps < 32*32) {
			if (adc_samps==-1){		//reset condition
				adc_accum=0;
				adc_samps=0;
				}else{
				adc_accum += ADC;	//add up samples
				adc_samps++;
				}
		}else{
			adc_lastval=adc_accum>>5;
			ADC_Voltage();
			adc_accum = ADC;
			adc_samps =1;
		}
		ADCSRA |= _BV(ADSC);  /* start next conversion */
	}
}
