Contiki 2.5
adc-drv.c
Go to the documentation of this file.
1 /* Copyright (c) 2010, Ulf Kulau
2  *
3  * Permission is hereby granted, free of charge, to any person
4  * obtaining a copy of this software and associated documentation
5  * files (the "Software"), to deal in the Software without
6  * restriction, including without limitation the rights to use,
7  * copy, modify, merge, publish, distribute, sublicense, and/or sell
8  * copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following
10  * conditions:
11  *
12  * The above copyright notice and this permission notice shall be
13  * included in all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17  * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19  * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22  * OTHER DEALINGS IN THE SOFTWARE.
23  */
24 
25 /**
26  * \addtogroup Drivers
27  * @{
28  *
29  * \addtogroup adc_driver
30  * @{
31  */
32 
33 /**
34  * \file
35  * ADC driver implementation
36  * \author
37  * Ulf Kulau <kulau@ibr.cs.tu-bs.de>
38  */
39 
40 #include "adc-drv.h"
41 
42 void adc_init(uint8_t mode, uint8_t ref){
43  ADCSRA = ((ADC_ENABLE) | (ADC_PRESCALE_64));
44  ADCSRB = 0x00;
45  ADMUX = ref;
46 
47  if(mode != ADC_SINGLE_CONVERSION){
48  ADCSRB |= (0x07 & mode);
49  ADCSRA |= ((ADC_TRIGGER_ENABLE) | (ADC_INTERRUPT_ENABLE));
50  }
51 }
52 
53 void adc_set_mux(uint8_t mux){
54  static uint8_t used_adcs = 0;
55  /*save energy by disabling the i/o input buffer*/
56  if(mux < 8){
57  used_adcs |= (1 << mux);
58  DIDR0 |= used_adcs;
59  }
60  ADMUX &= (0xE0);
61  ADMUX |= mux;
62  ADCSRA |= ADC_START;
63 }
64 
65 uint16_t adc_get_value(void) {
66  if(ADCSRA & ADC_TRIGGER_ENABLE){
67  /*just read the ADC data register*/
68  return ADCW;
69  }else{
70  /*start single conversion*/
71  while (ADCSRA & (1 << ADSC)) {
72  ;
73  }
74  return ADCW;
75  }
76 }
77 
78 uint16_t adc_get_value_from(uint8_t chn){
79  adc_set_mux(chn);
80  return adc_get_value();
81 }
82 
83 void adc_deinit(void){
84  ADCSRA = ADC_STOP;
85  ADCSRB = ADC_STOP;
86  ADMUX = ADC_STOP;
87 }