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 "PeripheralNames.h"
24 #include "fsl_adc_hal.h"
25 #include "fsl_clock_manager.h"
26 #include "PeripheralPins.h"
27 #include "fsl_device_registers.h"
29 #define MAX_FADC 6000000
31 void analogin_init(analogin_t
*obj
, PinName pin
) {
32 obj
->adc
= (ADCName
)pinmap_peripheral(pin
, PinMap_ADC
);
33 MBED_ASSERT(obj
->adc
!= (ADCName
)NC
);
35 uint32_t instance
= obj
->adc
>> ADC_INSTANCE_SHIFT
;
36 uint32_t adc_addrs
[] = ADC_BASE_ADDRS
;
38 CLOCK_SYS_EnableAdcClock(instance
);
41 CLOCK_SYS_GetFreq(kBusClock
, &bus_clock
);
43 for (clkdiv
= 0; clkdiv
< 4; clkdiv
++) {
44 if ((bus_clock
>> clkdiv
) <= MAX_FADC
)
48 clkdiv
= 0x3; //Set max div
50 /* adc is enabled/triggered when reading. */
51 ADC_HAL_Init(adc_addrs
[instance
]);
52 ADC_HAL_SetClkSrcMode(adc_addrs
[instance
], kAdcClkSrcOfBusClk
);
53 ADC_HAL_SetClkDividerMode(adc_addrs
[instance
], (adc_clk_divider_mode_t
)(clkdiv
& 0x3));
54 ADC_HAL_SetRefVoltSrcMode(adc_addrs
[instance
], kAdcRefVoltSrcOfVref
);
55 ADC_HAL_SetResolutionMode(adc_addrs
[instance
], kAdcResolutionBitOfSingleEndAs16
);
56 ADC_HAL_SetContinuousConvCmd(adc_addrs
[instance
], false);
57 ADC_HAL_SetHwTriggerCmd(adc_addrs
[instance
], false); /* sw trigger */
58 ADC_HAL_SetHwAverageCmd(adc_addrs
[instance
], true);
59 ADC_HAL_SetHwAverageMode(adc_addrs
[instance
], kAdcHwAverageCountOf4
);
60 ADC_HAL_SetChnMuxMode(adc_addrs
[instance
], kAdcChnMuxOfB
); /* only B channels are avail */
62 pinmap_pinout(pin
, PinMap_ADC
);
65 uint16_t analogin_read_u16(analogin_t
*obj
) {
66 uint32_t instance
= obj
->adc
>> ADC_INSTANCE_SHIFT
;
67 uint32_t adc_addrs
[] = ADC_BASE_ADDRS
;
68 /* sw trigger (SC1A) */
69 ADC_HAL_ConfigChn(adc_addrs
[instance
], 0, false, false, obj
->adc
& 0xF);
70 while (!ADC_HAL_GetChnConvCompletedCmd(adc_addrs
[instance
], 0));
71 return ADC_HAL_GetChnConvValueRAW(adc_addrs
[instance
], 0);
74 float analogin_read(analogin_t
*obj
) {
75 uint16_t value
= analogin_read_u16(obj
);
76 return (float)value
* (1.0f
/ (float)0xFFFF);