1 /**
2   ******************************************************************************
3   * @file    stm32c0xx_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 Converter (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   *          "stm32c0xx_hal_adc_ex.c".
21   *
22   ******************************************************************************
23   * @attention
24   *
25   * Copyright (c) 2022 STMicroelectronics.
26   * All rights reserved.
27   *
28   * This software is licensed under terms that can be found in the LICENSE file
29   * in the root directory of this software component.
30   * If no LICENSE file comes with this software, it is provided AS-IS.
31   *
32   ******************************************************************************
33   @verbatim
34   ==============================================================================
35                      ##### ADC peripheral features #####
36   ==============================================================================
37   [..]
38   (+) 12-bit, 10-bit, 8-bit or 6-bit configurable resolution.
39 
40   (+) Interrupt generation at the end of regular conversion and in case of
41       analog watchdog or overrun events.
42 
43   (+) Single and continuous conversion modes.
44 
45   (+) Scan mode for conversion of several channels sequentially.
46 
47   (+) Data alignment with in-built data coherency.
48 
49   (+) Programmable sampling time (common to group of channels)
50 
51   (+) External trigger (timer or EXTI) with configurable polarity
52 
53   (+) DMA request generation for transfer of conversions data of regular group.
54 
55   (+) ADC calibration
56 
57   (+) ADC conversion of regular group.
58 
59   (+) ADC supply requirements: 1.62 V to 3.6 V.
60 
61   (+) ADC input range: from Vref- (connected to Vssa) to Vref+ (connected to
62       Vdda or to an external voltage reference).
63 
64 
65                      ##### How to use this driver #####
66   ==============================================================================
67     [..]
68 
69      *** Configuration of top level parameters related to ADC ***
70      ============================================================
71      [..]
72 
73     (#) Enable the ADC interface
74         (++) As prerequisite, ADC clock must be configured at RCC top level.
75              Caution: On STM32C0, ADC clock frequency max is 35MHz (refer
76                       to device datasheet).
77                       Therefore, ADC clock source from RCC and ADC clock
78                       prescaler must be configured to remain below
79                       this maximum frequency.
80 
81         (++) Two clock settings are mandatory:
82              (+++) ADC clock (core clock, also possibly conversion clock).
83 
84              (+++) ADC clock (conversions clock).
85                    Four possible clock sources: synchronous clock from APB clock (same as ADC core clock)
86                    or asynchronous clock from RCC level: SYSCLK, HSI48.
87 
88              (+++) Example:
89                    Into HAL_ADC_MspInit() (recommended code location) or with
90                    other device clock parameters configuration:
91                (+++) __HAL_RCC_ADC_CLK_ENABLE();                  (mandatory: core clock)
92 
93         (++) ADC clock source and clock prescaler are configured at ADC level with
94              parameter "ClockPrescaler" using function HAL_ADC_Init().
95 
96     (#) ADC pins configuration
97          (++) Enable the clock for the ADC GPIOs
98               using macro __HAL_RCC_GPIOx_CLK_ENABLE()
99          (++) Configure these ADC pins in analog mode
100               using function HAL_GPIO_Init()
101 
102     (#) Optionally, in case of usage of ADC with interruptions:
103          (++) Configure the NVIC for ADC
104               using function HAL_NVIC_EnableIRQ(ADCx_IRQn)
105          (++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
106               into the function of corresponding ADC interruption vector
107               ADCx_IRQHandler().
108 
109     (#) Optionally, in case of usage of DMA:
110          (++) Configure the DMA (DMA channel, mode normal or circular, ...)
111               using function HAL_DMA_Init().
112          (++) Configure the NVIC for DMA
113               using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
114          (++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
115               into the function of corresponding DMA interruption vector
116               DMAx_Channelx_IRQHandler().
117 
118      *** Configuration of ADC, group regular, channels parameters ***
119      ================================================================
120      [..]
121 
122     (#) Configure the ADC parameters (resolution, data alignment, ...)
123         and regular group parameters (conversion trigger, sequencer, ...)
124         using function HAL_ADC_Init().
125 
126     (#) Configure the channels for regular group parameters (channel number,
127         channel rank into sequencer, ..., into regular group)
128         using function HAL_ADC_ConfigChannel().
129 
130     (#) Optionally, configure the analog watchdog parameters (channels
131         monitored, thresholds, ...)
132         using function HAL_ADC_AnalogWDGConfig().
133 
134      *** Execution of ADC conversions ***
135      ====================================
136      [..]
137 
138     (#) Optionally, perform an automatic ADC calibration to improve the
139         conversion accuracy
140         using function HAL_ADCEx_Calibration_Start().
141 
142     (#) ADC driver can be used among three modes: polling, interruption,
143         transfer by DMA.
144 
145         (++) ADC conversion by polling:
146           (+++) Activate the ADC peripheral and start conversions
147                 using function HAL_ADC_Start()
148           (+++) Wait for ADC conversion completion
149                 using function HAL_ADC_PollForConversion()
150           (+++) Retrieve conversion results
151                 using function HAL_ADC_GetValue()
152           (+++) Stop conversion and disable the ADC peripheral
153                 using function HAL_ADC_Stop()
154 
155         (++) ADC conversion by interruption:
156           (+++) Activate the ADC peripheral and start conversions
157                 using function HAL_ADC_Start_IT()
158           (+++) Wait for ADC conversion completion by call of function
159                 HAL_ADC_ConvCpltCallback()
160                 (this function must be implemented in user program)
161           (+++) Retrieve conversion results
162                 using function HAL_ADC_GetValue()
163           (+++) Stop conversion and disable the ADC peripheral
164                 using function HAL_ADC_Stop_IT()
165 
166         (++) ADC conversion with transfer by DMA:
167           (+++) Activate the ADC peripheral and start conversions
168                 using function HAL_ADC_Start_DMA()
169           (+++) Wait for ADC conversion completion by call of function
170                 HAL_ADC_ConvCpltCallback() or HAL_ADC_ConvHalfCpltCallback()
171                 (these functions must be implemented in user program)
172           (+++) Conversion results are automatically transferred by DMA into
173                 destination variable address.
174           (+++) Stop conversion and disable the ADC peripheral
175                 using function HAL_ADC_Stop_DMA()
176 
177      [..]
178 
179     (@) Callback functions must be implemented in user program:
180       (+@) HAL_ADC_ErrorCallback()
181       (+@) HAL_ADC_LevelOutOfWindowCallback() (callback of analog watchdog)
182       (+@) HAL_ADC_ConvCpltCallback()
183       (+@) HAL_ADC_ConvHalfCpltCallback
184 
185      *** Deinitialization of ADC ***
186      ============================================================
187      [..]
188 
189     (#) Disable the ADC interface
190       (++) ADC clock can be hard reset and disabled at RCC top level.
191         (++) Hard reset of ADC peripherals
192              using macro __ADCx_FORCE_RESET(), __ADCx_RELEASE_RESET().
193         (++) ADC clock disable
194              using the equivalent macro/functions as configuration step.
195              (+++) Example:
196                    Into HAL_ADC_MspDeInit() (recommended code location) or with
197                    other device clock parameters configuration:
198                (+++) RCC_OscInitStructure.OscillatorType = RCC_OSCILLATORTYPE_HSI14;
199                (+++) RCC_OscInitStructure.HSI14State = RCC_HSI14_OFF; (if not used for system clock)
200                (+++) HAL_RCC_OscConfig(&RCC_OscInitStructure);
201 
202     (#) ADC pins configuration
203          (++) Disable the clock for the ADC GPIOs
204               using macro __HAL_RCC_GPIOx_CLK_DISABLE()
205 
206     (#) Optionally, in case of usage of ADC with interruptions:
207          (++) Disable the NVIC for ADC
208               using function HAL_NVIC_EnableIRQ(ADCx_IRQn)
209 
210     (#) Optionally, in case of usage of DMA:
211          (++) Deinitialize the DMA
212               using function HAL_DMA_Init().
213          (++) Disable the NVIC for DMA
214               using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
215 
216     [..]
217 
218     *** Callback registration ***
219     =============================================
220     [..]
221 
222      The compilation flag USE_HAL_ADC_REGISTER_CALLBACKS, when set to 1,
223      allows the user to configure dynamically the driver callbacks.
224      Use Functions @ref HAL_ADC_RegisterCallback()
225      to register an interrupt callback.
226     [..]
227 
228      Function @ref HAL_ADC_RegisterCallback() allows to register following callbacks:
229        (+) ConvCpltCallback               : ADC conversion complete callback
230        (+) ConvHalfCpltCallback           : ADC conversion DMA half-transfer callback
231        (+) LevelOutOfWindowCallback       : ADC analog watchdog 1 callback
232        (+) ErrorCallback                  : ADC error callback
233        (+) LevelOutOfWindow2Callback      : ADC analog watchdog 2 callback
234        (+) LevelOutOfWindow3Callback      : ADC analog watchdog 3 callback
235        (+) EndOfSamplingCallback          : ADC end of sampling callback
236        (+) MspInitCallback                : ADC Msp Init callback
237        (+) MspDeInitCallback              : ADC Msp DeInit callback
238      This function takes as parameters the HAL peripheral handle, the Callback ID
239      and a pointer to the user callback function.
240     [..]
241 
242      Use function @ref HAL_ADC_UnRegisterCallback to reset a callback to the default
243      weak function.
244     [..]
245 
246      @ref HAL_ADC_UnRegisterCallback takes as parameters the HAL peripheral handle,
247      and the Callback ID.
248      This function allows to reset following callbacks:
249        (+) ConvCpltCallback               : ADC conversion complete callback
250        (+) ConvHalfCpltCallback           : ADC conversion DMA half-transfer callback
251        (+) LevelOutOfWindowCallback       : ADC analog watchdog 1 callback
252        (+) ErrorCallback                  : ADC error callback
253        (+) LevelOutOfWindow2Callback      : ADC analog watchdog 2 callback
254        (+) LevelOutOfWindow3Callback      : ADC analog watchdog 3 callback
255        (+) EndOfSamplingCallback          : ADC end of sampling callback
256        (+) MspInitCallback                : ADC Msp Init callback
257        (+) MspDeInitCallback              : ADC Msp DeInit callback
258      [..]
259 
260      By default, after the @ref HAL_ADC_Init() and when the state is @ref HAL_ADC_STATE_RESET
261      all callbacks are set to the corresponding weak functions:
262      examples @ref HAL_ADC_ConvCpltCallback(), @ref HAL_ADC_ErrorCallback().
263      Exception done for MspInit and MspDeInit functions that are
264      reset to the legacy weak functions in the @ref HAL_ADC_Init()/ @ref HAL_ADC_DeInit() only when
265      these callbacks are null (not registered beforehand).
266     [..]
267 
268      If MspInit or MspDeInit are not null, the @ref HAL_ADC_Init()/ @ref HAL_ADC_DeInit()
269      keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state.
270      [..]
271 
272      Callbacks can be registered/unregistered in @ref HAL_ADC_STATE_READY state only.
273      Exception done MspInit/MspDeInit functions that can be registered/unregistered
274      in @ref HAL_ADC_STATE_READY or @ref HAL_ADC_STATE_RESET state,
275      thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit.
276     [..]
277 
278      Then, the user first registers the MspInit/MspDeInit user callbacks
279      using @ref HAL_ADC_RegisterCallback() before calling @ref HAL_ADC_DeInit()
280      or @ref HAL_ADC_Init() function.
281      [..]
282 
283      When the compilation flag USE_HAL_ADC_REGISTER_CALLBACKS is set to 0 or
284      not defined, the callback registration feature is not available and all callbacks
285      are set to the corresponding weak functions.
286 
287   @endverbatim
288   ******************************************************************************
289   */
290 
291 /* Includes ------------------------------------------------------------------*/
292 #include "stm32c0xx_hal.h"
293 
294 /** @addtogroup STM32C0xx_HAL_Driver
295   * @{
296   */
297 
298 /** @defgroup ADC ADC
299   * @brief ADC HAL module driver
300   * @{
301   */
302 
303 #ifdef HAL_ADC_MODULE_ENABLED
304 
305 /* Private typedef -----------------------------------------------------------*/
306 /* Private define ------------------------------------------------------------*/
307 
308 /** @defgroup ADC_Private_Constants ADC Private Constants
309   * @{
310   */
311 
312 /* Fixed timeout values for ADC calibration, enable settling time, disable  */
313 /* settling time.                                                           */
314 /* Values defined to be higher than worst cases: low clock frequency,       */
315 /* maximum prescaler.                                                       */
316 /* Ex of profile low frequency : Clock source at 0.1 MHz, ADC clock         */
317 /* prescaler 4, sampling time 7.5 ADC clock cycles, resolution 12 bits.     */
318 /* Unit: ms                                                                 */
319 #define ADC_ENABLE_TIMEOUT              (2UL)
320 #define ADC_DISABLE_TIMEOUT             (2UL)
321 #define ADC_STOP_CONVERSION_TIMEOUT     (2UL)
322 #define ADC_CHANNEL_CONF_RDY_TIMEOUT    (1UL)
323 
324 /* Register CHSELR bits corresponding to ranks 2 to 8 .                     */
325 #define ADC_CHSELR_SQ2_TO_SQ8           (ADC_CHSELR_SQ2 | ADC_CHSELR_SQ3 | ADC_CHSELR_SQ4 | \
326                                          ADC_CHSELR_SQ5 | ADC_CHSELR_SQ6 | ADC_CHSELR_SQ7 | ADC_CHSELR_SQ8)
327 
328 /**
329   * @}
330   */
331 
332 /* Private macro -------------------------------------------------------------*/
333 /* Private variables ---------------------------------------------------------*/
334 /* Private function prototypes -----------------------------------------------*/
335 /** @defgroup ADC_Private_Functions ADC Private Functions
336   * @{
337   */
338 static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma);
339 static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma);
340 static void ADC_DMAError(DMA_HandleTypeDef *hdma);
341 /**
342   * @}
343   */
344 
345 /* Exported functions ---------------------------------------------------------*/
346 
347 /** @defgroup ADC_Exported_Functions ADC Exported Functions
348   * @{
349   */
350 
351 /** @defgroup ADC_Exported_Functions_Group1 Initialization and de-initialization functions
352   * @brief    ADC Initialization and Configuration functions
353   *
354 @verbatim
355  ===============================================================================
356               ##### Initialization and de-initialization functions #####
357  ===============================================================================
358     [..]  This section provides functions allowing to:
359       (+) Initialize and configure the ADC.
360       (+) De-initialize the ADC.
361 @endverbatim
362   * @{
363   */
364 
365 /**
366   * @brief  Initialize the ADC peripheral and regular group according to
367   *         parameters specified in structure "ADC_InitTypeDef".
368   * @note   As prerequisite, ADC clock must be configured at RCC top level
369   *         (refer to description of RCC configuration for ADC
370   *         in header of this file).
371   * @note   Possibility to update parameters on the fly:
372   *         This function initializes the ADC MSP (HAL_ADC_MspInit()) only when
373   *         coming from ADC state reset. Following calls to this function can
374   *         be used to reconfigure some parameters of ADC_InitTypeDef
375   *         structure on the fly, without modifying MSP configuration. If ADC
376   *         MSP has to be modified again, HAL_ADC_DeInit() must be called
377   *         before HAL_ADC_Init().
378   *         The setting of these parameters is conditioned to ADC state.
379   *         For parameters constraints, see comments of structure
380   *         "ADC_InitTypeDef".
381   * @note   This function configures the ADC within 2 scopes: scope of entire
382   *         ADC and scope of regular group. For parameters details, see comments
383   *         of structure "ADC_InitTypeDef".
384   * @param hadc ADC handle
385   * @retval HAL status
386   */
HAL_ADC_Init(ADC_HandleTypeDef * hadc)387 HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef *hadc)
388 {
389   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
390   uint32_t tmpCFGR1 = 0UL;
391   uint32_t tmpCFGR2 = 0UL;
392   uint32_t tmp_adc_reg_is_conversion_on_going;
393   __IO uint32_t wait_loop_index = 0UL;
394 
395   /* Check ADC handle */
396   if (hadc == NULL)
397   {
398     return HAL_ERROR;
399   }
400 
401   /* Check the parameters */
402   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
403   assert_param(IS_ADC_CLOCKPRESCALER(hadc->Init.ClockPrescaler));
404   assert_param(IS_ADC_RESOLUTION(hadc->Init.Resolution));
405   assert_param(IS_ADC_DATA_ALIGN(hadc->Init.DataAlign));
406   assert_param(IS_ADC_SCAN_MODE(hadc->Init.ScanConvMode));
407   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
408   assert_param(IS_ADC_EXTTRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
409   assert_param(IS_ADC_EXTTRIG(hadc->Init.ExternalTrigConv));
410   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests));
411   assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection));
412   assert_param(IS_ADC_OVERRUN(hadc->Init.Overrun));
413   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerAutoWait));
414   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerAutoPowerOff));
415   assert_param(IS_ADC_SAMPLE_TIME(hadc->Init.SamplingTimeCommon1));
416   assert_param(IS_ADC_SAMPLE_TIME(hadc->Init.SamplingTimeCommon2));
417   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.OversamplingMode));
418 
419   assert_param(IS_ADC_TRIGGER_FREQ(hadc->Init.TriggerFrequencyMode));
420 
421   if (hadc->Init.ScanConvMode != ADC_SCAN_DISABLE)
422   {
423     assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DiscontinuousConvMode));
424 
425     if (hadc->Init.ScanConvMode == ADC_SCAN_ENABLE)
426     {
427       assert_param(IS_ADC_REGULAR_NB_CONV(hadc->Init.NbrOfConversion));
428     }
429   }
430 
431   /* ADC group regular discontinuous mode can be enabled only if              */
432   /* continuous mode is disabled.                                             */
433   assert_param(!((hadc->Init.DiscontinuousConvMode == ENABLE) && (hadc->Init.ContinuousConvMode == ENABLE)));
434 
435   /* Actions performed only if ADC is coming from state reset:                */
436   /* - Initialization of ADC MSP                                              */
437   if (hadc->State == HAL_ADC_STATE_RESET)
438   {
439 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
440     /* Init the ADC Callback settings */
441     hadc->ConvCpltCallback              = HAL_ADC_ConvCpltCallback;                 /* Legacy weak callback */
442     hadc->ConvHalfCpltCallback          = HAL_ADC_ConvHalfCpltCallback;             /* Legacy weak callback */
443     hadc->LevelOutOfWindowCallback      = HAL_ADC_LevelOutOfWindowCallback;         /* Legacy weak callback */
444     hadc->ErrorCallback                 = HAL_ADC_ErrorCallback;                    /* Legacy weak callback */
445     hadc->LevelOutOfWindow2Callback     = HAL_ADCEx_LevelOutOfWindow2Callback;      /* Legacy weak callback */
446     hadc->LevelOutOfWindow3Callback     = HAL_ADCEx_LevelOutOfWindow3Callback;      /* Legacy weak callback */
447     hadc->EndOfSamplingCallback         = HAL_ADCEx_EndOfSamplingCallback;          /* Legacy weak callback */
448 
449     if (hadc->MspInitCallback == NULL)
450     {
451       hadc->MspInitCallback = HAL_ADC_MspInit; /* Legacy weak MspInit  */
452     }
453 
454     /* Init the low level hardware */
455     hadc->MspInitCallback(hadc);
456 #else
457     /* Init the low level hardware */
458     HAL_ADC_MspInit(hadc);
459 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
460 
461     /* Set ADC error code to none */
462     ADC_CLEAR_ERRORCODE(hadc);
463 
464     /* Initialize Lock */
465     hadc->Lock = HAL_UNLOCKED;
466   }
467 
468   if (LL_ADC_IsInternalRegulatorEnabled(hadc->Instance) == 0UL)
469   {
470     /* Enable ADC internal voltage regulator */
471     LL_ADC_EnableInternalRegulator(hadc->Instance);
472 
473     /* Delay for ADC stabilization time */
474     /* Wait loop initialization and execution */
475     /* Note: Variable divided by 2 to compensate partially              */
476     /*       CPU processing cycles, scaling in us split to not          */
477     /*       exceed 32 bits register capacity and handle low frequency. */
478     wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL)));
479     while (wait_loop_index != 0UL)
480     {
481       wait_loop_index--;
482     }
483   }
484 
485   /* Verification that ADC voltage regulator is correctly enabled, whether    */
486   /* or not ADC is coming from state reset (if any potential problem of       */
487   /* clocking, voltage regulator would not be enabled).                       */
488   if (LL_ADC_IsInternalRegulatorEnabled(hadc->Instance) == 0UL)
489   {
490     /* Update ADC state machine to error */
491     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
492 
493     /* Set ADC error code to ADC peripheral internal error */
494     SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
495 
496     tmp_hal_status = HAL_ERROR;
497   }
498 
499   /* Configuration of ADC parameters if previous preliminary actions are      */
500   /* correctly completed and if there is no conversion on going on regular    */
501   /* group (ADC may already be enabled at this point if HAL_ADC_Init() is     */
502   /* called to update a parameter on the fly).                                */
503   tmp_adc_reg_is_conversion_on_going = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
504 
505   if (((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
506       && (tmp_adc_reg_is_conversion_on_going == 0UL)
507      )
508   {
509     /* Set ADC state */
510     ADC_STATE_CLR_SET(hadc->State,
511                       HAL_ADC_STATE_REG_BUSY,
512                       HAL_ADC_STATE_BUSY_INTERNAL);
513 
514     /* Configuration of common ADC parameters                                 */
515 
516     /* Parameters update conditioned to ADC state:                            */
517     /* Parameters that can be updated only when ADC is disabled:              */
518     /*  - Internal voltage regulator (no parameter in HAL ADC init structure) */
519     /*  - Clock configuration                                                 */
520     /*  - ADC resolution                                                      */
521     /*  - Oversampling                                                        */
522     /*  - discontinuous mode                                                  */
523     /*  - LowPowerAutoWait mode                                               */
524     /*  - LowPowerAutoPowerOff mode                                           */
525     /*  - continuous conversion mode                                          */
526     /*  - overrun                                                             */
527     /*  - external trigger to start conversion                                */
528     /*  - external trigger polarity                                           */
529     /*  - data alignment                                                      */
530     /*  - resolution                                                          */
531     /*  - scan direction                                                      */
532     /*  - DMA continuous request                                              */
533     /*  - Trigger frequency mode                                              */
534     /* Note: If low power mode AutoPowerOff is enabled, ADC enable            */
535     /*       and disable phases are performed automatically by hardware       */
536     /*       (in this case, flag ADC_FLAG_RDY is not set).                    */
537     if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
538     {
539       /* Some parameters of this register are not reset, since they are set   */
540       /* by other functions and must be kept in case of usage of this         */
541       /* function on the fly (update of a parameter of ADC_InitTypeDef        */
542       /* without needing to reconfigure all other ADC groups/channels         */
543       /* parameters):                                                         */
544       /*   - internal measurement paths: temperature sensor, Vref             */
545       /*     (set into HAL_ADC_ConfigChannel() )                              */
546 
547       tmpCFGR1 |= (hadc->Init.Resolution                                          |
548                    ADC_CFGR1_AUTOWAIT((uint32_t)hadc->Init.LowPowerAutoWait)      |
549                    ADC_CFGR1_AUTOOFF((uint32_t)hadc->Init.LowPowerAutoPowerOff)   |
550                    ADC_CFGR1_CONTINUOUS((uint32_t)hadc->Init.ContinuousConvMode)  |
551                    ADC_CFGR1_OVERRUN(hadc->Init.Overrun)                          |
552                    hadc->Init.DataAlign                                           |
553                    ADC_SCAN_SEQ_MODE(hadc->Init.ScanConvMode)                     |
554                    ADC_CFGR1_DMACONTREQ((uint32_t)hadc->Init.DMAContinuousRequests));
555 
556       /* Update setting of discontinuous mode only if continuous mode is disabled */
557       if (hadc->Init.DiscontinuousConvMode == ENABLE)
558       {
559         if (hadc->Init.ContinuousConvMode == DISABLE)
560         {
561           /* Enable the selected ADC group regular discontinuous mode */
562           tmpCFGR1 |= ADC_CFGR1_DISCEN;
563         }
564         else
565         {
566           /* ADC regular group discontinuous was intended to be enabled,        */
567           /* but ADC regular group modes continuous and sequencer discontinuous */
568           /* cannot be enabled simultaneously.                                  */
569 
570           /* Update ADC state machine to error */
571           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
572 
573           /* Set ADC error code to ADC peripheral internal error */
574           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
575         }
576       }
577 
578       /* Enable external trigger if trigger selection is different of software  */
579       /* start.                                                                 */
580       /* Note: This configuration keeps the hardware feature of parameter       */
581       /*       ExternalTrigConvEdge "trigger edge none" equivalent to           */
582       /*       software start.                                                  */
583       if (hadc->Init.ExternalTrigConv != ADC_SOFTWARE_START)
584       {
585         tmpCFGR1 |= ((hadc->Init.ExternalTrigConv & ADC_CFGR1_EXTSEL) |
586                      hadc->Init.ExternalTrigConvEdge);
587       }
588 
589       /* Update ADC configuration register with previous settings */
590       MODIFY_REG(hadc->Instance->CFGR1,
591                  ADC_CFGR1_RES     |
592                  ADC_CFGR1_DISCEN  |
593                  ADC_CFGR1_CHSELRMOD |
594                  ADC_CFGR1_AUTOFF  |
595                  ADC_CFGR1_WAIT    |
596                  ADC_CFGR1_CONT    |
597                  ADC_CFGR1_OVRMOD  |
598                  ADC_CFGR1_EXTSEL  |
599                  ADC_CFGR1_EXTEN   |
600                  ADC_CFGR1_ALIGN   |
601                  ADC_CFGR1_SCANDIR |
602                  ADC_CFGR1_DMACFG,
603                  tmpCFGR1);
604 
605       tmpCFGR2 |= ((hadc->Init.ClockPrescaler & ADC_CFGR2_CKMODE) |
606                    hadc->Init.TriggerFrequencyMode
607                   );
608 
609       if (hadc->Init.OversamplingMode == ENABLE)
610       {
611         tmpCFGR2 |= (ADC_CFGR2_OVSE |
612                      (hadc->Init.ClockPrescaler & ADC_CFGR2_CKMODE) |
613                      hadc->Init.Oversampling.Ratio         |
614                      hadc->Init.Oversampling.RightBitShift |
615                      hadc->Init.Oversampling.TriggeredMode
616                     );
617       }
618 
619       MODIFY_REG(hadc->Instance->CFGR2,
620                  ADC_CFGR2_CKMODE |
621                  ADC_CFGR2_LFTRIG |
622                  ADC_CFGR2_OVSE   |
623                  ADC_CFGR2_OVSR   |
624                  ADC_CFGR2_OVSS   |
625                  ADC_CFGR2_TOVS,
626                  tmpCFGR2);
627 
628       /* Configuration of ADC clock mode: asynchronous clock source           */
629       /* with selectable prescaler.                                           */
630       if (((hadc->Init.ClockPrescaler) != ADC_CLOCK_SYNC_PCLK_DIV1) &&
631           ((hadc->Init.ClockPrescaler) != ADC_CLOCK_SYNC_PCLK_DIV2) &&
632           ((hadc->Init.ClockPrescaler) != ADC_CLOCK_SYNC_PCLK_DIV4))
633       {
634         MODIFY_REG(ADC1_COMMON->CCR,
635                    ADC_CCR_PRESC,
636                    hadc->Init.ClockPrescaler & ADC_CCR_PRESC);
637       }
638     }
639 
640     /* Channel sampling time configuration */
641     LL_ADC_SetSamplingTimeCommonChannels(hadc->Instance, LL_ADC_SAMPLINGTIME_COMMON_1, hadc->Init.SamplingTimeCommon1);
642     LL_ADC_SetSamplingTimeCommonChannels(hadc->Instance, LL_ADC_SAMPLINGTIME_COMMON_2, hadc->Init.SamplingTimeCommon2);
643 
644     /* Configuration of regular group sequencer:                              */
645     /* - if scan mode is disabled, regular channels sequence length is set to */
646     /*   0x00: 1 channel converted (channel on regular rank 1)                */
647     /*   Parameter "NbrOfConversion" is discarded.                            */
648     /*   Note: Scan mode is not present by hardware on this device, but       */
649     /*   emulated by software for alignment over all STM32 devices.           */
650     /* - if scan mode is enabled, regular channels sequence length is set to  */
651     /*   parameter "NbrOfConversion".                                         */
652     /*   Channels must be configured into each rank using function            */
653     /*   "HAL_ADC_ConfigChannel()".                                           */
654     if (hadc->Init.ScanConvMode == ADC_SCAN_DISABLE)
655     {
656       /* Set sequencer scan length by clearing ranks above rank 1             */
657       /* and do not modify rank 1 value.                                      */
658       SET_BIT(hadc->Instance->CHSELR,
659               ADC_CHSELR_SQ2_TO_SQ8);
660     }
661     else if (hadc->Init.ScanConvMode == ADC_SCAN_ENABLE)
662     {
663       /* Set ADC group regular sequencer:                                   */
664       /*  - Set ADC group regular sequencer to value memorized              */
665       /*    in HAL ADC handle                                               */
666       /*    Note: This value maybe be initialized at a unknown value,       */
667       /*          therefore after the first call of "HAL_ADC_Init()",       */
668       /*          each rank corresponding to parameter "NbrOfConversion"    */
669       /*          must be set using "HAL_ADC_ConfigChannel()".              */
670       /*  - Set sequencer scan length by clearing ranks above maximum rank  */
671       /*    and do not modify other ranks value.                            */
672       MODIFY_REG(hadc->Instance->CHSELR,
673                   ADC_CHSELR_SQ_ALL,
674                   (ADC_CHSELR_SQ2_TO_SQ8 << (((hadc->Init.NbrOfConversion - 1UL) * ADC_REGULAR_RANK_2) & 0x1FUL)) | (hadc->ADCGroupRegularSequencerRanks)
675                 );
676     }
677 
678     /* Check back that ADC registers have effectively been configured to      */
679     /* ensure of no potential problem of ADC core peripheral clocking.        */
680     if (LL_ADC_GetSamplingTimeCommonChannels(hadc->Instance, LL_ADC_SAMPLINGTIME_COMMON_1)
681         == hadc->Init.SamplingTimeCommon1)
682     {
683       /* Set ADC error code to none */
684       ADC_CLEAR_ERRORCODE(hadc);
685 
686       /* Set the ADC state */
687       ADC_STATE_CLR_SET(hadc->State,
688                         HAL_ADC_STATE_BUSY_INTERNAL,
689                         HAL_ADC_STATE_READY);
690     }
691     else
692     {
693       /* Update ADC state machine to error */
694       ADC_STATE_CLR_SET(hadc->State,
695                         HAL_ADC_STATE_BUSY_INTERNAL,
696                         HAL_ADC_STATE_ERROR_INTERNAL);
697 
698       /* Set ADC error code to ADC peripheral internal error */
699       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
700 
701       tmp_hal_status = HAL_ERROR;
702     }
703 
704   }
705   else
706   {
707     /* Update ADC state machine to error */
708     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
709 
710     tmp_hal_status = HAL_ERROR;
711   }
712 
713   /* Return function status */
714   return tmp_hal_status;
715 }
716 
717 /**
718   * @brief  Deinitialize the ADC peripheral registers to their default reset
719   *         values, with deinitialization of the ADC MSP.
720   * @note   For devices with several ADCs: reset of ADC common registers is done
721   *         only if all ADCs sharing the same common group are disabled.
722   *         (function "HAL_ADC_MspDeInit()" is also called under the same conditions:
723   *         all ADC instances use the same core clock at RCC level, disabling
724   *         the core clock reset all ADC instances).
725   *         If this is not the case, reset of these common parameters reset is
726   *         bypassed without error reporting: it can be the intended behavior in
727   *         case of reset of a single ADC while the other ADCs sharing the same
728   *         common group is still running.
729   * @note   By default, HAL_ADC_DeInit() set ADC in mode deep power-down:
730   *         this saves more power by reducing leakage currents
731   *         and is particularly interesting before entering MCU low-power modes.
732   * @param hadc ADC handle
733   * @retval HAL status
734   */
HAL_ADC_DeInit(ADC_HandleTypeDef * hadc)735 HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc)
736 {
737   HAL_StatusTypeDef tmp_hal_status;
738 
739   /* Check ADC handle */
740   if (hadc == NULL)
741   {
742     return HAL_ERROR;
743   }
744 
745   /* Check the parameters */
746   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
747 
748   /* Set ADC state */
749   SET_BIT(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL);
750 
751   /* Stop potential conversion on going, on regular group */
752   tmp_hal_status = ADC_ConversionStop(hadc);
753 
754   /* Disable ADC peripheral if conversions are effectively stopped */
755   if (tmp_hal_status == HAL_OK)
756   {
757     /* Disable the ADC peripheral */
758     tmp_hal_status = ADC_Disable(hadc);
759 
760     /* Check if ADC is effectively disabled */
761     if (tmp_hal_status == HAL_OK)
762     {
763       /* Change ADC state */
764       hadc->State = HAL_ADC_STATE_READY;
765     }
766 
767     /* Disable ADC internal voltage regulator */
768     LL_ADC_DisableInternalRegulator(hadc->Instance);
769   }
770 
771   /* Note: HAL ADC deInit is done independently of ADC conversion stop        */
772   /*       and disable return status. In case of status fail, attempt to      */
773   /*       perform deinitialization anyway and it is up user code in          */
774   /*       in HAL_ADC_MspDeInit() to reset the ADC peripheral using           */
775   /*       system RCC hard reset.                                             */
776 
777   /* ========== Reset ADC registers ========== */
778 
779   /* Reset register IER */
780   __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_AWD3  | ADC_IT_AWD2 |
781                               ADC_IT_AWD1  | ADC_IT_OVR  |
782                               ADC_IT_EOS   | ADC_IT_EOC  |
783                               ADC_IT_EOSMP | ADC_IT_RDY));
784 
785   /* Reset register ISR */
786   __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD3  | ADC_FLAG_AWD2 |
787                               ADC_FLAG_AWD1  | ADC_FLAG_OVR  |
788                               ADC_FLAG_EOS   | ADC_FLAG_EOC  |
789                               ADC_FLAG_EOSMP | ADC_FLAG_RDY));
790 
791   /* Reset register CR */
792   /* Bits ADC_CR_ADCAL, ADC_CR_ADSTP, ADC_CR_ADSTART are in access mode     */
793   /* "read-set": no direct reset applicable.                                */
794 
795   /* Reset register CFGR1 */
796   hadc->Instance->CFGR1 &= ~(ADC_CFGR1_AWD1CH  | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL | ADC_CFGR1_DISCEN |
797                              ADC_CFGR1_CHSELRMOD | ADC_CFGR1_AUTOFF |
798                              ADC_CFGR1_WAIT    | ADC_CFGR1_CONT   | ADC_CFGR1_OVRMOD  |
799                              ADC_CFGR1_EXTEN   | ADC_CFGR1_EXTSEL | ADC_CFGR1_ALIGN   | ADC_CFGR1_RES    |
800                              ADC_CFGR1_SCANDIR | ADC_CFGR1_DMACFG | ADC_CFGR1_DMAEN);
801 
802   /* Reset register CFGR2 */
803   /* Note: Update of ADC clock mode is conditioned to ADC state disabled:   */
804   /*       already done above.                                              */
805   hadc->Instance->CFGR2 &= ~ADC_CFGR2_CKMODE;
806 
807   /* Reset register SMPR */
808   hadc->Instance->SMPR &= ~ADC_SMPR_SMP1;
809 
810   /* Reset registers AWDxTR */
811   hadc->Instance->AWD1TR &= ~(ADC_AWD1TR_HT1 | ADC_AWD1TR_LT1);
812   hadc->Instance->AWD2TR &= ~(ADC_AWD2TR_HT2 | ADC_AWD2TR_LT2);
813   hadc->Instance->AWD3TR &= ~(ADC_AWD3TR_HT3 | ADC_AWD3TR_LT3);
814 
815   /* Reset register CHSELR */
816   hadc->Instance->CHSELR &= ~(ADC_CHSELR_SQ_ALL);
817 
818   /* Reset register DR */
819   /* bits in access mode read only, no direct reset applicable */
820 
821   /* Reset register CCR */
822   ADC1_COMMON->CCR &= ~(ADC_CCR_TSEN | ADC_CCR_VREFEN | ADC_CCR_PRESC);
823 
824   /* ========== Hard reset ADC peripheral ========== */
825   /* Performs a global reset of the entire ADC peripheral: ADC state is     */
826   /* forced to a similar state after device power-on.                       */
827   /* If needed, copy-paste and uncomment the following reset code into      */
828   /* function "void HAL_ADC_MspDeInit(ADC_HandleTypeDef *hadc)":            */
829   /*                                                                        */
830   /*  __HAL_RCC_ADC1_FORCE_RESET()                                          */
831   /*  __HAL_RCC_ADC1_RELEASE_RESET()                                        */
832 
833 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
834   if (hadc->MspDeInitCallback == NULL)
835   {
836     hadc->MspDeInitCallback = HAL_ADC_MspDeInit; /* Legacy weak MspDeInit  */
837   }
838 
839   /* DeInit the low level hardware */
840   hadc->MspDeInitCallback(hadc);
841 #else
842   /* DeInit the low level hardware */
843   HAL_ADC_MspDeInit(hadc);
844 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
845 
846   /* Reset HAL ADC handle variable */
847   hadc->ADCGroupRegularSequencerRanks = 0x00000000UL;
848 
849   /* Set ADC error code to none */
850   ADC_CLEAR_ERRORCODE(hadc);
851 
852   /* Set ADC state */
853   hadc->State = HAL_ADC_STATE_RESET;
854 
855   /* Process unlocked */
856   __HAL_UNLOCK(hadc);
857 
858   /* Return function status */
859   return tmp_hal_status;
860 }
861 
862 /**
863   * @brief  Initialize the ADC MSP.
864   * @param hadc ADC handle
865   * @retval None
866   */
HAL_ADC_MspInit(ADC_HandleTypeDef * hadc)867 __weak void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc)
868 {
869   /* Prevent unused argument(s) compilation warning */
870   UNUSED(hadc);
871 
872   /* NOTE : This function should not be modified. When the callback is needed,
873             function HAL_ADC_MspInit must be implemented in the user file.
874    */
875 }
876 
877 /**
878   * @brief  DeInitialize the ADC MSP.
879   * @param hadc ADC handle
880   * @note   All ADC instances use the same core clock at RCC level, disabling
881   *         the core clock reset all ADC instances).
882   * @retval None
883   */
HAL_ADC_MspDeInit(ADC_HandleTypeDef * hadc)884 __weak void HAL_ADC_MspDeInit(ADC_HandleTypeDef *hadc)
885 {
886   /* Prevent unused argument(s) compilation warning */
887   UNUSED(hadc);
888 
889   /* NOTE : This function should not be modified. When the callback is needed,
890             function HAL_ADC_MspDeInit must be implemented in the user file.
891    */
892 }
893 
894 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
895 /**
896   * @brief  Register a User ADC Callback
897   *         To be used instead of the weak predefined callback
898   * @param  hadc Pointer to a ADC_HandleTypeDef structure that contains
899   *                the configuration information for the specified ADC.
900   * @param  CallbackID ID of the callback to be registered
901   *         This parameter can be one of the following values:
902   *          @arg @ref HAL_ADC_CONVERSION_COMPLETE_CB_ID      ADC conversion complete callback ID
903   *          @arg @ref HAL_ADC_CONVERSION_HALF_CB_ID          ADC conversion DMA half-transfer callback ID
904   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID    ADC analog watchdog 1 callback ID
905   *          @arg @ref HAL_ADC_ERROR_CB_ID                    ADC error callback ID
906   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID    ADC analog watchdog 2 callback ID
907   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID    ADC analog watchdog 3 callback ID
908   *          @arg @ref HAL_ADC_END_OF_SAMPLING_CB_ID          ADC end of sampling callback ID
909   *          @arg @ref HAL_ADC_MSPINIT_CB_ID                  ADC Msp Init callback ID
910   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID                ADC Msp DeInit callback ID
911   *          @arg @ref HAL_ADC_MSPINIT_CB_ID MspInit callback ID
912   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID MspDeInit callback ID
913   * @param  pCallback pointer to the Callback function
914   * @retval HAL status
915   */
HAL_ADC_RegisterCallback(ADC_HandleTypeDef * hadc,HAL_ADC_CallbackIDTypeDef CallbackID,pADC_CallbackTypeDef pCallback)916 HAL_StatusTypeDef HAL_ADC_RegisterCallback(ADC_HandleTypeDef *hadc, HAL_ADC_CallbackIDTypeDef CallbackID,
917                                            pADC_CallbackTypeDef pCallback)
918 {
919   HAL_StatusTypeDef status = HAL_OK;
920 
921   if (pCallback == NULL)
922   {
923     /* Update the error code */
924     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
925 
926     return HAL_ERROR;
927   }
928 
929   if ((hadc->State & HAL_ADC_STATE_READY) != 0UL)
930   {
931     switch (CallbackID)
932     {
933       case HAL_ADC_CONVERSION_COMPLETE_CB_ID :
934         hadc->ConvCpltCallback = pCallback;
935         break;
936 
937       case HAL_ADC_CONVERSION_HALF_CB_ID :
938         hadc->ConvHalfCpltCallback = pCallback;
939         break;
940 
941       case HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID :
942         hadc->LevelOutOfWindowCallback = pCallback;
943         break;
944 
945       case HAL_ADC_ERROR_CB_ID :
946         hadc->ErrorCallback = pCallback;
947         break;
948 
949       case HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID :
950         hadc->LevelOutOfWindow2Callback = pCallback;
951         break;
952 
953       case HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID :
954         hadc->LevelOutOfWindow3Callback = pCallback;
955         break;
956 
957       case HAL_ADC_END_OF_SAMPLING_CB_ID :
958         hadc->EndOfSamplingCallback = pCallback;
959         break;
960 
961       case HAL_ADC_MSPINIT_CB_ID :
962         hadc->MspInitCallback = pCallback;
963         break;
964 
965       case HAL_ADC_MSPDEINIT_CB_ID :
966         hadc->MspDeInitCallback = pCallback;
967         break;
968 
969       default :
970         /* Update the error code */
971         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
972 
973         /* Return error status */
974         status = HAL_ERROR;
975         break;
976     }
977   }
978   else if (HAL_ADC_STATE_RESET == hadc->State)
979   {
980     switch (CallbackID)
981     {
982       case HAL_ADC_MSPINIT_CB_ID :
983         hadc->MspInitCallback = pCallback;
984         break;
985 
986       case HAL_ADC_MSPDEINIT_CB_ID :
987         hadc->MspDeInitCallback = pCallback;
988         break;
989 
990       default :
991         /* Update the error code */
992         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
993 
994         /* Return error status */
995         status = HAL_ERROR;
996         break;
997     }
998   }
999   else
1000   {
1001     /* Update the error code */
1002     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1003 
1004     /* Return error status */
1005     status =  HAL_ERROR;
1006   }
1007 
1008   return status;
1009 }
1010 
1011 /**
1012   * @brief  Unregister a ADC Callback
1013   *         ADC callback is redirected to the weak predefined callback
1014   * @param  hadc Pointer to a ADC_HandleTypeDef structure that contains
1015   *                the configuration information for the specified ADC.
1016   * @param  CallbackID ID of the callback to be unregistered
1017   *         This parameter can be one of the following values:
1018   *          @arg @ref HAL_ADC_CONVERSION_COMPLETE_CB_ID      ADC conversion complete callback ID
1019   *          @arg @ref HAL_ADC_CONVERSION_HALF_CB_ID          ADC conversion DMA half-transfer callback ID
1020   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID    ADC analog watchdog 1 callback ID
1021   *          @arg @ref HAL_ADC_ERROR_CB_ID                    ADC error callback ID
1022   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID    ADC analog watchdog 2 callback ID
1023   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID    ADC analog watchdog 3 callback ID
1024   *          @arg @ref HAL_ADC_END_OF_SAMPLING_CB_ID          ADC end of sampling callback ID
1025   *          @arg @ref HAL_ADC_MSPINIT_CB_ID                  ADC Msp Init callback ID
1026   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID                ADC Msp DeInit callback ID
1027   *          @arg @ref HAL_ADC_MSPINIT_CB_ID MspInit callback ID
1028   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID MspDeInit callback ID
1029   * @retval HAL status
1030   */
HAL_ADC_UnRegisterCallback(ADC_HandleTypeDef * hadc,HAL_ADC_CallbackIDTypeDef CallbackID)1031 HAL_StatusTypeDef HAL_ADC_UnRegisterCallback(ADC_HandleTypeDef *hadc, HAL_ADC_CallbackIDTypeDef CallbackID)
1032 {
1033   HAL_StatusTypeDef status = HAL_OK;
1034 
1035   if ((hadc->State & HAL_ADC_STATE_READY) != 0)
1036   {
1037     switch (CallbackID)
1038     {
1039       case HAL_ADC_CONVERSION_COMPLETE_CB_ID :
1040         hadc->ConvCpltCallback = HAL_ADC_ConvCpltCallback;
1041         break;
1042 
1043       case HAL_ADC_CONVERSION_HALF_CB_ID :
1044         hadc->ConvHalfCpltCallback = HAL_ADC_ConvHalfCpltCallback;
1045         break;
1046 
1047       case HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID :
1048         hadc->LevelOutOfWindowCallback = HAL_ADC_LevelOutOfWindowCallback;
1049         break;
1050 
1051       case HAL_ADC_ERROR_CB_ID :
1052         hadc->ErrorCallback = HAL_ADC_ErrorCallback;
1053         break;
1054 
1055       case HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID :
1056         hadc->LevelOutOfWindow2Callback = HAL_ADCEx_LevelOutOfWindow2Callback;
1057         break;
1058 
1059       case HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID :
1060         hadc->LevelOutOfWindow3Callback = HAL_ADCEx_LevelOutOfWindow3Callback;
1061         break;
1062 
1063       case HAL_ADC_END_OF_SAMPLING_CB_ID :
1064         hadc->EndOfSamplingCallback = HAL_ADCEx_EndOfSamplingCallback;
1065         break;
1066 
1067       case HAL_ADC_MSPINIT_CB_ID :
1068         hadc->MspInitCallback = HAL_ADC_MspInit; /* Legacy weak MspInit              */
1069         break;
1070 
1071       case HAL_ADC_MSPDEINIT_CB_ID :
1072         hadc->MspDeInitCallback = HAL_ADC_MspDeInit; /* Legacy weak MspDeInit            */
1073         break;
1074 
1075       default :
1076         /* Update the error code */
1077         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1078 
1079         /* Return error status */
1080         status =  HAL_ERROR;
1081         break;
1082     }
1083   }
1084   else if (HAL_ADC_STATE_RESET == hadc->State)
1085   {
1086     switch (CallbackID)
1087     {
1088       case HAL_ADC_MSPINIT_CB_ID :
1089         hadc->MspInitCallback = HAL_ADC_MspInit;                   /* Legacy weak MspInit              */
1090         break;
1091 
1092       case HAL_ADC_MSPDEINIT_CB_ID :
1093         hadc->MspDeInitCallback = HAL_ADC_MspDeInit;               /* Legacy weak MspDeInit            */
1094         break;
1095 
1096       default :
1097         /* Update the error code */
1098         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1099 
1100         /* Return error status */
1101         status =  HAL_ERROR;
1102         break;
1103     }
1104   }
1105   else
1106   {
1107     /* Update the error code */
1108     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1109 
1110     /* Return error status */
1111     status =  HAL_ERROR;
1112   }
1113 
1114   return status;
1115 }
1116 
1117 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1118 
1119 /**
1120   * @}
1121   */
1122 
1123 /** @defgroup ADC_Exported_Functions_Group2 ADC Input and Output operation functions
1124   *  @brief    ADC IO operation functions
1125   *
1126 @verbatim
1127  ===============================================================================
1128                       ##### IO operation functions #####
1129  ===============================================================================
1130     [..]  This section provides functions allowing to:
1131       (+) Start conversion of regular group.
1132       (+) Stop conversion of regular group.
1133       (+) Poll for conversion complete on regular group.
1134       (+) Poll for conversion event.
1135       (+) Get result of regular channel conversion.
1136       (+) Start conversion of regular group and enable interruptions.
1137       (+) Stop conversion of regular group and disable interruptions.
1138       (+) Handle ADC interrupt request
1139       (+) Start conversion of regular group and enable DMA transfer.
1140       (+) Stop conversion of regular group and disable ADC DMA transfer.
1141 @endverbatim
1142   * @{
1143   */
1144 
1145 /**
1146   * @brief  Enable ADC, start conversion of regular group.
1147   * @note   Interruptions enabled in this function: None.
1148   * @param hadc ADC handle
1149   * @retval HAL status
1150   */
HAL_ADC_Start(ADC_HandleTypeDef * hadc)1151 HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef *hadc)
1152 {
1153   HAL_StatusTypeDef tmp_hal_status;
1154 
1155   /* Check the parameters */
1156   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1157 
1158   /* Perform ADC enable and conversion start if no conversion is on going */
1159   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1160   {
1161     /* Process locked */
1162     __HAL_LOCK(hadc);
1163 
1164     /* Enable the ADC peripheral */
1165     tmp_hal_status = ADC_Enable(hadc);
1166 
1167     /* Start conversion if ADC is effectively enabled */
1168     if (tmp_hal_status == HAL_OK)
1169     {
1170       /* Set ADC state                                                        */
1171       /* - Clear state bitfield related to regular group conversion results   */
1172       /* - Set state bitfield related to regular operation                    */
1173       ADC_STATE_CLR_SET(hadc->State,
1174                         HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
1175                         HAL_ADC_STATE_REG_BUSY);
1176 
1177       /* Set ADC error code */
1178       /* Reset all ADC error code fields */
1179       ADC_CLEAR_ERRORCODE(hadc);
1180 
1181       /* Clear ADC group regular conversion flag and overrun flag               */
1182       /* (To ensure of no unknown state from potential previous ADC operations) */
1183       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
1184 
1185       /* Process unlocked */
1186       /* Unlock before starting ADC conversions: in case of potential         */
1187       /* interruption, to let the process to ADC IRQ Handler.                 */
1188       __HAL_UNLOCK(hadc);
1189 
1190       /* Enable conversion of regular group.                                  */
1191       /* If software start has been selected, conversion starts immediately.  */
1192       /* If external trigger has been selected, conversion will start at next */
1193       /* trigger event.                                                       */
1194       /* Start ADC group regular conversion */
1195       LL_ADC_REG_StartConversion(hadc->Instance);
1196     }
1197     else
1198     {
1199       /* Process unlocked */
1200       __HAL_UNLOCK(hadc);
1201     }
1202   }
1203   else
1204   {
1205     tmp_hal_status = HAL_BUSY;
1206   }
1207 
1208   /* Return function status */
1209   return tmp_hal_status;
1210 }
1211 
1212 /**
1213   * @brief  Stop ADC conversion of regular group (and injected channels in
1214   *         case of auto_injection mode), disable ADC peripheral.
1215   * @note:  ADC peripheral disable is forcing stop of potential
1216   *         conversion on injected group. If injected group is under use, it
1217   *         should be preliminarily stopped using HAL_ADCEx_InjectedStop function.
1218   * @param hadc ADC handle
1219   * @retval HAL status.
1220   */
HAL_ADC_Stop(ADC_HandleTypeDef * hadc)1221 HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef *hadc)
1222 {
1223   HAL_StatusTypeDef tmp_hal_status;
1224 
1225   /* Check the parameters */
1226   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1227 
1228   /* Process locked */
1229   __HAL_LOCK(hadc);
1230 
1231   /* 1. Stop potential conversion on going, on ADC group regular */
1232   tmp_hal_status = ADC_ConversionStop(hadc);
1233 
1234   /* Disable ADC peripheral if conversions are effectively stopped */
1235   if (tmp_hal_status == HAL_OK)
1236   {
1237     /* 2. Disable the ADC peripheral */
1238     tmp_hal_status = ADC_Disable(hadc);
1239 
1240     /* Check if ADC is effectively disabled */
1241     if (tmp_hal_status == HAL_OK)
1242     {
1243       /* Set ADC state */
1244       ADC_STATE_CLR_SET(hadc->State,
1245                         HAL_ADC_STATE_REG_BUSY,
1246                         HAL_ADC_STATE_READY);
1247     }
1248   }
1249 
1250   /* Process unlocked */
1251   __HAL_UNLOCK(hadc);
1252 
1253   /* Return function status */
1254   return tmp_hal_status;
1255 }
1256 
1257 /**
1258   * @brief  Wait for regular group conversion to be completed.
1259   * @note   ADC conversion flags EOS (end of sequence) and EOC (end of
1260   *         conversion) are cleared by this function, with an exception:
1261   *         if low power feature "LowPowerAutoWait" is enabled, flags are
1262   *         not cleared to not interfere with this feature until data register
1263   *         is read using function HAL_ADC_GetValue().
1264   * @note   This function cannot be used in a particular setup: ADC configured
1265   *         in DMA mode and polling for end of each conversion (ADC init
1266   *         parameter "EOCSelection" set to ADC_EOC_SINGLE_CONV).
1267   *         In this case, DMA resets the flag EOC and polling cannot be
1268   *         performed on each conversion. Nevertheless, polling can still
1269   *         be performed on the complete sequence (ADC init
1270   *         parameter "EOCSelection" set to ADC_EOC_SEQ_CONV).
1271   * @param hadc ADC handle
1272   * @param Timeout Timeout value in millisecond.
1273   * @retval HAL status
1274   */
HAL_ADC_PollForConversion(ADC_HandleTypeDef * hadc,uint32_t Timeout)1275 HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef *hadc, uint32_t Timeout)
1276 {
1277   uint32_t tickstart;
1278   uint32_t tmp_Flag_End;
1279 
1280   /* Check the parameters */
1281   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1282 
1283   /* If end of conversion selected to end of sequence conversions */
1284   if (hadc->Init.EOCSelection == ADC_EOC_SEQ_CONV)
1285   {
1286     tmp_Flag_End = ADC_FLAG_EOS;
1287   }
1288   /* If end of conversion selected to end of unitary conversion */
1289   else /* ADC_EOC_SINGLE_CONV */
1290   {
1291     /* Verification that ADC configuration is compliant with polling for      */
1292     /* each conversion:                                                       */
1293     /* Particular case is ADC configured in DMA mode and ADC sequencer with   */
1294     /* several ranks and polling for end of each conversion.                  */
1295     /* For code simplicity sake, this particular case is generalized to       */
1296     /* ADC configured in DMA mode and and polling for end of each conversion. */
1297     if ((hadc->Instance->CFGR1 & ADC_CFGR1_DMAEN) != 0UL)
1298     {
1299       /* Update ADC state machine to error */
1300       SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1301 
1302       return HAL_ERROR;
1303     }
1304     else
1305     {
1306       tmp_Flag_End = (ADC_FLAG_EOC);
1307     }
1308   }
1309 
1310   /* Get tick count */
1311   tickstart = HAL_GetTick();
1312 
1313   /* Wait until End of unitary conversion or sequence conversions flag is raised */
1314   while ((hadc->Instance->ISR & tmp_Flag_End) == 0UL)
1315   {
1316     /* Check if timeout is disabled (set to infinite wait) */
1317     if (Timeout != HAL_MAX_DELAY)
1318     {
1319       if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
1320       {
1321         /* Update ADC state machine to timeout */
1322         SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
1323 
1324         /* Process unlocked */
1325         __HAL_UNLOCK(hadc);
1326 
1327         return HAL_TIMEOUT;
1328       }
1329     }
1330   }
1331 
1332   /* Update ADC state machine */
1333   SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
1334 
1335   /* Determine whether any further conversion upcoming on group regular       */
1336   /* by external trigger, continuous mode or scan sequence on going.          */
1337   if ((LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
1338       && (hadc->Init.ContinuousConvMode == DISABLE)
1339      )
1340   {
1341     /* Check whether end of sequence is reached */
1342     if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS))
1343     {
1344       /* Allowed to modify bits ADC_IT_EOC/ADC_IT_EOS only if bit             */
1345       /* ADSTART==0 (no conversion on going)                                  */
1346       if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1347       {
1348         /* Disable ADC end of single conversion interrupt on group regular */
1349         /* Note: Overrun interrupt was enabled with EOC interrupt in          */
1350         /* HAL_Start_IT(), but is not disabled here because can be used       */
1351         /* by overrun IRQ process below.                                      */
1352         __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_EOS);
1353 
1354         /* Set ADC state */
1355         ADC_STATE_CLR_SET(hadc->State,
1356                           HAL_ADC_STATE_REG_BUSY,
1357                           HAL_ADC_STATE_READY);
1358       }
1359       else
1360       {
1361         /* Change ADC state to error state */
1362         SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1363 
1364         /* Set ADC error code to ADC peripheral internal error */
1365         SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
1366       }
1367     }
1368   }
1369 
1370   /* Clear end of conversion flag of regular group if low power feature       */
1371   /* "LowPowerAutoWait " is disabled, to not interfere with this feature      */
1372   /* until data register is read using function HAL_ADC_GetValue().           */
1373   if (hadc->Init.LowPowerAutoWait == DISABLE)
1374   {
1375     /* Clear regular group conversion flag */
1376     __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS));
1377   }
1378 
1379   /* Return function status */
1380   return HAL_OK;
1381 }
1382 
1383 /**
1384   * @brief  Poll for ADC event.
1385   * @param hadc ADC handle
1386   * @param EventType the ADC event type.
1387   *          This parameter can be one of the following values:
1388   *            @arg @ref ADC_EOSMP_EVENT  ADC End of Sampling event
1389   *            @arg @ref ADC_AWD1_EVENT   ADC Analog watchdog 1 event (main analog watchdog, present on all STM32 devices)
1390   *            @arg @ref ADC_AWD2_EVENT   ADC Analog watchdog 2 event (additional analog watchdog, not present on all STM32 families)
1391   *            @arg @ref ADC_AWD3_EVENT   ADC Analog watchdog 3 event (additional analog watchdog, not present on all STM32 families)
1392   *            @arg @ref ADC_OVR_EVENT    ADC Overrun event
1393   * @param Timeout Timeout value in millisecond.
1394   * @note   The relevant flag is cleared if found to be set, except for ADC_FLAG_OVR.
1395   *         Indeed, the latter is reset only if hadc->Init.Overrun field is set
1396   *         to ADC_OVR_DATA_OVERWRITTEN. Otherwise, data register may be potentially overwritten
1397   *         by a new converted data as soon as OVR is cleared.
1398   *         To reset OVR flag once the preserved data is retrieved, the user can resort
1399   *         to macro __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1400   * @retval HAL status
1401   */
HAL_ADC_PollForEvent(ADC_HandleTypeDef * hadc,uint32_t EventType,uint32_t Timeout)1402 HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef *hadc, uint32_t EventType, uint32_t Timeout)
1403 {
1404   uint32_t tickstart;
1405 
1406   /* Check the parameters */
1407   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1408   assert_param(IS_ADC_EVENT_TYPE(EventType));
1409 
1410   /* Get tick count */
1411   tickstart = HAL_GetTick();
1412 
1413   /* Check selected event flag */
1414   while (__HAL_ADC_GET_FLAG(hadc, EventType) == 0UL)
1415   {
1416     /* Check if timeout is disabled (set to infinite wait) */
1417     if (Timeout != HAL_MAX_DELAY)
1418     {
1419       if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
1420       {
1421         /* Update ADC state machine to timeout */
1422         SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
1423 
1424         /* Process unlocked */
1425         __HAL_UNLOCK(hadc);
1426 
1427         return HAL_TIMEOUT;
1428       }
1429     }
1430   }
1431 
1432   switch (EventType)
1433   {
1434     /* End Of Sampling event */
1435     case ADC_EOSMP_EVENT:
1436       /* Set ADC state */
1437       SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOSMP);
1438 
1439       /* Clear the End Of Sampling flag */
1440       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP);
1441 
1442       break;
1443 
1444     /* Analog watchdog (level out of window) event */
1445     /* Note: In case of several analog watchdog enabled, if needed to know      */
1446     /* which one triggered and on which ADCx, test ADC state of analog watchdog */
1447     /* flags HAL_ADC_STATE_AWD1/2/3 using function "HAL_ADC_GetState()".        */
1448     /* For example:                                                             */
1449     /*  " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD1) != 0UL) "          */
1450     /*  " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD2) != 0UL) "          */
1451     /*  " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD3) != 0UL) "          */
1452 
1453     /* Check analog watchdog 1 flag */
1454     case ADC_AWD_EVENT:
1455       /* Set ADC state */
1456       SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
1457 
1458       /* Clear ADC analog watchdog flag */
1459       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD1);
1460 
1461       break;
1462 
1463     /* Check analog watchdog 2 flag */
1464     case ADC_AWD2_EVENT:
1465       /* Set ADC state */
1466       SET_BIT(hadc->State, HAL_ADC_STATE_AWD2);
1467 
1468       /* Clear ADC analog watchdog flag */
1469       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD2);
1470 
1471       break;
1472 
1473     /* Check analog watchdog 3 flag */
1474     case ADC_AWD3_EVENT:
1475       /* Set ADC state */
1476       SET_BIT(hadc->State, HAL_ADC_STATE_AWD3);
1477 
1478       /* Clear ADC analog watchdog flag */
1479       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD3);
1480 
1481       break;
1482 
1483     /* Overrun event */
1484     default: /* Case ADC_OVR_EVENT */
1485       /* If overrun is set to overwrite previous data, overrun event is not     */
1486       /* considered as an error.                                                */
1487       /* (cf ref manual "Managing conversions without using the DMA and without */
1488       /* overrun ")                                                             */
1489       if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
1490       {
1491         /* Set ADC state */
1492         SET_BIT(hadc->State, HAL_ADC_STATE_REG_OVR);
1493 
1494         /* Set ADC error code to overrun */
1495         SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_OVR);
1496       }
1497       else
1498       {
1499         /* Clear ADC Overrun flag only if Overrun is set to ADC_OVR_DATA_OVERWRITTEN
1500            otherwise, data register is potentially overwritten by new converted data as soon
1501            as OVR is cleared. */
1502         __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1503       }
1504       break;
1505   }
1506 
1507   /* Return function status */
1508   return HAL_OK;
1509 }
1510 
1511 /**
1512   * @brief  Enable ADC, start conversion of regular group with interruption.
1513   * @note   Interruptions enabled in this function according to initialization
1514   *         setting : EOC (end of conversion), EOS (end of sequence),
1515   *         OVR overrun.
1516   *         Each of these interruptions has its dedicated callback function.
1517   * @note   To guarantee a proper reset of all interruptions once all the needed
1518   *         conversions are obtained, HAL_ADC_Stop_IT() must be called to ensure
1519   *         a correct stop of the IT-based conversions.
1520   * @note   By default, HAL_ADC_Start_IT() does not enable the End Of Sampling
1521   *         interruption. If required (e.g. in case of oversampling with trigger
1522   *         mode), the user must:
1523   *          1. first clear the EOSMP flag if set with macro __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP)
1524   *          2. then enable the EOSMP interrupt with macro __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOSMP)
1525   *          before calling HAL_ADC_Start_IT().
1526   * @param hadc ADC handle
1527   * @retval HAL status
1528   */
HAL_ADC_Start_IT(ADC_HandleTypeDef * hadc)1529 HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef *hadc)
1530 {
1531   HAL_StatusTypeDef tmp_hal_status;
1532 
1533   /* Check the parameters */
1534   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1535 
1536   /* Perform ADC enable and conversion start if no conversion is on going */
1537   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1538   {
1539     /* Process locked */
1540     __HAL_LOCK(hadc);
1541 
1542     /* Enable the ADC peripheral */
1543     tmp_hal_status = ADC_Enable(hadc);
1544 
1545     /* Start conversion if ADC is effectively enabled */
1546     if (tmp_hal_status == HAL_OK)
1547     {
1548       /* Set ADC state                                                        */
1549       /* - Clear state bitfield related to regular group conversion results   */
1550       /* - Set state bitfield related to regular operation                    */
1551       ADC_STATE_CLR_SET(hadc->State,
1552                         HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
1553                         HAL_ADC_STATE_REG_BUSY);
1554 
1555 
1556       /* Set ADC error code */
1557       /* Reset all ADC error code fields */
1558       ADC_CLEAR_ERRORCODE(hadc);
1559 
1560       /* Clear ADC group regular conversion flag and overrun flag               */
1561       /* (To ensure of no unknown state from potential previous ADC operations) */
1562       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
1563 
1564       /* Process unlocked */
1565       /* Unlock before starting ADC conversions: in case of potential         */
1566       /* interruption, to let the process to ADC IRQ Handler.                 */
1567       __HAL_UNLOCK(hadc);
1568 
1569       /* Disable all interruptions before enabling the desired ones */
1570       __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR));
1571 
1572       /* Enable ADC end of conversion interrupt */
1573       switch (hadc->Init.EOCSelection)
1574       {
1575         case ADC_EOC_SEQ_CONV:
1576           __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOS);
1577           break;
1578         /* case ADC_EOC_SINGLE_CONV */
1579         default:
1580           __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOC);
1581           break;
1582       }
1583 
1584       /* Enable ADC overrun interrupt */
1585       /* If hadc->Init.Overrun is set to ADC_OVR_DATA_PRESERVED, only then is
1586          ADC_IT_OVR enabled; otherwise data overwrite is considered as normal
1587          behavior and no CPU time is lost for a non-processed interruption */
1588       if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
1589       {
1590         __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
1591       }
1592 
1593       /* Enable conversion of regular group.                                  */
1594       /* If software start has been selected, conversion starts immediately.  */
1595       /* If external trigger has been selected, conversion will start at next */
1596       /* trigger event.                                                       */
1597       /* Start ADC group regular conversion */
1598       LL_ADC_REG_StartConversion(hadc->Instance);
1599     }
1600     else
1601     {
1602       /* Process unlocked */
1603       __HAL_UNLOCK(hadc);
1604     }
1605 
1606   }
1607   else
1608   {
1609     tmp_hal_status = HAL_BUSY;
1610   }
1611 
1612   /* Return function status */
1613   return tmp_hal_status;
1614 }
1615 
1616 /**
1617   * @brief  Stop ADC conversion of regular group (and injected group in
1618   *         case of auto_injection mode), disable interrution of
1619   *         end-of-conversion, disable ADC peripheral.
1620   * @param hadc ADC handle
1621   * @retval HAL status.
1622   */
HAL_ADC_Stop_IT(ADC_HandleTypeDef * hadc)1623 HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef *hadc)
1624 {
1625   HAL_StatusTypeDef tmp_hal_status;
1626 
1627   /* Check the parameters */
1628   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1629 
1630   /* Process locked */
1631   __HAL_LOCK(hadc);
1632 
1633   /* 1. Stop potential conversion on going, on ADC group regular */
1634   tmp_hal_status = ADC_ConversionStop(hadc);
1635 
1636   /* Disable ADC peripheral if conversions are effectively stopped */
1637   if (tmp_hal_status == HAL_OK)
1638   {
1639     /* Disable ADC end of conversion interrupt for regular group */
1640     /* Disable ADC overrun interrupt */
1641     __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR));
1642 
1643     /* 2. Disable the ADC peripheral */
1644     tmp_hal_status = ADC_Disable(hadc);
1645 
1646     /* Check if ADC is effectively disabled */
1647     if (tmp_hal_status == HAL_OK)
1648     {
1649       /* Set ADC state */
1650       ADC_STATE_CLR_SET(hadc->State,
1651                         HAL_ADC_STATE_REG_BUSY,
1652                         HAL_ADC_STATE_READY);
1653     }
1654   }
1655 
1656   /* Process unlocked */
1657   __HAL_UNLOCK(hadc);
1658 
1659   /* Return function status */
1660   return tmp_hal_status;
1661 }
1662 
1663 /**
1664   * @brief  Enable ADC, start conversion of regular group and transfer result through DMA.
1665   * @note   Interruptions enabled in this function:
1666   *         overrun (if applicable), DMA half transfer, DMA transfer complete.
1667   *         Each of these interruptions has its dedicated callback function.
1668   * @param hadc ADC handle
1669   * @param pData Destination Buffer address.
1670   * @param Length Number of data to be transferred from ADC peripheral to memory
1671   * @retval HAL status.
1672   */
HAL_ADC_Start_DMA(ADC_HandleTypeDef * hadc,uint32_t * pData,uint32_t Length)1673 HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef *hadc, uint32_t *pData, uint32_t Length)
1674 {
1675   HAL_StatusTypeDef tmp_hal_status;
1676 
1677   /* Check the parameters */
1678   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1679 
1680   /* Perform ADC enable and conversion start if no conversion is on going */
1681   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1682   {
1683     /* Process locked */
1684     __HAL_LOCK(hadc);
1685 
1686     /* Specific case for first call occurrence of this function (DMA transfer */
1687     /* not activated and ADC disabled), DMA transfer must be activated        */
1688     /* with ADC disabled.                                                     */
1689     if ((hadc->Instance->CFGR1 & ADC_CFGR1_DMAEN) == 0UL)
1690     {
1691       if (LL_ADC_IsEnabled(hadc->Instance) != 0UL)
1692       {
1693         /* Disable ADC */
1694         LL_ADC_Disable(hadc->Instance);
1695       }
1696 
1697       /* Enable ADC DMA mode */
1698       hadc->Instance->CFGR1 |= ADC_CFGR1_DMAEN;
1699     }
1700 
1701     /* Enable the ADC peripheral */
1702     tmp_hal_status = ADC_Enable(hadc);
1703 
1704     /* Start conversion if ADC is effectively enabled */
1705     if (tmp_hal_status == HAL_OK)
1706     {
1707       /* Set ADC state                                                        */
1708       /* - Clear state bitfield related to regular group conversion results   */
1709       /* - Set state bitfield related to regular operation                    */
1710       ADC_STATE_CLR_SET(hadc->State,
1711                         HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
1712                         HAL_ADC_STATE_REG_BUSY);
1713 
1714       /* Set ADC error code */
1715       /* Reset all ADC error code fields */
1716       ADC_CLEAR_ERRORCODE(hadc);
1717 
1718       /* Set the DMA transfer complete callback */
1719       hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt;
1720 
1721       /* Set the DMA half transfer complete callback */
1722       hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt;
1723 
1724       /* Set the DMA error callback */
1725       hadc->DMA_Handle->XferErrorCallback = ADC_DMAError;
1726 
1727 
1728       /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC   */
1729       /* start (in case of SW start):                                         */
1730 
1731       /* Clear regular group conversion flag and overrun flag */
1732       /* (To ensure of no unknown state from potential previous ADC           */
1733       /* operations)                                                          */
1734       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
1735 
1736       /* Process unlocked */
1737       /* Unlock before starting ADC conversions: in case of potential         */
1738       /* interruption, to let the process to ADC IRQ Handler.                 */
1739       __HAL_UNLOCK(hadc);
1740 
1741       /* Enable ADC overrun interrupt */
1742       __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
1743 
1744       /* Start the DMA channel */
1745       tmp_hal_status = HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->DR, (uint32_t)pData, Length);
1746 
1747       /* Enable conversion of regular group.                                  */
1748       /* If software start has been selected, conversion starts immediately.  */
1749       /* If external trigger has been selected, conversion will start at next */
1750       /* trigger event.                                                       */
1751       /* Start ADC group regular conversion */
1752       LL_ADC_REG_StartConversion(hadc->Instance);
1753     }
1754   }
1755   else
1756   {
1757     tmp_hal_status = HAL_BUSY;
1758   }
1759 
1760   /* Return function status */
1761   return tmp_hal_status;
1762 }
1763 
1764 /**
1765   * @brief  Stop ADC conversion of regular group (and injected group in
1766   *         case of auto_injection mode), disable ADC DMA transfer, disable
1767   *         ADC peripheral.
1768   * @param hadc ADC handle
1769   * @retval HAL status.
1770   */
HAL_ADC_Stop_DMA(ADC_HandleTypeDef * hadc)1771 HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef *hadc)
1772 {
1773   HAL_StatusTypeDef tmp_hal_status;
1774 
1775   /* Check the parameters */
1776   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1777 
1778   /* Process locked */
1779   __HAL_LOCK(hadc);
1780 
1781   /* 1. Stop potential ADC group regular conversion on going */
1782   tmp_hal_status = ADC_ConversionStop(hadc);
1783 
1784   /* Disable ADC peripheral if conversions are effectively stopped */
1785   if (tmp_hal_status == HAL_OK)
1786   {
1787     /* Disable the DMA channel (in case of DMA in circular mode or stop       */
1788     /* while DMA transfer is on going)                                        */
1789     if (hadc->DMA_Handle->State == HAL_DMA_STATE_BUSY)
1790     {
1791       tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle);
1792 
1793       /* Check if DMA channel effectively disabled */
1794       if (tmp_hal_status != HAL_OK)
1795       {
1796         /* Update ADC state machine to error */
1797         SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
1798       }
1799     }
1800 
1801     /* Disable ADC overrun interrupt */
1802     __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
1803 
1804     /* 2. Disable the ADC peripheral */
1805     /* Update "tmp_hal_status" only if DMA channel disabling passed,          */
1806     /* to keep in memory a potential failing status.                          */
1807     if (tmp_hal_status == HAL_OK)
1808     {
1809       tmp_hal_status = ADC_Disable(hadc);
1810     }
1811     else
1812     {
1813       (void)ADC_Disable(hadc);
1814     }
1815 
1816     /* Check if ADC is effectively disabled */
1817     if (tmp_hal_status == HAL_OK)
1818     {
1819       /* Set ADC state */
1820       ADC_STATE_CLR_SET(hadc->State,
1821                         HAL_ADC_STATE_REG_BUSY,
1822                         HAL_ADC_STATE_READY);
1823     }
1824 
1825     /* Disable ADC DMA (ADC DMA configuration of continuous requests is kept) */
1826     CLEAR_BIT(hadc->Instance->CFGR1, ADC_CFGR1_DMAEN);
1827   }
1828 
1829   /* Process unlocked */
1830   __HAL_UNLOCK(hadc);
1831 
1832   /* Return function status */
1833   return tmp_hal_status;
1834 }
1835 
1836 /**
1837   * @brief  Get ADC regular group conversion result.
1838   * @note   Reading register DR automatically clears ADC flag EOC
1839   *         (ADC group regular end of unitary conversion).
1840   * @note   This function does not clear ADC flag EOS
1841   *         (ADC group regular end of sequence conversion).
1842   *         Occurrence of flag EOS rising:
1843   *          - If sequencer is composed of 1 rank, flag EOS is equivalent
1844   *            to flag EOC.
1845   *          - If sequencer is composed of several ranks, during the scan
1846   *            sequence flag EOC only is raised, at the end of the scan sequence
1847   *            both flags EOC and EOS are raised.
1848   *         To clear this flag, either use function:
1849   *         in programming model IT: @ref HAL_ADC_IRQHandler(), in programming
1850   *         model polling: @ref HAL_ADC_PollForConversion()
1851   *         or @ref __HAL_ADC_CLEAR_FLAG(&hadc, ADC_FLAG_EOS).
1852   * @param hadc ADC handle
1853   * @retval ADC group regular conversion data
1854   */
HAL_ADC_GetValue(ADC_HandleTypeDef * hadc)1855 uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef *hadc)
1856 {
1857   /* Check the parameters */
1858   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1859 
1860   /* Note: EOC flag is not cleared here by software because automatically     */
1861   /*       cleared by hardware when reading register DR.                      */
1862 
1863   /* Return ADC converted value */
1864   return hadc->Instance->DR;
1865 }
1866 
1867 /**
1868   * @brief  Handle ADC interrupt request.
1869   * @param hadc ADC handle
1870   * @retval None
1871   */
HAL_ADC_IRQHandler(ADC_HandleTypeDef * hadc)1872 void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc)
1873 {
1874   uint32_t overrun_error = 0UL; /* flag set if overrun occurrence has to be considered as an error */
1875   uint32_t tmp_isr = hadc->Instance->ISR;
1876   uint32_t tmp_ier = hadc->Instance->IER;
1877 
1878   /* Check the parameters */
1879   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1880   assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection));
1881 
1882   /* ========== Check End of Sampling flag for ADC group regular ========== */
1883   if (((tmp_isr & ADC_FLAG_EOSMP) == ADC_FLAG_EOSMP) && ((tmp_ier & ADC_IT_EOSMP) == ADC_IT_EOSMP))
1884   {
1885     /* Update state machine on end of sampling status if not in error state */
1886     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
1887     {
1888       /* Set ADC state */
1889       SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOSMP);
1890     }
1891 
1892     /* End Of Sampling callback */
1893 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
1894     hadc->EndOfSamplingCallback(hadc);
1895 #else
1896     HAL_ADCEx_EndOfSamplingCallback(hadc);
1897 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1898 
1899     /* Clear regular group conversion flag */
1900     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP);
1901   }
1902 
1903   /* ====== Check ADC group regular end of unitary conversion sequence conversions ===== */
1904   if ((((tmp_isr & ADC_FLAG_EOC) == ADC_FLAG_EOC) && ((tmp_ier & ADC_IT_EOC) == ADC_IT_EOC)) ||
1905       (((tmp_isr & ADC_FLAG_EOS) == ADC_FLAG_EOS) && ((tmp_ier & ADC_IT_EOS) == ADC_IT_EOS)))
1906   {
1907     /* Update state machine on conversion status if not in error state */
1908     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
1909     {
1910       /* Set ADC state */
1911       SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
1912     }
1913 
1914     /* Determine whether any further conversion upcoming on group regular     */
1915     /* by external trigger, continuous mode or scan sequence on going         */
1916     /* to disable interruption.                                               */
1917     if ((LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
1918         && (hadc->Init.ContinuousConvMode == DISABLE)
1919        )
1920     {
1921       /* If End of Sequence is reached, disable interrupts */
1922       if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS))
1923       {
1924         /* Allowed to modify bits ADC_IT_EOC/ADC_IT_EOS only if bit           */
1925         /* ADSTART==0 (no conversion on going)                                */
1926         if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1927         {
1928           /* Disable ADC end of single conversion interrupt on group regular */
1929           /* Note: Overrun interrupt was enabled with EOC interrupt in        */
1930           /* HAL_Start_IT(), but is not disabled here because can be used     */
1931           /* by overrun IRQ process below.                                    */
1932           __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_EOS);
1933 
1934           /* Set ADC state */
1935           ADC_STATE_CLR_SET(hadc->State,
1936                             HAL_ADC_STATE_REG_BUSY,
1937                             HAL_ADC_STATE_READY);
1938         }
1939         else
1940         {
1941           /* Change ADC state to error state */
1942           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1943 
1944           /* Set ADC error code to ADC peripheral internal error */
1945           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
1946         }
1947       }
1948     }
1949 
1950     /* Conversion complete callback */
1951     /* Note: Into callback function "HAL_ADC_ConvCpltCallback()",             */
1952     /*       to determine if conversion has been triggered from EOC or EOS,   */
1953     /*       possibility to use:                                              */
1954     /*        " if ( __HAL_ADC_GET_FLAG(&hadc, ADC_FLAG_EOS)) "               */
1955 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
1956     hadc->ConvCpltCallback(hadc);
1957 #else
1958     HAL_ADC_ConvCpltCallback(hadc);
1959 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1960 
1961     /* Clear regular group conversion flag */
1962     /* Note: in case of overrun set to ADC_OVR_DATA_PRESERVED, end of         */
1963     /*       conversion flags clear induces the release of the preserved data.*/
1964     /*       Therefore, if the preserved data value is needed, it must be     */
1965     /*       read preliminarily into HAL_ADC_ConvCpltCallback().              */
1966     __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS));
1967   }
1968 
1969   /* ========== Check Analog watchdog 1 flag ========== */
1970   if (((tmp_isr & ADC_FLAG_AWD1) == ADC_FLAG_AWD1) && ((tmp_ier & ADC_IT_AWD1) == ADC_IT_AWD1))
1971   {
1972     /* Set ADC state */
1973     SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
1974 
1975     /* Level out of window 1 callback */
1976 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
1977     hadc->LevelOutOfWindowCallback(hadc);
1978 #else
1979     HAL_ADC_LevelOutOfWindowCallback(hadc);
1980 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1981 
1982     /* Clear ADC analog watchdog flag */
1983     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD1);
1984   }
1985 
1986   /* ========== Check analog watchdog 2 flag ========== */
1987   if (((tmp_isr & ADC_FLAG_AWD2) == ADC_FLAG_AWD2) && ((tmp_ier & ADC_IT_AWD2) == ADC_IT_AWD2))
1988   {
1989     /* Set ADC state */
1990     SET_BIT(hadc->State, HAL_ADC_STATE_AWD2);
1991 
1992     /* Level out of window 2 callback */
1993 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
1994     hadc->LevelOutOfWindow2Callback(hadc);
1995 #else
1996     HAL_ADCEx_LevelOutOfWindow2Callback(hadc);
1997 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1998 
1999     /* Clear ADC analog watchdog flag */
2000     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD2);
2001   }
2002 
2003   /* ========== Check analog watchdog 3 flag ========== */
2004   if (((tmp_isr & ADC_FLAG_AWD3) == ADC_FLAG_AWD3) && ((tmp_ier & ADC_IT_AWD3) == ADC_IT_AWD3))
2005   {
2006     /* Set ADC state */
2007     SET_BIT(hadc->State, HAL_ADC_STATE_AWD3);
2008 
2009     /* Level out of window 3 callback */
2010 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2011     hadc->LevelOutOfWindow3Callback(hadc);
2012 #else
2013     HAL_ADCEx_LevelOutOfWindow3Callback(hadc);
2014 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2015 
2016     /* Clear ADC analog watchdog flag */
2017     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD3);
2018   }
2019   /* ========== Check Overrun flag ========== */
2020   if (((tmp_isr & ADC_FLAG_OVR) == ADC_FLAG_OVR) && ((tmp_ier & ADC_IT_OVR) == ADC_IT_OVR))
2021   {
2022     /* If overrun is set to overwrite previous data (default setting),        */
2023     /* overrun event is not considered as an error.                           */
2024     /* (cf ref manual "Managing conversions without using the DMA and without */
2025     /* overrun ")                                                             */
2026     /* Exception for usage with DMA overrun event always considered as an     */
2027     /* error.                                                                 */
2028     if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
2029     {
2030       overrun_error = 1UL;
2031     }
2032     else
2033     {
2034       /* Check DMA configuration */
2035       if (LL_ADC_REG_GetDMATransfer(hadc->Instance) != LL_ADC_REG_DMA_TRANSFER_NONE)
2036       {
2037         overrun_error = 1UL;
2038       }
2039     }
2040 
2041     if (overrun_error == 1UL)
2042     {
2043       /* Change ADC state to error state */
2044       SET_BIT(hadc->State, HAL_ADC_STATE_REG_OVR);
2045 
2046       /* Set ADC error code to overrun */
2047       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_OVR);
2048 
2049       /* Error callback */
2050       /* Note: In case of overrun, ADC conversion data is preserved until     */
2051       /*       flag OVR is reset.                                             */
2052       /*       Therefore, old ADC conversion data can be retrieved in         */
2053       /*       function "HAL_ADC_ErrorCallback()".                            */
2054 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2055       hadc->ErrorCallback(hadc);
2056 #else
2057       HAL_ADC_ErrorCallback(hadc);
2058 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2059     }
2060 
2061     /* Clear ADC overrun flag */
2062     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
2063   }
2064 
2065   /* ========== Check channel configuration ready flag ========== */
2066   if (((tmp_isr & ADC_FLAG_CCRDY) == ADC_FLAG_CCRDY) && ((tmp_ier & ADC_IT_CCRDY) == ADC_IT_CCRDY))
2067   {
2068     /* Level out of window 1 callback */
2069     HAL_ADCEx_ChannelConfigReadyCallback(hadc);
2070 
2071     /* Clear ADC analog watchdog flag */
2072     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_CCRDY);
2073   }
2074 }
2075 
2076 /**
2077   * @brief  Conversion complete callback in non-blocking mode.
2078   * @param hadc ADC handle
2079   * @retval None
2080   */
HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef * hadc)2081 __weak void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
2082 {
2083   /* Prevent unused argument(s) compilation warning */
2084   UNUSED(hadc);
2085 
2086   /* NOTE : This function should not be modified. When the callback is needed,
2087             function HAL_ADC_ConvCpltCallback must be implemented in the user file.
2088    */
2089 }
2090 
2091 /**
2092   * @brief  Conversion DMA half-transfer callback in non-blocking mode.
2093   * @param hadc ADC handle
2094   * @retval None
2095   */
HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef * hadc)2096 __weak void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef *hadc)
2097 {
2098   /* Prevent unused argument(s) compilation warning */
2099   UNUSED(hadc);
2100 
2101   /* NOTE : This function should not be modified. When the callback is needed,
2102             function HAL_ADC_ConvHalfCpltCallback must be implemented in the user file.
2103   */
2104 }
2105 
2106 /**
2107   * @brief  Analog watchdog 1 callback in non-blocking mode.
2108   * @param hadc ADC handle
2109   * @retval None
2110   */
HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef * hadc)2111 __weak void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef *hadc)
2112 {
2113   /* Prevent unused argument(s) compilation warning */
2114   UNUSED(hadc);
2115 
2116   /* NOTE : This function should not be modified. When the callback is needed,
2117             function HAL_ADC_LevelOutOfWindowCallback must be implemented in the user file.
2118   */
2119 }
2120 
2121 /**
2122   * @brief  ADC error callback in non-blocking mode
2123   *         (ADC conversion with interruption or transfer by DMA).
2124   * @note   In case of error due to overrun when using ADC with DMA transfer
2125   *         (HAL ADC handle parameter "ErrorCode" to state "HAL_ADC_ERROR_OVR"):
2126   *         - Reinitialize the DMA using function "HAL_ADC_Stop_DMA()".
2127   *         - If needed, restart a new ADC conversion using function
2128   *           "HAL_ADC_Start_DMA()"
2129   *           (this function is also clearing overrun flag)
2130   * @param hadc ADC handle
2131   * @retval None
2132   */
HAL_ADC_ErrorCallback(ADC_HandleTypeDef * hadc)2133 __weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc)
2134 {
2135   /* Prevent unused argument(s) compilation warning */
2136   UNUSED(hadc);
2137 
2138   /* NOTE : This function should not be modified. When the callback is needed,
2139             function HAL_ADC_ErrorCallback must be implemented in the user file.
2140   */
2141 }
2142 
2143 /**
2144   * @}
2145   */
2146 
2147 /** @defgroup ADC_Exported_Functions_Group3 Peripheral Control functions
2148   * @brief    Peripheral Control functions
2149   *
2150 @verbatim
2151  ===============================================================================
2152              ##### Peripheral Control functions #####
2153  ===============================================================================
2154     [..]  This section provides functions allowing to:
2155       (+) Configure channels on regular group
2156       (+) Configure the analog watchdog
2157 
2158 @endverbatim
2159   * @{
2160   */
2161 
2162 /**
2163   * @brief  Configure a channel to be assigned to ADC group regular.
2164   * @note   In case of usage of internal measurement channels:
2165   *         VrefInt/TempSensor.
2166   *         These internal paths can be disabled using function
2167   *         HAL_ADC_DeInit().
2168   * @note   Possibility to update parameters on the fly:
2169   *         This function initializes channel into ADC group regular,
2170   *         following calls to this function can be used to reconfigure
2171   *         some parameters of structure "ADC_ChannelConfTypeDef" on the fly,
2172   *         without resetting the ADC.
2173   *         The setting of these parameters is conditioned to ADC state:
2174   *         Refer to comments of structure "ADC_ChannelConfTypeDef".
2175   * @param hadc ADC handle
2176   * @param sConfig Structure of ADC channel assigned to ADC group regular.
2177   * @retval HAL status
2178   */
HAL_ADC_ConfigChannel(ADC_HandleTypeDef * hadc,ADC_ChannelConfTypeDef * sConfig)2179 HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef *hadc, ADC_ChannelConfTypeDef *sConfig)
2180 {
2181   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
2182   uint32_t tmp_config_internal_channel;
2183   __IO uint32_t wait_loop_index = 0UL;
2184 
2185   /* Check the parameters */
2186   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2187   assert_param(IS_ADC_CHANNEL(sConfig->Channel));
2188   assert_param(IS_ADC_SAMPLING_TIME_COMMON(sConfig->SamplingTime));
2189 
2190   if ((hadc->Init.ScanConvMode == ADC_SCAN_SEQ_FIXED)       ||
2191       (hadc->Init.ScanConvMode == ADC_SCAN_SEQ_FIXED_BACKWARD))
2192   {
2193     assert_param(IS_ADC_REGULAR_RANK_SEQ_FIXED(sConfig->Rank));
2194   }
2195   else
2196   {
2197     assert_param(IS_ADC_REGULAR_NB_CONV(hadc->Init.NbrOfConversion));
2198 
2199     assert_param(IS_ADC_REGULAR_RANK(sConfig->Rank));
2200   }
2201 
2202   /* Process locked */
2203   __HAL_LOCK(hadc);
2204 
2205   /* Parameters update conditioned to ADC state:                              */
2206   /* Parameters that can be updated when ADC is disabled or enabled without   */
2207   /* conversion on going on regular group:                                    */
2208   /*  - Channel number                                                        */
2209   /*  - Channel sampling time                                                 */
2210   /*  - Management of internal measurement channels: VrefInt/TempSensor       */
2211   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
2212   {
2213     /* Configure channel: depending on rank setting, add it or remove it from */
2214     /* ADC sequencer.                                                         */
2215     /* If sequencer set to not fully configurable with channel rank set to    */
2216     /* none, remove the channel from the sequencer.                           */
2217     /* Otherwise (sequencer set to fully configurable or to to not fully      */
2218     /* configurable with channel rank to be set), configure the selected      */
2219     /* channel.                                                               */
2220     if (sConfig->Rank != ADC_RANK_NONE)
2221     {
2222       /* Regular sequence configuration */
2223       /* Note: ADC channel configuration requires few ADC clock cycles        */
2224       /*       to be ready. Processing of ADC settings in this function       */
2225       /*       induce that a specific wait time is not necessary.             */
2226       /*       For more details on ADC channel configuration ready,           */
2227       /*       refer to function "LL_ADC_IsActiveFlag_CCRDY()".               */
2228       if ((hadc->Init.ScanConvMode == ADC_SCAN_SEQ_FIXED)       ||
2229           (hadc->Init.ScanConvMode == ADC_SCAN_SEQ_FIXED_BACKWARD))
2230       {
2231         /* Sequencer set to not fully configurable:                           */
2232         /* Set the channel by enabling the corresponding bitfield.            */
2233         LL_ADC_REG_SetSequencerChAdd(hadc->Instance, sConfig->Channel);
2234       }
2235       else
2236       {
2237         /* Sequencer set to fully configurable:                               */
2238         /* Set the channel by entering it into the selected rank.             */
2239 
2240         /* Memorize the channel set into variable in HAL ADC handle */
2241         MODIFY_REG(hadc->ADCGroupRegularSequencerRanks,
2242                    ADC_CHSELR_SQ1 << (sConfig->Rank & 0x1FUL),
2243                    __LL_ADC_CHANNEL_TO_DECIMAL_NB(sConfig->Channel) << (sConfig->Rank & 0x1FUL));
2244 
2245         /* If the selected rank is below ADC group regular sequencer length,  */
2246         /* apply the configuration in ADC register.                           */
2247         /* Note: Otherwise, configuration is not applied.                     */
2248         /*       To apply it, parameter'NbrOfConversion' must be increased.   */
2249         if (((sConfig->Rank >> 2UL) + 1UL) <= hadc->Init.NbrOfConversion)
2250         {
2251           LL_ADC_REG_SetSequencerRanks(hadc->Instance, sConfig->Rank, sConfig->Channel);
2252         }
2253       }
2254 
2255       /* Set sampling time of the selected ADC channel */
2256       LL_ADC_SetChannelSamplingTime(hadc->Instance, sConfig->Channel, sConfig->SamplingTime);
2257 
2258       /* Management of internal measurement channels: VrefInt/TempSensor      */
2259       /* internal measurement paths enable: If internal channel selected,     */
2260       /* enable dedicated internal buffers and path.                          */
2261       /* Note: these internal measurement paths can be disabled using         */
2262       /*       HAL_ADC_DeInit() or removing the channel from sequencer with   */
2263       /*       channel configuration parameter "Rank".                        */
2264       if (__LL_ADC_IS_CHANNEL_INTERNAL(sConfig->Channel))
2265       {
2266         tmp_config_internal_channel = LL_ADC_GetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
2267 
2268         /* If the requested internal measurement path has already been enabled,   */
2269         /* bypass the configuration processing.                                   */
2270         if ((sConfig->Channel == ADC_CHANNEL_TEMPSENSOR) &&
2271             ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_TEMPSENSOR) == 0UL))
2272         {
2273           LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
2274                                          LL_ADC_PATH_INTERNAL_TEMPSENSOR | tmp_config_internal_channel);
2275 
2276           /* Delay for temperature sensor stabilization time */
2277           /* Wait loop initialization and execution */
2278           /* Note: Variable divided by 2 to compensate partially              */
2279           /*       CPU processing cycles, scaling in us split to not          */
2280           /*       exceed 32 bits register capacity and handle low frequency. */
2281           wait_loop_index = (((LL_ADC_DELAY_TEMPSENSOR_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))) + 1UL);
2282           while (wait_loop_index != 0UL)
2283           {
2284             wait_loop_index--;
2285           }
2286         }
2287         else if ((sConfig->Channel == ADC_CHANNEL_VREFINT) &&
2288                  ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_VREFINT) == 0UL))
2289         {
2290           LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
2291                                          LL_ADC_PATH_INTERNAL_VREFINT | tmp_config_internal_channel);
2292         }
2293         else
2294         {
2295           /* nothing to do */
2296         }
2297       }
2298     }
2299     else
2300     {
2301       /* Regular sequencer configuration */
2302       /* Note: Case of sequencer set to fully configurable:                   */
2303       /*       Sequencer rank cannot be disabled, only affected to            */
2304       /*       another channel.                                               */
2305       /*       To remove a rank, use parameter 'NbrOfConversion".             */
2306       if ((hadc->Init.ScanConvMode == ADC_SCAN_SEQ_FIXED)       ||
2307           (hadc->Init.ScanConvMode == ADC_SCAN_SEQ_FIXED_BACKWARD))
2308       {
2309         /* Sequencer set to not fully configurable:                           */
2310         /* Reset the channel by disabling the corresponding bitfield.         */
2311         LL_ADC_REG_SetSequencerChRem(hadc->Instance, sConfig->Channel);
2312       }
2313 
2314       /* Management of internal measurement channels: VrefInt/TempSensor.       */
2315       /* If internal channel selected, enable dedicated internal buffers and    */
2316       /* paths.                                                                 */
2317       if (__LL_ADC_IS_CHANNEL_INTERNAL(sConfig->Channel))
2318       {
2319         tmp_config_internal_channel = LL_ADC_GetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
2320 
2321         if (sConfig->Channel == ADC_CHANNEL_TEMPSENSOR)
2322         {
2323           LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
2324                                          ~LL_ADC_PATH_INTERNAL_TEMPSENSOR & tmp_config_internal_channel);
2325         }
2326         else if (sConfig->Channel == ADC_CHANNEL_VREFINT)
2327         {
2328           LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
2329                                          ~LL_ADC_PATH_INTERNAL_VREFINT & tmp_config_internal_channel);
2330         }
2331         else
2332         {
2333           /* nothing to do */
2334         }
2335       }
2336     }
2337   }
2338 
2339   /* If a conversion is on going on regular group, no update on regular       */
2340   /* channel could be done on neither of the channel configuration structure  */
2341   /* parameters.                                                              */
2342   else
2343   {
2344     /* Update ADC state machine to error */
2345     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
2346 
2347     tmp_hal_status = HAL_ERROR;
2348   }
2349 
2350   /* Process unlocked */
2351   __HAL_UNLOCK(hadc);
2352 
2353   /* Return function status */
2354   return tmp_hal_status;
2355 }
2356 
2357 /**
2358   * @brief  Configure the analog watchdog.
2359   * @note   Possibility to update parameters on the fly:
2360   *         This function initializes the selected analog watchdog, successive
2361   *         calls to this function can be used to reconfigure some parameters
2362   *         of structure "ADC_AnalogWDGConfTypeDef" on the fly, without resetting
2363   *         the ADC.
2364   *         The setting of these parameters is conditioned to ADC state.
2365   *         For parameters constraints, see comments of structure
2366   *         "ADC_AnalogWDGConfTypeDef".
2367   * @note   On this STM32 series, analog watchdog thresholds can be modified
2368   *         while ADC conversion is on going.
2369   *         In this case, some constraints must be taken into account:
2370   *         the programmed threshold values are effective from the next
2371   *         ADC EOC (end of unitary conversion).
2372   *         Considering that registers write delay may happen due to
2373   *         bus activity, this might cause an uncertainty on the
2374   *         effective timing of the new programmed threshold values.
2375   * @param hadc ADC handle
2376   * @param AnalogWDGConfig Structure of ADC analog watchdog configuration
2377   * @retval HAL status
2378   */
HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef * hadc,ADC_AnalogWDGConfTypeDef * AnalogWDGConfig)2379 HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef *hadc, ADC_AnalogWDGConfTypeDef *AnalogWDGConfig)
2380 {
2381   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
2382   uint32_t tmpAWDHighThresholdShifted;
2383   uint32_t tmpAWDLowThresholdShifted;
2384   uint32_t backup_setting_adc_enable_state = 0UL;
2385 
2386   /* Check the parameters */
2387   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2388   assert_param(IS_ADC_ANALOG_WATCHDOG_NUMBER(AnalogWDGConfig->WatchdogNumber));
2389   assert_param(IS_ADC_ANALOG_WATCHDOG_MODE(AnalogWDGConfig->WatchdogMode));
2390   assert_param(IS_FUNCTIONAL_STATE(AnalogWDGConfig->ITMode));
2391 
2392   if (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG)
2393   {
2394     assert_param(IS_ADC_CHANNEL(AnalogWDGConfig->Channel));
2395   }
2396 
2397   /* Verify thresholds range */
2398   if (hadc->Init.OversamplingMode == ENABLE)
2399   {
2400     /* Case of oversampling enabled: depending on ratio and shift configuration,
2401        analog watchdog thresholds can be higher than ADC resolution.
2402        Verify if thresholds are within maximum thresholds range. */
2403     assert_param(IS_ADC_RANGE(ADC_RESOLUTION_12B, AnalogWDGConfig->HighThreshold));
2404     assert_param(IS_ADC_RANGE(ADC_RESOLUTION_12B, AnalogWDGConfig->LowThreshold));
2405   }
2406   else
2407   {
2408     /* Verify if thresholds are within the selected ADC resolution */
2409     assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), AnalogWDGConfig->HighThreshold));
2410     assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), AnalogWDGConfig->LowThreshold));
2411   }
2412 
2413   /* Process locked */
2414   __HAL_LOCK(hadc);
2415 
2416   /* Parameters update conditioned to ADC state:                              */
2417   /* Parameters that can be updated when ADC is disabled or enabled without   */
2418   /* conversion on going on ADC group regular:                                */
2419   /*  - Analog watchdog channels                                              */
2420   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
2421   {
2422     /* Analog watchdog configuration */
2423     if (AnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_1)
2424     {
2425       /* Constraint of ADC on this STM32 series: ADC must be disable
2426          to modify bitfields of register ADC_CFGR1 */
2427       if (LL_ADC_IsEnabled(hadc->Instance) != 0UL)
2428       {
2429         backup_setting_adc_enable_state = 1UL;
2430         tmp_hal_status = ADC_Disable(hadc);
2431 
2432         /* Check if ADC is effectively disabled */
2433         if (tmp_hal_status == HAL_OK)
2434         {
2435            /* Set ADC state */
2436            ADC_STATE_CLR_SET(hadc->State,
2437                              HAL_ADC_STATE_REG_BUSY,
2438                              HAL_ADC_STATE_READY);
2439         }
2440       }
2441 
2442       /* Configuration of analog watchdog:                                    */
2443       /*  - Set the analog watchdog enable mode: one or overall group of      */
2444       /*    channels.                                                         */
2445       switch (AnalogWDGConfig->WatchdogMode)
2446       {
2447         case ADC_ANALOGWATCHDOG_SINGLE_REG:
2448           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1,
2449                                           __LL_ADC_ANALOGWD_CHANNEL_GROUP(AnalogWDGConfig->Channel, LL_ADC_GROUP_REGULAR));
2450           break;
2451 
2452         case ADC_ANALOGWATCHDOG_ALL_REG:
2453           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_ALL_CHANNELS_REG);
2454           break;
2455 
2456         default: /* ADC_ANALOGWATCHDOG_NONE */
2457           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_DISABLE);
2458           break;
2459       }
2460 
2461       if (backup_setting_adc_enable_state == 1UL)
2462       {
2463         tmp_hal_status = ADC_Enable(hadc);
2464       }
2465 
2466       /* Update state, clear previous result related to AWD1 */
2467       CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD1);
2468 
2469       /* Clear flag ADC analog watchdog */
2470       /* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready  */
2471       /* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent()          */
2472       /* (in case left enabled by previous ADC operations).                 */
2473       LL_ADC_ClearFlag_AWD1(hadc->Instance);
2474 
2475       /* Configure ADC analog watchdog interrupt */
2476       if (AnalogWDGConfig->ITMode == ENABLE)
2477       {
2478         LL_ADC_EnableIT_AWD1(hadc->Instance);
2479       }
2480       else
2481       {
2482         LL_ADC_DisableIT_AWD1(hadc->Instance);
2483       }
2484     }
2485     /* Case of ADC_ANALOGWATCHDOG_2 or ADC_ANALOGWATCHDOG_3 */
2486     else
2487     {
2488       switch (AnalogWDGConfig->WatchdogMode)
2489       {
2490         case ADC_ANALOGWATCHDOG_SINGLE_REG:
2491           /* Update AWD by bitfield to keep the possibility to monitor        */
2492           /* several channels by successive calls of this function.           */
2493           if (AnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_2)
2494           {
2495             SET_BIT(hadc->Instance->AWD2CR, (1UL << __LL_ADC_CHANNEL_TO_DECIMAL_NB(AnalogWDGConfig->Channel)));
2496           }
2497           else
2498           {
2499             SET_BIT(hadc->Instance->AWD3CR, (1UL << __LL_ADC_CHANNEL_TO_DECIMAL_NB(AnalogWDGConfig->Channel)));
2500           }
2501           break;
2502 
2503         case ADC_ANALOGWATCHDOG_ALL_REG:
2504           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, AnalogWDGConfig->WatchdogNumber, LL_ADC_AWD_ALL_CHANNELS_REG);
2505           break;
2506 
2507         default: /* ADC_ANALOGWATCHDOG_NONE */
2508           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, AnalogWDGConfig->WatchdogNumber, LL_ADC_AWD_DISABLE);
2509           break;
2510       }
2511 
2512       if (AnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_2)
2513       {
2514         /* Update state, clear previous result related to AWD2 */
2515         CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD2);
2516 
2517         /* Clear flag ADC analog watchdog */
2518         /* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready  */
2519         /* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent()          */
2520         /* (in case left enabled by previous ADC operations).                 */
2521         LL_ADC_ClearFlag_AWD2(hadc->Instance);
2522 
2523         /* Configure ADC analog watchdog interrupt */
2524         if (AnalogWDGConfig->ITMode == ENABLE)
2525         {
2526           LL_ADC_EnableIT_AWD2(hadc->Instance);
2527         }
2528         else
2529         {
2530           LL_ADC_DisableIT_AWD2(hadc->Instance);
2531         }
2532       }
2533       /* (AnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_3) */
2534       else
2535       {
2536         /* Update state, clear previous result related to AWD3 */
2537         CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD3);
2538 
2539         /* Clear flag ADC analog watchdog */
2540         /* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready  */
2541         /* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent()          */
2542         /* (in case left enabled by previous ADC operations).                 */
2543         LL_ADC_ClearFlag_AWD3(hadc->Instance);
2544 
2545         /* Configure ADC analog watchdog interrupt */
2546         if (AnalogWDGConfig->ITMode == ENABLE)
2547         {
2548           LL_ADC_EnableIT_AWD3(hadc->Instance);
2549         }
2550         else
2551         {
2552           LL_ADC_DisableIT_AWD3(hadc->Instance);
2553         }
2554       }
2555     }
2556 
2557   }
2558 
2559   /* Analog watchdog thresholds configuration */
2560   if (AnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_1)
2561   {
2562     /* Shift the offset with respect to the selected ADC resolution:        */
2563     /* Thresholds have to be left-aligned on bit 11, the LSB (right bits)   */
2564     /* are set to 0.                                                        */
2565     tmpAWDHighThresholdShifted = ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(hadc, AnalogWDGConfig->HighThreshold);
2566     tmpAWDLowThresholdShifted  = ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(hadc, AnalogWDGConfig->LowThreshold);
2567   }
2568   /* Case of ADC_ANALOGWATCHDOG_2 and ADC_ANALOGWATCHDOG_3 */
2569   else
2570   {
2571     /* No need to shift the offset with respect to the selected ADC resolution: */
2572     /* Thresholds have to be left-aligned on bit 11, the LSB (right bits)   */
2573     /* are set to 0.                                                        */
2574     tmpAWDHighThresholdShifted = AnalogWDGConfig->HighThreshold;
2575     tmpAWDLowThresholdShifted  = AnalogWDGConfig->LowThreshold;
2576   }
2577 
2578   /* Set ADC analog watchdog thresholds value of both thresholds high and low */
2579   LL_ADC_ConfigAnalogWDThresholds(hadc->Instance, AnalogWDGConfig->WatchdogNumber, tmpAWDHighThresholdShifted,
2580                                   tmpAWDLowThresholdShifted);
2581 
2582   /* Process unlocked */
2583   __HAL_UNLOCK(hadc);
2584 
2585   /* Return function status */
2586   return tmp_hal_status;
2587 }
2588 
2589 
2590 /**
2591   * @}
2592   */
2593 
2594 /** @defgroup ADC_Exported_Functions_Group4 Peripheral State functions
2595   *  @brief    ADC Peripheral State functions
2596   *
2597 @verbatim
2598  ===============================================================================
2599             ##### Peripheral state and errors functions #####
2600  ===============================================================================
2601     [..]
2602     This subsection provides functions to get in run-time the status of the
2603     peripheral.
2604       (+) Check the ADC state
2605       (+) Check the ADC error code
2606 
2607 @endverbatim
2608   * @{
2609   */
2610 
2611 /**
2612   * @brief  Return the ADC handle state.
2613   * @note   ADC state machine is managed by bitfields, ADC status must be
2614   *         compared with states bits.
2615   *         For example:
2616   *           " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_REG_BUSY) != 0UL) "
2617   *           " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD1) != 0UL) "
2618   * @param hadc ADC handle
2619   * @retval ADC handle state (bitfield on 32 bits)
2620   */
HAL_ADC_GetState(ADC_HandleTypeDef * hadc)2621 uint32_t HAL_ADC_GetState(ADC_HandleTypeDef *hadc)
2622 {
2623   /* Check the parameters */
2624   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2625 
2626   /* Return ADC handle state */
2627   return hadc->State;
2628 }
2629 
2630 /**
2631   * @brief  Return the ADC error code.
2632   * @param hadc ADC handle
2633   * @retval ADC error code (bitfield on 32 bits)
2634   */
HAL_ADC_GetError(ADC_HandleTypeDef * hadc)2635 uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc)
2636 {
2637   /* Check the parameters */
2638   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2639 
2640   return hadc->ErrorCode;
2641 }
2642 
2643 /**
2644   * @}
2645   */
2646 
2647 /**
2648   * @}
2649   */
2650 
2651 /** @defgroup ADC_Private_Functions ADC Private Functions
2652   * @{
2653   */
2654 
2655 /**
2656   * @brief  Stop ADC conversion.
2657   * @note   Prerequisite condition to use this function: ADC conversions must be
2658   *         stopped to disable the ADC.
2659   * @param  hadc ADC handle
2660   * @retval HAL status.
2661   */
ADC_ConversionStop(ADC_HandleTypeDef * hadc)2662 HAL_StatusTypeDef ADC_ConversionStop(ADC_HandleTypeDef *hadc)
2663 {
2664   uint32_t tickstart;
2665 
2666   /* Check the parameters */
2667   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2668 
2669   /* Verification if ADC is not already stopped on regular group to bypass    */
2670   /* this function if not needed.                                             */
2671   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) != 0UL)
2672   {
2673     /* Stop potential conversion on going on regular group */
2674     /* Software is allowed to set ADSTP only when ADSTART=1 and ADDIS=0 */
2675     if (LL_ADC_IsDisableOngoing(hadc->Instance) == 0UL)
2676     {
2677       /* Stop ADC group regular conversion */
2678       LL_ADC_REG_StopConversion(hadc->Instance);
2679     }
2680 
2681     /* Wait for conversion effectively stopped */
2682     /* Get tick count */
2683     tickstart = HAL_GetTick();
2684 
2685     while ((hadc->Instance->CR & ADC_CR_ADSTART) != 0UL)
2686     {
2687       if ((HAL_GetTick() - tickstart) > ADC_STOP_CONVERSION_TIMEOUT)
2688       {
2689         /* Update ADC state machine to error */
2690         SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2691 
2692         /* Set ADC error code to ADC peripheral internal error */
2693         SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2694 
2695         return HAL_ERROR;
2696       }
2697     }
2698 
2699   }
2700 
2701   /* Return HAL status */
2702   return HAL_OK;
2703 }
2704 
2705 /**
2706   * @brief  Enable the selected ADC.
2707   * @note   Prerequisite condition to use this function: ADC must be disabled
2708   *         and voltage regulator must be enabled (done into HAL_ADC_Init()).
2709   * @param hadc ADC handle
2710   * @retval HAL status.
2711   */
ADC_Enable(ADC_HandleTypeDef * hadc)2712 HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef *hadc)
2713 {
2714   uint32_t tickstart;
2715   __IO uint32_t wait_loop_index = 0UL;
2716 
2717   /* ADC enable and wait for ADC ready (in case of ADC is disabled or         */
2718   /* enabling phase not yet completed: flag ADC ready not yet set).           */
2719   /* Timeout implemented to not be stuck if ADC cannot be enabled (possible   */
2720   /* causes: ADC clock not running, ...).                                     */
2721   if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
2722   {
2723     /* Check if conditions to enable the ADC are fulfilled */
2724     if ((hadc->Instance->CR & (ADC_CR_ADCAL | ADC_CR_ADSTP | ADC_CR_ADSTART | ADC_CR_ADDIS | ADC_CR_ADEN)) != 0UL)
2725     {
2726       /* Update ADC state machine to error */
2727       SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2728 
2729       /* Set ADC error code to ADC peripheral internal error */
2730       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2731 
2732       return HAL_ERROR;
2733     }
2734 
2735     /* Enable the ADC peripheral */
2736     LL_ADC_Enable(hadc->Instance);
2737 
2738     if ((LL_ADC_GetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) & LL_ADC_PATH_INTERNAL_TEMPSENSOR) != 0UL)
2739     {
2740       /* Delay for temperature sensor buffer stabilization time */
2741       /* Wait loop initialization and execution */
2742       /* Note: Variable divided by 2 to compensate partially              */
2743       /*       CPU processing cycles, scaling in us split to not          */
2744       /*       exceed 32 bits register capacity and handle low frequency. */
2745       wait_loop_index = (((LL_ADC_DELAY_TEMPSENSOR_BUFFER_STAB_US / 10UL) * (SystemCoreClock / (100000UL * 2UL))) + 1UL);
2746       while (wait_loop_index != 0UL)
2747       {
2748         wait_loop_index--;
2749       }
2750     }
2751 
2752     /* If low power mode AutoPowerOff is enabled, power-on/off phases are     */
2753     /* performed automatically by hardware and flag ADC ready is not set.     */
2754     if (hadc->Init.LowPowerAutoPowerOff != ENABLE)
2755     {
2756       /* Wait for ADC effectively enabled */
2757       tickstart = HAL_GetTick();
2758 
2759       while (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_RDY) == 0UL)
2760       {
2761         /*  If ADEN bit is set less than 4 ADC clock cycles after the ADCAL bit
2762             has been cleared (after a calibration), ADEN bit is reset by the
2763             calibration logic.
2764             The workaround is to continue setting ADEN until ADRDY is becomes 1.
2765             Additionally, ADC_ENABLE_TIMEOUT is defined to encompass this
2766             4 ADC clock cycle duration */
2767         /* Note: Test of ADC enabled required due to hardware constraint to     */
2768         /*       not enable ADC if already enabled.                             */
2769         if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
2770         {
2771           LL_ADC_Enable(hadc->Instance);
2772         }
2773 
2774         if ((HAL_GetTick() - tickstart) > ADC_ENABLE_TIMEOUT)
2775         {
2776           /* Update ADC state machine to error */
2777           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2778 
2779           /* Set ADC error code to ADC peripheral internal error */
2780           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2781 
2782           return HAL_ERROR;
2783         }
2784       }
2785     }
2786   }
2787 
2788   /* Return HAL status */
2789   return HAL_OK;
2790 }
2791 
2792 /**
2793   * @brief  Disable the selected ADC.
2794   * @note   Prerequisite condition to use this function: ADC conversions must be
2795   *         stopped.
2796   * @param hadc ADC handle
2797   * @retval HAL status.
2798   */
ADC_Disable(ADC_HandleTypeDef * hadc)2799 HAL_StatusTypeDef ADC_Disable(ADC_HandleTypeDef *hadc)
2800 {
2801   uint32_t tickstart;
2802   const uint32_t tmp_adc_is_disable_on_going = LL_ADC_IsDisableOngoing(hadc->Instance);
2803 
2804   /* Verification if ADC is not already disabled:                             */
2805   /* Note: forbidden to disable ADC (set bit ADC_CR_ADDIS) if ADC is already  */
2806   /*       disabled.                                                          */
2807   if ((LL_ADC_IsEnabled(hadc->Instance) != 0UL)
2808       && (tmp_adc_is_disable_on_going == 0UL)
2809      )
2810   {
2811     /* Check if conditions to disable the ADC are fulfilled */
2812     if ((hadc->Instance->CR & (ADC_CR_ADSTART | ADC_CR_ADEN)) == ADC_CR_ADEN)
2813     {
2814       /* Disable the ADC peripheral */
2815       LL_ADC_Disable(hadc->Instance);
2816       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOSMP | ADC_FLAG_RDY));
2817     }
2818     else
2819     {
2820       /* Update ADC state machine to error */
2821       SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2822 
2823       /* Set ADC error code to ADC peripheral internal error */
2824       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2825 
2826       return HAL_ERROR;
2827     }
2828 
2829     /* Wait for ADC effectively disabled */
2830     /* Get tick count */
2831     tickstart = HAL_GetTick();
2832 
2833     while ((hadc->Instance->CR & ADC_CR_ADEN) != 0UL)
2834     {
2835       if ((HAL_GetTick() - tickstart) > ADC_DISABLE_TIMEOUT)
2836       {
2837         /* Update ADC state machine to error */
2838         SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2839 
2840         /* Set ADC error code to ADC peripheral internal error */
2841         SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2842 
2843         return HAL_ERROR;
2844       }
2845     }
2846   }
2847 
2848   /* Return HAL status */
2849   return HAL_OK;
2850 }
2851 
2852 /**
2853   * @brief  DMA transfer complete callback.
2854   * @param hdma pointer to DMA handle.
2855   * @retval None
2856   */
ADC_DMAConvCplt(DMA_HandleTypeDef * hdma)2857 static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma)
2858 {
2859   /* Retrieve ADC handle corresponding to current DMA handle */
2860   ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
2861 
2862   /* Update state machine on conversion status if not in error state */
2863   if ((hadc->State & (HAL_ADC_STATE_ERROR_INTERNAL | HAL_ADC_STATE_ERROR_DMA)) == 0UL)
2864   {
2865     /* Set ADC state */
2866     SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
2867 
2868     /* Determine whether any further conversion upcoming on group regular     */
2869     /* by external trigger, continuous mode or scan sequence on going         */
2870     /* to disable interruption.                                               */
2871     if ((LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
2872         && (hadc->Init.ContinuousConvMode == DISABLE)
2873        )
2874     {
2875       /* If End of Sequence is reached, disable interrupts */
2876       if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS))
2877       {
2878         /* Allowed to modify bits ADC_IT_EOC/ADC_IT_EOS only if bit           */
2879         /* ADSTART==0 (no conversion on going)                                */
2880         if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
2881         {
2882           /* Disable ADC end of single conversion interrupt on group regular */
2883           /* Note: Overrun interrupt was enabled with EOC interrupt in        */
2884           /* HAL_Start_IT(), but is not disabled here because can be used     */
2885           /* by overrun IRQ process below.                                    */
2886           __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_EOS);
2887 
2888           /* Set ADC state */
2889           ADC_STATE_CLR_SET(hadc->State,
2890                             HAL_ADC_STATE_REG_BUSY,
2891                             HAL_ADC_STATE_READY);
2892         }
2893         else
2894         {
2895           /* Change ADC state to error state */
2896           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
2897 
2898           /* Set ADC error code to ADC peripheral internal error */
2899           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2900         }
2901       }
2902     }
2903 
2904     /* Conversion complete callback */
2905 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2906     hadc->ConvCpltCallback(hadc);
2907 #else
2908     HAL_ADC_ConvCpltCallback(hadc);
2909 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2910   }
2911   else /* DMA and-or internal error occurred */
2912   {
2913     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) != 0UL)
2914     {
2915       /* Call HAL ADC Error Callback function */
2916 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2917       hadc->ErrorCallback(hadc);
2918 #else
2919       HAL_ADC_ErrorCallback(hadc);
2920 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2921     }
2922     else
2923     {
2924       /* Call ADC DMA error callback */
2925       hadc->DMA_Handle->XferErrorCallback(hdma);
2926     }
2927   }
2928 }
2929 
2930 /**
2931   * @brief  DMA half transfer complete callback.
2932   * @param hdma pointer to DMA handle.
2933   * @retval None
2934   */
ADC_DMAHalfConvCplt(DMA_HandleTypeDef * hdma)2935 static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma)
2936 {
2937   /* Retrieve ADC handle corresponding to current DMA handle */
2938   ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
2939 
2940   /* Half conversion callback */
2941 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2942   hadc->ConvHalfCpltCallback(hadc);
2943 #else
2944   HAL_ADC_ConvHalfCpltCallback(hadc);
2945 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2946 }
2947 
2948 /**
2949   * @brief  DMA error callback.
2950   * @param hdma pointer to DMA handle.
2951   * @retval None
2952   */
ADC_DMAError(DMA_HandleTypeDef * hdma)2953 static void ADC_DMAError(DMA_HandleTypeDef *hdma)
2954 {
2955   /* Retrieve ADC handle corresponding to current DMA handle */
2956   ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
2957 
2958   /* Set ADC state */
2959   SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
2960 
2961   /* Set ADC error code to DMA error */
2962   SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_DMA);
2963 
2964   /* Error callback */
2965 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2966   hadc->ErrorCallback(hadc);
2967 #else
2968   HAL_ADC_ErrorCallback(hadc);
2969 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2970 }
2971 
2972 /**
2973   * @}
2974   */
2975 
2976 #endif /* HAL_ADC_MODULE_ENABLED */
2977 /**
2978   * @}
2979   */
2980 
2981 /**
2982   * @}
2983   */
2984 
2985