| 1 |
/* adc.c -- routines for handling the Analog to Digital converter |
| 2 |
|
| 3 |
Copyright (C) 2008 Ajith Kumar, Inter-University Accelerator Centre, |
| 4 |
New Delhi. |
| 5 |
|
| 6 |
This program is free software; you can redistribute it and/or modify |
| 7 |
it under the terms of the GNU General Public License as published by |
| 8 |
the Free Software Foundation; either version 3, or (at your option) |
| 9 |
any later version. |
| 10 |
*/ |
| 11 |
|
| 12 |
#include <avr/io.h> |
| 13 |
|
| 14 |
#ifndef BV |
| 15 |
#define BV(bit) (1 << (bit)) |
| 16 |
#endif |
| 17 |
|
| 18 |
#define REF_EXT 0 // Feed reference voltage externally |
| 19 |
#define REF_INT (3<<6) // use the 2.56 V internal reference |
| 20 |
#define REF_AVCC (1<<6) // Connect AVCC internally to reference |
| 21 |
#define ADMAX 7 // channels 0 to 7 |
| 22 |
#define ADC_SPEED 7 // ADCClk = (8 MHz/ 128) = 62.5 KHz =>208 usec |
| 23 |
|
| 24 |
|
| 25 |
uint8_t adc_active = 0; |
| 26 |
uint8_t adc_ref = REF_AVCC; // Default is to use AVCC |
| 27 |
|
| 28 |
void adc_enable(void) |
| 29 |
{ |
| 30 |
ADCSRA = BV(ADEN); // Enable the ADC |
| 31 |
ADMUX = REF_AVCC; // Use AVCC as reference |
| 32 |
adc_active = 1; |
| 33 |
} |
| 34 |
|
| 35 |
void adc_disable(void) |
| 36 |
{ |
| 37 |
ADCSRA = 0; // Disable the ADC |
| 38 |
adc_active = 0; |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
void adc_set_ref(uint8_t val) |
| 43 |
{ |
| 44 |
ADMUX &= 0x3f; // Clear reference selection bits |
| 45 |
ADMUX |= val; // Set the selected reference source |
| 46 |
} |
| 47 |
|
| 48 |
uint16_t read_adc(uint8_t ch) // Returns 10 bit number |
| 49 |
{ |
| 50 |
uint8_t low; |
| 51 |
uint16_t val; |
| 52 |
|
| 53 |
if (!adc_active) |
| 54 |
adc_enable(); |
| 55 |
if (ch > ADMAX) |
| 56 |
return 0; |
| 57 |
ADMUX = adc_ref | ch; // Set channel & reference |
| 58 |
ADCSRA = BV(ADEN) | BV(ADSC) | ADC_SPEED; |
| 59 |
while ( !(ADCSRA & (1<<ADIF)) ) ; // wait for ADC conversion |
| 60 |
ADCSRA |= ADIF; |
| 61 |
low = ADCL; |
| 62 |
val = ADCH; |
| 63 |
return (val << 8) | low; |
| 64 |
} |
| 65 |
|