From OmegaV-wiki
Jump to: navigation, search

Analog-Digital Example


Here we read out an analog voltage and get a 10 bit result according to AREF. In other words the result in volts will be <math>\frac{ReadADC() \cdot AREF}{1024}</math>. This function will do one conversion, then shut down the AD-module completely, saving precious power. This code is written for Atmega48/88/168 but can easily be ported to other AVR-devices. <source lang=c> //Read a single-ADC-value according to AREF uint16_t ReadADC(){

       //Temporary variable

uint16_t result = 0; PRR ^= (1<<PRADC);//Set the Power Reduction ADC-bit to 0 //Set the adc-channel in use, and the reference voltage ADMUX = (0<<MUX3)|(1<<MUX2)|(0<<MUX1)|(0<<MUX0);//ADC4 and AREF voltage-reference DIDR0 = (1<<ADC4D);//Disable the digital buffer at this pin

ADCSRA = (1<<ADEN)|(1<<ADSC);//Start conversion while(ADCSRA & (1<<ADSC))//Wait until the conversion is finished ;

       //Get the result, first get the 8 lower bits

result = (uint16_t)ADCL;

       //Then the 2 higher bits(since this is a 10 bit conversion, only the two lowest bits will ever be set)

result += (((uint16_t)ADCH)<<8);

ADCSRA = 0x00;//Turn off the ADC-module PRR |= (1<<PRADC);

return result;//Return } </source>

--Oybo 06:06, 31 October 2007 (CET)

Personal tools