#include <avr/io.h>


void adc_init(void) {
	uint16_t dummyResult;
	// AVCC with external capacitor at AREF pin
	ADMUX = _BV(REFS0);  
 
	// set frequency prescaler to 8
	ADCSRA = _BV(ADPS1) | _BV(ADPS0);
	
	// enable ADC	
	ADCSRA |= _BV(ADEN);
 
	// make a dummy read out
	ADCSRA |= _BV(ADSC);
	while (ADCSRA & _BV(ADSC) ) {
	}
	
	// we have to read, otherwise the next result is not available
	dummyResult = ADCW;
}


uint16_t adc_read_single(uint8_t channel) {
  ADMUX = (ADMUX & ~(0x1F)) | (channel & 0x1F);
  ADCSRA |= _BV(ADSC);
  while (ADCSRA & (1<<ADSC) ) {
  }
  return ADCW;
}
 
uint16_t adc_read_avg(const uint8_t channel, const uint8_t nsamples) {
  uint16_t sum = 0;
  uint8_t count = nsamples % 60;
 
  for (uint8_t i=0; i<count;++i ) {
    sum += adc_read_single(channel);
  }
 
  return (sum / count);
}
