AVR/Examples/AD

From OmgaV Wiki

Jump to: navigation, search

Analog-Digital Example

Code

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 \frac{ReadADC() \cdot AREF}{1024}. 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.

  1. //Read a single-ADC-value according to AREF
  2. uint16_t ReadADC(){
  3. //Temporary variable
  4. uint16_t result = 0;
  5. PRR ^= (1<<PRADC);//Set the Power Reduction ADC-bit to 0
  6. //Set the adc-channel in use, and the reference voltage
  7. ADMUX = (0<<MUX3)|(1<<MUX2)|(0<<MUX1)|(0<<MUX0);//ADC4 and AREF voltage-reference
  8. DIDR0 = (1<<ADC4D);//Disable the digital buffer at this pin
  9.  
  10. ADCSRA = (1<<ADEN)|(1<<ADSC);//Start conversion
  11. while(ADCSRA & (1<<ADSC))//Wait until the conversion is finished
  12. ;
  13. //Get the result, first get the 8 lower bits
  14. result = (uint16_t)ADCL;
  15. //Then the 2 higher bits(since this is a 10 bit conversion, only the two lowest bits will ever be set)
  16. result += (((uint16_t)ADCH)<<8);
  17.  
  18. ADCSRA = 0x00;//Turn off the ADC-module
  19. PRR |= (1<<PRADC);
  20.  
  21. return result;//Return
  22. }

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

Personal tools