1 /*!
2 * \file adc-board.c
3 *
4 * \brief Target board ADC driver implementation
5 *
6 * \copyright Revised BSD License, see section \ref LICENSE.
7 *
8 * \code
9 * ______ _
10 * / _____) _ | |
11 * ( (____ _____ ____ _| |_ _____ ____| |__
12 * \____ \| ___ | (_ _) ___ |/ ___) _ \
13 * _____) ) ____| | | || |_| ____( (___| | | |
14 * (______/|_____)_|_|_| \__)_____)\____)_| |_|
15 * (C)2013-2017 Semtech
16 *
17 * \endcode
18 *
19 * \author Miguel Luis ( Semtech )
20 *
21 * \author Gregory Cristian ( Semtech )
22 */
23 #include "stm32l1xx.h"
24 #include "board-config.h"
25 #include "adc-board.h"
26
27 ADC_HandleTypeDef AdcHandle;
28
AdcMcuInit(Adc_t * obj,PinNames adcInput)29 void AdcMcuInit( Adc_t *obj, PinNames adcInput )
30 {
31 AdcHandle.Instance = ADC1;
32
33 __HAL_RCC_ADC1_CLK_ENABLE( );
34
35 HAL_ADC_DeInit( &AdcHandle );
36
37 if( adcInput != NC )
38 {
39 GpioInit( &obj->AdcInput, adcInput, PIN_ANALOGIC, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
40 }
41 }
42
AdcMcuConfig(void)43 void AdcMcuConfig( void )
44 {
45 // Configure ADC
46 AdcHandle.Init.Resolution = ADC_RESOLUTION_12B;
47 AdcHandle.Init.DataAlign = ADC_DATAALIGN_RIGHT;
48 AdcHandle.Init.ContinuousConvMode = DISABLE;
49 AdcHandle.Init.DiscontinuousConvMode = DISABLE;
50 AdcHandle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
51 AdcHandle.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T6_TRGO;
52 AdcHandle.Init.DMAContinuousRequests = DISABLE;
53 AdcHandle.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
54 AdcHandle.Init.NbrOfConversion = 1;
55 AdcHandle.Init.LowPowerAutoWait = DISABLE;
56 AdcHandle.Init.LowPowerAutoPowerOff = DISABLE;
57 HAL_ADC_Init( &AdcHandle );
58 }
59
AdcMcuReadChannel(Adc_t * obj,uint32_t channel)60 uint16_t AdcMcuReadChannel( Adc_t *obj, uint32_t channel )
61 {
62 ADC_ChannelConfTypeDef adcConf = { 0 };
63 uint16_t adcData = 0;
64
65 // Enable HSI
66 __HAL_RCC_HSI_ENABLE( );
67
68 // Wait till HSI is ready
69 while( __HAL_RCC_GET_FLAG( RCC_FLAG_HSIRDY ) == RESET )
70 {
71 }
72
73 // Wait the the Vrefint used by adc is set
74 while( __HAL_PWR_GET_FLAG( PWR_FLAG_VREFINTRDY ) == RESET )
75 {
76 }
77
78 __HAL_RCC_ADC1_CLK_ENABLE( );
79
80 adcConf.Channel = channel;
81 adcConf.Rank = ADC_REGULAR_RANK_1;
82 adcConf.SamplingTime = ADC_SAMPLETIME_192CYCLES;
83
84 HAL_ADC_ConfigChannel( &AdcHandle, &adcConf );
85
86 // Enable ADC1
87 // Start ADC Software Conversion
88 HAL_ADC_Start( &AdcHandle );
89
90 HAL_ADC_PollForConversion( &AdcHandle, HAL_MAX_DELAY );
91
92 adcData = HAL_ADC_GetValue( &AdcHandle );
93
94 __HAL_ADC_DISABLE( &AdcHandle );
95
96 __HAL_RCC_ADC1_CLK_DISABLE( );
97
98 // Disable HSI
99 __HAL_RCC_HSI_DISABLE( );
100
101 return adcData;
102 }
103