]>
git.gir.st - tmk_keyboard.git/blob - tmk_core/tool/mbed/mbed-sdk/libraries/mbed/targets/hal/TARGET_STM/TARGET_STM32F4XX/analogin_api.c
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"
23 #include "mbed_error.h"
25 #define ADC_10BIT_RANGE 0x3FF
26 #define ADC_12BIT_RANGE 0xFFF
28 static const PinMap PinMap_ADC
[] = {
29 {PA_0
, ADC0_0
, STM_PIN_DATA(3, 0)},
30 {PA_1
, ADC0_1
, STM_PIN_DATA(3, 0)},
31 {PA_2
, ADC0_2
, STM_PIN_DATA(3, 0)},
32 {PA_3
, ADC0_3
, STM_PIN_DATA(3, 0)},
33 {PA_4
, ADC0_4
, STM_PIN_DATA(3, 0)},
34 {PA_5
, ADC0_5
, STM_PIN_DATA(3, 0)},
35 {PA_6
, ADC0_6
, STM_PIN_DATA(3, 0)},
36 {PA_7
, ADC0_7
, STM_PIN_DATA(3, 0)},
37 {PB_0
, ADC0_8
, STM_PIN_DATA(3, 0)},
38 {PB_1
, ADC0_9
, STM_PIN_DATA(3, 0)},
39 {PC_0
, ADC0_10
, STM_PIN_DATA(3, 0)},
40 {PC_1
, ADC0_11
, STM_PIN_DATA(3, 0)},
41 {PC_2
, ADC0_12
, STM_PIN_DATA(3, 0)},
42 {PC_3
, ADC0_13
, STM_PIN_DATA(3, 0)},
43 {PC_4
, ADC0_14
, STM_PIN_DATA(3, 0)},
44 {PC_5
, ADC0_15
, STM_PIN_DATA(3, 0)},
48 # define ADC_RANGE ADC_12BIT_RANGE
50 void analogin_init(analogin_t
*obj
, PinName pin
) {
51 obj
->adc
= (ADCName
)pinmap_peripheral(pin
, PinMap_ADC
);
52 MBED_ASSERT(obj
->adc
!= (uint32_t)NC
);
54 // ensure power is turned on
55 RCC
->AHB1ENR
|= RCC_AHB1ENR_GPIOAEN
| RCC_AHB1ENR_GPIOBEN
|
57 RCC
->APB2ENR
|= RCC_APB2ENR_ADC1EN
;
60 ADC1
->CR2
|= ADC_CR2_ADON
;
62 pinmap_pinout(pin
, PinMap_ADC
);
65 static inline uint32_t adc_read(analogin_t
*obj
) {
66 // Select the appropriate channel
67 ADC1
->SQR3
= (int) obj
->adc
;
70 ADC1
->CR2
|= ADC_CR2_SWSTART
;
72 // Wait for conversion to finish
73 while (!(ADC1
->SR
& ADC_SR_EOC
));
75 uint32_t data
= ADC1
->DR
;
76 return data
; // 12 bit
79 static inline uint32_t adc_read_u32(analogin_t
*obj
) {
81 value
= adc_read(obj
);
85 uint16_t analogin_read_u16(analogin_t
*obj
) {
86 uint32_t value
= adc_read_u32(obj
);
88 return (value
<< 4) | ((value
>> 8) & 0x000F); // 12 bit
91 float analogin_read(analogin_t
*obj
) {
92 uint32_t value
= adc_read_u32(obj
);
93 return (float)value
* (1.0f
/ (float)ADC_RANGE
);