1 /**
2 ******************************************************************************
3 * @file stm32l0xx_hal_adc.c
4 * @author MCD Application Team
5 * @brief This file provides firmware functions to manage the following
6 * functionalities of the Analog to Digital Convertor (ADC)
7 * peripheral:
8 * + Initialization and de-initialization functions
9 * ++ Initialization and Configuration of ADC
10 * + Operation functions
11 * ++ Start, stop, get result of conversions of regular
12 * group, using 3 possible modes: polling, interruption or DMA.
13 * + Control functions
14 * ++ Channels configuration on regular group
15 * ++ Analog Watchdog configuration
16 * + State functions
17 * ++ ADC state machine management
18 * ++ Interrupts and flags management
19 * Other functions (extended functions) are available in file
20 * "stm32l0xx_hal_adc_ex.c".
21 *
22 @verbatim
23 ==============================================================================
24 ##### ADC peripheral features #####
25 ==============================================================================
26 [..]
27 (+) 12-bit, 10-bit, 8-bit or 6-bit configurable resolution.
28
29 (+) Interrupt generation at the end of regular conversion and in case of
30 analog watchdog or overrun events.
31
32 (+) Single and continuous conversion modes.
33
34 (+) Scan mode for conversion of several channels sequentially.
35
36 (+) Data alignment with in-built data coherency.
37
38 (+) Programmable sampling time (common for all channels)
39
40 (+) External trigger (timer or EXTI) with configurable polarity
41
42 (+) DMA request generation for transfer of conversions data of regular group.
43
44 (+) ADC calibration
45
46 (+) ADC conversion of regular group.
47
48 (+) ADC supply requirements: 1.62 V to 3.6 V.
49
50 (+) ADC input range: from Vref- (connected to Vssa) to Vref+ (connected to
51 Vdda or to an external voltage reference).
52
53
54 ##### How to use this driver #####
55 ==============================================================================
56 [..]
57
58 *** Configuration of top level parameters related to ADC ***
59 ============================================================
60 [..]
61
62 (#) Enable the ADC interface
63 (++) As prerequisite, ADC clock must be configured at RCC top level.
64 Caution: On STM32L0, ADC clock frequency max is 16MHz (refer
65 to device datasheet).
66 Therefore, ADC clock prescaler must be configured in
67 function of ADC clock source frequency to remain below
68 this maximum frequency.
69
70 (++) Two clock settings are mandatory:
71 (+++) ADC clock (core clock, also possibly conversion clock).
72
73 (+++) ADC clock (conversions clock).
74 Two possible clock sources: synchronous clock derived from APB clock
75 or asynchronous clock derived from ADC dedicated HSI RC oscillator
76 16MHz.
77 If asynchronous clock is selected, parameter "HSIState" must be set either:
78 - to "...HSIState = RCC_HSI_ON" to maintain the HSI16 oscillator
79 always enabled: can be used to supply the main system clock.
80
81 (+++) Example:
82 Into HAL_ADC_MspInit() (recommended code location) or with
83 other device clock parameters configuration:
84 (+++) __HAL_RCC_ADC1_CLK_ENABLE(); (mandatory)
85
86 HSI enable (optional: if asynchronous clock selected)
87 (+++) RCC_OscInitTypeDef RCC_OscInitStructure;
88 (+++) RCC_OscInitStructure.OscillatorType = RCC_OSCILLATORTYPE_HSI;
89 (+++) RCC_OscInitStructure.HSI16CalibrationValue = RCC_HSICALIBRATION_DEFAULT;
90 (+++) RCC_OscInitStructure.HSIState = RCC_HSI_ON;
91 (+++) RCC_OscInitStructure.PLL... (optional if used for system clock)
92 (+++) HAL_RCC_OscConfig(&RCC_OscInitStructure);
93
94 (++) ADC clock source and clock prescaler are configured at ADC level with
95 parameter "ClockPrescaler" using function HAL_ADC_Init().
96
97 (#) ADC pins configuration
98 (++) Enable the clock for the ADC GPIOs
99 using macro __HAL_RCC_GPIOx_CLK_ENABLE()
100 (++) Configure these ADC pins in analog mode
101 using function HAL_GPIO_Init()
102
103 (#) Optionally, in case of usage of ADC with interruptions:
104 (++) Configure the NVIC for ADC
105 using function HAL_NVIC_EnableIRQ(ADCx_IRQn)
106 (++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
107 into the function of corresponding ADC interruption vector
108 ADCx_IRQHandler().
109
110 (#) Optionally, in case of usage of DMA:
111 (++) Configure the DMA (DMA channel, mode normal or circular, ...)
112 using function HAL_DMA_Init().
113 (++) Configure the NVIC for DMA
114 using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
115 (++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
116 into the function of corresponding DMA interruption vector
117 DMAx_Channelx_IRQHandler().
118
119 *** Configuration of ADC, group regular, channels parameters ***
120 ================================================================
121 [..]
122
123 (#) Configure the ADC parameters (resolution, data alignment, ...)
124 and regular group parameters (conversion trigger, sequencer, ...)
125 using function HAL_ADC_Init().
126
127 (#) Configure the channels for regular group parameters (channel number,
128 channel rank into sequencer, ..., into regular group)
129 using function HAL_ADC_ConfigChannel().
130
131 (#) Optionally, configure the analog watchdog parameters (channels
132 monitored, thresholds, ...)
133 using function HAL_ADC_AnalogWDGConfig().
134
135
136 (#) When device is in mode low-power (low-power run, low-power sleep or stop mode),
137 function "HAL_ADCEx_EnableVREFINT()" must be called before function HAL_ADC_Init().
138 In case of internal temperature sensor to be measured:
139 function "HAL_ADCEx_EnableVREFINTTempSensor()" must be called similarilly
140
141 *** Execution of ADC conversions ***
142 ====================================
143 [..]
144
145 (#) Optionally, perform an automatic ADC calibration to improve the
146 conversion accuracy
147 using function HAL_ADCEx_Calibration_Start().
148
149 (#) ADC driver can be used among three modes: polling, interruption,
150 transfer by DMA.
151
152 (++) ADC conversion by polling:
153 (+++) Activate the ADC peripheral and start conversions
154 using function HAL_ADC_Start()
155 (+++) Wait for ADC conversion completion
156 using function HAL_ADC_PollForConversion()
157 (+++) Retrieve conversion results
158 using function HAL_ADC_GetValue()
159 (+++) Stop conversion and disable the ADC peripheral
160 using function HAL_ADC_Stop()
161
162 (++) ADC conversion by interruption:
163 (+++) Activate the ADC peripheral and start conversions
164 using function HAL_ADC_Start_IT()
165 (+++) Wait for ADC conversion completion by call of function
166 HAL_ADC_ConvCpltCallback()
167 (this function must be implemented in user program)
168 (+++) Retrieve conversion results
169 using function HAL_ADC_GetValue()
170 (+++) Stop conversion and disable the ADC peripheral
171 using function HAL_ADC_Stop_IT()
172
173 (++) ADC conversion with transfer by DMA:
174 (+++) Activate the ADC peripheral and start conversions
175 using function HAL_ADC_Start_DMA()
176 (+++) Wait for ADC conversion completion by call of function
177 HAL_ADC_ConvCpltCallback() or HAL_ADC_ConvHalfCpltCallback()
178 (these functions must be implemented in user program)
179 (+++) Conversion results are automatically transferred by DMA into
180 destination variable address.
181 (+++) Stop conversion and disable the ADC peripheral
182 using function HAL_ADC_Stop_DMA()
183
184 [..]
185
186 (@) Callback functions must be implemented in user program:
187 (+@) HAL_ADC_ErrorCallback()
188 (+@) HAL_ADC_LevelOutOfWindowCallback() (callback of analog watchdog)
189 (+@) HAL_ADC_ConvCpltCallback()
190 (+@) HAL_ADC_ConvHalfCpltCallback
191
192 *** Deinitialization of ADC ***
193 ============================================================
194 [..]
195
196 (#) Disable the ADC interface
197 (++) ADC clock can be hard reset and disabled at RCC top level.
198 (++) Hard reset of ADC peripherals
199 using macro __ADCx_FORCE_RESET(), __ADCx_RELEASE_RESET().
200 (++) ADC clock disable
201 using the equivalent macro/functions as configuration step.
202 (+++) Example:
203 Into HAL_ADC_MspDeInit() (recommended code location) or with
204 other device clock parameters configuration:
205 (+++) RCC_OscInitStructure.OscillatorType = RCC_OSCILLATORTYPE_HSI;
206 (+++) RCC_OscInitStructure.HSIState = RCC_HSI_OFF; (if not used for system clock)
207 (+++) HAL_RCC_OscConfig(&RCC_OscInitStructure);
208
209 (#) ADC pins configuration
210 (++) Disable the clock for the ADC GPIOs
211 using macro __HAL_RCC_GPIOx_CLK_DISABLE()
212
213 (#) Optionally, in case of usage of ADC with interruptions:
214 (++) Disable the NVIC for ADC
215 using function HAL_NVIC_EnableIRQ(ADCx_IRQn)
216
217 (#) Optionally, in case of usage of DMA:
218 (++) Deinitialize the DMA
219 using function HAL_DMA_Init().
220 (++) Disable the NVIC for DMA
221 using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
222
223 [..]
224
225 @endverbatim
226 ******************************************************************************
227 * @attention
228 *
229 * <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
230 *
231 * Redistribution and use in source and binary forms, with or without modification,
232 * are permitted provided that the following conditions are met:
233 * 1. Redistributions of source code must retain the above copyright notice,
234 * this list of conditions and the following disclaimer.
235 * 2. Redistributions in binary form must reproduce the above copyright notice,
236 * this list of conditions and the following disclaimer in the documentation
237 * and/or other materials provided with the distribution.
238 * 3. Neither the name of STMicroelectronics nor the names of its contributors
239 * may be used to endorse or promote products derived from this software
240 * without specific prior written permission.
241 *
242 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
243 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
244 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
245 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
246 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
247 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
248 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
249 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
250 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
251 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
252 *
253 ******************************************************************************
254 */
255
256 /* Includes ------------------------------------------------------------------*/
257 #include "stm32l0xx_hal.h"
258
259 /** @addtogroup STM32L0xx_HAL_Driver
260 * @{
261 */
262
263 /** @defgroup ADC ADC
264 * @brief ADC HAL module driver
265 * @{
266 */
267
268 #ifdef HAL_ADC_MODULE_ENABLED
269
270 /* Private typedef -----------------------------------------------------------*/
271 /* Private define ------------------------------------------------------------*/
272
273 /** @defgroup ADC_Private_Constants ADC Private Constants
274 * @{
275 */
276
277 /* Delay for ADC stabilization time. */
278 /* Maximum delay is 1us (refer to device datasheet, parameter tSTART). */
279 /* Unit: us */
280 #define ADC_STAB_DELAY_US ((uint32_t) 1U)
281
282 /* Delay for temperature sensor stabilization time. */
283 /* Maximum delay is 10us (refer to device datasheet, parameter tSTART). */
284 /* Unit: us */
285 #define ADC_TEMPSENSOR_DELAY_US ((uint32_t) 10U)
286 /**
287 * @}
288 */
289
290 /* Private macro -------------------------------------------------------------*/
291 /* Private variables ---------------------------------------------------------*/
292 /* Private function prototypes -----------------------------------------------*/
293 /** @defgroup ADC_Private_Functions ADC Private Functions
294 * @{
295 */
296 static HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef* hadc);
297 static HAL_StatusTypeDef ADC_Disable(ADC_HandleTypeDef* hadc);
298 static HAL_StatusTypeDef ADC_ConversionStop(ADC_HandleTypeDef* hadc);
299 static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma);
300 static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma);
301 static void ADC_DMAError(DMA_HandleTypeDef *hdma);
302 static void ADC_DelayMicroSecond(uint32_t microSecond);
303 /**
304 * @}
305 */
306
307 /* Exported functions ---------------------------------------------------------*/
308
309 /** @defgroup ADC_Exported_Functions ADC Exported Functions
310 * @{
311 */
312
313 /** @defgroup ADC_Exported_Functions_Group1 Initialization and de-initialization functions
314 * @brief ADC Initialization and Configuration functions
315 *
316 @verbatim
317 ===============================================================================
318 ##### Initialization and de-initialization functions #####
319 ===============================================================================
320 [..] This section provides functions allowing to:
321 (+) Initialize and configure the ADC.
322 (+) De-initialize the ADC.
323 @endverbatim
324 * @{
325 */
326
327 /**
328 * @brief Initialize the ADC peripheral and regular group according to
329 * parameters specified in structure "ADC_InitTypeDef".
330 * @note As prerequisite, ADC clock must be configured at RCC top level
331 * depending on possible clock sources: APB clock of HSI clock.
332 * See commented example code below that can be copied and uncommented
333 * into HAL_ADC_MspInit().
334 * @note Possibility to update parameters on the fly:
335 * This function initializes the ADC MSP (HAL_ADC_MspInit()) only when
336 * coming from ADC state reset. Following calls to this function can
337 * be used to reconfigure some parameters of ADC_InitTypeDef
338 * structure on the fly, without modifying MSP configuration. If ADC
339 * MSP has to be modified again, HAL_ADC_DeInit() must be called
340 * before HAL_ADC_Init().
341 * The setting of these parameters is conditioned to ADC state.
342 * For parameters constraints, see comments of structure
343 * "ADC_InitTypeDef".
344 * @note This function configures the ADC within 2 scopes: scope of entire
345 * ADC and scope of regular group. For parameters details, see comments
346 * of structure "ADC_InitTypeDef".
347 * @note When device is in mode low-power (low-power run, low-power sleep or stop mode),
348 * function "HAL_ADCEx_EnableVREFINT()" must be called before function HAL_ADC_Init()
349 * (in case of previous ADC operations: function HAL_ADC_DeInit() must be called first).
350 * In case of internal temperature sensor to be measured:
351 * function "HAL_ADCEx_EnableVREFINTTempSensor()" must be called similarilly.
352 * @param hadc: ADC handle
353 * @retval HAL status
354 */
HAL_ADC_Init(ADC_HandleTypeDef * hadc)355 HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc)
356 {
357
358 /* Check ADC handle */
359 if(hadc == NULL)
360 {
361 return HAL_ERROR;
362 }
363
364 /* Check the parameters */
365 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
366 assert_param(IS_ADC_CLOCKPRESCALER(hadc->Init.ClockPrescaler));
367 assert_param(IS_ADC_RESOLUTION(hadc->Init.Resolution));
368 assert_param(IS_ADC_DATA_ALIGN(hadc->Init.DataAlign));
369 assert_param(IS_ADC_SCAN_MODE(hadc->Init.ScanConvMode));
370 assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
371 assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DiscontinuousConvMode));
372 assert_param(IS_ADC_EXTTRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
373 assert_param(IS_ADC_EXTTRIG(hadc->Init.ExternalTrigConv));
374 assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests));
375 assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection));
376 assert_param(IS_ADC_OVERRUN(hadc->Init.Overrun));
377 assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerAutoWait));
378 assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerFrequencyMode));
379 assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerAutoPowerOff));
380 assert_param(IS_ADC_SAMPLE_TIME(hadc->Init.SamplingTime));
381 assert_param(IS_FUNCTIONAL_STATE(hadc->Init.OversamplingMode));
382
383 /* As prerequisite, into HAL_ADC_MspInit(), ADC clock must be configured */
384 /* at RCC top level depending on both possible clock sources: */
385 /* APB clock or HSI clock. */
386 /* Refer to header of this file for more details on clock enabling procedure*/
387
388 /* Actions performed only if ADC is coming from state reset: */
389 /* - Initialization of ADC MSP */
390 /* - ADC voltage regulator enable */
391 if(hadc->State == HAL_ADC_STATE_RESET)
392 {
393 /* Initialize ADC error code */
394 ADC_CLEAR_ERRORCODE(hadc);
395
396 /* Allocate lock resource and initialize it */
397 hadc->Lock = HAL_UNLOCKED;
398
399 /* Init the low level hardware */
400 HAL_ADC_MspInit(hadc);
401 }
402
403 /* Configuration of ADC parameters if previous preliminary actions are */
404 /* correctly completed. */
405 /* and if there is no conversion on going on regular group (ADC can be */
406 /* enabled anyway, in case of call of this function to update a parameter */
407 /* on the fly). */
408 if (HAL_IS_BIT_SET(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL) ||
409 (ADC_IS_CONVERSION_ONGOING_REGULAR(hadc) != RESET) )
410 {
411 /* Update ADC state machine to error */
412 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
413
414 /* Process unlocked */
415 __HAL_UNLOCK(hadc);
416 return HAL_ERROR;
417 }
418
419 /* Set ADC state */
420 ADC_STATE_CLR_SET(hadc->State,
421 HAL_ADC_STATE_REG_BUSY,
422 HAL_ADC_STATE_BUSY_INTERNAL);
423
424 /* Parameters update conditioned to ADC state: */
425 /* Parameters that can be updated only when ADC is disabled: */
426 /* - ADC clock mode */
427 /* - ADC clock prescaler */
428 /* - ADC Resolution */
429 if (ADC_IS_ENABLE(hadc) == RESET)
430 {
431 /* Some parameters of this register are not reset, since they are set */
432 /* by other functions and must be kept in case of usage of this */
433 /* function on the fly (update of a parameter of ADC_InitTypeDef */
434 /* without needing to reconfigure all other ADC groups/channels */
435 /* parameters): */
436 /* - internal measurement paths: Vbat, temperature sensor, Vref */
437 /* (set into HAL_ADC_ConfigChannel() ) */
438
439 /* Configuration of ADC clock: clock source PCLK or asynchronous with
440 selectable prescaler */
441 __HAL_ADC_CLOCK_PRESCALER(hadc);
442
443 /* Configuration of ADC: */
444 /* - Resolution */
445 hadc->Instance->CFGR1 &= ~( ADC_CFGR1_RES);
446 hadc->Instance->CFGR1 |= hadc->Init.Resolution;
447 }
448
449 /* Set the Low Frequency mode */
450 ADC->CCR &= (uint32_t)~ADC_CCR_LFMEN;
451 ADC->CCR |=__HAL_ADC_CCR_LOWFREQUENCY(hadc->Init.LowPowerFrequencyMode);
452
453 /* Enable voltage regulator (if disabled at this step) */
454 if (HAL_IS_BIT_CLR(hadc->Instance->CR, ADC_CR_ADVREGEN))
455 {
456 /* Set ADVREGEN bit */
457 hadc->Instance->CR |= ADC_CR_ADVREGEN;
458 }
459
460 /* Configuration of ADC: */
461 /* - Resolution */
462 /* - Data alignment */
463 /* - Scan direction */
464 /* - External trigger to start conversion */
465 /* - External trigger polarity */
466 /* - Continuous conversion mode */
467 /* - DMA continuous request */
468 /* - Overrun */
469 /* - AutoDelay feature */
470 /* - Discontinuous mode */
471 hadc->Instance->CFGR1 &= ~(ADC_CFGR1_ALIGN |
472 ADC_CFGR1_SCANDIR |
473 ADC_CFGR1_EXTSEL |
474 ADC_CFGR1_EXTEN |
475 ADC_CFGR1_CONT |
476 ADC_CFGR1_DMACFG |
477 ADC_CFGR1_OVRMOD |
478 ADC_CFGR1_AUTDLY |
479 ADC_CFGR1_AUTOFF |
480 ADC_CFGR1_DISCEN );
481
482 hadc->Instance->CFGR1 |= (hadc->Init.DataAlign |
483 ADC_SCANDIR(hadc->Init.ScanConvMode) |
484 ADC_CONTINUOUS(hadc->Init.ContinuousConvMode) |
485 ADC_DMACONTREQ(hadc->Init.DMAContinuousRequests) |
486 hadc->Init.Overrun |
487 __HAL_ADC_CFGR1_AutoDelay(hadc->Init.LowPowerAutoWait) |
488 __HAL_ADC_CFGR1_AUTOFF(hadc->Init.LowPowerAutoPowerOff));
489
490 /* Enable external trigger if trigger selection is different of software */
491 /* start. */
492 /* Note: This configuration keeps the hardware feature of parameter */
493 /* ExternalTrigConvEdge "trigger edge none" equivalent to */
494 /* software start. */
495 if (hadc->Init.ExternalTrigConv != ADC_SOFTWARE_START)
496 {
497 hadc->Instance->CFGR1 |= hadc->Init.ExternalTrigConv |
498 hadc->Init.ExternalTrigConvEdge;
499 }
500
501 /* Enable discontinuous mode only if continuous mode is disabled */
502 if (hadc->Init.DiscontinuousConvMode == ENABLE)
503 {
504 if (hadc->Init.ContinuousConvMode == DISABLE)
505 {
506 /* Enable the selected ADC group regular discontinuous mode */
507 hadc->Instance->CFGR1 |= (ADC_CFGR1_DISCEN);
508 }
509 else
510 {
511 /* ADC regular group discontinuous was intended to be enabled, */
512 /* but ADC regular group modes continuous and sequencer discontinuous */
513 /* cannot be enabled simultaneously. */
514
515 /* Update ADC state machine to error */
516 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
517
518 /* Set ADC error code to ADC IP internal error */
519 SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
520 }
521 }
522
523 if (hadc->Init.OversamplingMode == ENABLE)
524 {
525 assert_param(IS_ADC_OVERSAMPLING_RATIO(hadc->Init.Oversample.Ratio));
526 assert_param(IS_ADC_RIGHT_BIT_SHIFT(hadc->Init.Oversample.RightBitShift));
527 assert_param(IS_ADC_TRIGGERED_OVERSAMPLING_MODE(hadc->Init.Oversample.TriggeredMode));
528
529 /* Configuration of Oversampler: */
530 /* - Oversampling Ratio */
531 /* - Right bit shift */
532 /* - Triggered mode */
533
534 hadc->Instance->CFGR2 &= ~( ADC_CFGR2_OVSR |
535 ADC_CFGR2_OVSS |
536 ADC_CFGR2_TOVS );
537
538 hadc->Instance->CFGR2 |= ( hadc->Init.Oversample.Ratio |
539 hadc->Init.Oversample.RightBitShift |
540 hadc->Init.Oversample.TriggeredMode );
541
542 /* Enable OverSampling mode */
543 hadc->Instance->CFGR2 |= ADC_CFGR2_OVSE;
544 }
545 else
546 {
547 if(HAL_IS_BIT_SET(hadc->Instance->CFGR2, ADC_CFGR2_OVSE))
548 {
549 /* Disable OverSampling mode if needed */
550 hadc->Instance->CFGR2 &= ~ADC_CFGR2_OVSE;
551 }
552 }
553
554 /* Clear the old sampling time */
555 hadc->Instance->SMPR &= (uint32_t)(~ADC_SMPR_SMPR);
556
557 /* Set the new sample time */
558 hadc->Instance->SMPR |= hadc->Init.SamplingTime;
559
560 /* Clear ADC error code */
561 ADC_CLEAR_ERRORCODE(hadc);
562
563 /* Set the ADC state */
564 ADC_STATE_CLR_SET(hadc->State,
565 HAL_ADC_STATE_BUSY_INTERNAL,
566 HAL_ADC_STATE_READY);
567
568
569 /* Return function status */
570 return HAL_OK;
571 }
572
573 /**
574 * @brief Deinitialize the ADC peripheral registers to their default reset
575 * values, with deinitialization of the ADC MSP.
576 * @note For devices with several ADCs: reset of ADC common registers is done
577 * only if all ADCs sharing the same common group are disabled.
578 * If this is not the case, reset of these common parameters reset is
579 * bypassed without error reporting: it can be the intended behavior in
580 * case of reset of a single ADC while the other ADCs sharing the same
581 * common group is still running.
582 * @param hadc: ADC handle
583 * @retval HAL status
584 */
HAL_ADC_DeInit(ADC_HandleTypeDef * hadc)585 HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef* hadc)
586 {
587 HAL_StatusTypeDef tmp_hal_status = HAL_OK;
588
589 /* Check ADC handle */
590 if(hadc == NULL)
591 {
592 return HAL_ERROR;
593 }
594
595 /* Check the parameters */
596 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
597
598 /* Set ADC state */
599 SET_BIT(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL);
600
601 /* Stop potential conversion on going, on regular group */
602 tmp_hal_status = ADC_ConversionStop(hadc);
603
604 /* Disable ADC peripheral if conversions are effectively stopped */
605 if (tmp_hal_status == HAL_OK)
606 {
607 /* Disable the ADC peripheral */
608 tmp_hal_status = ADC_Disable(hadc);
609
610 /* Check if ADC is effectively disabled */
611 if (tmp_hal_status != HAL_ERROR)
612 {
613 /* Change ADC state */
614 hadc->State = HAL_ADC_STATE_READY;
615 }
616 }
617
618
619 /* Configuration of ADC parameters if previous preliminary actions are */
620 /* correctly completed. */
621 if (tmp_hal_status != HAL_ERROR)
622 {
623
624 /* ========== Reset ADC registers ========== */
625 /* Reset register IER */
626 __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_AWD | ADC_IT_OVR | ADC_IT_EOCAL | ADC_IT_EOS | \
627 ADC_IT_EOC | ADC_IT_RDY | ADC_IT_EOSMP ));
628
629
630 /* Reset register ISR */
631 __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD | ADC_FLAG_EOCAL | ADC_FLAG_OVR | ADC_FLAG_EOS | \
632 ADC_FLAG_EOC | ADC_FLAG_EOSMP | ADC_FLAG_RDY));
633
634
635 /* Reset register CR */
636 /* Disable voltage regulator */
637 /* Note: Regulator disable useful for power saving */
638 /* Reset ADVREGEN bit */
639 hadc->Instance->CR &= ~ADC_CR_ADVREGEN;
640
641 /* Bits ADC_CR_ADSTP, ADC_CR_ADSTART are in access mode "read-set": no direct reset applicable */
642 /* No action */
643
644 /* Reset register CFGR1 */
645 hadc->Instance->CFGR1 &= ~(ADC_CFGR1_AWDCH | ADC_CFGR1_AWDEN | ADC_CFGR1_AWDSGL | \
646 ADC_CFGR1_DISCEN | ADC_CFGR1_AUTOFF | ADC_CFGR1_AUTDLY | \
647 ADC_CFGR1_CONT | ADC_CFGR1_OVRMOD | ADC_CFGR1_EXTEN | \
648 ADC_CFGR1_EXTSEL | ADC_CFGR1_ALIGN | ADC_CFGR1_RES | \
649 ADC_CFGR1_SCANDIR| ADC_CFGR1_DMACFG | ADC_CFGR1_DMAEN);
650
651 /* Reset register CFGR2 */
652 hadc->Instance->CFGR2 &= ~(ADC_CFGR2_TOVS | ADC_CFGR2_OVSS | ADC_CFGR2_OVSR | \
653 ADC_CFGR2_OVSE | ADC_CFGR2_CKMODE );
654
655
656 /* Reset register SMPR */
657 hadc->Instance->SMPR &= ~(ADC_SMPR_SMPR);
658
659 /* Reset register TR */
660 hadc->Instance->TR &= ~(ADC_TR_LT | ADC_TR_HT);
661
662 /* Reset register CALFACT */
663 hadc->Instance->CALFACT &= ~(ADC_CALFACT_CALFACT);
664
665
666
667
668
669 /* Reset register DR */
670 /* bits in access mode read only, no direct reset applicable*/
671
672 /* Reset register CALFACT */
673 hadc->Instance->CALFACT &= ~(ADC_CALFACT_CALFACT);
674
675 /* ========== Hard reset ADC peripheral ========== */
676 /* Performs a global reset of the entire ADC peripheral: ADC state is */
677 /* forced to a similar state after device power-on. */
678 /* If needed, copy-paste and uncomment the following reset code into */
679 /* function "void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc)": */
680 /* */
681 /* __HAL_RCC_ADC1_FORCE_RESET() */
682 /* __HAL_RCC_ADC1_RELEASE_RESET() */
683
684 /* DeInit the low level hardware */
685 HAL_ADC_MspDeInit(hadc);
686
687 /* Set ADC error code to none */
688 ADC_CLEAR_ERRORCODE(hadc);
689
690 /* Set ADC state */
691 hadc->State = HAL_ADC_STATE_RESET;
692 }
693
694 /* Process unlocked */
695 __HAL_UNLOCK(hadc);
696
697 /* Return function status */
698 return tmp_hal_status;
699 }
700
701 /**
702 * @brief Initialize the ADC MSP.
703 * @param hadc: ADC handle
704 * @retval None
705 */
HAL_ADC_MspInit(ADC_HandleTypeDef * hadc)706 __weak void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc)
707 {
708 /* Prevent unused argument(s) compilation warning */
709 UNUSED(hadc);
710
711 /* NOTE : This function should not be modified. When the callback is needed,
712 function HAL_ADC_MspInit must be implemented in the user file.
713 */
714 }
715
716 /**
717 * @brief DeInitialize the ADC MSP.
718 * @param hadc: ADC handle
719 * @retval None
720 */
HAL_ADC_MspDeInit(ADC_HandleTypeDef * hadc)721 __weak void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc)
722 {
723 /* Prevent unused argument(s) compilation warning */
724 UNUSED(hadc);
725
726 /* NOTE : This function should not be modified. When the callback is needed,
727 function HAL_ADC_MspDeInit must be implemented in the user file.
728 */
729 }
730
731 /**
732 * @}
733 */
734
735 /** @defgroup ADC_Exported_Functions_Group2 ADC Input and Output operation functions
736 * @brief ADC IO operation functions
737 *
738 @verbatim
739 ===============================================================================
740 ##### IO operation functions #####
741 ===============================================================================
742 [..] This section provides functions allowing to:
743 (+) Start conversion of regular group.
744 (+) Stop conversion of regular group.
745 (+) Poll for conversion complete on regular group.
746 (+) Poll for conversion event.
747 (+) Get result of regular channel conversion.
748 (+) Start conversion of regular group and enable interruptions.
749 (+) Stop conversion of regular group and disable interruptions.
750 (+) Handle ADC interrupt request
751 (+) Start conversion of regular group and enable DMA transfer.
752 (+) Stop conversion of regular group and disable ADC DMA transfer.
753 @endverbatim
754 * @{
755 */
756
757 /**
758 * @brief Enable ADC, start conversion of regular group.
759 * @note Interruptions enabled in this function: None.
760 * @param hadc: ADC handle
761 * @retval HAL status
762 */
HAL_ADC_Start(ADC_HandleTypeDef * hadc)763 HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc)
764 {
765 HAL_StatusTypeDef tmp_hal_status = HAL_OK;
766
767 /* Check the parameters */
768 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
769
770 /* Perform ADC enable and conversion start if no conversion is on going */
771 if (ADC_IS_CONVERSION_ONGOING_REGULAR(hadc) == RESET)
772 {
773 /* Process locked */
774 __HAL_LOCK(hadc);
775
776 /* Enable the ADC peripheral */
777 /* If low power mode AutoPowerOff is enabled, power-on/off phases are */
778 /* performed automatically by hardware. */
779 if (hadc->Init.LowPowerAutoPowerOff != ENABLE)
780 {
781 tmp_hal_status = ADC_Enable(hadc);
782 }
783
784 /* Start conversion if ADC is effectively enabled */
785 if (tmp_hal_status == HAL_OK)
786 {
787 /* Set ADC state */
788 /* - Clear state bitfield related to regular group conversion results */
789 /* - Set state bitfield related to regular operation */
790 ADC_STATE_CLR_SET(hadc->State,
791 HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
792 HAL_ADC_STATE_REG_BUSY);
793
794 /* Reset ADC all error code fields */
795 ADC_CLEAR_ERRORCODE(hadc);
796
797 /* Process unlocked */
798 /* Unlock before starting ADC conversions: in case of potential */
799 /* interruption, to let the process to ADC IRQ Handler. */
800 __HAL_UNLOCK(hadc);
801
802 /* Clear regular group conversion flag and overrun flag */
803 /* (To ensure of no unknown state from potential previous ADC */
804 /* operations) */
805 __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
806
807 /* Enable conversion of regular group. */
808 /* If software start has been selected, conversion starts immediately. */
809 /* If external trigger has been selected, conversion will start at next */
810 /* trigger event. */
811 hadc->Instance->CR |= ADC_CR_ADSTART;
812 }
813 }
814 else
815 {
816 tmp_hal_status = HAL_BUSY;
817 }
818
819 /* Return function status */
820 return tmp_hal_status;
821 }
822
823 /**
824 * @brief Stop ADC conversion of regular group (and injected channels in
825 * case of auto_injection mode), disable ADC peripheral.
826 * @param hadc: ADC handle
827 * @retval HAL status.
828 */
HAL_ADC_Stop(ADC_HandleTypeDef * hadc)829 HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc)
830 {
831 HAL_StatusTypeDef tmp_hal_status = HAL_OK;
832
833 /* Check the parameters */
834 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
835
836 /* Process locked */
837 __HAL_LOCK(hadc);
838
839 /* 1. Stop potential conversion on going, on ADC group regular */
840 tmp_hal_status = ADC_ConversionStop(hadc);
841
842 /* Disable ADC peripheral if conversions are effectively stopped */
843 if (tmp_hal_status == HAL_OK)
844 {
845 /* 2. Disable the ADC peripheral */
846 tmp_hal_status = ADC_Disable(hadc);
847
848 /* Check if ADC is effectively disabled */
849 if (tmp_hal_status == HAL_OK)
850 {
851 /* Set ADC state */
852 ADC_STATE_CLR_SET(hadc->State,
853 HAL_ADC_STATE_REG_BUSY,
854 HAL_ADC_STATE_READY);
855 }
856 }
857
858 /* Process unlocked */
859 __HAL_UNLOCK(hadc);
860
861 /* Return function status */
862 return tmp_hal_status;
863 }
864
865 /**
866 * @brief Wait for regular group conversion to be completed.
867 * @note ADC conversion flags EOS (end of sequence) and EOC (end of
868 * conversion) are cleared by this function, with an exception:
869 * if low power feature "LowPowerAutoWait" is enabled, flags are
870 * not cleared to not interfere with this feature until data register
871 * is read using function HAL_ADC_GetValue().
872 * @note This function cannot be used in a particular setup: ADC configured
873 * in DMA mode and polling for end of each conversion (ADC init
874 * parameter "EOCSelection" set to ADC_EOC_SINGLE_CONV).
875 * In this case, DMA resets the flag EOC and polling cannot be
876 * performed on each conversion. Nevertheless, polling can still
877 * be performed on the complete sequence (ADC init
878 * parameter "EOCSelection" set to ADC_EOC_SEQ_CONV).
879 * @param hadc: ADC handle
880 * @param Timeout: Timeout value in millisecond.
881 * @retval HAL status
882 */
HAL_ADC_PollForConversion(ADC_HandleTypeDef * hadc,uint32_t Timeout)883 HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout)
884 {
885 uint32_t tickstart = 0;
886 uint32_t tmp_Flag_EOC = 0x00;
887
888 /* Check the parameters */
889 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
890
891 /* If end of conversion selected to end of sequence conversions */
892 if (hadc->Init.EOCSelection == ADC_EOC_SEQ_CONV)
893 {
894 tmp_Flag_EOC = ADC_FLAG_EOS;
895 }
896 /* If end of conversion selected to end of unitary conversion */
897 else /* ADC_EOC_SINGLE_CONV */
898 {
899 /* Verification that ADC configuration is compliant with polling for */
900 /* each conversion: */
901 /* Particular case is ADC configured in DMA mode and ADC sequencer with */
902 /* several ranks and polling for end of each conversion. */
903 /* For code simplicity sake, this particular case is generalized to */
904 /* ADC configured in DMA mode and and polling for end of each conversion. */
905 if (HAL_IS_BIT_SET(hadc->Instance->CFGR1, ADC_CFGR1_DMAEN))
906 {
907 /* Update ADC state machine to error */
908 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
909
910 /* Process unlocked */
911 __HAL_UNLOCK(hadc);
912
913 return HAL_ERROR;
914 }
915 else
916 {
917 tmp_Flag_EOC = (ADC_FLAG_EOC | ADC_FLAG_EOS);
918 }
919 }
920
921 /* Get tick count */
922 tickstart = HAL_GetTick();
923
924 /* Wait until End of unitary conversion or sequence conversions flag is raised */
925 while(HAL_IS_BIT_CLR(hadc->Instance->ISR, tmp_Flag_EOC))
926 {
927 /* Check if timeout is disabled (set to infinite wait) */
928 if(Timeout != HAL_MAX_DELAY)
929 {
930 if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout))
931 {
932 /* Update ADC state machine to timeout */
933 SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
934
935 /* Process unlocked */
936 __HAL_UNLOCK(hadc);
937
938 return HAL_TIMEOUT;
939 }
940 }
941 }
942
943 /* Update ADC state machine */
944 SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
945
946 /* Determine whether any further conversion upcoming on group regular */
947 /* by external trigger, continuous mode or scan sequence on going. */
948 if(ADC_IS_SOFTWARE_START_REGULAR(hadc) &&
949 (hadc->Init.ContinuousConvMode == DISABLE) )
950 {
951 /* If End of Sequence is reached, disable interrupts */
952 if( __HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS) )
953 {
954 /* Allowed to modify bits ADC_IT_EOC/ADC_IT_EOS only if bit */
955 /* ADSTART==0 (no conversion on going) */
956 if (ADC_IS_CONVERSION_ONGOING_REGULAR(hadc) == RESET)
957 {
958 /* Disable ADC end of single conversion interrupt on group regular */
959 /* Note: Overrun interrupt was enabled with EOC interrupt in */
960 /* HAL_Start_IT(), but is not disabled here because can be used */
961 /* by overrun IRQ process below. */
962 __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_EOS);
963
964 /* Set ADC state */
965 ADC_STATE_CLR_SET(hadc->State,
966 HAL_ADC_STATE_REG_BUSY,
967 HAL_ADC_STATE_READY);
968 }
969 else
970 {
971 /* Change ADC state to error state */
972 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
973
974 /* Set ADC error code to ADC IP internal error */
975 SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
976 }
977 }
978 }
979
980 /* Clear end of conversion flag of regular group if low power feature */
981 /* "LowPowerAutoWait " is disabled, to not interfere with this feature */
982 /* until data register is read using function HAL_ADC_GetValue(). */
983 if (hadc->Init.LowPowerAutoWait == DISABLE)
984 {
985 /* Clear regular group conversion flag */
986 __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS));
987 }
988
989 /* Return function status */
990 return HAL_OK;
991 }
992
993 /**
994 * @brief Poll for ADC event.
995 * @param hadc: ADC handle
996 * @param EventType: the ADC event type.
997 * This parameter can be one of the following values:
998 * @arg ADC_AWD_EVENT: ADC Analog watchdog event
999 * @arg ADC_OVR_EVENT: ADC Overrun event
1000 * @param Timeout: Timeout value in millisecond.
1001 * @note The relevant flag is cleared if found to be set, except for ADC_FLAG_OVR.
1002 * Indeed, the latter is reset only if hadc->Init.Overrun field is set
1003 * to ADC_OVR_DATA_OVERWRITTEN. Otherwise, data register may be potentially overwritten
1004 * by a new converted data as soon as OVR is cleared.
1005 * To reset OVR flag once the preserved data is retrieved, the user can resort
1006 * to macro __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1007 * @retval HAL status
1008 */
HAL_ADC_PollForEvent(ADC_HandleTypeDef * hadc,uint32_t EventType,uint32_t Timeout)1009 HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout)
1010 {
1011 uint32_t tickstart = 0U;
1012
1013 /* Check the parameters */
1014 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1015 assert_param(IS_ADC_EVENT_TYPE(EventType));
1016
1017 /* Get tick count */
1018 tickstart = HAL_GetTick();
1019
1020 /* Check selected event flag */
1021 while(__HAL_ADC_GET_FLAG(hadc, EventType) == RESET)
1022 {
1023 /* Check if timeout is disabled (set to infinite wait) */
1024 if(Timeout != HAL_MAX_DELAY)
1025 {
1026 if((Timeout == 0U) ||((HAL_GetTick() - tickstart ) > Timeout))
1027 {
1028 /* Update ADC state machine to timeout */
1029 SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
1030
1031 /* Process unlocked */
1032 __HAL_UNLOCK(hadc);
1033
1034 return HAL_TIMEOUT;
1035 }
1036 }
1037 }
1038
1039 switch(EventType)
1040 {
1041 /* Analog watchdog (level out of window) event */
1042 case ADC_AWD_EVENT:
1043 /* Set ADC state */
1044 SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
1045
1046 /* Clear ADC analog watchdog flag */
1047 __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD);
1048 break;
1049
1050 /* Overrun event */
1051 default: /* Case ADC_OVR_EVENT */
1052 /* If overrun is set to overwrite previous data, overrun event is not */
1053 /* considered as an error. */
1054 /* (cf ref manual "Managing conversions without using the DMA and without */
1055 /* overrun ") */
1056 if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
1057 {
1058 /* Set ADC state */
1059 SET_BIT(hadc->State, HAL_ADC_STATE_REG_OVR);
1060
1061 /* Set ADC error code to overrun */
1062 SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_OVR);
1063 }
1064
1065 /* Clear ADC Overrun flag */
1066 __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1067 break;
1068 }
1069
1070 /* Return function status */
1071 return HAL_OK;
1072 }
1073
1074 /**
1075 * @brief Enable ADC, start conversion of regular group with interruption.
1076 * @note Interruptions enabled in this function according to initialization
1077 * setting : EOC (end of conversion), EOS (end of sequence),
1078 * OVR overrun.
1079 * Each of these interruptions has its dedicated callback function.
1080 * @note To guarantee a proper reset of all interruptions once all the needed
1081 * conversions are obtained, HAL_ADC_Stop_IT() must be called to ensure
1082 * a correct stop of the IT-based conversions.
1083 * @note By default, HAL_ADC_Start_IT() doesn't enable the End Of Sampling
1084 * interruption. If required (e.g. in case of oversampling with trigger
1085 * mode), the user must:
1086 * 1. first clear the EOSMP flag if set with macro __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP)
1087 * 2. then enable the EOSMP interrupt with macro __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOSMP)
1088 * before calling HAL_ADC_Start_IT().
1089 * @param hadc: ADC handle
1090 * @retval HAL status
1091 */
HAL_ADC_Start_IT(ADC_HandleTypeDef * hadc)1092 HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc)
1093 {
1094 HAL_StatusTypeDef tmp_hal_status = HAL_OK;
1095
1096 /* Check the parameters */
1097 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1098
1099 /* Perform ADC enable and conversion start if no conversion is on going */
1100 if (ADC_IS_CONVERSION_ONGOING_REGULAR(hadc) == RESET)
1101 {
1102 /* Process locked */
1103 __HAL_LOCK(hadc);
1104
1105 /* Enable the ADC peripheral */
1106 /* If low power mode AutoPowerOff is enabled, power-on/off phases are */
1107 /* performed automatically by hardware. */
1108 if (hadc->Init.LowPowerAutoPowerOff != ENABLE)
1109 {
1110 tmp_hal_status = ADC_Enable(hadc);
1111 }
1112
1113 /* Start conversion if ADC is effectively enabled */
1114 if (tmp_hal_status == HAL_OK)
1115 {
1116 /* Set ADC state */
1117 /* - Clear state bitfield related to regular group conversion results */
1118 /* - Set state bitfield related to regular operation */
1119 ADC_STATE_CLR_SET(hadc->State,
1120 HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
1121 HAL_ADC_STATE_REG_BUSY);
1122
1123 /* Reset ADC all error code fields */
1124 ADC_CLEAR_ERRORCODE(hadc);
1125
1126 /* Process unlocked */
1127 /* Unlock before starting ADC conversions: in case of potential */
1128 /* interruption, to let the process to ADC IRQ Handler. */
1129 __HAL_UNLOCK(hadc);
1130
1131 /* Clear regular group conversion flag and overrun flag */
1132 /* (To ensure of no unknown state from potential previous ADC */
1133 /* operations) */
1134 __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
1135
1136 /* Enable ADC end of conversion interrupt */
1137 /* Enable ADC overrun interrupt */
1138 switch(hadc->Init.EOCSelection)
1139 {
1140 case ADC_EOC_SEQ_CONV:
1141 __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC);
1142 __HAL_ADC_ENABLE_IT(hadc, (ADC_IT_EOS | ADC_IT_OVR));
1143 break;
1144 /* case ADC_EOC_SINGLE_CONV */
1145 default:
1146 __HAL_ADC_ENABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR));
1147 break;
1148 }
1149
1150 /* Enable conversion of regular group. */
1151 /* If software start has been selected, conversion starts immediately. */
1152 /* If external trigger has been selected, conversion will start at next */
1153 /* trigger event. */
1154 hadc->Instance->CR |= ADC_CR_ADSTART;
1155 }
1156 }
1157 else
1158 {
1159 tmp_hal_status = HAL_BUSY;
1160 }
1161
1162 /* Return function status */
1163 return tmp_hal_status;
1164 }
1165
1166 /**
1167 * @brief Stop ADC conversion of regular group (and injected group in
1168 * case of auto_injection mode), disable interrution of
1169 * end-of-conversion, disable ADC peripheral.
1170 * @param hadc: ADC handle
1171 * @retval HAL status.
1172 */
HAL_ADC_Stop_IT(ADC_HandleTypeDef * hadc)1173 HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc)
1174 {
1175 HAL_StatusTypeDef tmp_hal_status = HAL_OK;
1176
1177 /* Check the parameters */
1178 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1179
1180 /* Process locked */
1181 __HAL_LOCK(hadc);
1182
1183 /* 1. Stop potential conversion on going, on ADC group regular */
1184 tmp_hal_status = ADC_ConversionStop(hadc);
1185
1186 /* Disable ADC peripheral if conversions are effectively stopped */
1187 if (tmp_hal_status == HAL_OK)
1188 {
1189 /* Disable ADC end of conversion interrupt for regular group */
1190 /* Disable ADC overrun interrupt */
1191 __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR));
1192
1193 /* 2. Disable the ADC peripheral */
1194 tmp_hal_status = ADC_Disable(hadc);
1195
1196 /* Check if ADC is effectively disabled */
1197 if (tmp_hal_status == HAL_OK)
1198 {
1199 /* Set ADC state */
1200 ADC_STATE_CLR_SET(hadc->State,
1201 HAL_ADC_STATE_REG_BUSY,
1202 HAL_ADC_STATE_READY);
1203 }
1204 }
1205
1206 /* Process unlocked */
1207 __HAL_UNLOCK(hadc);
1208
1209 /* Return function status */
1210 return tmp_hal_status;
1211 }
1212
1213 /**
1214 * @brief Enable ADC, start conversion of regular group and transfer result through DMA.
1215 * @note Interruptions enabled in this function:
1216 * overrun (if applicable), DMA half transfer, DMA transfer complete.
1217 * Each of these interruptions has its dedicated callback function.
1218 * @param hadc: ADC handle
1219 * @param pData: Destination Buffer address.
1220 * @param Length: Length of data to be transferred from ADC peripheral to memory (in bytes)
1221 * @retval HAL status.
1222 */
HAL_ADC_Start_DMA(ADC_HandleTypeDef * hadc,uint32_t * pData,uint32_t Length)1223 HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length)
1224 {
1225 HAL_StatusTypeDef tmp_hal_status = HAL_OK;
1226
1227 /* Check the parameters */
1228 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1229
1230 /* Perform ADC enable and conversion start if no conversion is on going */
1231 if (ADC_IS_CONVERSION_ONGOING_REGULAR(hadc) == RESET)
1232 {
1233 /* Process locked */
1234 __HAL_LOCK(hadc);
1235
1236 /* Enable the ADC peripheral */
1237 /* If low power mode AutoPowerOff is enabled, power-on/off phases are */
1238 /* performed automatically by hardware. */
1239 if (hadc->Init.LowPowerAutoPowerOff != ENABLE)
1240 {
1241 tmp_hal_status = ADC_Enable(hadc);
1242 }
1243
1244 /* Start conversion if ADC is effectively enabled */
1245 if (tmp_hal_status == HAL_OK)
1246 {
1247 /* Set ADC state */
1248 /* - Clear state bitfield related to regular group conversion results */
1249 /* - Set state bitfield related to regular operation */
1250 ADC_STATE_CLR_SET(hadc->State,
1251 HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
1252 HAL_ADC_STATE_REG_BUSY);
1253
1254 /* Reset ADC all error code fields */
1255 ADC_CLEAR_ERRORCODE(hadc);
1256
1257 /* Process unlocked */
1258 /* Unlock before starting ADC conversions: in case of potential */
1259 /* interruption, to let the process to ADC IRQ Handler. */
1260 __HAL_UNLOCK(hadc);
1261
1262 /* Set the DMA transfer complete callback */
1263 hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt;
1264
1265 /* Set the DMA half transfer complete callback */
1266 hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt;
1267
1268 /* Set the DMA error callback */
1269 hadc->DMA_Handle->XferErrorCallback = ADC_DMAError;
1270
1271
1272 /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */
1273 /* start (in case of SW start): */
1274
1275 /* Clear regular group conversion flag and overrun flag */
1276 /* (To ensure of no unknown state from potential previous ADC */
1277 /* operations) */
1278 __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
1279
1280 /* Enable ADC overrun interrupt */
1281 __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
1282
1283 /* Enable ADC DMA mode */
1284 hadc->Instance->CFGR1 |= ADC_CFGR1_DMAEN;
1285
1286 /* Start the DMA channel */
1287 HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->DR, (uint32_t)pData, Length);
1288
1289 /* Enable conversion of regular group. */
1290 /* If software start has been selected, conversion starts immediately. */
1291 /* If external trigger has been selected, conversion will start at next */
1292 /* trigger event. */
1293 hadc->Instance->CR |= ADC_CR_ADSTART;
1294 }
1295 }
1296 else
1297 {
1298 tmp_hal_status = HAL_BUSY;
1299 }
1300
1301 /* Return function status */
1302 return tmp_hal_status;
1303 }
1304
1305 /**
1306 * @brief Stop ADC conversion of regular group (and injected group in
1307 * case of auto_injection mode), disable ADC DMA transfer, disable
1308 * ADC peripheral.
1309 * Each of these interruptions has its dedicated callback function.
1310 * @param hadc: ADC handle
1311 * @retval HAL status.
1312 */
HAL_ADC_Stop_DMA(ADC_HandleTypeDef * hadc)1313 HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc)
1314 {
1315 HAL_StatusTypeDef tmp_hal_status = HAL_OK;
1316
1317 /* Check the parameters */
1318 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1319
1320 /* Process locked */
1321 __HAL_LOCK(hadc);
1322
1323 /* 1. Stop potential ADC group regular conversion on going */
1324 tmp_hal_status = ADC_ConversionStop(hadc);
1325
1326 /* Disable ADC peripheral if conversions are effectively stopped */
1327 if (tmp_hal_status == HAL_OK)
1328 {
1329 /* Disable ADC DMA (ADC DMA configuration ADC_CFGR_DMACFG is kept) */
1330 CLEAR_BIT(hadc->Instance->CFGR1, ADC_CFGR1_DMAEN);
1331
1332 /* Disable the DMA channel (in case of DMA in circular mode or stop */
1333 /* while DMA transfer is on going) */
1334 tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle);
1335
1336 /* Check if DMA channel effectively disabled */
1337 if (tmp_hal_status != HAL_OK)
1338 {
1339 /* Update ADC state machine to error */
1340 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
1341 }
1342
1343 /* Disable ADC overrun interrupt */
1344 __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
1345
1346 /* 2. Disable the ADC peripheral */
1347 /* Update "tmp_hal_status" only if DMA channel disabling passed, to keep */
1348 /* in memory a potential failing status. */
1349 if (tmp_hal_status == HAL_OK)
1350 {
1351 tmp_hal_status = ADC_Disable(hadc);
1352 }
1353 else
1354 {
1355 ADC_Disable(hadc);
1356 }
1357
1358 /* Check if ADC is effectively disabled */
1359 if (tmp_hal_status == HAL_OK)
1360 {
1361 /* Set ADC state */
1362 ADC_STATE_CLR_SET(hadc->State,
1363 HAL_ADC_STATE_REG_BUSY,
1364 HAL_ADC_STATE_READY);
1365 }
1366
1367 }
1368
1369 /* Process unlocked */
1370 __HAL_UNLOCK(hadc);
1371
1372 /* Return function status */
1373 return tmp_hal_status;
1374 }
1375
1376 /**
1377 * @brief Get ADC regular group conversion result.
1378 * @note Reading register DR automatically clears ADC flag EOC
1379 * (ADC group regular end of unitary conversion).
1380 * @note This function does not clear ADC flag EOS
1381 * (ADC group regular end of sequence conversion).
1382 * Occurrence of flag EOS rising:
1383 * - If sequencer is composed of 1 rank, flag EOS is equivalent
1384 * to flag EOC.
1385 * - If sequencer is composed of several ranks, during the scan
1386 * sequence flag EOC only is raised, at the end of the scan sequence
1387 * both flags EOC and EOS are raised.
1388 * To clear this flag, either use function:
1389 * in programming model IT: @ref HAL_ADC_IRQHandler(), in programming
1390 * model polling: @ref HAL_ADC_PollForConversion()
1391 * or @ref __HAL_ADC_CLEAR_FLAG(&hadc, ADC_FLAG_EOS).
1392 * @param hadc: ADC handle
1393 * @retval ADC group regular conversion data
1394 */
HAL_ADC_GetValue(ADC_HandleTypeDef * hadc)1395 uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef* hadc)
1396 {
1397 /* Check the parameters */
1398 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1399
1400 /* Note: EOC flag is not cleared here by software because automatically */
1401 /* cleared by hardware when reading register DR. */
1402
1403 /* Return ADC converted value */
1404 return hadc->Instance->DR;
1405 }
1406
1407 /**
1408 * @brief Handle ADC interrupt request.
1409 * @param hadc: ADC handle
1410 * @retval None
1411 */
HAL_ADC_IRQHandler(ADC_HandleTypeDef * hadc)1412 void HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc)
1413 {
1414 /* Check the parameters */
1415 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1416 assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
1417 assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection));
1418
1419 /* ========== Check End of Conversion flag for regular group ========== */
1420 if( (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC) && __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_EOC)) ||
1421 (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS) && __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_EOS)) )
1422 {
1423 /* Update state machine on conversion status if not in error state */
1424 if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL))
1425 {
1426 /* Set ADC state */
1427 SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
1428 }
1429
1430 /* Determine whether any further conversion upcoming on group regular */
1431 /* by external trigger, continuous mode or scan sequence on going. */
1432 if(ADC_IS_SOFTWARE_START_REGULAR(hadc) &&
1433 (hadc->Init.ContinuousConvMode == DISABLE) )
1434 {
1435 /* If End of Sequence is reached, disable interrupts */
1436 if( __HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS) )
1437 {
1438 /* Allowed to modify bits ADC_IT_EOC/ADC_IT_EOS only if bit */
1439 /* ADSTART==0 (no conversion on going) */
1440 if (ADC_IS_CONVERSION_ONGOING_REGULAR(hadc) == RESET)
1441 {
1442 /* Disable ADC end of single conversion interrupt on group regular */
1443 /* Note: Overrun interrupt was enabled with EOC interrupt in */
1444 /* HAL_Start_IT(), but is not disabled here because can be used */
1445 /* by overrun IRQ process below. */
1446 __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_EOS);
1447
1448 /* Set ADC state */
1449 ADC_STATE_CLR_SET(hadc->State,
1450 HAL_ADC_STATE_REG_BUSY,
1451 HAL_ADC_STATE_READY);
1452 }
1453 else
1454 {
1455 /* Change ADC state to error state */
1456 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1457
1458 /* Set ADC error code to ADC IP internal error */
1459 SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
1460 }
1461 }
1462 }
1463
1464 /* Conversion complete callback */
1465 /* Note: into callback, to determine if conversion has been triggered */
1466 /* from EOC or EOS, possibility to use: */
1467 /* " if( __HAL_ADC_GET_FLAG(&hadc, ADC_FLAG_EOS)) " */
1468 HAL_ADC_ConvCpltCallback(hadc);
1469
1470 /* Clear regular group conversion flag */
1471 /* Note: in case of overrun set to ADC_OVR_DATA_PRESERVED, end of */
1472 /* conversion flags clear induces the release of the preserved data.*/
1473 /* Therefore, if the preserved data value is needed, it must be */
1474 /* read preliminarily into HAL_ADC_ConvCpltCallback(). */
1475 /* Note: Management of low power auto-wait enabled: flags must be cleared */
1476 /* by user when fetching ADC conversion data. */
1477 /* This case is managed in IRQ handler, but this low-power mode */
1478 /* should not be used with programming model IT or DMA. */
1479 /* Refer to comment of parameter "LowPowerAutoWait". */
1480 if (hadc->Init.LowPowerAutoWait != ENABLE)
1481 {
1482 __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS));
1483 }
1484 }
1485
1486 /* ========== Check analog watchdog 1 flag ========== */
1487 if(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_AWD) && __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_AWD))
1488 {
1489 /* Set ADC state */
1490 SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
1491
1492 /* Level out of window 1 callback */
1493 HAL_ADC_LevelOutOfWindowCallback(hadc);
1494
1495 /* Clear ADC Analog watchdog flag */
1496 __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD);
1497
1498 }
1499
1500
1501 /* ========== Check Overrun flag ========== */
1502 if(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_OVR) && __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_OVR))
1503 {
1504 /* If overrun is set to overwrite previous data (default setting), */
1505 /* overrun event is not considered as an error. */
1506 /* (cf ref manual "Managing conversions without using the DMA and without */
1507 /* overrun ") */
1508 /* Exception for usage with DMA overrun event always considered as an */
1509 /* error. */
1510 if ((hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED) ||
1511 HAL_IS_BIT_SET(hadc->Instance->CFGR1, ADC_CFGR1_DMAEN) )
1512 {
1513 /* Set ADC error code to overrun */
1514 SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_OVR);
1515
1516 /* Clear ADC overrun flag */
1517 __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1518
1519 /* Error callback */
1520 HAL_ADC_ErrorCallback(hadc);
1521 }
1522
1523 /* Clear the Overrun flag */
1524 __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1525 }
1526
1527 }
1528
1529 /**
1530 * @brief Conversion complete callback in non-blocking mode.
1531 * @param hadc: ADC handle
1532 * @retval None
1533 */
HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef * hadc)1534 __weak void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
1535 {
1536 /* Prevent unused argument(s) compilation warning */
1537 UNUSED(hadc);
1538
1539 /* NOTE : This function should not be modified. When the callback is needed,
1540 function HAL_ADC_ConvCpltCallback must be implemented in the user file.
1541 */
1542 }
1543
1544 /**
1545 * @brief Conversion DMA half-transfer callback in non-blocking mode.
1546 * @param hadc: ADC handle
1547 * @retval None
1548 */
HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef * hadc)1549 __weak void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc)
1550 {
1551 /* Prevent unused argument(s) compilation warning */
1552 UNUSED(hadc);
1553
1554 /* NOTE : This function should not be modified. When the callback is needed,
1555 function HAL_ADC_ConvHalfCpltCallback must be implemented in the user file.
1556 */
1557 }
1558
1559 /**
1560 * @brief Analog watchdog 1 callback in non-blocking mode.
1561 * @param hadc: ADC handle
1562 * @retval None
1563 */
HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef * hadc)1564 __weak void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc)
1565 {
1566 /* Prevent unused argument(s) compilation warning */
1567 UNUSED(hadc);
1568
1569 /* NOTE : This function should not be modified. When the callback is needed,
1570 function HAL_ADC_LevelOutOfWindowCallback must be implemented in the user file.
1571 */
1572 }
1573
1574 /**
1575 * @brief ADC error callback in non-blocking mode
1576 * (ADC conversion with interruption or transfer by DMA).
1577 * @note In case of error due to overrun when using ADC with DMA transfer
1578 * (HAL ADC handle paramater "ErrorCode" to state "HAL_ADC_ERROR_OVR"):
1579 * - Reinitialize the DMA using function "HAL_ADC_Stop_DMA()".
1580 * - If needed, restart a new ADC conversion using function
1581 * "HAL_ADC_Start_DMA()"
1582 * (this function is also clearing overrun flag)
1583 * @param hadc: ADC handle
1584 * @retval None
1585 */
HAL_ADC_ErrorCallback(ADC_HandleTypeDef * hadc)1586 __weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc)
1587 {
1588 /* Prevent unused argument(s) compilation warning */
1589 UNUSED(hadc);
1590
1591 /* NOTE : This function should not be modified. When the callback is needed,
1592 function HAL_ADC_ErrorCallback must be implemented in the user file.
1593 */
1594 }
1595
1596 /**
1597 * @}
1598 */
1599
1600 /** @defgroup ADC_Exported_Functions_Group3 Peripheral Control functions
1601 * @brief Peripheral Control functions
1602 *
1603 @verbatim
1604 ===============================================================================
1605 ##### Peripheral Control functions #####
1606 ===============================================================================
1607 [..] This section provides functions allowing to:
1608 (+) Configure channels on regular group
1609 (+) Configure the analog watchdog
1610
1611 @endverbatim
1612 * @{
1613 */
1614
1615 /**
1616 * @brief Configure a channel to be assigned to ADC group regular.
1617 * @note In case of usage of internal measurement channels:
1618 * VrefInt/Vlcd(STM32L0x3xx only)/TempSensor.
1619 * Sampling time constraints must be respected (sampling time can be
1620 * adjusted in function of ADC clock frequency and sampling time
1621 * setting).
1622 * Refer to device datasheet for timings values, parameters TS_vrefint,
1623 * TS_vlcd (STM32L0x3xx only), TS_temp (values rough order: 5us to 17us).
1624 * These internal paths can be be disabled using function
1625 * HAL_ADC_DeInit().
1626 * @note Possibility to update parameters on the fly:
1627 * This function initializes channel into ADC group regular,
1628 * following calls to this function can be used to reconfigure
1629 * some parameters of structure "ADC_ChannelConfTypeDef" on the fly,
1630 * without resetting the ADC.
1631 * The setting of these parameters is conditioned to ADC state:
1632 * Refer to comments of structure "ADC_ChannelConfTypeDef".
1633 * @param hadc: ADC handle
1634 * @param sConfig: Structure of ADC channel assigned to ADC group regular.
1635 * @retval HAL status
1636 */
HAL_ADC_ConfigChannel(ADC_HandleTypeDef * hadc,ADC_ChannelConfTypeDef * sConfig)1637 HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig)
1638 {
1639 /* Check the parameters */
1640 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1641 assert_param(IS_ADC_CHANNEL(sConfig->Channel));
1642 assert_param(IS_ADC_RANK(sConfig->Rank));
1643
1644 /* Process locked */
1645 __HAL_LOCK(hadc);
1646
1647 /* Parameters update conditioned to ADC state: */
1648 /* Parameters that can be updated when ADC is disabled or enabled without */
1649 /* conversion on going on regular group: */
1650 /* - Channel number */
1651 /* - Management of internal measurement channels: Vbat/VrefInt/TempSensor */
1652 if (ADC_IS_CONVERSION_ONGOING_REGULAR(hadc) != RESET)
1653 {
1654 /* Update ADC state machine to error */
1655 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1656 /* Process unlocked */
1657 __HAL_UNLOCK(hadc);
1658 return HAL_ERROR;
1659 }
1660
1661 if (sConfig->Rank != ADC_RANK_NONE)
1662 {
1663 /* Enable selected channels */
1664 hadc->Instance->CHSELR |= (uint32_t)(sConfig->Channel & ADC_CHANNEL_MASK);
1665
1666 /* Management of internal measurement channels: Vlcd (STM32L0x3xx only)/VrefInt/TempSensor */
1667 /* internal measurement paths enable: If internal channel selected, enable */
1668 /* dedicated internal buffers and path. */
1669
1670 /* If Temperature sensor channel is selected, then enable the internal */
1671 /* buffers and path */
1672 if (((sConfig->Channel & ADC_CHANNEL_MASK) & ADC_CHANNEL_TEMPSENSOR ) == (ADC_CHANNEL_TEMPSENSOR & ADC_CHANNEL_MASK))
1673 {
1674 ADC->CCR |= ADC_CCR_TSEN;
1675
1676 /* Delay for temperature sensor stabilization time */
1677 ADC_DelayMicroSecond(ADC_TEMPSENSOR_DELAY_US);
1678 }
1679
1680 /* If VRefInt channel is selected, then enable the internal buffers and path */
1681 if (((sConfig->Channel & ADC_CHANNEL_MASK) & ADC_CHANNEL_VREFINT) == (ADC_CHANNEL_VREFINT & ADC_CHANNEL_MASK))
1682 {
1683 ADC->CCR |= ADC_CCR_VREFEN;
1684 }
1685
1686 #if defined (STM32L053xx) || defined (STM32L063xx) || defined (STM32L073xx) || defined (STM32L083xx)
1687 /* If Vlcd channel is selected, then enable the internal buffers and path */
1688 if (((sConfig->Channel & ADC_CHANNEL_MASK) & ADC_CHANNEL_VLCD) == (ADC_CHANNEL_VLCD & ADC_CHANNEL_MASK))
1689 {
1690 ADC->CCR |= ADC_CCR_VLCDEN;
1691 }
1692 #endif
1693 }
1694 else
1695 {
1696 /* Regular sequence configuration */
1697 /* Reset the channel selection register from the selected channel */
1698 hadc->Instance->CHSELR &= ~((uint32_t)(sConfig->Channel & ADC_CHANNEL_MASK));
1699
1700 /* Management of internal measurement channels: VrefInt/TempSensor/Vbat */
1701 /* internal measurement paths disable: If internal channel selected, */
1702 /* disable dedicated internal buffers and path. */
1703 if (((sConfig->Channel & ADC_CHANNEL_MASK) & ADC_CHANNEL_TEMPSENSOR ) == (ADC_CHANNEL_TEMPSENSOR & ADC_CHANNEL_MASK))
1704 {
1705 ADC->CCR &= ~ADC_CCR_TSEN;
1706 }
1707
1708 /* If VRefInt channel is selected, then enable the internal buffers and path */
1709 if (((sConfig->Channel & ADC_CHANNEL_MASK) & ADC_CHANNEL_VREFINT) == (ADC_CHANNEL_VREFINT & ADC_CHANNEL_MASK))
1710 {
1711 ADC->CCR &= ~ADC_CCR_VREFEN;
1712 }
1713
1714 #if defined (STM32L053xx) || defined (STM32L063xx) || defined (STM32L073xx) || defined (STM32L083xx)
1715 /* If Vlcd channel is selected, then enable the internal buffers and path */
1716 if (((sConfig->Channel & ADC_CHANNEL_MASK) & ADC_CHANNEL_VLCD) == (ADC_CHANNEL_VLCD & ADC_CHANNEL_MASK))
1717 {
1718 ADC->CCR &= ~ADC_CCR_VLCDEN;
1719 }
1720 #endif
1721 }
1722
1723 /* Process unlocked */
1724 __HAL_UNLOCK(hadc);
1725
1726 /* Return function status */
1727 return HAL_OK;
1728 }
1729
1730 /**
1731 * @brief Configure the analog watchdog.
1732 * @note Possibility to update parameters on the fly:
1733 * This function initializes the selected analog watchdog, successive
1734 * calls to this function can be used to reconfigure some parameters
1735 * of structure "ADC_AnalogWDGConfTypeDef" on the fly, without resetting
1736 * the ADC.
1737 * The setting of these parameters is conditioned to ADC state.
1738 * For parameters constraints, see comments of structure
1739 * "ADC_AnalogWDGConfTypeDef".
1740 * @note Analog watchdog thresholds can be modified while ADC conversion
1741 * is on going.
1742 * In this case, some constraints must be taken into account:
1743 * the programmed threshold values are effective from the next
1744 * ADC EOC (end of unitary conversion).
1745 * Considering that registers write delay may happen due to
1746 * bus activity, this might cause an uncertainty on the
1747 * effective timing of the new programmed threshold values.
1748 * @param hadc: ADC handle
1749 * @param AnalogWDGConfig: Structure of ADC analog watchdog configuration
1750 * @retval HAL status
1751 */
HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef * hadc,ADC_AnalogWDGConfTypeDef * AnalogWDGConfig)1752 HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig)
1753 {
1754 HAL_StatusTypeDef tmp_hal_status = HAL_OK;
1755
1756 uint32_t tmpAWDHighThresholdShifted;
1757 uint32_t tmpAWDLowThresholdShifted;
1758
1759 /* Check the parameters */
1760 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1761 assert_param(IS_ADC_ANALOG_WATCHDOG_MODE(AnalogWDGConfig->WatchdogMode));
1762 assert_param(IS_FUNCTIONAL_STATE(AnalogWDGConfig->ITMode));
1763
1764 if(AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG)
1765 {
1766 assert_param(IS_ADC_CHANNEL(AnalogWDGConfig->Channel));
1767 }
1768
1769 /* Verify if threshold is within the selected ADC resolution */
1770 assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), AnalogWDGConfig->HighThreshold));
1771 assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), AnalogWDGConfig->LowThreshold));
1772
1773 /* Process locked */
1774 __HAL_LOCK(hadc);
1775
1776 /* Parameters update conditioned to ADC state: */
1777 /* Parameters that can be updated when ADC is disabled or enabled without */
1778 /* conversion on going on regular group: */
1779 /* - Analog watchdog channels */
1780 /* - Analog watchdog thresholds */
1781 if (ADC_IS_CONVERSION_ONGOING_REGULAR(hadc) == RESET)
1782 {
1783 /* Configure ADC Analog watchdog interrupt */
1784 if(AnalogWDGConfig->ITMode == ENABLE)
1785 {
1786 /* Enable the ADC Analog watchdog interrupt */
1787 __HAL_ADC_ENABLE_IT(hadc, ADC_IT_AWD);
1788 }
1789 else
1790 {
1791 /* Disable the ADC Analog watchdog interrupt */
1792 __HAL_ADC_DISABLE_IT(hadc, ADC_IT_AWD);
1793 }
1794
1795 /* Configuration of analog watchdog: */
1796 /* - Set the analog watchdog mode */
1797 /* - Set the Analog watchdog channel (is not used if watchdog */
1798 /* mode "all channels": ADC_CFGR1_AWD1SGL=0) */
1799 hadc->Instance->CFGR1 &= ~( ADC_CFGR1_AWDSGL |
1800 ADC_CFGR1_AWDEN |
1801 ADC_CFGR1_AWDCH);
1802
1803 hadc->Instance->CFGR1 |= ( AnalogWDGConfig->WatchdogMode |
1804 (AnalogWDGConfig->Channel & ADC_CHANNEL_AWD_MASK));
1805
1806
1807 /* Shift the offset in function of the selected ADC resolution: Thresholds */
1808 /* have to be left-aligned on bit 11, the LSB (right bits) are set to 0 */
1809 tmpAWDHighThresholdShifted = ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(hadc, AnalogWDGConfig->HighThreshold);
1810 tmpAWDLowThresholdShifted = ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(hadc, AnalogWDGConfig->LowThreshold);
1811
1812 /* Clear High & Low high thresholds */
1813 hadc->Instance->TR &= (uint32_t) ~ (ADC_TR_HT | ADC_TR_LT);
1814
1815 /* Set the high threshold */
1816 hadc->Instance->TR = ADC_TRX_HIGHTHRESHOLD (tmpAWDHighThresholdShifted);
1817 /* Set the low threshold */
1818 hadc->Instance->TR |= tmpAWDLowThresholdShifted;
1819 }
1820 /* If a conversion is on going on regular group, no update could be done */
1821 /* on neither of the AWD configuration structure parameters. */
1822 else
1823 {
1824 /* Update ADC state machine to error */
1825 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1826
1827 tmp_hal_status = HAL_ERROR;
1828 }
1829
1830 /* Process unlocked */
1831 __HAL_UNLOCK(hadc);
1832
1833 /* Return function status */
1834 return tmp_hal_status;
1835 }
1836
1837
1838 /**
1839 * @}
1840 */
1841
1842 /** @defgroup ADC_Exported_Functions_Group4 Peripheral State functions
1843 * @brief ADC Peripheral State functions
1844 *
1845 @verbatim
1846 ===============================================================================
1847 ##### Peripheral state and errors functions #####
1848 ===============================================================================
1849 [..]
1850 This subsection provides functions to get in run-time the status of the
1851 peripheral.
1852 (+) Check the ADC state
1853 (+) Check the ADC error code
1854
1855 @endverbatim
1856 * @{
1857 */
1858
1859 /**
1860 * @brief Return the ADC handle state.
1861 * @note ADC state machine is managed by bitfields, ADC status must be
1862 * compared with states bits.
1863 * For example:
1864 * " if (HAL_IS_BIT_SET(HAL_ADC_GetState(hadc1), HAL_ADC_STATE_REG_BUSY)) "
1865 * " if (HAL_IS_BIT_SET(HAL_ADC_GetState(hadc1), HAL_ADC_STATE_AWD1) ) "
1866 * @param hadc: ADC handle
1867 * @retval ADC handle state (bitfield on 32 bits)
1868 */
HAL_ADC_GetState(ADC_HandleTypeDef * hadc)1869 uint32_t HAL_ADC_GetState(ADC_HandleTypeDef* hadc)
1870 {
1871 /* Check the parameters */
1872 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1873
1874 /* Return ADC handle state */
1875 return hadc->State;
1876 }
1877
1878 /**
1879 * @brief Return the ADC error code.
1880 * @param hadc: ADC handle
1881 * @retval ADC error code (bitfield on 32 bits)
1882 */
HAL_ADC_GetError(ADC_HandleTypeDef * hadc)1883 uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc)
1884 {
1885 /* Check the parameters */
1886 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1887
1888 return hadc->ErrorCode;
1889 }
1890
1891 /**
1892 * @}
1893 */
1894
1895 /**
1896 * @}
1897 */
1898
1899 /** @defgroup ADC_Private_Functions ADC Private Functions
1900 * @{
1901 */
1902
1903 /**
1904 * @brief Enable the selected ADC.
1905 * @note Prerequisite condition to use this function: ADC must be disabled
1906 * and voltage regulator must be enabled (done into HAL_ADC_Init()).
1907 * @note If low power mode AutoPowerOff is enabled, power-on/off phases are
1908 * performed automatically by hardware.
1909 * In this mode, this function is useless and must not be called because
1910 * flag ADC_FLAG_RDY is not usable.
1911 * Therefore, this function must be called under condition of
1912 * "if (hadc->Init.LowPowerAutoPowerOff != ENABLE)".
1913 * @param hadc: ADC handle
1914 * @retval HAL status.
1915 */
ADC_Enable(ADC_HandleTypeDef * hadc)1916 static HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef* hadc)
1917 {
1918 uint32_t tickstart = 0U;
1919
1920 /* ADC enable and wait for ADC ready (in case of ADC is disabled or */
1921 /* enabling phase not yet completed: flag ADC ready not yet set). */
1922 /* Timeout implemented to not be stuck if ADC cannot be enabled (possible */
1923 /* causes: ADC clock not running, ...). */
1924 if (ADC_IS_ENABLE(hadc) == RESET)
1925 {
1926 /* Check if conditions to enable the ADC are fulfilled */
1927 if (ADC_ENABLING_CONDITIONS(hadc) == RESET)
1928 {
1929 /* Update ADC state machine to error */
1930 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
1931
1932 /* Set ADC error code to ADC IP internal error */
1933 SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
1934
1935 return HAL_ERROR;
1936 }
1937
1938 /* Enable the ADC peripheral */
1939 __HAL_ADC_ENABLE(hadc);
1940
1941 /* Delay for ADC stabilization time. */
1942 ADC_DelayMicroSecond(ADC_STAB_DELAY_US);
1943
1944 /* Get tick count */
1945 tickstart = HAL_GetTick();
1946
1947 /* Wait for ADC effectively enabled */
1948 while(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_RDY) == RESET)
1949 {
1950 if((HAL_GetTick() - tickstart) > ADC_ENABLE_TIMEOUT)
1951 {
1952 /* Update ADC state machine to error */
1953 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
1954
1955 /* Set ADC error code to ADC IP internal error */
1956 SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
1957
1958 return HAL_ERROR;
1959 }
1960 }
1961 }
1962
1963 /* Return HAL status */
1964 return HAL_OK;
1965 }
1966
1967 /**
1968 * @brief Disable the selected ADC.
1969 * @note Prerequisite condition to use this function: ADC conversions must be
1970 * stopped.
1971 * @param hadc: ADC handle
1972 * @retval HAL status.
1973 */
ADC_Disable(ADC_HandleTypeDef * hadc)1974 static HAL_StatusTypeDef ADC_Disable(ADC_HandleTypeDef* hadc)
1975 {
1976 uint32_t tickstart = 0U;
1977
1978 /* Verification if ADC is not already disabled: */
1979 /* Note: forbidden to disable ADC (set bit ADC_CR_ADDIS) if ADC is already */
1980 /* disabled. */
1981 if (ADC_IS_ENABLE(hadc) != RESET)
1982 {
1983 /* Check if conditions to disable the ADC are fulfilled */
1984 if (ADC_DISABLING_CONDITIONS(hadc) != RESET)
1985 {
1986 /* Disable the ADC peripheral */
1987 __HAL_ADC_DISABLE(hadc);
1988 }
1989 else
1990 {
1991 /* Update ADC state machine to error */
1992 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
1993
1994 /* Set ADC error code to ADC IP internal error */
1995 SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
1996
1997 return HAL_ERROR;
1998 }
1999
2000 /* Wait for ADC effectively disabled */
2001 /* Get tick count */
2002 tickstart = HAL_GetTick();
2003
2004 while(HAL_IS_BIT_SET(hadc->Instance->CR, ADC_CR_ADEN))
2005 {
2006 if((HAL_GetTick() - tickstart) > ADC_DISABLE_TIMEOUT)
2007 {
2008 /* Update ADC state machine to error */
2009 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2010
2011 /* Set ADC error code to ADC IP internal error */
2012 SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2013
2014 return HAL_ERROR;
2015 }
2016 }
2017 }
2018
2019 /* Return HAL status */
2020 return HAL_OK;
2021 }
2022
2023
2024 /**
2025 * @brief Stop ADC conversion.
2026 * @note Prerequisite condition to use this function: ADC conversions must be
2027 * stopped to disable the ADC.
2028 * @param hadc: ADC handle
2029 * @retval HAL status.
2030 */
ADC_ConversionStop(ADC_HandleTypeDef * hadc)2031 static HAL_StatusTypeDef ADC_ConversionStop(ADC_HandleTypeDef* hadc)
2032 {
2033 uint32_t tickstart = 0U;
2034
2035 /* Check the parameters */
2036 assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2037
2038 /* Verification if ADC is not already stopped on regular group to bypass */
2039 /* this function if not needed. */
2040 if (ADC_IS_CONVERSION_ONGOING_REGULAR(hadc))
2041 {
2042
2043 /* Stop potential conversion on going on regular group */
2044 /* Software is allowed to set ADSTP only when ADSTART=1 and ADDIS=0 */
2045 if (HAL_IS_BIT_SET(hadc->Instance->CR, ADC_CR_ADSTART) &&
2046 HAL_IS_BIT_CLR(hadc->Instance->CR, ADC_CR_ADDIS) )
2047 {
2048 /* Stop conversions on regular group */
2049 hadc->Instance->CR |= ADC_CR_ADSTP;
2050 }
2051
2052 /* Wait for conversion effectively stopped */
2053 /* Get tick count */
2054 tickstart = HAL_GetTick();
2055
2056 while((hadc->Instance->CR & ADC_CR_ADSTART) != RESET)
2057 {
2058 if((HAL_GetTick() - tickstart) > ADC_STOP_CONVERSION_TIMEOUT)
2059 {
2060 /* Update ADC state machine to error */
2061 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2062
2063 /* Set ADC error code to ADC IP internal error */
2064 SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2065
2066 return HAL_ERROR;
2067 }
2068 }
2069
2070 }
2071
2072 /* Return HAL status */
2073 return HAL_OK;
2074 }
2075
2076
2077 /**
2078 * @brief DMA transfer complete callback.
2079 * @param hdma: pointer to DMA handle.
2080 * @retval None
2081 */
ADC_DMAConvCplt(DMA_HandleTypeDef * hdma)2082 static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma)
2083 {
2084 /* Retrieve ADC handle corresponding to current DMA handle */
2085 ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
2086
2087 /* Update state machine on conversion status if not in error state */
2088 if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL | HAL_ADC_STATE_ERROR_DMA))
2089 {
2090 /* Set ADC state */
2091 SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
2092
2093 /* Determine whether any further conversion upcoming on group regular */
2094 /* by external trigger, continuous mode or scan sequence on going. */
2095 if(ADC_IS_SOFTWARE_START_REGULAR(hadc) &&
2096 (hadc->Init.ContinuousConvMode == DISABLE) )
2097 {
2098 /* If End of Sequence is reached, disable interrupts */
2099 if( __HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS) )
2100 {
2101 /* Allowed to modify bits ADC_IT_EOC/ADC_IT_EOS only if bit */
2102 /* ADSTART==0 (no conversion on going) */
2103 if (ADC_IS_CONVERSION_ONGOING_REGULAR(hadc) == RESET)
2104 {
2105 /* Disable ADC end of single conversion interrupt on group regular */
2106 /* Note: Overrun interrupt was enabled with EOC interrupt in */
2107 /* HAL_Start_IT(), but is not disabled here because can be used */
2108 /* by overrun IRQ process below. */
2109 __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_EOS);
2110
2111 /* Set ADC state */
2112 ADC_STATE_CLR_SET(hadc->State,
2113 HAL_ADC_STATE_REG_BUSY,
2114 HAL_ADC_STATE_READY);
2115 }
2116 else
2117 {
2118 /* Change ADC state to error state */
2119 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
2120
2121 /* Set ADC error code to ADC IP internal error */
2122 SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2123 }
2124 }
2125 }
2126
2127 /* Conversion complete callback */
2128 HAL_ADC_ConvCpltCallback(hadc);
2129 }
2130 else
2131 {
2132 /* Call DMA error callback */
2133 hadc->DMA_Handle->XferErrorCallback(hdma);
2134 }
2135 }
2136
2137 /**
2138 * @brief DMA half transfer complete callback.
2139 * @param hdma: pointer to DMA handle.
2140 * @retval None
2141 */
ADC_DMAHalfConvCplt(DMA_HandleTypeDef * hdma)2142 static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma)
2143 {
2144 /* Retrieve ADC handle corresponding to current DMA handle */
2145 ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
2146
2147 /* Half conversion callback */
2148 HAL_ADC_ConvHalfCpltCallback(hadc);
2149 }
2150
2151 /**
2152 * @brief DMA error callback.
2153 * @param hdma: pointer to DMA handle.
2154 * @retval None
2155 */
ADC_DMAError(DMA_HandleTypeDef * hdma)2156 static void ADC_DMAError(DMA_HandleTypeDef *hdma)
2157 {
2158 /* Retrieve ADC handle corresponding to current DMA handle */
2159 ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
2160
2161 /* Set ADC state */
2162 SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
2163
2164 /* Set ADC error code to DMA error */
2165 SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_DMA);
2166
2167 /* Error callback */
2168 HAL_ADC_ErrorCallback(hadc);
2169 }
2170
2171 /**
2172 * @brief Delay micro seconds
2173 * @param microSecond : delay
2174 * @retval None
2175 */
ADC_DelayMicroSecond(uint32_t microSecond)2176 static void ADC_DelayMicroSecond(uint32_t microSecond)
2177 {
2178 /* Compute number of CPU cycles to wait for */
2179 __IO uint32_t waitLoopIndex = (microSecond * (SystemCoreClock / 1000000U));
2180
2181 while(waitLoopIndex != 0U)
2182 {
2183 waitLoopIndex--;
2184 }
2185 }
2186
2187 #endif /* HAL_ADC_MODULE_ENABLED */
2188 /**
2189 * @}
2190 */
2191
2192 /**
2193 * @}
2194 */
2195
2196 /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
2197