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"
20 #include "mbed_error.h"
24 #define ANALOGIN_MEDIAN_FILTER 1
26 #define ADC_10BIT_RANGE 0x3FF
27 #define ADC_12BIT_RANGE 0xFFF
28 #define PDRUN_VALID_BITS 0x000025FFL
29 #define PDRUN_RESERVED_ONE 0x0000C800L
31 #define ADC_RANGE ADC_12BIT_RANGE
33 static const PinMap PinMap_ADC[] = {
50 void analogin_init(analogin_t *obj, PinName pin) {
51 volatile uint32_t tmp;
52 obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC);
53 MBED_ASSERT(obj->adc != (ADCName)NC);
55 pinmap_pinout(pin, PinMap_ADC);
57 __IO uint32_t *reg = (__IO uint32_t*)(LPC_IOCON_BASE + (pin & 0x1FF));
58 // set pin to ADC mode
59 *reg &= ~(1 << 7); // set ADMODE = 0 (analog mode)
62 tmp = (LPC_SYSCON->PDRUNCFG & PDRUN_VALID_BITS);
63 tmp &= ~((1 << 4) & PDRUN_VALID_BITS);
64 LPC_SYSCON->PDRUNCFG = (tmp | PDRUN_RESERVED_ONE);
66 // Enable clock for ADC
67 LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 13);
69 // Determine the clock divider for a 500kHz ADC clock during calibration
70 uint32_t clkdiv = (SystemCoreClock / 500000) - 1;
72 // Perform a self-calibration
73 LPC_ADC->CTRL = (1UL << 30) | (clkdiv & 0xFF);
74 while ((LPC_ADC->CTRL & (1UL << 30)) != 0);
76 // Sampling clock: SystemClock divided by 1
80 static inline uint32_t adc_read(analogin_t *obj) {
83 LPC_ADC->SEQA_CTRL &= ~(0xFFF);
84 LPC_ADC->SEQA_CTRL |= (1UL << obj->adc);
86 // start conversion, sequence enable with async mode
87 LPC_ADC->SEQA_CTRL |= ((1UL << 26) | (1UL << 31) | (1UL << 19));
89 // Repeatedly get the sample data until DONE bit
90 volatile uint32_t data;
92 data = LPC_ADC->SEQA_GDAT;
93 } while ((data & (1UL << 31)) == 0);
94 data = LPC_ADC->DAT[obj->adc];
97 LPC_ADC->SEQA_CTRL &= ~(1UL << 31);
99 return ((data >> 4) & ADC_RANGE);
102 static inline void order(uint32_t *a, uint32_t *b) {
110 static inline uint32_t adc_read_u32(analogin_t *obj) {
112 #if ANALOGIN_MEDIAN_FILTER
113 uint32_t v1 = adc_read(obj);
114 uint32_t v2 = adc_read(obj);
115 uint32_t v3 = adc_read(obj);
121 value = adc_read(obj);
126 uint16_t analogin_read_u16(analogin_t *obj) {
127 uint32_t value = adc_read_u32(obj);
128 return (value << 4) | ((value >> 8) & 0x000F); // 12 bit
131 float analogin_read(analogin_t *obj) {
132 uint32_t value = adc_read_u32(obj);
133 return (float)value * (1.0f / (float)ADC_RANGE);