#include "adc.h"
#include <avr/io.h>
#include <stdint.h>

void wait(void){
	unsigned int i,j;
	for(i=0;i<10;i++){
		j=0;
		while(j<15){
			j++;
		}
	}
}

/** activates the analog digital conversion and sets the prescaler to system clock.
    reference voltage is set to external reference.
    result of the conversion will left by setting ADLAR to one 
    @return void
**/ 
void adc_init(){
	// ADEN Enable Analog Digital Conversion
	ADCSRA = (1<<ADEN);
	// ADPSx Setzen des Prescaler für eine Frequenz zwischen 50 und 200 KHz 
	ADCSRA = (1<<ADEN) | (1<<ADPS2)|(0<<ADPS1) | (1<<ADPS0);    // Frequenzvorteiler 
                               				 // setzen auf 128 (1) und ADC aktivieren (1)
	ADMUX = (0<<REFS0)&(0<<REFS1);
}

/** performs an AD conversion and returns an 10 Bit result.
 	@param channel channel from which AD conversion is needed possible values are 0 to 7
	@return the result of the conversion represented in 16 Bit
**/ 
uint16_t adc_getValue(unsigned char channel){
	uint16_t result;
	ADMUX &= 0xE0;					// löschen des Multiplexers 
	ADMUX = channel;				// Auswahl des Kanals
							// Die Zusatzfunktionen sind gesperrt
	ADCSRA |= (1<<ADSC);				// Starten der Messung
	while(!(ADCSRA & (1<<ADIF)) )wait();   		// auf Abschluss der Konvertierung warten (ADIF-bit)
	ADCSRA &= ~(1<<ADIF);              		// ADIF löschen

	ADCSRA |= (1<<ADSC);				// Starten der Messung
	while(!(ADCSRA & (1<<ADIF)) )wait();  		// auf Abschluss der Konvertierung warten (ADIF-bit)
	ADCSRA &= ~(1<<ADIF);              		// ADIF löschen
	result= ADCL;
	result+= (ADCH<<8);
	return result;
}

