Debian Codegraph @

kpy/mh-adc.c

raw symbols SCIP
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 and Pramode C.E, GnuVision.com.
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 = (1 << 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 adc_ref = val; // save the value
47 }
48
49 uint16_t read_adc(uint8_t ch) // Returns 10 bit number
50 {
51 uint8_t low;
52 uint16_t val;
53
54 if (!adc_active)
55 adc_enable();
56 if (ch > ADMAX)
57 return 0;
58 ADMUX = adc_ref | ch; // Set channel & reference
59 ADCSRA = (1 << ADEN) | (1 << ADSC) | ADC_SPEED;
60 while ( !(ADCSRA & (1<<ADIF)) ) ; // wait for ADC conversion
61 ADCSRA |= ADIF;
62 low = ADCL;
63 val = ADCH;
64 return (val << 8) | low;
65 }
66