1 /* mbed Microcontroller Library
2 * Copyright (c) 2006-2013 ARM Limited
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 #include "mbed_assert.h"
17 #include "analogin_api.h"
22 #define ANALOGIN_MEDIAN_FILTER 1
24 #define ADC_10BIT_RANGE 0x3FF
25 #define ADC_12BIT_RANGE 0xFFF
27 static inline int div_round_up(int x, int y) {
28 return (x + (y - 1)) / y;
31 static const PinMap PinMap_ADC[] = {
43 #define ADC_RANGE ADC_12BIT_RANGE
45 void analogin_init(analogin_t *obj, PinName pin) {
46 obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC);
47 MBED_ASSERT(obj->adc != (ADCName)NC);
49 // ensure power is turned on
50 LPC_SC->PCONP |= (1 << 12);
52 // set PCLK of ADC to /1
53 LPC_SC->PCLKSEL0 &= ~(0x3 << 24);
54 LPC_SC->PCLKSEL0 |= (0x1 << 24);
55 uint32_t PCLK = SystemCoreClock;
57 // calculate minimum clock divider
58 // clkdiv = divider - 1
59 uint32_t MAX_ADC_CLK = 13000000;
60 uint32_t clkdiv = div_round_up(PCLK, MAX_ADC_CLK) - 1;
62 // Set the generic software-controlled ADC settings
63 LPC_ADC->ADCR = (0 << 0) // SEL: 0 = no channels selected
64 | (clkdiv << 8) // CLKDIV: PCLK max ~= 25MHz, /25 to give safe 1MHz at fastest
65 | (0 << 16) // BURST: 0 = software control
66 | (0 << 17) // CLKS: not applicable
67 | (1 << 21) // PDN: 1 = operational
68 | (0 << 24) // START: 0 = no start
69 | (0 << 27); // EDGE: not applicable
71 pinmap_pinout(pin, PinMap_ADC);
74 static inline uint32_t adc_read(analogin_t *obj) {
75 // Select the appropriate channel and start conversion
76 LPC_ADC->ADCR &= ~0xFF;
77 LPC_ADC->ADCR |= 1 << (int)obj->adc;
78 LPC_ADC->ADCR |= 1 << 24;
80 // Repeatedly get the sample data until DONE bit
83 data = LPC_ADC->ADGDR;
84 } while ((data & ((unsigned int)1 << 31)) == 0);
87 LPC_ADC->ADCR &= ~(1 << 24);
89 return (data >> 4) & ADC_RANGE; // 12 bit
92 static inline void order(uint32_t *a, uint32_t *b) {
100 static inline uint32_t adc_read_u32(analogin_t *obj) {
102 #if ANALOGIN_MEDIAN_FILTER
103 uint32_t v1 = adc_read(obj);
104 uint32_t v2 = adc_read(obj);
105 uint32_t v3 = adc_read(obj);
111 value = adc_read(obj);
116 uint16_t analogin_read_u16(analogin_t *obj) {
117 uint32_t value = adc_read_u32(obj);
119 return (value << 4) | ((value >> 8) & 0x000F); // 12 bit
122 float analogin_read(analogin_t *obj) {
123 uint32_t value = adc_read_u32(obj);
124 return (float)value * (1.0f / (float)ADC_RANGE);