Subversion Repositories HomeAutomation

Rev

Rev 796 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | SVN | RSS feed

  1.  
  2. /*-----------------------------------------------
  3.  * Includes
  4.  * ---------------------------------------------*/
  5. #include <avr/io.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8.  
  9. #include <config.h>
  10. #include "adc.h"
  11.  
  12. #define BV(x) (1<<(x))
  13.  
  14. /*----------------------------------------------
  15.  * Functions
  16.  * --------------------------------------------*/
  17.  
  18.  static uint8_t currentChannel; //Used to keep the channel of the last measurement. This is used to determine if the channel needs to be changed.
  19.  
  20. uint8_t ADC_Init(void)
  21. {
  22.     /* Enable AVcc as Voltage Reference */
  23.     ADMUX |= (1<<REFS0);
  24.     ADMUX &= ~(1<<REFS1);
  25.  
  26.     /* Right adjust the result */
  27.     ADMUX &= ~(1<<ADLAR);
  28.  
  29.     /* Wake up ADC and enable it */
  30.     PRR &= ~(1<<PRADC);
  31.     ADCSRA |= (1<<ADEN);
  32.  
  33.     /* Make sure that the next ADC_Get will do an empty measurement first by setting the channel to an impossible value */
  34.     currentChannel = 10;
  35.    
  36.     return 0;
  37. }
  38.  
  39. /*
  40.  * Start reading adc value.
  41.  */
  42. uint16_t ADC_Get(uint8_t channel)
  43. {
  44.     uint16_t adcdata;
  45.    
  46.     if (currentChannel != channel) //Did we use this channel the last time?
  47.     {
  48.         /* Set to 0 all mux registers */
  49.         ADMUX &= ~( BV(MUX3) | BV(MUX2) | BV(MUX1) | BV(MUX0) );
  50.         /* Select channel, only first 8 channel modes are supported for now */
  51.         ADMUX |= (channel & 0x07);
  52.        
  53.         currentChannel = channel;   //Update the channel for the last measurement to the one we want this time
  54.         ADC_Get(channel);   //And do a dummy-read
  55.     }
  56.  
  57.     /* Start measurement (takes 13 ADC clock cycles) */
  58.     ADCSRA |= (1<<ADSC);
  59.  
  60.     while( ADCSRA & (1<<ADSC) ){ /* Wait for conversion to complete */ }
  61.  
  62.     /* Get the result and return */
  63.     adcdata = ADCW; //>>2;
  64.  
  65.     return adcdata;
  66.    
  67. }
  68.