1 /**
2   ******************************************************************************
3   * @file    stm32l5xx_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   *           + Peripheral Control functions
10   *           + Peripheral State functions
11   *          Other functions (extended functions) are available in file
12   *          "stm32l5xx_hal_adc_ex.c".
13   *
14   ******************************************************************************
15   * @attention
16   *
17   * Copyright (c) 2019 STMicroelectronics.
18   * All rights reserved.
19   *
20   * This software is licensed under terms that can be found in the LICENSE file
21   * in the root directory of this software component.
22   * If no LICENSE file comes with this software, it is provided AS-IS.
23   *
24   ******************************************************************************
25   @verbatim
26   ==============================================================================
27                      ##### ADC peripheral features #####
28   ==============================================================================
29   [..]
30   (+) 12-bit, 10-bit, 8-bit or 6-bit configurable resolution.
31 
32   (+) Interrupt generation at the end of regular conversion and in case of
33       analog watchdog or overrun events.
34 
35   (+) Single and continuous conversion modes.
36 
37   (+) Scan mode for conversion of several channels sequentially.
38 
39   (+) Data alignment with in-built data coherency.
40 
41   (+) Programmable sampling time (channel wise)
42 
43   (+) External trigger (timer or EXTI) with configurable polarity
44 
45   (+) DMA request generation for transfer of conversions data of regular group.
46 
47   (+) Configurable delay between conversions in Dual interleaved mode.
48 
49   (+) ADC channels selectable single/differential input.
50 
51   (+) ADC offset shared on 4 offset instances.
52   (+) ADC calibration
53 
54   (+) ADC conversion of regular group.
55 
56   (+) ADC supply requirements: 1.62 V to 3.6 V.
57 
58   (+) ADC input range: from Vref- (connected to Vssa) to Vref+ (connected to
59       Vdda or to an external voltage reference).
60 
61 
62                      ##### How to use this driver #####
63   ==============================================================================
64     [..]
65 
66      *** Configuration of top level parameters related to ADC ***
67      ============================================================
68      [..]
69 
70     (#) Enable the ADC interface
71         (++) As prerequisite, ADC clock must be configured at RCC top level.
72 
73         (++) Two clock settings are mandatory:
74              (+++) ADC clock (core clock, also possibly conversion clock).
75 
76              (+++) ADC clock (conversions clock).
77                    Two possible clock sources: synchronous clock derived from AHB2 clock
78                    or asynchronous clock derived from system clock or PLLSAI1 (output divider R)
79                    running up to 120MHz.
80 
81              (+++) Example:
82                    Into HAL_ADC_MspInit() (recommended code location) or with
83                    other device clock parameters configuration:
84                (+++) __HAL_RCC_ADC_CLK_ENABLE();                  (mandatory)
85 
86                RCC_ADCCLKSOURCE_PLL enable:                       (optional: if asynchronous clock selected)
87                (+++) RCC_PeriphClkInitTypeDef   RCC_PeriphClkInit;
88                (+++) PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
89                (+++) PeriphClkInit.AdcClockSelection    = RCC_ADCCLKSOURCE_PLL;
90                (+++) HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit);
91 
92         (++) ADC clock source and clock prescaler are configured at ADC level with
93              parameter "ClockPrescaler" using function HAL_ADC_Init().
94 
95     (#) ADC pins configuration
96          (++) Enable the clock for the ADC GPIOs
97               using macro __HAL_RCC_GPIOx_CLK_ENABLE()
98          (++) Configure these ADC pins in analog mode
99               using function HAL_GPIO_Init()
100 
101     (#) Optionally, in case of usage of ADC with interruptions:
102          (++) Configure the NVIC for ADC
103               using function HAL_NVIC_EnableIRQ(ADCx_IRQn)
104          (++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
105               into the function of corresponding ADC interruption vector
106               ADCx_IRQHandler().
107 
108     (#) Optionally, in case of usage of DMA:
109          (++) Configure the DMA (DMA channel, mode normal or circular, ...)
110               using function HAL_DMA_Init().
111          (++) Configure the NVIC for DMA
112               using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
113          (++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
114               into the function of corresponding DMA interruption vector
115               DMAx_Channelx_IRQHandler().
116 
117      *** Configuration of ADC, group regular, channels parameters ***
118      ================================================================
119      [..]
120 
121     (#) Configure the ADC parameters (resolution, data alignment, ...)
122         and regular group parameters (conversion trigger, sequencer, ...)
123         using function HAL_ADC_Init().
124 
125     (#) Configure the channels for regular group parameters (channel number,
126         channel rank into sequencer, ..., into regular group)
127         using function HAL_ADC_ConfigChannel().
128 
129     (#) Optionally, configure the analog watchdog parameters (channels
130         monitored, thresholds, ...)
131         using function HAL_ADC_AnalogWDGConfig().
132 
133      *** Execution of ADC conversions ***
134      ====================================
135      [..]
136 
137     (#) Optionally, perform an automatic ADC calibration to improve the
138         conversion accuracy
139         using function HAL_ADCEx_Calibration_Start().
140 
141     (#) ADC driver can be used among three modes: polling, interruption,
142         transfer by DMA.
143 
144         (++) ADC conversion by polling:
145           (+++) Activate the ADC peripheral and start conversions
146                 using function HAL_ADC_Start()
147           (+++) Wait for ADC conversion completion
148                 using function HAL_ADC_PollForConversion()
149           (+++) Retrieve conversion results
150                 using function HAL_ADC_GetValue()
151           (+++) Stop conversion and disable the ADC peripheral
152                 using function HAL_ADC_Stop()
153 
154         (++) ADC conversion by interruption:
155           (+++) Activate the ADC peripheral and start conversions
156                 using function HAL_ADC_Start_IT()
157           (+++) Wait for ADC conversion completion by call of function
158                 HAL_ADC_ConvCpltCallback()
159                 (this function must be implemented in user program)
160           (+++) Retrieve conversion results
161                 using function HAL_ADC_GetValue()
162           (+++) Stop conversion and disable the ADC peripheral
163                 using function HAL_ADC_Stop_IT()
164 
165         (++) ADC conversion with transfer by DMA:
166           (+++) Activate the ADC peripheral and start conversions
167                 using function HAL_ADC_Start_DMA()
168           (+++) Wait for ADC conversion completion by call of function
169                 HAL_ADC_ConvCpltCallback() or HAL_ADC_ConvHalfCpltCallback()
170                 (these functions must be implemented in user program)
171           (+++) Conversion results are automatically transferred by DMA into
172                 destination variable address.
173           (+++) Stop conversion and disable the ADC peripheral
174                 using function HAL_ADC_Stop_DMA()
175 
176      [..]
177 
178     (@) Callback functions must be implemented in user program:
179       (+@) HAL_ADC_ErrorCallback()
180       (+@) HAL_ADC_LevelOutOfWindowCallback() (callback of analog watchdog)
181       (+@) HAL_ADC_ConvCpltCallback()
182       (+@) HAL_ADC_ConvHalfCpltCallback
183 
184      *** Deinitialization of ADC ***
185      ============================================================
186      [..]
187 
188     (#) Disable the ADC interface
189       (++) ADC clock can be hard reset and disabled at RCC top level.
190         (++) Hard reset of ADC peripherals
191              using macro __ADCx_FORCE_RESET(), __ADCx_RELEASE_RESET().
192         (++) ADC clock disable
193              using the equivalent macro/functions as configuration step.
194              (+++) Example:
195                    Into HAL_ADC_MspDeInit() (recommended code location) or with
196                    other device clock parameters configuration:
197                (+++) RCC_OscInitStructure.OscillatorType = RCC_OSCILLATORTYPE_HSI14;
198                (+++) RCC_OscInitStructure.HSI14State = RCC_HSI14_OFF; (if not used for system clock)
199                (+++) HAL_RCC_OscConfig(&RCC_OscInitStructure);
200 
201     (#) ADC pins configuration
202          (++) Disable the clock for the ADC GPIOs
203               using macro __HAL_RCC_GPIOx_CLK_DISABLE()
204 
205     (#) Optionally, in case of usage of ADC with interruptions:
206          (++) Disable the NVIC for ADC
207               using function HAL_NVIC_EnableIRQ(ADCx_IRQn)
208 
209     (#) Optionally, in case of usage of DMA:
210          (++) Deinitialize the DMA
211               using function HAL_DMA_Init().
212          (++) Disable the NVIC for DMA
213               using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
214 
215     [..]
216 
217     *** Callback registration ***
218     =============================================
219     [..]
220 
221      The compilation flag USE_HAL_ADC_REGISTER_CALLBACKS, when set to 1,
222      allows the user to configure dynamically the driver callbacks.
223      Use Functions @ref HAL_ADC_RegisterCallback()
224      to register an interrupt callback.
225     [..]
226 
227      Function @ref HAL_ADC_RegisterCallback() allows to register following callbacks:
228        (+) ConvCpltCallback               : ADC conversion complete callback
229        (+) ConvHalfCpltCallback           : ADC conversion DMA half-transfer callback
230        (+) LevelOutOfWindowCallback       : ADC analog watchdog 1 callback
231        (+) ErrorCallback                  : ADC error callback
232        (+) InjectedConvCpltCallback       : ADC group injected conversion complete callback
233        (+) InjectedQueueOverflowCallback  : ADC group injected context queue overflow callback
234        (+) LevelOutOfWindow2Callback      : ADC analog watchdog 2 callback
235        (+) LevelOutOfWindow3Callback      : ADC analog watchdog 3 callback
236        (+) EndOfSamplingCallback          : ADC end of sampling callback
237        (+) MspInitCallback                : ADC Msp Init callback
238        (+) MspDeInitCallback              : ADC Msp DeInit callback
239      This function takes as parameters the HAL peripheral handle, the Callback ID
240      and a pointer to the user callback function.
241     [..]
242 
243      Use function @ref HAL_ADC_UnRegisterCallback to reset a callback to the default
244      weak function.
245     [..]
246 
247      @ref HAL_ADC_UnRegisterCallback takes as parameters the HAL peripheral handle,
248      and the Callback ID.
249      This function allows to reset following callbacks:
250        (+) ConvCpltCallback               : ADC conversion complete callback
251        (+) ConvHalfCpltCallback           : ADC conversion DMA half-transfer callback
252        (+) LevelOutOfWindowCallback       : ADC analog watchdog 1 callback
253        (+) ErrorCallback                  : ADC error callback
254        (+) InjectedConvCpltCallback       : ADC group injected conversion complete callback
255        (+) InjectedQueueOverflowCallback  : ADC group injected context queue overflow callback
256        (+) LevelOutOfWindow2Callback      : ADC analog watchdog 2 callback
257        (+) LevelOutOfWindow3Callback      : ADC analog watchdog 3 callback
258        (+) EndOfSamplingCallback          : ADC end of sampling callback
259        (+) MspInitCallback                : ADC Msp Init callback
260        (+) MspDeInitCallback              : ADC Msp DeInit callback
261      [..]
262 
263      By default, after the @ref HAL_ADC_Init() and when the state is @ref HAL_ADC_STATE_RESET
264      all callbacks are set to the corresponding weak functions:
265      examples @ref HAL_ADC_ConvCpltCallback(), @ref HAL_ADC_ErrorCallback().
266      Exception done for MspInit and MspDeInit functions that are
267      reset to the legacy weak functions in the @ref HAL_ADC_Init()/ @ref HAL_ADC_DeInit() only when
268      these callbacks are null (not registered beforehand).
269     [..]
270 
271      If MspInit or MspDeInit are not null, the @ref HAL_ADC_Init()/ @ref HAL_ADC_DeInit()
272      keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state.
273      [..]
274 
275      Callbacks can be registered/unregistered in @ref HAL_ADC_STATE_READY state only.
276      Exception done MspInit/MspDeInit functions that can be registered/unregistered
277      in @ref HAL_ADC_STATE_READY or @ref HAL_ADC_STATE_RESET state,
278      thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit.
279     [..]
280 
281      Then, the user first registers the MspInit/MspDeInit user callbacks
282      using @ref HAL_ADC_RegisterCallback() before calling @ref HAL_ADC_DeInit()
283      or @ref HAL_ADC_Init() function.
284      [..]
285 
286      When the compilation flag USE_HAL_ADC_REGISTER_CALLBACKS is set to 0 or
287      not defined, the callback registration feature is not available and all callbacks
288      are set to the corresponding weak functions.
289 
290   @endverbatim
291   ******************************************************************************
292   */
293 
294 /* Includes ------------------------------------------------------------------*/
295 #include "stm32l5xx_hal.h"
296 
297 /** @addtogroup STM32L5xx_HAL_Driver
298   * @{
299   */
300 
301 /** @defgroup ADC ADC
302   * @brief ADC HAL module driver
303   * @{
304   */
305 
306 #ifdef HAL_ADC_MODULE_ENABLED
307 
308 /* Private typedef -----------------------------------------------------------*/
309 /* Private define ------------------------------------------------------------*/
310 
311 /** @defgroup ADC_Private_Constants ADC Private Constants
312   * @{
313   */
314 
315 #define ADC_CFGR_FIELDS_1 (ADC_CFGR_RES    | ADC_CFGR_ALIGN   |\
316                            ADC_CFGR_CONT   | ADC_CFGR_OVRMOD  |\
317                            ADC_CFGR_DISCEN | ADC_CFGR_DISCNUM |\
318                            ADC_CFGR_EXTEN  | ADC_CFGR_EXTSEL)              /*!< ADC_CFGR fields of parameters that can
319                           be updated when no regular conversion is on-going */
320 
321 /* Timeout values for ADC operations (enable settling time,                   */
322 /*   disable settling time, ...).                                             */
323 /*   Values defined to be higher than worst cases: low clock frequency,       */
324 /*   maximum prescalers.                                                      */
325 #define ADC_ENABLE_TIMEOUT              (2UL)    /*!< ADC enable time-out value  */
326 #define ADC_DISABLE_TIMEOUT             (2UL)    /*!< ADC disable time-out value */
327 
328 /* Timeout to wait for current conversion on going to be completed.           */
329 /* Timeout fixed to longest ADC conversion possible, for 1 channel:           */
330 /*   - maximum sampling time (640.5 adc_clk)                                  */
331 /*   - ADC resolution (Tsar 12 bits= 12.5 adc_clk)                            */
332 /*   - System clock / ADC clock <= 4096 (hypothesis of maximum clock ratio)   */
333 /*   - ADC oversampling ratio 256                                             */
334 /*   Calculation: 653 * 4096 * 256 CPU clock cycles max                       */
335 /* Unit: cycles of CPU clock.                                                 */
336 #define ADC_CONVERSION_TIME_MAX_CPU_CYCLES (653UL * 4096UL * 256UL)  /*!< ADC conversion completion time-out value */
337 
338 
339 /**
340   * @}
341   */
342 
343 /* Private macro -------------------------------------------------------------*/
344 /* Private variables ---------------------------------------------------------*/
345 /* Private function prototypes -----------------------------------------------*/
346 /* Exported functions --------------------------------------------------------*/
347 
348 /** @defgroup ADC_Exported_Functions ADC Exported Functions
349   * @{
350   */
351 
352 /** @defgroup ADC_Exported_Functions_Group1 Initialization and de-initialization functions
353   * @brief    ADC Initialization and Configuration functions
354   *
355 @verbatim
356  ===============================================================================
357               ##### Initialization and de-initialization functions #####
358  ===============================================================================
359     [..]  This section provides functions allowing to:
360       (+) Initialize and configure the ADC.
361       (+) De-initialize the ADC.
362 @endverbatim
363   * @{
364   */
365 
366 /**
367   * @brief  Initialize the ADC peripheral and regular group according to
368   *         parameters specified in structure "ADC_InitTypeDef".
369   * @note   As prerequisite, ADC clock must be configured at RCC top level
370   *         (refer to description of RCC configuration for ADC
371   *         in header of this file).
372   * @note   Possibility to update parameters on the fly:
373   *         This function initializes the ADC MSP (HAL_ADC_MspInit()) only when
374   *         coming from ADC state reset. Following calls to this function can
375   *         be used to reconfigure some parameters of ADC_InitTypeDef
376   *         structure on the fly, without modifying MSP configuration. If ADC
377   *         MSP has to be modified again, HAL_ADC_DeInit() must be called
378   *         before HAL_ADC_Init().
379   *         The setting of these parameters is conditioned to ADC state.
380   *         For parameters constraints, see comments of structure
381   *         "ADC_InitTypeDef".
382   * @note   This function configures the ADC within 2 scopes: scope of entire
383   *         ADC and scope of regular group. For parameters details, see comments
384   *         of structure "ADC_InitTypeDef".
385   * @note   Parameters related to common ADC registers (ADC clock mode) are set
386   *         only if all ADCs are disabled.
387   *         If this is not the case, these common parameters setting are
388   *         bypassed without error reporting: it can be the intended behaviour in
389   *         case of update of a parameter of ADC_InitTypeDef on the fly,
390   *         without  disabling the other ADCs.
391   * @param hadc ADC handle
392   * @retval HAL status
393   */
HAL_ADC_Init(ADC_HandleTypeDef * hadc)394 HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef *hadc)
395 {
396   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
397   uint32_t tmp_cfgr;
398   uint32_t tmp_adc_is_conversion_on_going_regular;
399   uint32_t tmp_adc_is_conversion_on_going_injected;
400   __IO uint32_t wait_loop_index = 0UL;
401 
402   /* Check ADC handle */
403   if (hadc == NULL)
404   {
405     return HAL_ERROR;
406   }
407 
408   /* Check the parameters */
409   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
410   assert_param(IS_ADC_CLOCKPRESCALER(hadc->Init.ClockPrescaler));
411   assert_param(IS_ADC_RESOLUTION(hadc->Init.Resolution));
412 #if defined(DFSDM1_Channel0)
413   assert_param(IS_ADC_DFSDMCFG_MODE(hadc));
414 #endif /* DFSDM */
415   assert_param(IS_ADC_DATA_ALIGN(hadc->Init.DataAlign));
416   assert_param(IS_ADC_SCAN_MODE(hadc->Init.ScanConvMode));
417   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
418   assert_param(IS_ADC_EXTTRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
419   assert_param(IS_ADC_EXTTRIG(hadc, hadc->Init.ExternalTrigConv));
420   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests));
421   assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection));
422   assert_param(IS_ADC_OVERRUN(hadc->Init.Overrun));
423   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerAutoWait));
424   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.OversamplingMode));
425 
426   if (hadc->Init.ScanConvMode != ADC_SCAN_DISABLE)
427   {
428     assert_param(IS_ADC_REGULAR_NB_CONV(hadc->Init.NbrOfConversion));
429     assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DiscontinuousConvMode));
430 
431     if (hadc->Init.DiscontinuousConvMode == ENABLE)
432     {
433       assert_param(IS_ADC_REGULAR_DISCONT_NUMBER(hadc->Init.NbrOfDiscConversion));
434     }
435   }
436 
437   /* DISCEN and CONT bits cannot be set at the same time */
438   assert_param(!((hadc->Init.DiscontinuousConvMode == ENABLE) && (hadc->Init.ContinuousConvMode == ENABLE)));
439 
440   /* Actions performed only if ADC is coming from state reset:                */
441   /* - Initialization of ADC MSP                                              */
442   if (hadc->State == HAL_ADC_STATE_RESET)
443   {
444 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
445     /* Init the ADC Callback settings */
446     hadc->ConvCpltCallback              = HAL_ADC_ConvCpltCallback;                 /* Legacy weak callback */
447     hadc->ConvHalfCpltCallback          = HAL_ADC_ConvHalfCpltCallback;             /* Legacy weak callback */
448     hadc->LevelOutOfWindowCallback      = HAL_ADC_LevelOutOfWindowCallback;         /* Legacy weak callback */
449     hadc->ErrorCallback                 = HAL_ADC_ErrorCallback;                    /* Legacy weak callback */
450     hadc->InjectedConvCpltCallback      = HAL_ADCEx_InjectedConvCpltCallback;       /* Legacy weak callback */
451     hadc->InjectedQueueOverflowCallback = HAL_ADCEx_InjectedQueueOverflowCallback;  /* Legacy weak callback */
452     hadc->LevelOutOfWindow2Callback     = HAL_ADCEx_LevelOutOfWindow2Callback;      /* Legacy weak callback */
453     hadc->LevelOutOfWindow3Callback     = HAL_ADCEx_LevelOutOfWindow3Callback;      /* Legacy weak callback */
454     hadc->EndOfSamplingCallback         = HAL_ADCEx_EndOfSamplingCallback;          /* Legacy weak callback */
455 
456     if (hadc->MspInitCallback == NULL)
457     {
458       hadc->MspInitCallback = HAL_ADC_MspInit; /* Legacy weak MspInit  */
459     }
460 
461     /* Init the low level hardware */
462     hadc->MspInitCallback(hadc);
463 #else
464     /* Init the low level hardware */
465     HAL_ADC_MspInit(hadc);
466 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
467 
468     /* Set ADC error code to none */
469     ADC_CLEAR_ERRORCODE(hadc);
470 
471     /* Initialize Lock */
472     hadc->Lock = HAL_UNLOCKED;
473   }
474 
475   /* - Exit from deep-power-down mode and ADC voltage regulator enable        */
476   if (LL_ADC_IsDeepPowerDownEnabled(hadc->Instance) != 0UL)
477   {
478     /* Disable ADC deep power down mode */
479     LL_ADC_DisableDeepPowerDown(hadc->Instance);
480 
481     /* System was in deep power down mode, calibration must
482      be relaunched or a previously saved calibration factor
483      re-applied once the ADC voltage regulator is enabled */
484   }
485 
486   if (LL_ADC_IsInternalRegulatorEnabled(hadc->Instance) == 0UL)
487   {
488     /* Enable ADC internal voltage regulator */
489     LL_ADC_EnableInternalRegulator(hadc->Instance);
490 
491     /* Note: Variable divided by 2 to compensate partially              */
492     /*       CPU processing cycles, scaling in us split to not          */
493     /*       exceed 32 bits register capacity and handle low frequency. */
494     wait_loop_index = ((LL_ADC_DELAY_INTERNAL_REGUL_STAB_US / 10UL) * ((SystemCoreClock / (100000UL * 2UL)) + 1UL));
495     while (wait_loop_index != 0UL)
496     {
497       wait_loop_index--;
498     }
499   }
500 
501   /* Verification that ADC voltage regulator is correctly enabled, whether    */
502   /* or not ADC is coming from state reset (if any potential problem of       */
503   /* clocking, voltage regulator would not be enabled).                       */
504   if (LL_ADC_IsInternalRegulatorEnabled(hadc->Instance) == 0UL)
505   {
506     /* Update ADC state machine to error */
507     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
508 
509     /* Set ADC error code to ADC peripheral internal error */
510     SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
511 
512     tmp_hal_status = HAL_ERROR;
513   }
514 
515   /* Configuration of ADC parameters if previous preliminary actions are      */
516   /* correctly completed and if there is no conversion on going on regular    */
517   /* group (ADC may already be enabled at this point if HAL_ADC_Init() is     */
518   /* called to update a parameter on the fly).                                */
519   tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
520 
521   if (((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
522       && (tmp_adc_is_conversion_on_going_regular == 0UL)
523      )
524   {
525     /* Set ADC state */
526     ADC_STATE_CLR_SET(hadc->State,
527                       HAL_ADC_STATE_REG_BUSY,
528                       HAL_ADC_STATE_BUSY_INTERNAL);
529 
530     /* Configuration of common ADC parameters                                 */
531 
532     /* Parameters update conditioned to ADC state:                            */
533     /* Parameters that can be updated only when ADC is disabled:              */
534     /*  - clock configuration                                                 */
535     if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
536     {
537       if (__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) == 0UL)
538       {
539         /* Reset configuration of ADC common register CCR:                      */
540         /*                                                                      */
541         /*   - ADC clock mode and ACC prescaler (CKMODE and PRESC bits)are set  */
542         /*     according to adc->Init.ClockPrescaler. It selects the clock      */
543         /*    source and sets the clock division factor.                        */
544         /*                                                                      */
545         /* Some parameters of this register are not reset, since they are set   */
546         /* by other functions and must be kept in case of usage of this         */
547         /* function on the fly (update of a parameter of ADC_InitTypeDef        */
548         /* without needing to reconfigure all other ADC groups/channels         */
549         /* parameters):                                                         */
550         /*   - when multimode feature is available, multimode-related           */
551         /*     parameters: MDMA, DMACFG, DELAY, DUAL (set by API                */
552         /*     HAL_ADCEx_MultiModeConfigChannel() )                             */
553         /*   - internal measurement paths: Vbat, temperature sensor, Vref       */
554         /*     (set into HAL_ADC_ConfigChannel() or                             */
555         /*     HAL_ADCEx_InjectedConfigChannel() )                              */
556         LL_ADC_SetCommonClock(__LL_ADC_COMMON_INSTANCE(hadc->Instance), hadc->Init.ClockPrescaler);
557       }
558     }
559 
560     /* Configuration of ADC:                                                  */
561     /*  - resolution                               Init.Resolution            */
562     /*  - data alignment                           Init.DataAlign             */
563     /*  - external trigger to start conversion     Init.ExternalTrigConv      */
564     /*  - external trigger polarity                Init.ExternalTrigConvEdge  */
565     /*  - continuous conversion mode               Init.ContinuousConvMode    */
566     /*  - overrun                                  Init.Overrun               */
567     /*  - discontinuous mode                       Init.DiscontinuousConvMode */
568     /*  - discontinuous mode channel count         Init.NbrOfDiscConversion   */
569     tmp_cfgr  = (ADC_CFGR_CONTINUOUS((uint32_t)hadc->Init.ContinuousConvMode)           |
570                  hadc->Init.Overrun                                                     |
571                  hadc->Init.DataAlign                                                   |
572                  hadc->Init.Resolution                                                  |
573                  ADC_CFGR_REG_DISCONTINUOUS((uint32_t)hadc->Init.DiscontinuousConvMode));
574 
575     if (hadc->Init.DiscontinuousConvMode == ENABLE)
576     {
577       tmp_cfgr |= ADC_CFGR_DISCONTINUOUS_NUM(hadc->Init.NbrOfDiscConversion);
578     }
579 
580     /* Enable external trigger if trigger selection is different of software  */
581     /* start.                                                                 */
582     /* Note: This configuration keeps the hardware feature of parameter       */
583     /*       ExternalTrigConvEdge "trigger edge none" equivalent to           */
584     /*       software start.                                                  */
585     if (hadc->Init.ExternalTrigConv != ADC_SOFTWARE_START)
586     {
587       tmp_cfgr |= ((hadc->Init.ExternalTrigConv & ADC_CFGR_EXTSEL)
588                    | hadc->Init.ExternalTrigConvEdge
589                   );
590     }
591 
592     /* Update Configuration Register CFGR */
593     MODIFY_REG(hadc->Instance->CFGR, ADC_CFGR_FIELDS_1, tmp_cfgr);
594 
595     /* Parameters update conditioned to ADC state:                            */
596     /* Parameters that can be updated when ADC is disabled or enabled without */
597     /* conversion on going on regular and injected groups:                    */
598     /*  - DMA continuous request          Init.DMAContinuousRequests          */
599     /*  - LowPowerAutoWait feature        Init.LowPowerAutoWait               */
600     /*  - Oversampling parameters         Init.Oversampling                   */
601     tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
602     if ((tmp_adc_is_conversion_on_going_regular == 0UL)
603         && (tmp_adc_is_conversion_on_going_injected == 0UL)
604        )
605     {
606       tmp_cfgr = (ADC_CFGR_DFSDM(hadc)                                            |
607                    ADC_CFGR_AUTOWAIT((uint32_t)hadc->Init.LowPowerAutoWait)        |
608                    ADC_CFGR_DMACONTREQ((uint32_t)hadc->Init.DMAContinuousRequests));
609 
610       MODIFY_REG(hadc->Instance->CFGR, ADC_CFGR_FIELDS_2, tmp_cfgr);
611 
612       if (hadc->Init.OversamplingMode == ENABLE)
613       {
614         assert_param(IS_ADC_OVERSAMPLING_RATIO(hadc->Init.Oversampling.Ratio));
615         assert_param(IS_ADC_RIGHT_BIT_SHIFT(hadc->Init.Oversampling.RightBitShift));
616         assert_param(IS_ADC_TRIGGERED_OVERSAMPLING_MODE(hadc->Init.Oversampling.TriggeredMode));
617         assert_param(IS_ADC_REGOVERSAMPLING_MODE(hadc->Init.Oversampling.OversamplingStopReset));
618 
619         /* Configuration of Oversampler:                                      */
620         /*  - Oversampling Ratio                                              */
621         /*  - Right bit shift                                                 */
622         /*  - Triggered mode                                                  */
623         /*  - Oversampling mode (continued/resumed)                           */
624         MODIFY_REG(hadc->Instance->CFGR2,
625                    ADC_CFGR2_OVSR  |
626                    ADC_CFGR2_OVSS  |
627                    ADC_CFGR2_TROVS |
628                    ADC_CFGR2_ROVSM,
629                    ADC_CFGR2_ROVSE                       |
630                    hadc->Init.Oversampling.Ratio         |
631                    hadc->Init.Oversampling.RightBitShift |
632                    hadc->Init.Oversampling.TriggeredMode |
633                    hadc->Init.Oversampling.OversamplingStopReset
634                   );
635       }
636       else
637       {
638         /* Disable ADC oversampling scope on ADC group regular */
639         CLEAR_BIT(hadc->Instance->CFGR2, ADC_CFGR2_ROVSE);
640       }
641 
642     }
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 
653     if (hadc->Init.ScanConvMode == ADC_SCAN_ENABLE)
654     {
655       /* Set number of ranks in regular group sequencer */
656       MODIFY_REG(hadc->Instance->SQR1, ADC_SQR1_L, (hadc->Init.NbrOfConversion - (uint8_t)1));
657     }
658     else
659     {
660       CLEAR_BIT(hadc->Instance->SQR1, ADC_SQR1_L);
661     }
662 
663     /* Initialize the ADC state */
664     /* Clear HAL_ADC_STATE_BUSY_INTERNAL bit, set HAL_ADC_STATE_READY bit */
665     ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL, HAL_ADC_STATE_READY);
666   }
667   else
668   {
669     /* Update ADC state machine to error */
670     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
671 
672     tmp_hal_status = HAL_ERROR;
673   }
674 
675   /* Return function status */
676   return tmp_hal_status;
677 }
678 
679 /**
680   * @brief  Deinitialize the ADC peripheral registers to their default reset
681   *         values, with deinitialization of the ADC MSP.
682   * @note   For devices with several ADCs: reset of ADC common registers is done
683   *         only if all ADCs sharing the same common group are disabled.
684   *         (function "HAL_ADC_MspDeInit()" is also called under the same conditions:
685   *         all ADC instances use the same core clock at RCC level, disabling
686   *         the core clock reset all ADC instances).
687   *         If this is not the case, reset of these common parameters reset is
688   *         bypassed without error reporting: it can be the intended behavior in
689   *         case of reset of a single ADC while the other ADCs sharing the same
690   *         common group is still running.
691   * @note   By default, HAL_ADC_DeInit() set ADC in mode deep power-down:
692   *         this saves more power by reducing leakage currents
693   *         and is particularly interesting before entering MCU low-power modes.
694   * @param hadc ADC handle
695   * @retval HAL status
696   */
HAL_ADC_DeInit(ADC_HandleTypeDef * hadc)697 HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc)
698 {
699   HAL_StatusTypeDef tmp_hal_status;
700 
701   /* Check ADC handle */
702   if (hadc == NULL)
703   {
704     return HAL_ERROR;
705   }
706 
707   /* Check the parameters */
708   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
709 
710   /* Set ADC state */
711   SET_BIT(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL);
712 
713   /* Stop potential conversion on going */
714   tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_INJECTED_GROUP);
715 
716   /* Disable ADC peripheral if conversions are effectively stopped            */
717   /* Flush register JSQR: reset the queue sequencer when injected             */
718   /* queue sequencer is enabled and ADC disabled.                             */
719   /* The software and hardware triggers of the injected sequence are both     */
720   /* internally disabled just after the completion of the last valid          */
721   /* injected sequence.                                                       */
722   SET_BIT(hadc->Instance->CFGR, ADC_CFGR_JQM);
723 
724   /* Disable ADC peripheral if conversions are effectively stopped */
725   if (tmp_hal_status == HAL_OK)
726   {
727     /* Disable the ADC peripheral */
728     tmp_hal_status = ADC_Disable(hadc);
729 
730     /* Check if ADC is effectively disabled */
731     if (tmp_hal_status == HAL_OK)
732     {
733       /* Change ADC state */
734       hadc->State = HAL_ADC_STATE_READY;
735     }
736   }
737 
738   /* Note: HAL ADC deInit is done independently of ADC conversion stop        */
739   /*       and disable return status. In case of status fail, attempt to      */
740   /*       perform deinitialization anyway and it is up user code in          */
741   /*       in HAL_ADC_MspDeInit() to reset the ADC peripheral using           */
742   /*       system RCC hard reset.                                             */
743 
744   /* ========== Reset ADC registers ========== */
745   /* Reset register IER */
746   __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_AWD3  | ADC_IT_AWD2 | ADC_IT_AWD1 |
747                               ADC_IT_JQOVF | ADC_IT_OVR  |
748                               ADC_IT_JEOS  | ADC_IT_JEOC |
749                               ADC_IT_EOS   | ADC_IT_EOC  |
750                               ADC_IT_EOSMP | ADC_IT_RDY));
751 
752   /* Reset register ISR */
753   __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD3  | ADC_FLAG_AWD2 | ADC_FLAG_AWD1 |
754                               ADC_FLAG_JQOVF | ADC_FLAG_OVR  |
755                               ADC_FLAG_JEOS  | ADC_FLAG_JEOC |
756                               ADC_FLAG_EOS   | ADC_FLAG_EOC  |
757                               ADC_FLAG_EOSMP | ADC_FLAG_RDY));
758 
759   /* Reset register CR */
760   /* Bits ADC_CR_JADSTP, ADC_CR_ADSTP, ADC_CR_JADSTART, ADC_CR_ADSTART,
761      ADC_CR_ADCAL, ADC_CR_ADDIS and ADC_CR_ADEN are in access mode "read-set":
762      no direct reset applicable.
763      Update CR register to reset value where doable by software */
764   CLEAR_BIT(hadc->Instance->CR, ADC_CR_ADVREGEN | ADC_CR_ADCALDIF);
765   SET_BIT(hadc->Instance->CR, ADC_CR_DEEPPWD);
766 
767   /* Reset register CFGR */
768   CLEAR_BIT(hadc->Instance->CFGR, ADC_CFGR_FIELDS);
769   SET_BIT(hadc->Instance->CFGR, ADC_CFGR_JQDIS);
770 
771   /* Reset register CFGR2 */
772   CLEAR_BIT(hadc->Instance->CFGR2, ADC_CFGR2_ROVSM  | ADC_CFGR2_TROVS   | ADC_CFGR2_OVSS |
773             ADC_CFGR2_OVSR  | ADC_CFGR2_JOVSE | ADC_CFGR2_ROVSE);
774 
775   /* Reset register SMPR1 */
776   CLEAR_BIT(hadc->Instance->SMPR1, ADC_SMPR1_FIELDS);
777 
778   /* Reset register SMPR2 */
779   CLEAR_BIT(hadc->Instance->SMPR2, ADC_SMPR2_SMP18 | ADC_SMPR2_SMP17 | ADC_SMPR2_SMP16 |
780             ADC_SMPR2_SMP15 | ADC_SMPR2_SMP14 | ADC_SMPR2_SMP13 |
781             ADC_SMPR2_SMP12 | ADC_SMPR2_SMP11 | ADC_SMPR2_SMP10);
782 
783   /* Reset register TR1 */
784   CLEAR_BIT(hadc->Instance->TR1, ADC_TR1_HT1 | ADC_TR1_LT1);
785 
786   /* Reset register TR2 */
787   CLEAR_BIT(hadc->Instance->TR2, ADC_TR2_HT2 | ADC_TR2_LT2);
788 
789   /* Reset register TR3 */
790   CLEAR_BIT(hadc->Instance->TR3, ADC_TR3_HT3 | ADC_TR3_LT3);
791 
792   /* Reset register SQR1 */
793   CLEAR_BIT(hadc->Instance->SQR1, ADC_SQR1_SQ4 | ADC_SQR1_SQ3 | ADC_SQR1_SQ2 |
794             ADC_SQR1_SQ1 | ADC_SQR1_L);
795 
796   /* Reset register SQR2 */
797   CLEAR_BIT(hadc->Instance->SQR2, ADC_SQR2_SQ9 | ADC_SQR2_SQ8 | ADC_SQR2_SQ7 |
798             ADC_SQR2_SQ6 | ADC_SQR2_SQ5);
799 
800   /* Reset register SQR3 */
801   CLEAR_BIT(hadc->Instance->SQR3, ADC_SQR3_SQ14 | ADC_SQR3_SQ13 | ADC_SQR3_SQ12 |
802             ADC_SQR3_SQ11 | ADC_SQR3_SQ10);
803 
804   /* Reset register SQR4 */
805   CLEAR_BIT(hadc->Instance->SQR4, ADC_SQR4_SQ16 | ADC_SQR4_SQ15);
806 
807   /* Register JSQR was reset when the ADC was disabled */
808 
809   /* Reset register DR */
810   /* bits in access mode read only, no direct reset applicable*/
811 
812   /* Reset register OFR1 */
813   CLEAR_BIT(hadc->Instance->OFR1, ADC_OFR1_OFFSET1_EN | ADC_OFR1_OFFSET1_CH | ADC_OFR1_OFFSET1);
814   /* Reset register OFR2 */
815   CLEAR_BIT(hadc->Instance->OFR2, ADC_OFR2_OFFSET2_EN | ADC_OFR2_OFFSET2_CH | ADC_OFR2_OFFSET2);
816   /* Reset register OFR3 */
817   CLEAR_BIT(hadc->Instance->OFR3, ADC_OFR3_OFFSET3_EN | ADC_OFR3_OFFSET3_CH | ADC_OFR3_OFFSET3);
818   /* Reset register OFR4 */
819   CLEAR_BIT(hadc->Instance->OFR4, ADC_OFR4_OFFSET4_EN | ADC_OFR4_OFFSET4_CH | ADC_OFR4_OFFSET4);
820 
821   /* Reset registers JDR1, JDR2, JDR3, JDR4 */
822   /* bits in access mode read only, no direct reset applicable*/
823 
824   /* Reset register AWD2CR */
825   CLEAR_BIT(hadc->Instance->AWD2CR, ADC_AWD2CR_AWD2CH);
826 
827   /* Reset register AWD3CR */
828   CLEAR_BIT(hadc->Instance->AWD3CR, ADC_AWD3CR_AWD3CH);
829 
830   /* Reset register DIFSEL */
831   CLEAR_BIT(hadc->Instance->DIFSEL, ADC_DIFSEL_DIFSEL);
832 
833   /* Reset register CALFACT */
834   CLEAR_BIT(hadc->Instance->CALFACT, ADC_CALFACT_CALFACT_D | ADC_CALFACT_CALFACT_S);
835 
836 
837   /* ========== Reset common ADC registers ========== */
838 
839   /* Software is allowed to change common parameters only when all the other
840      ADCs are disabled.   */
841   if (__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) == 0UL)
842   {
843     /* Reset configuration of ADC common register CCR:
844       - clock mode: CKMODE, PRESCEN
845       - multimode related parameters (when this feature is available): MDMA,
846         DMACFG, DELAY, DUAL (set by HAL_ADCEx_MultiModeConfigChannel() API)
847       - internal measurement paths: Vbat, temperature sensor, Vref (set into
848         HAL_ADC_ConfigChannel() or HAL_ADCEx_InjectedConfigChannel() )
849     */
850     ADC_CLEAR_COMMON_CONTROL_REGISTER(hadc);
851 
852     /* ========== Hard reset ADC peripheral ========== */
853     /* Performs a global reset of the entire ADC peripherals instances        */
854     /* sharing the same common ADC instance: ADC state is forced to           */
855     /* a similar state as after device power-on.                              */
856     /* Note: A possible implementation is to add RCC bus reset of ADC         */
857     /* (for example, using macro                                              */
858     /*  __HAL_RCC_ADC..._FORCE_RESET()/..._RELEASE_RESET()/..._CLK_DISABLE()) */
859     /* in function "void HAL_ADC_MspDeInit(ADC_HandleTypeDef *hadc)":         */
860 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
861     if (hadc->MspDeInitCallback == NULL)
862     {
863       hadc->MspDeInitCallback = HAL_ADC_MspDeInit; /* Legacy weak MspDeInit  */
864     }
865 
866     /* DeInit the low level hardware */
867     hadc->MspDeInitCallback(hadc);
868 #else
869     /* DeInit the low level hardware */
870     HAL_ADC_MspDeInit(hadc);
871 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
872   }
873 
874   /* Set ADC error code to none */
875   ADC_CLEAR_ERRORCODE(hadc);
876 
877   /* Reset injected channel configuration parameters */
878   hadc->InjectionConfig.ContextQueue = 0;
879   hadc->InjectionConfig.ChannelCount = 0;
880 
881   /* Set ADC state */
882   hadc->State = HAL_ADC_STATE_RESET;
883 
884   /* Process unlocked */
885   __HAL_UNLOCK(hadc);
886 
887   /* Return function status */
888   return tmp_hal_status;
889 }
890 
891 /**
892   * @brief  Initialize the ADC MSP.
893   * @param hadc ADC handle
894   * @retval None
895   */
HAL_ADC_MspInit(ADC_HandleTypeDef * hadc)896 __weak void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc)
897 {
898   /* Prevent unused argument(s) compilation warning */
899   UNUSED(hadc);
900 
901   /* NOTE : This function should not be modified. When the callback is needed,
902             function HAL_ADC_MspInit must be implemented in the user file.
903    */
904 }
905 
906 /**
907   * @brief  DeInitialize the ADC MSP.
908   * @param hadc ADC handle
909   * @note   All ADC instances use the same core clock at RCC level, disabling
910   *         the core clock reset all ADC instances).
911   * @retval None
912   */
HAL_ADC_MspDeInit(ADC_HandleTypeDef * hadc)913 __weak void HAL_ADC_MspDeInit(ADC_HandleTypeDef *hadc)
914 {
915   /* Prevent unused argument(s) compilation warning */
916   UNUSED(hadc);
917 
918   /* NOTE : This function should not be modified. When the callback is needed,
919             function HAL_ADC_MspDeInit must be implemented in the user file.
920    */
921 }
922 
923 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
924 /**
925   * @brief  Register a User ADC Callback
926   *         To be used instead of the weak predefined callback
927   * @param  hadc Pointer to a ADC_HandleTypeDef structure that contains
928   *                the configuration information for the specified ADC.
929   * @param  CallbackID ID of the callback to be registered
930   *         This parameter can be one of the following values:
931   *          @arg @ref HAL_ADC_CONVERSION_COMPLETE_CB_ID      ADC conversion complete callback ID
932   *          @arg @ref HAL_ADC_CONVERSION_HALF_CB_ID          ADC conversion DMA half-transfer callback ID
933   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID    ADC analog watchdog 1 callback ID
934   *          @arg @ref HAL_ADC_ERROR_CB_ID                    ADC error callback ID
935   *          @arg @ref HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID  ADC group injected conversion complete callback ID
936   *          @arg @ref HAL_ADC_INJ_QUEUE_OVEFLOW_CB_ID        ADC group injected context queue overflow callback ID
937   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID    ADC analog watchdog 2 callback ID
938   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID    ADC analog watchdog 3 callback ID
939   *          @arg @ref HAL_ADC_END_OF_SAMPLING_CB_ID          ADC end of sampling callback ID
940   *          @arg @ref HAL_ADC_MSPINIT_CB_ID                  ADC Msp Init callback ID
941   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID                ADC Msp DeInit callback ID
942   *          @arg @ref HAL_ADC_MSPINIT_CB_ID MspInit callback ID
943   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID MspDeInit callback ID
944   * @param  pCallback pointer to the Callback function
945   * @retval HAL status
946   */
HAL_ADC_RegisterCallback(ADC_HandleTypeDef * hadc,HAL_ADC_CallbackIDTypeDef CallbackID,pADC_CallbackTypeDef pCallback)947 HAL_StatusTypeDef HAL_ADC_RegisterCallback(ADC_HandleTypeDef *hadc, HAL_ADC_CallbackIDTypeDef CallbackID,
948                                            pADC_CallbackTypeDef pCallback)
949 {
950   HAL_StatusTypeDef status = HAL_OK;
951 
952   if (pCallback == NULL)
953   {
954     /* Update the error code */
955     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
956 
957     return HAL_ERROR;
958   }
959 
960   if ((hadc->State & HAL_ADC_STATE_READY) != 0UL)
961   {
962     switch (CallbackID)
963     {
964       case HAL_ADC_CONVERSION_COMPLETE_CB_ID :
965         hadc->ConvCpltCallback = pCallback;
966         break;
967 
968       case HAL_ADC_CONVERSION_HALF_CB_ID :
969         hadc->ConvHalfCpltCallback = pCallback;
970         break;
971 
972       case HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID :
973         hadc->LevelOutOfWindowCallback = pCallback;
974         break;
975 
976       case HAL_ADC_ERROR_CB_ID :
977         hadc->ErrorCallback = pCallback;
978         break;
979 
980       case HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID :
981         hadc->InjectedConvCpltCallback = pCallback;
982         break;
983 
984       case HAL_ADC_INJ_QUEUE_OVEFLOW_CB_ID :
985         hadc->InjectedQueueOverflowCallback = pCallback;
986         break;
987 
988       case HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID :
989         hadc->LevelOutOfWindow2Callback = pCallback;
990         break;
991 
992       case HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID :
993         hadc->LevelOutOfWindow3Callback = pCallback;
994         break;
995 
996       case HAL_ADC_END_OF_SAMPLING_CB_ID :
997         hadc->EndOfSamplingCallback = pCallback;
998         break;
999 
1000       case HAL_ADC_MSPINIT_CB_ID :
1001         hadc->MspInitCallback = pCallback;
1002         break;
1003 
1004       case HAL_ADC_MSPDEINIT_CB_ID :
1005         hadc->MspDeInitCallback = pCallback;
1006         break;
1007 
1008       default :
1009         /* Update the error code */
1010         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1011 
1012         /* Return error status */
1013         status = HAL_ERROR;
1014         break;
1015     }
1016   }
1017   else if (HAL_ADC_STATE_RESET == hadc->State)
1018   {
1019     switch (CallbackID)
1020     {
1021       case HAL_ADC_MSPINIT_CB_ID :
1022         hadc->MspInitCallback = pCallback;
1023         break;
1024 
1025       case HAL_ADC_MSPDEINIT_CB_ID :
1026         hadc->MspDeInitCallback = pCallback;
1027         break;
1028 
1029       default :
1030         /* Update the error code */
1031         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1032 
1033         /* Return error status */
1034         status = HAL_ERROR;
1035         break;
1036     }
1037   }
1038   else
1039   {
1040     /* Update the error code */
1041     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1042 
1043     /* Return error status */
1044     status =  HAL_ERROR;
1045   }
1046 
1047   return status;
1048 }
1049 
1050 /**
1051   * @brief  Unregister a ADC Callback
1052   *         ADC callback is redirected to the weak predefined callback
1053   * @param  hadc Pointer to a ADC_HandleTypeDef structure that contains
1054   *                the configuration information for the specified ADC.
1055   * @param  CallbackID ID of the callback to be unregistered
1056   *         This parameter can be one of the following values:
1057   *          @arg @ref HAL_ADC_CONVERSION_COMPLETE_CB_ID      ADC conversion complete callback ID
1058   *          @arg @ref HAL_ADC_CONVERSION_HALF_CB_ID          ADC conversion DMA half-transfer callback ID
1059   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID    ADC analog watchdog 1 callback ID
1060   *          @arg @ref HAL_ADC_ERROR_CB_ID                    ADC error callback ID
1061   *          @arg @ref HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID  ADC group injected conversion complete callback ID
1062   *          @arg @ref HAL_ADC_INJ_QUEUE_OVEFLOW_CB_ID        ADC group injected context queue overflow callback ID
1063   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID    ADC analog watchdog 2 callback ID
1064   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID    ADC analog watchdog 3 callback ID
1065   *          @arg @ref HAL_ADC_END_OF_SAMPLING_CB_ID          ADC end of sampling callback ID
1066   *          @arg @ref HAL_ADC_MSPINIT_CB_ID                  ADC Msp Init callback ID
1067   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID                ADC Msp DeInit callback ID
1068   *          @arg @ref HAL_ADC_MSPINIT_CB_ID MspInit callback ID
1069   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID MspDeInit callback ID
1070   * @retval HAL status
1071   */
HAL_ADC_UnRegisterCallback(ADC_HandleTypeDef * hadc,HAL_ADC_CallbackIDTypeDef CallbackID)1072 HAL_StatusTypeDef HAL_ADC_UnRegisterCallback(ADC_HandleTypeDef *hadc, HAL_ADC_CallbackIDTypeDef CallbackID)
1073 {
1074   HAL_StatusTypeDef status = HAL_OK;
1075 
1076   if ((hadc->State & HAL_ADC_STATE_READY) != 0UL)
1077   {
1078     switch (CallbackID)
1079     {
1080       case HAL_ADC_CONVERSION_COMPLETE_CB_ID :
1081         hadc->ConvCpltCallback = HAL_ADC_ConvCpltCallback;
1082         break;
1083 
1084       case HAL_ADC_CONVERSION_HALF_CB_ID :
1085         hadc->ConvHalfCpltCallback = HAL_ADC_ConvHalfCpltCallback;
1086         break;
1087 
1088       case HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID :
1089         hadc->LevelOutOfWindowCallback = HAL_ADC_LevelOutOfWindowCallback;
1090         break;
1091 
1092       case HAL_ADC_ERROR_CB_ID :
1093         hadc->ErrorCallback = HAL_ADC_ErrorCallback;
1094         break;
1095 
1096       case HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID :
1097         hadc->InjectedConvCpltCallback = HAL_ADCEx_InjectedConvCpltCallback;
1098         break;
1099 
1100       case HAL_ADC_INJ_QUEUE_OVEFLOW_CB_ID :
1101         hadc->InjectedQueueOverflowCallback = HAL_ADCEx_InjectedQueueOverflowCallback;
1102         break;
1103 
1104       case HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID :
1105         hadc->LevelOutOfWindow2Callback = HAL_ADCEx_LevelOutOfWindow2Callback;
1106         break;
1107 
1108       case HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID :
1109         hadc->LevelOutOfWindow3Callback = HAL_ADCEx_LevelOutOfWindow3Callback;
1110         break;
1111 
1112       case HAL_ADC_END_OF_SAMPLING_CB_ID :
1113         hadc->EndOfSamplingCallback = HAL_ADCEx_EndOfSamplingCallback;
1114         break;
1115 
1116       case HAL_ADC_MSPINIT_CB_ID :
1117         hadc->MspInitCallback = HAL_ADC_MspInit; /* Legacy weak MspInit              */
1118         break;
1119 
1120       case HAL_ADC_MSPDEINIT_CB_ID :
1121         hadc->MspDeInitCallback = HAL_ADC_MspDeInit; /* Legacy weak MspDeInit            */
1122         break;
1123 
1124       default :
1125         /* Update the error code */
1126         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1127 
1128         /* Return error status */
1129         status =  HAL_ERROR;
1130         break;
1131     }
1132   }
1133   else if (HAL_ADC_STATE_RESET == hadc->State)
1134   {
1135     switch (CallbackID)
1136     {
1137       case HAL_ADC_MSPINIT_CB_ID :
1138         hadc->MspInitCallback = HAL_ADC_MspInit;                   /* Legacy weak MspInit              */
1139         break;
1140 
1141       case HAL_ADC_MSPDEINIT_CB_ID :
1142         hadc->MspDeInitCallback = HAL_ADC_MspDeInit;               /* Legacy weak MspDeInit            */
1143         break;
1144 
1145       default :
1146         /* Update the error code */
1147         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1148 
1149         /* Return error status */
1150         status =  HAL_ERROR;
1151         break;
1152     }
1153   }
1154   else
1155   {
1156     /* Update the error code */
1157     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1158 
1159     /* Return error status */
1160     status =  HAL_ERROR;
1161   }
1162 
1163   return status;
1164 }
1165 
1166 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1167 
1168 /**
1169   * @}
1170   */
1171 
1172 /** @defgroup ADC_Exported_Functions_Group2 ADC Input and Output operation functions
1173   * @brief    ADC IO operation functions
1174   *
1175 @verbatim
1176  ===============================================================================
1177                       ##### IO operation functions #####
1178  ===============================================================================
1179     [..]  This section provides functions allowing to:
1180       (+) Start conversion of regular group.
1181       (+) Stop conversion of regular group.
1182       (+) Poll for conversion complete on regular group.
1183       (+) Poll for conversion event.
1184       (+) Get result of regular channel conversion.
1185       (+) Start conversion of regular group and enable interruptions.
1186       (+) Stop conversion of regular group and disable interruptions.
1187       (+) Handle ADC interrupt request
1188       (+) Start conversion of regular group and enable DMA transfer.
1189       (+) Stop conversion of regular group and disable ADC DMA transfer.
1190 @endverbatim
1191   * @{
1192   */
1193 
1194 /**
1195   * @brief  Enable ADC, start conversion of regular group.
1196   * @note   Interruptions enabled in this function: None.
1197   * @note   Case of multimode enabled (when multimode feature is available):
1198   *           if ADC is Slave, ADC is enabled but conversion is not started,
1199   *           if ADC is master, ADC is enabled and multimode conversion is started.
1200   * @param hadc ADC handle
1201   * @retval HAL status
1202   */
HAL_ADC_Start(ADC_HandleTypeDef * hadc)1203 HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef *hadc)
1204 {
1205   HAL_StatusTypeDef tmp_hal_status;
1206 #if defined(ADC_MULTIMODE_SUPPORT)
1207   const ADC_TypeDef *tmpADC_Master;
1208   uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
1209 #endif /* ADC_MULTIMODE_SUPPORT */
1210 
1211   /* Check the parameters */
1212   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1213 
1214   /* Perform ADC enable and conversion start if no conversion is on going */
1215   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1216   {
1217     /* Process locked */
1218     __HAL_LOCK(hadc);
1219 
1220     /* Enable the ADC peripheral */
1221     tmp_hal_status = ADC_Enable(hadc);
1222 
1223     /* Start conversion if ADC is effectively enabled */
1224     if (tmp_hal_status == HAL_OK)
1225     {
1226       /* Set ADC state                                                        */
1227       /* - Clear state bitfield related to regular group conversion results   */
1228       /* - Set state bitfield related to regular operation                    */
1229       ADC_STATE_CLR_SET(hadc->State,
1230                         HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
1231                         HAL_ADC_STATE_REG_BUSY);
1232 
1233 #if defined(ADC_MULTIMODE_SUPPORT)
1234       /* Reset HAL_ADC_STATE_MULTIMODE_SLAVE bit
1235         - if ADC instance is master or if multimode feature is not available
1236         - if multimode setting is disabled (ADC instance slave in independent mode) */
1237       if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
1238           || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
1239          )
1240       {
1241         CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
1242       }
1243 #endif /* ADC_MULTIMODE_SUPPORT */
1244 
1245       /* Set ADC error code */
1246       /* Check if a conversion is on going on ADC group injected */
1247       if (HAL_IS_BIT_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY))
1248       {
1249         /* Reset ADC error code fields related to regular conversions only */
1250         CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
1251       }
1252       else
1253       {
1254         /* Reset all ADC error code fields */
1255         ADC_CLEAR_ERRORCODE(hadc);
1256       }
1257 
1258       /* Clear ADC group regular conversion flag and overrun flag               */
1259       /* (To ensure of no unknown state from potential previous ADC operations) */
1260       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
1261 
1262       /* Process unlocked */
1263       /* Unlock before starting ADC conversions: in case of potential         */
1264       /* interruption, to let the process to ADC IRQ Handler.                 */
1265       __HAL_UNLOCK(hadc);
1266 
1267       /* Enable conversion of regular group.                                  */
1268       /* If software start has been selected, conversion starts immediately.  */
1269       /* If external trigger has been selected, conversion will start at next */
1270       /* trigger event.                                                       */
1271       /* Case of multimode enabled (when multimode feature is available):     */
1272       /*  - if ADC is slave and dual regular conversions are enabled, ADC is  */
1273       /*    enabled only (conversion is not started),                         */
1274       /*  - if ADC is master, ADC is enabled and conversion is started.       */
1275 #if defined(ADC_MULTIMODE_SUPPORT)
1276       if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
1277           || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
1278           || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
1279           || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
1280          )
1281       {
1282         /* ADC instance is not a multimode slave instance with multimode regular conversions enabled */
1283         if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_JAUTO) != 0UL)
1284         {
1285           ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
1286         }
1287 
1288         /* Start ADC group regular conversion */
1289         LL_ADC_REG_StartConversion(hadc->Instance);
1290       }
1291       else
1292       {
1293         /* ADC instance is a multimode slave instance with multimode regular conversions enabled */
1294         SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
1295         /* if Master ADC JAUTO bit is set, update Slave State in setting
1296            HAL_ADC_STATE_INJ_BUSY bit and in resetting HAL_ADC_STATE_INJ_EOC bit */
1297         tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
1298         if (READ_BIT(tmpADC_Master->CFGR, ADC_CFGR_JAUTO) != 0UL)
1299         {
1300           ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
1301         }
1302 
1303       }
1304 #else
1305       if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_JAUTO) != 0UL)
1306       {
1307         ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
1308       }
1309 
1310       /* Start ADC group regular conversion */
1311       LL_ADC_REG_StartConversion(hadc->Instance);
1312 #endif /* ADC_MULTIMODE_SUPPORT */
1313     }
1314     else
1315     {
1316       /* Process unlocked */
1317       __HAL_UNLOCK(hadc);
1318     }
1319   }
1320   else
1321   {
1322     tmp_hal_status = HAL_BUSY;
1323   }
1324 
1325   /* Return function status */
1326   return tmp_hal_status;
1327 }
1328 
1329 /**
1330   * @brief  Stop ADC conversion of regular group (and injected channels in
1331   *         case of auto_injection mode), disable ADC peripheral.
1332   * @note:  ADC peripheral disable is forcing stop of potential
1333   *         conversion on injected group. If injected group is under use, it
1334   *         should be preliminarily stopped using HAL_ADCEx_InjectedStop function.
1335   * @param hadc ADC handle
1336   * @retval HAL status.
1337   */
HAL_ADC_Stop(ADC_HandleTypeDef * hadc)1338 HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef *hadc)
1339 {
1340   HAL_StatusTypeDef tmp_hal_status;
1341 
1342   /* Check the parameters */
1343   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1344 
1345   /* Process locked */
1346   __HAL_LOCK(hadc);
1347 
1348   /* 1. Stop potential conversion on going, on ADC groups regular and injected */
1349   tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_INJECTED_GROUP);
1350 
1351   /* Disable ADC peripheral if conversions are effectively stopped */
1352   if (tmp_hal_status == HAL_OK)
1353   {
1354     /* 2. Disable the ADC peripheral */
1355     tmp_hal_status = ADC_Disable(hadc);
1356 
1357     /* Check if ADC is effectively disabled */
1358     if (tmp_hal_status == HAL_OK)
1359     {
1360       /* Set ADC state */
1361       ADC_STATE_CLR_SET(hadc->State,
1362                         HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
1363                         HAL_ADC_STATE_READY);
1364     }
1365   }
1366 
1367   /* Process unlocked */
1368   __HAL_UNLOCK(hadc);
1369 
1370   /* Return function status */
1371   return tmp_hal_status;
1372 }
1373 
1374 /**
1375   * @brief  Wait for regular group conversion to be completed.
1376   * @note   ADC conversion flags EOS (end of sequence) and EOC (end of
1377   *         conversion) are cleared by this function, with an exception:
1378   *         if low power feature "LowPowerAutoWait" is enabled, flags are
1379   *         not cleared to not interfere with this feature until data register
1380   *         is read using function HAL_ADC_GetValue().
1381   * @note   This function cannot be used in a particular setup: ADC configured
1382   *         in DMA mode and polling for end of each conversion (ADC init
1383   *         parameter "EOCSelection" set to ADC_EOC_SINGLE_CONV).
1384   *         In this case, DMA resets the flag EOC and polling cannot be
1385   *         performed on each conversion. Nevertheless, polling can still
1386   *         be performed on the complete sequence (ADC init
1387   *         parameter "EOCSelection" set to ADC_EOC_SEQ_CONV).
1388   * @param hadc ADC handle
1389   * @param Timeout Timeout value in millisecond.
1390   * @retval HAL status
1391   */
HAL_ADC_PollForConversion(ADC_HandleTypeDef * hadc,uint32_t Timeout)1392 HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef *hadc, uint32_t Timeout)
1393 {
1394   uint32_t tickstart;
1395   uint32_t tmp_Flag_End;
1396   uint32_t tmp_cfgr;
1397 #if defined(ADC_MULTIMODE_SUPPORT)
1398   const ADC_TypeDef *tmpADC_Master;
1399   uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
1400 #endif /* ADC_MULTIMODE_SUPPORT */
1401 
1402   /* Check the parameters */
1403   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1404 
1405   /* If end of conversion selected to end of sequence conversions */
1406   if (hadc->Init.EOCSelection == ADC_EOC_SEQ_CONV)
1407   {
1408     tmp_Flag_End = ADC_FLAG_EOS;
1409   }
1410   /* If end of conversion selected to end of unitary conversion */
1411   else /* ADC_EOC_SINGLE_CONV */
1412   {
1413     /* Verification that ADC configuration is compliant with polling for      */
1414     /* each conversion:                                                       */
1415     /* Particular case is ADC configured in DMA mode and ADC sequencer with   */
1416     /* several ranks and polling for end of each conversion.                  */
1417     /* For code simplicity sake, this particular case is generalized to       */
1418     /* ADC configured in DMA mode and and polling for end of each conversion. */
1419 #if defined(ADC_MULTIMODE_SUPPORT)
1420     if ((tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
1421         || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
1422         || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
1423        )
1424     {
1425       /* Check ADC DMA mode in independent mode on ADC group regular */
1426       if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_DMAEN) != 0UL)
1427       {
1428         SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1429         return HAL_ERROR;
1430       }
1431       else
1432       {
1433         tmp_Flag_End = (ADC_FLAG_EOC);
1434       }
1435     }
1436     else
1437     {
1438       /* Check ADC DMA mode in multimode on ADC group regular */
1439       if (LL_ADC_GetMultiDMATransfer(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) != LL_ADC_MULTI_REG_DMA_EACH_ADC)
1440       {
1441         SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1442         return HAL_ERROR;
1443       }
1444       else
1445       {
1446         tmp_Flag_End = (ADC_FLAG_EOC);
1447       }
1448     }
1449 #else
1450     /* Check ADC DMA mode */
1451     if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_DMAEN) != 0UL)
1452     {
1453       SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1454       return HAL_ERROR;
1455     }
1456     else
1457     {
1458       tmp_Flag_End = (ADC_FLAG_EOC);
1459     }
1460 #endif /* ADC_MULTIMODE_SUPPORT */
1461   }
1462 
1463   /* Get tick count */
1464   tickstart = HAL_GetTick();
1465 
1466   /* Wait until End of unitary conversion or sequence conversions flag is raised */
1467   while ((hadc->Instance->ISR & tmp_Flag_End) == 0UL)
1468   {
1469     /* Check if timeout is disabled (set to infinite wait) */
1470     if (Timeout != HAL_MAX_DELAY)
1471     {
1472       if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
1473       {
1474         /* New check to avoid false timeout detection in case of preemption */
1475         if ((hadc->Instance->ISR & tmp_Flag_End) == 0UL)
1476         {
1477           /* Update ADC state machine to timeout */
1478           SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
1479 
1480           /* Process unlocked */
1481           __HAL_UNLOCK(hadc);
1482 
1483           return HAL_TIMEOUT;
1484         }
1485       }
1486     }
1487   }
1488 
1489   /* Update ADC state machine */
1490   SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
1491 
1492   /* Determine whether any further conversion upcoming on group regular       */
1493   /* by external trigger, continuous mode or scan sequence on going.          */
1494   if ((LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
1495       && (hadc->Init.ContinuousConvMode == DISABLE)
1496      )
1497   {
1498     /* Check whether end of sequence is reached */
1499     if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS))
1500     {
1501       /* Set ADC state */
1502       CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
1503 
1504       if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) == 0UL)
1505       {
1506         SET_BIT(hadc->State, HAL_ADC_STATE_READY);
1507       }
1508     }
1509   }
1510 
1511   /* Get relevant register CFGR in ADC instance of ADC master or slave        */
1512   /* in function of multimode state (for devices with multimode               */
1513   /* available).                                                              */
1514 #if defined(ADC_MULTIMODE_SUPPORT)
1515   if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
1516       || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
1517       || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
1518       || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
1519      )
1520   {
1521     /* Retrieve handle ADC CFGR register */
1522     tmp_cfgr = READ_REG(hadc->Instance->CFGR);
1523   }
1524   else
1525   {
1526     /* Retrieve Master ADC CFGR register */
1527     tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
1528     tmp_cfgr = READ_REG(tmpADC_Master->CFGR);
1529   }
1530 #else
1531   /* Retrieve handle ADC CFGR register */
1532   tmp_cfgr = READ_REG(hadc->Instance->CFGR);
1533 #endif /* ADC_MULTIMODE_SUPPORT */
1534 
1535   /* Clear polled flag */
1536   if (tmp_Flag_End == ADC_FLAG_EOS)
1537   {
1538     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOS);
1539   }
1540   else
1541   {
1542     /* Clear end of conversion EOC flag of regular group if low power feature */
1543     /* "LowPowerAutoWait " is disabled, to not interfere with this feature    */
1544     /* until data register is read using function HAL_ADC_GetValue().         */
1545     if (READ_BIT(tmp_cfgr, ADC_CFGR_AUTDLY) == 0UL)
1546     {
1547       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS));
1548     }
1549   }
1550 
1551   /* Return function status */
1552   return HAL_OK;
1553 }
1554 
1555 /**
1556   * @brief  Poll for ADC event.
1557   * @param hadc ADC handle
1558   * @param EventType the ADC event type.
1559   *          This parameter can be one of the following values:
1560   *            @arg @ref ADC_EOSMP_EVENT  ADC End of Sampling event
1561   *            @arg @ref ADC_AWD1_EVENT   ADC Analog watchdog 1 event (main analog watchdog, present on
1562   *                                       all STM32 series)
1563   *            @arg @ref ADC_AWD2_EVENT   ADC Analog watchdog 2 event (additional analog watchdog, not present on
1564   *                                       all STM32 series)
1565   *            @arg @ref ADC_AWD3_EVENT   ADC Analog watchdog 3 event (additional analog watchdog, not present on
1566   *                                       all STM32 series)
1567   *            @arg @ref ADC_OVR_EVENT    ADC Overrun event
1568   *            @arg @ref ADC_JQOVF_EVENT  ADC Injected context queue overflow event
1569   * @param Timeout Timeout value in millisecond.
1570   * @note   The relevant flag is cleared if found to be set, except for ADC_FLAG_OVR.
1571   *         Indeed, the latter is reset only if hadc->Init.Overrun field is set
1572   *         to ADC_OVR_DATA_OVERWRITTEN. Otherwise, data register may be potentially overwritten
1573   *         by a new converted data as soon as OVR is cleared.
1574   *         To reset OVR flag once the preserved data is retrieved, the user can resort
1575   *         to macro __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1576   * @retval HAL status
1577   */
HAL_ADC_PollForEvent(ADC_HandleTypeDef * hadc,uint32_t EventType,uint32_t Timeout)1578 HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef *hadc, uint32_t EventType, uint32_t Timeout)
1579 {
1580   uint32_t tickstart;
1581 
1582   /* Check the parameters */
1583   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1584   assert_param(IS_ADC_EVENT_TYPE(EventType));
1585 
1586   /* Get tick count */
1587   tickstart = HAL_GetTick();
1588 
1589   /* Check selected event flag */
1590   while (__HAL_ADC_GET_FLAG(hadc, EventType) == 0UL)
1591   {
1592     /* Check if timeout is disabled (set to infinite wait) */
1593     if (Timeout != HAL_MAX_DELAY)
1594     {
1595       if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
1596       {
1597         /* New check to avoid false timeout detection in case of preemption */
1598         if (__HAL_ADC_GET_FLAG(hadc, EventType) == 0UL)
1599         {
1600           /* Update ADC state machine to timeout */
1601           SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
1602 
1603           /* Process unlocked */
1604           __HAL_UNLOCK(hadc);
1605 
1606           return HAL_TIMEOUT;
1607         }
1608       }
1609     }
1610   }
1611 
1612   switch (EventType)
1613   {
1614     /* End Of Sampling event */
1615     case ADC_EOSMP_EVENT:
1616       /* Set ADC state */
1617       SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOSMP);
1618 
1619       /* Clear the End Of Sampling flag */
1620       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP);
1621 
1622       break;
1623 
1624     /* Analog watchdog (level out of window) event */
1625     /* Note: In case of several analog watchdog enabled, if needed to know      */
1626     /* which one triggered and on which ADCx, test ADC state of analog watchdog */
1627     /* flags HAL_ADC_STATE_AWD1/2/3 using function "HAL_ADC_GetState()".        */
1628     /* For example:                                                             */
1629     /*  " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD1) != 0UL) "          */
1630     /*  " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD2) != 0UL) "          */
1631     /*  " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD3) != 0UL) "          */
1632 
1633     /* Check analog watchdog 1 flag */
1634     case ADC_AWD_EVENT:
1635       /* Set ADC state */
1636       SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
1637 
1638       /* Clear ADC analog watchdog flag */
1639       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD1);
1640 
1641       break;
1642 
1643     /* Check analog watchdog 2 flag */
1644     case ADC_AWD2_EVENT:
1645       /* Set ADC state */
1646       SET_BIT(hadc->State, HAL_ADC_STATE_AWD2);
1647 
1648       /* Clear ADC analog watchdog flag */
1649       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD2);
1650 
1651       break;
1652 
1653     /* Check analog watchdog 3 flag */
1654     case ADC_AWD3_EVENT:
1655       /* Set ADC state */
1656       SET_BIT(hadc->State, HAL_ADC_STATE_AWD3);
1657 
1658       /* Clear ADC analog watchdog flag */
1659       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD3);
1660 
1661       break;
1662 
1663     /* Injected context queue overflow event */
1664     case ADC_JQOVF_EVENT:
1665       /* Set ADC state */
1666       SET_BIT(hadc->State, HAL_ADC_STATE_INJ_JQOVF);
1667 
1668       /* Set ADC error code to Injected context queue overflow */
1669       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_JQOVF);
1670 
1671       /* Clear ADC Injected context queue overflow flag */
1672       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JQOVF);
1673 
1674       break;
1675 
1676     /* Overrun event */
1677     default: /* Case ADC_OVR_EVENT */
1678       /* If overrun is set to overwrite previous data, overrun event is not     */
1679       /* considered as an error.                                                */
1680       /* (cf ref manual "Managing conversions without using the DMA and without */
1681       /* overrun ")                                                             */
1682       if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
1683       {
1684         /* Set ADC state */
1685         SET_BIT(hadc->State, HAL_ADC_STATE_REG_OVR);
1686 
1687         /* Set ADC error code to overrun */
1688         SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_OVR);
1689       }
1690       else
1691       {
1692         /* Clear ADC Overrun flag only if Overrun is set to ADC_OVR_DATA_OVERWRITTEN
1693            otherwise, data register is potentially overwritten by new converted data as soon
1694            as OVR is cleared. */
1695         __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1696       }
1697       break;
1698   }
1699 
1700   /* Return function status */
1701   return HAL_OK;
1702 }
1703 
1704 /**
1705   * @brief  Enable ADC, start conversion of regular group with interruption.
1706   * @note   Interruptions enabled in this function according to initialization
1707   *         setting : EOC (end of conversion), EOS (end of sequence),
1708   *         OVR overrun.
1709   *         Each of these interruptions has its dedicated callback function.
1710   * @note   Case of multimode enabled (when multimode feature is available):
1711   *         HAL_ADC_Start_IT() must be called for ADC Slave first, then for
1712   *         ADC Master.
1713   *         For ADC Slave, ADC is enabled only (conversion is not started).
1714   *         For ADC Master, ADC is enabled and multimode conversion is started.
1715   * @note   To guarantee a proper reset of all interruptions once all the needed
1716   *         conversions are obtained, HAL_ADC_Stop_IT() must be called to ensure
1717   *         a correct stop of the IT-based conversions.
1718   * @note   By default, HAL_ADC_Start_IT() does not enable the End Of Sampling
1719   *         interruption. If required (e.g. in case of oversampling with trigger
1720   *         mode), the user must:
1721   *          1. first clear the EOSMP flag if set with macro __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP)
1722   *          2. then enable the EOSMP interrupt with macro __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOSMP)
1723   *          before calling HAL_ADC_Start_IT().
1724   * @param hadc ADC handle
1725   * @retval HAL status
1726   */
HAL_ADC_Start_IT(ADC_HandleTypeDef * hadc)1727 HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef *hadc)
1728 {
1729   HAL_StatusTypeDef tmp_hal_status;
1730 #if defined(ADC_MULTIMODE_SUPPORT)
1731   const ADC_TypeDef *tmpADC_Master;
1732   uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
1733 #endif /* ADC_MULTIMODE_SUPPORT */
1734 
1735   /* Check the parameters */
1736   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1737 
1738   /* Perform ADC enable and conversion start if no conversion is on going */
1739   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1740   {
1741     /* Process locked */
1742     __HAL_LOCK(hadc);
1743 
1744     /* Enable the ADC peripheral */
1745     tmp_hal_status = ADC_Enable(hadc);
1746 
1747     /* Start conversion if ADC is effectively enabled */
1748     if (tmp_hal_status == HAL_OK)
1749     {
1750       /* Set ADC state                                                        */
1751       /* - Clear state bitfield related to regular group conversion results   */
1752       /* - Set state bitfield related to regular operation                    */
1753       ADC_STATE_CLR_SET(hadc->State,
1754                         HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
1755                         HAL_ADC_STATE_REG_BUSY);
1756 
1757 #if defined(ADC_MULTIMODE_SUPPORT)
1758       /* Reset HAL_ADC_STATE_MULTIMODE_SLAVE bit
1759         - if ADC instance is master or if multimode feature is not available
1760         - if multimode setting is disabled (ADC instance slave in independent mode) */
1761       if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
1762           || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
1763          )
1764       {
1765         CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
1766       }
1767 #endif /* ADC_MULTIMODE_SUPPORT */
1768 
1769       /* Set ADC error code */
1770       /* Check if a conversion is on going on ADC group injected */
1771       if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) != 0UL)
1772       {
1773         /* Reset ADC error code fields related to regular conversions only */
1774         CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
1775       }
1776       else
1777       {
1778         /* Reset all ADC error code fields */
1779         ADC_CLEAR_ERRORCODE(hadc);
1780       }
1781 
1782       /* Clear ADC group regular conversion flag and overrun flag               */
1783       /* (To ensure of no unknown state from potential previous ADC operations) */
1784       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
1785 
1786       /* Process unlocked */
1787       /* Unlock before starting ADC conversions: in case of potential         */
1788       /* interruption, to let the process to ADC IRQ Handler.                 */
1789       __HAL_UNLOCK(hadc);
1790 
1791       /* Disable all interruptions before enabling the desired ones */
1792       __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR));
1793 
1794       /* Enable ADC end of conversion interrupt */
1795       switch (hadc->Init.EOCSelection)
1796       {
1797         case ADC_EOC_SEQ_CONV:
1798           __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOS);
1799           break;
1800         /* case ADC_EOC_SINGLE_CONV */
1801         default:
1802           __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOC);
1803           break;
1804       }
1805 
1806       /* Enable ADC overrun interrupt */
1807       /* If hadc->Init.Overrun is set to ADC_OVR_DATA_PRESERVED, only then is
1808          ADC_IT_OVR enabled; otherwise data overwrite is considered as normal
1809          behavior and no CPU time is lost for a non-processed interruption */
1810       if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
1811       {
1812         __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
1813       }
1814 
1815       /* Enable conversion of regular group.                                  */
1816       /* If software start has been selected, conversion starts immediately.  */
1817       /* If external trigger has been selected, conversion will start at next */
1818       /* trigger event.                                                       */
1819       /* Case of multimode enabled (when multimode feature is available):     */
1820       /*  - if ADC is slave and dual regular conversions are enabled, ADC is  */
1821       /*    enabled only (conversion is not started),                         */
1822       /*  - if ADC is master, ADC is enabled and conversion is started.       */
1823 #if defined(ADC_MULTIMODE_SUPPORT)
1824       if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
1825           || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
1826           || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
1827           || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
1828          )
1829       {
1830         /* ADC instance is not a multimode slave instance with multimode regular conversions enabled */
1831         if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_JAUTO) != 0UL)
1832         {
1833           ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
1834 
1835           /* Enable as well injected interruptions in case
1836            HAL_ADCEx_InjectedStart_IT() has not been called beforehand. This
1837            allows to start regular and injected conversions when JAUTO is
1838            set with a single call to HAL_ADC_Start_IT() */
1839           switch (hadc->Init.EOCSelection)
1840           {
1841             case ADC_EOC_SEQ_CONV:
1842               __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
1843               __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOS);
1844               break;
1845             /* case ADC_EOC_SINGLE_CONV */
1846             default:
1847               __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOS);
1848               __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC);
1849               break;
1850           }
1851         }
1852 
1853         /* Start ADC group regular conversion */
1854         LL_ADC_REG_StartConversion(hadc->Instance);
1855       }
1856       else
1857       {
1858         /* ADC instance is a multimode slave instance with multimode regular conversions enabled */
1859         SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
1860         /* if Master ADC JAUTO bit is set, Slave injected interruptions
1861            are enabled nevertheless (for same reason as above) */
1862         tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
1863         if (READ_BIT(tmpADC_Master->CFGR, ADC_CFGR_JAUTO) != 0UL)
1864         {
1865           /* First, update Slave State in setting HAL_ADC_STATE_INJ_BUSY bit
1866              and in resetting HAL_ADC_STATE_INJ_EOC bit */
1867           ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
1868           /* Next, set Slave injected interruptions */
1869           switch (hadc->Init.EOCSelection)
1870           {
1871             case ADC_EOC_SEQ_CONV:
1872               __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
1873               __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOS);
1874               break;
1875             /* case ADC_EOC_SINGLE_CONV */
1876             default:
1877               __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOS);
1878               __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC);
1879               break;
1880           }
1881         }
1882       }
1883 #else
1884       /* ADC instance is not a multimode slave instance with multimode regular conversions enabled */
1885       if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_JAUTO) != 0UL)
1886       {
1887         ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
1888 
1889         /* Enable as well injected interruptions in case
1890          HAL_ADCEx_InjectedStart_IT() has not been called beforehand. This
1891          allows to start regular and injected conversions when JAUTO is
1892          set with a single call to HAL_ADC_Start_IT() */
1893         switch (hadc->Init.EOCSelection)
1894         {
1895           case ADC_EOC_SEQ_CONV:
1896             __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
1897             __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOS);
1898             break;
1899           /* case ADC_EOC_SINGLE_CONV */
1900           default:
1901             __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOS);
1902             __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC);
1903             break;
1904         }
1905       }
1906 
1907       /* Start ADC group regular conversion */
1908       LL_ADC_REG_StartConversion(hadc->Instance);
1909 #endif /* ADC_MULTIMODE_SUPPORT */
1910     }
1911     else
1912     {
1913       /* Process unlocked */
1914       __HAL_UNLOCK(hadc);
1915     }
1916 
1917   }
1918   else
1919   {
1920     tmp_hal_status = HAL_BUSY;
1921   }
1922 
1923   /* Return function status */
1924   return tmp_hal_status;
1925 }
1926 
1927 /**
1928   * @brief  Stop ADC conversion of regular group (and injected group in
1929   *         case of auto_injection mode), disable interrution of
1930   *         end-of-conversion, disable ADC peripheral.
1931   * @param hadc ADC handle
1932   * @retval HAL status.
1933   */
HAL_ADC_Stop_IT(ADC_HandleTypeDef * hadc)1934 HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef *hadc)
1935 {
1936   HAL_StatusTypeDef tmp_hal_status;
1937 
1938   /* Check the parameters */
1939   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1940 
1941   /* Process locked */
1942   __HAL_LOCK(hadc);
1943 
1944   /* 1. Stop potential conversion on going, on ADC groups regular and injected */
1945   tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_INJECTED_GROUP);
1946 
1947   /* Disable ADC peripheral if conversions are effectively stopped */
1948   if (tmp_hal_status == HAL_OK)
1949   {
1950     /* Disable ADC end of conversion interrupt for regular group */
1951     /* Disable ADC overrun interrupt */
1952     __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR));
1953 
1954     /* 2. Disable the ADC peripheral */
1955     tmp_hal_status = ADC_Disable(hadc);
1956 
1957     /* Check if ADC is effectively disabled */
1958     if (tmp_hal_status == HAL_OK)
1959     {
1960       /* Set ADC state */
1961       ADC_STATE_CLR_SET(hadc->State,
1962                         HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
1963                         HAL_ADC_STATE_READY);
1964     }
1965   }
1966 
1967   /* Process unlocked */
1968   __HAL_UNLOCK(hadc);
1969 
1970   /* Return function status */
1971   return tmp_hal_status;
1972 }
1973 
1974 /**
1975   * @brief  Enable ADC, start conversion of regular group and transfer result through DMA.
1976   * @note   Interruptions enabled in this function:
1977   *         overrun (if applicable), DMA half transfer, DMA transfer complete.
1978   *         Each of these interruptions has its dedicated callback function.
1979   * @note   Case of multimode enabled (when multimode feature is available): HAL_ADC_Start_DMA()
1980   *         is designed for single-ADC mode only. For multimode, the dedicated
1981   *         HAL_ADCEx_MultiModeStart_DMA() function must be used.
1982   * @param hadc ADC handle
1983   * @param pData Destination Buffer address.
1984   * @param Length Number of data to be transferred from ADC peripheral to memory
1985   * @retval HAL status.
1986   */
HAL_ADC_Start_DMA(ADC_HandleTypeDef * hadc,uint32_t * pData,uint32_t Length)1987 HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef *hadc, uint32_t *pData, uint32_t Length)
1988 {
1989   HAL_StatusTypeDef tmp_hal_status;
1990 #if defined(ADC_MULTIMODE_SUPPORT)
1991   uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
1992 #endif /* ADC_MULTIMODE_SUPPORT */
1993 
1994   /* Check the parameters */
1995   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1996 
1997   /* Perform ADC enable and conversion start if no conversion is on going */
1998   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1999   {
2000     /* Process locked */
2001     __HAL_LOCK(hadc);
2002 
2003 #if defined(ADC_MULTIMODE_SUPPORT)
2004     /* Ensure that multimode regular conversions are not enabled.   */
2005     /* Otherwise, dedicated API HAL_ADCEx_MultiModeStart_DMA() must be used.  */
2006     if ((tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
2007         || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
2008         || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
2009        )
2010 #endif /* ADC_MULTIMODE_SUPPORT */
2011     {
2012       /* Enable the ADC peripheral */
2013       tmp_hal_status = ADC_Enable(hadc);
2014 
2015       /* Start conversion if ADC is effectively enabled */
2016       if (tmp_hal_status == HAL_OK)
2017       {
2018         /* Set ADC state                                                        */
2019         /* - Clear state bitfield related to regular group conversion results   */
2020         /* - Set state bitfield related to regular operation                    */
2021         ADC_STATE_CLR_SET(hadc->State,
2022                           HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
2023                           HAL_ADC_STATE_REG_BUSY);
2024 
2025 #if defined(ADC_MULTIMODE_SUPPORT)
2026         /* Reset HAL_ADC_STATE_MULTIMODE_SLAVE bit
2027           - if ADC instance is master or if multimode feature is not available
2028           - if multimode setting is disabled (ADC instance slave in independent mode) */
2029         if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
2030             || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
2031            )
2032         {
2033           CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
2034         }
2035 #endif /* ADC_MULTIMODE_SUPPORT */
2036 
2037         /* Check if a conversion is on going on ADC group injected */
2038         if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) != 0UL)
2039         {
2040           /* Reset ADC error code fields related to regular conversions only */
2041           CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
2042         }
2043         else
2044         {
2045           /* Reset all ADC error code fields */
2046           ADC_CLEAR_ERRORCODE(hadc);
2047         }
2048 
2049         /* Set the DMA transfer complete callback */
2050         hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt;
2051 
2052         /* Set the DMA half transfer complete callback */
2053         hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt;
2054 
2055         /* Set the DMA error callback */
2056         hadc->DMA_Handle->XferErrorCallback = ADC_DMAError;
2057 
2058 
2059         /* Manage ADC and DMA start: ADC overrun interruption, DMA start,     */
2060         /* ADC start (in case of SW start):                                   */
2061 
2062         /* Clear regular group conversion flag and overrun flag               */
2063         /* (To ensure of no unknown state from potential previous ADC         */
2064         /* operations)                                                        */
2065         __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
2066 
2067         /* Process unlocked */
2068         /* Unlock before starting ADC conversions: in case of potential         */
2069         /* interruption, to let the process to ADC IRQ Handler.                 */
2070         __HAL_UNLOCK(hadc);
2071 
2072         /* With DMA, overrun event is always considered as an error even if
2073            hadc->Init.Overrun is set to ADC_OVR_DATA_OVERWRITTEN. Therefore,
2074            ADC_IT_OVR is enabled. */
2075         __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
2076 
2077         /* Enable ADC DMA mode */
2078         SET_BIT(hadc->Instance->CFGR, ADC_CFGR_DMAEN);
2079 
2080         /* Start the DMA channel */
2081         tmp_hal_status = HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->DR, (uint32_t)pData, Length);
2082 
2083         /* Enable conversion of regular group.                                  */
2084         /* If software start has been selected, conversion starts immediately.  */
2085         /* If external trigger has been selected, conversion will start at next */
2086         /* trigger event.                                                       */
2087         /* Start ADC group regular conversion */
2088         LL_ADC_REG_StartConversion(hadc->Instance);
2089       }
2090       else
2091       {
2092         /* Process unlocked */
2093         __HAL_UNLOCK(hadc);
2094       }
2095 
2096     }
2097 #if defined(ADC_MULTIMODE_SUPPORT)
2098     else
2099     {
2100       tmp_hal_status = HAL_ERROR;
2101       /* Process unlocked */
2102       __HAL_UNLOCK(hadc);
2103     }
2104 #endif /* ADC_MULTIMODE_SUPPORT */
2105   }
2106   else
2107   {
2108     tmp_hal_status = HAL_BUSY;
2109   }
2110 
2111   /* Return function status */
2112   return tmp_hal_status;
2113 }
2114 
2115 /**
2116   * @brief  Stop ADC conversion of regular group (and injected group in
2117   *         case of auto_injection mode), disable ADC DMA transfer, disable
2118   *         ADC peripheral.
2119   * @note:  ADC peripheral disable is forcing stop of potential
2120   *         conversion on ADC group injected. If ADC group injected is under use, it
2121   *         should be preliminarily stopped using HAL_ADCEx_InjectedStop function.
2122   * @note   Case of multimode enabled (when multimode feature is available):
2123   *         HAL_ADC_Stop_DMA() function is dedicated to single-ADC mode only.
2124   *         For multimode, the dedicated HAL_ADCEx_MultiModeStop_DMA() API must be used.
2125   * @param hadc ADC handle
2126   * @retval HAL status.
2127   */
HAL_ADC_Stop_DMA(ADC_HandleTypeDef * hadc)2128 HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef *hadc)
2129 {
2130   HAL_StatusTypeDef tmp_hal_status;
2131 
2132   /* Check the parameters */
2133   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2134 
2135   /* Process locked */
2136   __HAL_LOCK(hadc);
2137 
2138   /* 1. Stop potential ADC group regular conversion on going */
2139   tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_INJECTED_GROUP);
2140 
2141   /* Disable ADC peripheral if conversions are effectively stopped */
2142   if (tmp_hal_status == HAL_OK)
2143   {
2144     /* Disable ADC DMA (ADC DMA configuration of continuous requests is kept) */
2145     CLEAR_BIT(hadc->Instance->CFGR, ADC_CFGR_DMAEN);
2146 
2147     /* Disable the DMA channel (in case of DMA in circular mode or stop       */
2148     /* while DMA transfer is on going)                                        */
2149     if (hadc->DMA_Handle->State == HAL_DMA_STATE_BUSY)
2150     {
2151       tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle);
2152 
2153       /* Check if DMA channel effectively disabled */
2154       if (tmp_hal_status != HAL_OK)
2155       {
2156         /* Update ADC state machine to error */
2157         SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
2158       }
2159     }
2160 
2161     /* Disable ADC overrun interrupt */
2162     __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
2163 
2164     /* 2. Disable the ADC peripheral */
2165     /* Update "tmp_hal_status" only if DMA channel disabling passed,          */
2166     /* to keep in memory a potential failing status.                          */
2167     if (tmp_hal_status == HAL_OK)
2168     {
2169       tmp_hal_status = ADC_Disable(hadc);
2170     }
2171     else
2172     {
2173       (void)ADC_Disable(hadc);
2174     }
2175 
2176     /* Check if ADC is effectively disabled */
2177     if (tmp_hal_status == HAL_OK)
2178     {
2179       /* Set ADC state */
2180       ADC_STATE_CLR_SET(hadc->State,
2181                         HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
2182                         HAL_ADC_STATE_READY);
2183     }
2184 
2185   }
2186 
2187   /* Process unlocked */
2188   __HAL_UNLOCK(hadc);
2189 
2190   /* Return function status */
2191   return tmp_hal_status;
2192 }
2193 
2194 /**
2195   * @brief  Get ADC regular group conversion result.
2196   * @note   Reading register DR automatically clears ADC flag EOC
2197   *         (ADC group regular end of unitary conversion).
2198   * @note   This function does not clear ADC flag EOS
2199   *         (ADC group regular end of sequence conversion).
2200   *         Occurrence of flag EOS rising:
2201   *          - If sequencer is composed of 1 rank, flag EOS is equivalent
2202   *            to flag EOC.
2203   *          - If sequencer is composed of several ranks, during the scan
2204   *            sequence flag EOC only is raised, at the end of the scan sequence
2205   *            both flags EOC and EOS are raised.
2206   *         To clear this flag, either use function:
2207   *         in programming model IT: @ref HAL_ADC_IRQHandler(), in programming
2208   *         model polling: @ref HAL_ADC_PollForConversion()
2209   *         or @ref __HAL_ADC_CLEAR_FLAG(&hadc, ADC_FLAG_EOS).
2210   * @param hadc ADC handle
2211   * @retval ADC group regular conversion data
2212   */
HAL_ADC_GetValue(const ADC_HandleTypeDef * hadc)2213 uint32_t HAL_ADC_GetValue(const ADC_HandleTypeDef *hadc)
2214 {
2215   /* Check the parameters */
2216   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2217 
2218   /* Note: EOC flag is not cleared here by software because automatically     */
2219   /*       cleared by hardware when reading register DR.                      */
2220 
2221   /* Return ADC converted value */
2222   return hadc->Instance->DR;
2223 }
2224 
2225 /**
2226   * @brief  Handle ADC interrupt request.
2227   * @param hadc ADC handle
2228   * @retval None
2229   */
HAL_ADC_IRQHandler(ADC_HandleTypeDef * hadc)2230 void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc)
2231 {
2232   uint32_t overrun_error = 0UL; /* flag set if overrun occurrence has to be considered as an error */
2233   uint32_t tmp_isr = hadc->Instance->ISR;
2234   uint32_t tmp_ier = hadc->Instance->IER;
2235   uint32_t tmp_adc_inj_is_trigger_source_sw_start;
2236   uint32_t tmp_adc_reg_is_trigger_source_sw_start;
2237   uint32_t tmp_cfgr;
2238 #if defined(ADC_MULTIMODE_SUPPORT)
2239   const ADC_TypeDef *tmpADC_Master;
2240   uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
2241 #endif /* ADC_MULTIMODE_SUPPORT */
2242 
2243   /* Check the parameters */
2244   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2245   assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection));
2246 
2247   /* ========== Check End of Sampling flag for ADC group regular ========== */
2248   if (((tmp_isr & ADC_FLAG_EOSMP) == ADC_FLAG_EOSMP) && ((tmp_ier & ADC_IT_EOSMP) == ADC_IT_EOSMP))
2249   {
2250     /* Update state machine on end of sampling status if not in error state */
2251     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
2252     {
2253       /* Set ADC state */
2254       SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOSMP);
2255     }
2256 
2257     /* End Of Sampling callback */
2258 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2259     hadc->EndOfSamplingCallback(hadc);
2260 #else
2261     HAL_ADCEx_EndOfSamplingCallback(hadc);
2262 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2263 
2264     /* Clear regular group conversion flag */
2265     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP);
2266   }
2267 
2268   /* ====== Check ADC group regular end of unitary conversion sequence conversions ===== */
2269   if ((((tmp_isr & ADC_FLAG_EOC) == ADC_FLAG_EOC) && ((tmp_ier & ADC_IT_EOC) == ADC_IT_EOC)) ||
2270       (((tmp_isr & ADC_FLAG_EOS) == ADC_FLAG_EOS) && ((tmp_ier & ADC_IT_EOS) == ADC_IT_EOS)))
2271   {
2272     /* Update state machine on conversion status if not in error state */
2273     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
2274     {
2275       /* Set ADC state */
2276       SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
2277     }
2278 
2279     /* Determine whether any further conversion upcoming on group regular     */
2280     /* by external trigger, continuous mode or scan sequence on going         */
2281     /* to disable interruption.                                               */
2282     if (LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
2283     {
2284       /* Get relevant register CFGR in ADC instance of ADC master or slave    */
2285       /* in function of multimode state (for devices with multimode           */
2286       /* available).                                                          */
2287 #if defined(ADC_MULTIMODE_SUPPORT)
2288       if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
2289           || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
2290           || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
2291           || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
2292          )
2293       {
2294         /* check CONT bit directly in handle ADC CFGR register */
2295         tmp_cfgr = READ_REG(hadc->Instance->CFGR);
2296       }
2297       else
2298       {
2299         /* else need to check Master ADC CONT bit */
2300         tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
2301         tmp_cfgr = READ_REG(tmpADC_Master->CFGR);
2302       }
2303 #else
2304       tmp_cfgr = READ_REG(hadc->Instance->CFGR);
2305 #endif /* ADC_MULTIMODE_SUPPORT */
2306 
2307       /* Carry on if continuous mode is disabled */
2308       if (READ_BIT(tmp_cfgr, ADC_CFGR_CONT) != ADC_CFGR_CONT)
2309       {
2310         /* If End of Sequence is reached, disable interrupts */
2311         if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS))
2312         {
2313           /* Allowed to modify bits ADC_IT_EOC/ADC_IT_EOS only if bit         */
2314           /* ADSTART==0 (no conversion on going)                              */
2315           if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
2316           {
2317             /* Disable ADC end of sequence conversion interrupt */
2318             /* Note: Overrun interrupt was enabled with EOC interrupt in      */
2319             /* HAL_Start_IT(), but is not disabled here because can be used   */
2320             /* by overrun IRQ process below.                                  */
2321             __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_EOS);
2322 
2323             /* Set ADC state */
2324             CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
2325 
2326             if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) == 0UL)
2327             {
2328               SET_BIT(hadc->State, HAL_ADC_STATE_READY);
2329             }
2330           }
2331           else
2332           {
2333             /* Change ADC state to error state */
2334             SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2335 
2336             /* Set ADC error code to ADC peripheral internal error */
2337             SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2338           }
2339         }
2340       }
2341     }
2342 
2343     /* Conversion complete callback */
2344     /* Note: Into callback function "HAL_ADC_ConvCpltCallback()",             */
2345     /*       to determine if conversion has been triggered from EOC or EOS,   */
2346     /*       possibility to use:                                              */
2347     /*        " if ( __HAL_ADC_GET_FLAG(&hadc, ADC_FLAG_EOS)) "               */
2348 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2349     hadc->ConvCpltCallback(hadc);
2350 #else
2351     HAL_ADC_ConvCpltCallback(hadc);
2352 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2353 
2354     /* Clear regular group conversion flag */
2355     /* Note: in case of overrun set to ADC_OVR_DATA_PRESERVED, end of         */
2356     /*       conversion flags clear induces the release of the preserved data.*/
2357     /*       Therefore, if the preserved data value is needed, it must be     */
2358     /*       read preliminarily into HAL_ADC_ConvCpltCallback().              */
2359     __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS));
2360   }
2361 
2362   /* ====== Check ADC group injected end of unitary conversion sequence conversions ===== */
2363   if ((((tmp_isr & ADC_FLAG_JEOC) == ADC_FLAG_JEOC) && ((tmp_ier & ADC_IT_JEOC) == ADC_IT_JEOC)) ||
2364       (((tmp_isr & ADC_FLAG_JEOS) == ADC_FLAG_JEOS) && ((tmp_ier & ADC_IT_JEOS) == ADC_IT_JEOS)))
2365   {
2366     /* Update state machine on conversion status if not in error state */
2367     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
2368     {
2369       /* Set ADC state */
2370       SET_BIT(hadc->State, HAL_ADC_STATE_INJ_EOC);
2371     }
2372 
2373     /* Retrieve ADC configuration */
2374     tmp_adc_inj_is_trigger_source_sw_start = LL_ADC_INJ_IsTriggerSourceSWStart(hadc->Instance);
2375     tmp_adc_reg_is_trigger_source_sw_start = LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance);
2376     /* Get relevant register CFGR in ADC instance of ADC master or slave  */
2377     /* in function of multimode state (for devices with multimode         */
2378     /* available).                                                        */
2379 #if defined(ADC_MULTIMODE_SUPPORT)
2380     if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
2381         || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
2382         || (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_SIMULT)
2383         || (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_INTERL)
2384        )
2385     {
2386       tmp_cfgr = READ_REG(hadc->Instance->CFGR);
2387     }
2388     else
2389     {
2390       tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
2391       tmp_cfgr = READ_REG(tmpADC_Master->CFGR);
2392     }
2393 #else
2394     tmp_cfgr = READ_REG(hadc->Instance->CFGR);
2395 #endif /* ADC_MULTIMODE_SUPPORT */
2396 
2397     /* Disable interruption if no further conversion upcoming by injected     */
2398     /* external trigger or by automatic injected conversion with regular      */
2399     /* group having no further conversion upcoming (same conditions as        */
2400     /* regular group interruption disabling above),                           */
2401     /* and if injected scan sequence is completed.                            */
2402     if (tmp_adc_inj_is_trigger_source_sw_start != 0UL)
2403     {
2404       if ((READ_BIT(tmp_cfgr, ADC_CFGR_JAUTO) == 0UL) ||
2405           ((tmp_adc_reg_is_trigger_source_sw_start != 0UL) &&
2406            (READ_BIT(tmp_cfgr, ADC_CFGR_CONT) == 0UL)))
2407       {
2408         /* If End of Sequence is reached, disable interrupts */
2409         if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOS))
2410         {
2411           /* Particular case if injected contexts queue is enabled:             */
2412           /* when the last context has been fully processed, JSQR is reset      */
2413           /* by the hardware. Even if no injected conversion is planned to come */
2414           /* (queue empty, triggers are ignored), it can start again            */
2415           /* immediately after setting a new context (JADSTART is still set).   */
2416           /* Therefore, state of HAL ADC injected group is kept to busy.        */
2417           if (READ_BIT(tmp_cfgr, ADC_CFGR_JQM) == 0UL)
2418           {
2419             /* Allowed to modify bits ADC_IT_JEOC/ADC_IT_JEOS only if bit       */
2420             /* JADSTART==0 (no conversion on going)                             */
2421             if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) == 0UL)
2422             {
2423               /* Disable ADC end of sequence conversion interrupt  */
2424               __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC | ADC_IT_JEOS);
2425 
2426               /* Set ADC state */
2427               CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY);
2428 
2429               if ((hadc->State & HAL_ADC_STATE_REG_BUSY) == 0UL)
2430               {
2431                 SET_BIT(hadc->State, HAL_ADC_STATE_READY);
2432               }
2433             }
2434             else
2435             {
2436               /* Update ADC state machine to error */
2437               SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2438 
2439               /* Set ADC error code to ADC peripheral internal error */
2440               SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2441             }
2442           }
2443         }
2444       }
2445     }
2446 
2447     /* Injected Conversion complete callback */
2448     /* Note:  HAL_ADCEx_InjectedConvCpltCallback can resort to
2449               if (__HAL_ADC_GET_FLAG(&hadc, ADC_FLAG_JEOS)) or
2450               if (__HAL_ADC_GET_FLAG(&hadc, ADC_FLAG_JEOC)) to determine whether
2451               interruption has been triggered by end of conversion or end of
2452               sequence.    */
2453 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2454     hadc->InjectedConvCpltCallback(hadc);
2455 #else
2456     HAL_ADCEx_InjectedConvCpltCallback(hadc);
2457 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2458 
2459     /* Clear injected group conversion flag */
2460     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOC | ADC_FLAG_JEOS);
2461   }
2462 
2463   /* ========== Check Analog watchdog 1 flag ========== */
2464   if (((tmp_isr & ADC_FLAG_AWD1) == ADC_FLAG_AWD1) && ((tmp_ier & ADC_IT_AWD1) == ADC_IT_AWD1))
2465   {
2466     /* Set ADC state */
2467     SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
2468 
2469     /* Level out of window 1 callback */
2470 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2471     hadc->LevelOutOfWindowCallback(hadc);
2472 #else
2473     HAL_ADC_LevelOutOfWindowCallback(hadc);
2474 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2475 
2476     /* Clear ADC analog watchdog flag */
2477     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD1);
2478   }
2479 
2480   /* ========== Check analog watchdog 2 flag ========== */
2481   if (((tmp_isr & ADC_FLAG_AWD2) == ADC_FLAG_AWD2) && ((tmp_ier & ADC_IT_AWD2) == ADC_IT_AWD2))
2482   {
2483     /* Set ADC state */
2484     SET_BIT(hadc->State, HAL_ADC_STATE_AWD2);
2485 
2486     /* Level out of window 2 callback */
2487 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2488     hadc->LevelOutOfWindow2Callback(hadc);
2489 #else
2490     HAL_ADCEx_LevelOutOfWindow2Callback(hadc);
2491 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2492 
2493     /* Clear ADC analog watchdog flag */
2494     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD2);
2495   }
2496 
2497   /* ========== Check analog watchdog 3 flag ========== */
2498   if (((tmp_isr & ADC_FLAG_AWD3) == ADC_FLAG_AWD3) && ((tmp_ier & ADC_IT_AWD3) == ADC_IT_AWD3))
2499   {
2500     /* Set ADC state */
2501     SET_BIT(hadc->State, HAL_ADC_STATE_AWD3);
2502 
2503     /* Level out of window 3 callback */
2504 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2505     hadc->LevelOutOfWindow3Callback(hadc);
2506 #else
2507     HAL_ADCEx_LevelOutOfWindow3Callback(hadc);
2508 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2509 
2510     /* Clear ADC analog watchdog flag */
2511     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD3);
2512   }
2513 
2514   /* ========== Check Overrun flag ========== */
2515   if (((tmp_isr & ADC_FLAG_OVR) == ADC_FLAG_OVR) && ((tmp_ier & ADC_IT_OVR) == ADC_IT_OVR))
2516   {
2517     /* If overrun is set to overwrite previous data (default setting),        */
2518     /* overrun event is not considered as an error.                           */
2519     /* (cf ref manual "Managing conversions without using the DMA and without */
2520     /* overrun ")                                                             */
2521     /* Exception for usage with DMA overrun event always considered as an     */
2522     /* error.                                                                 */
2523     if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
2524     {
2525       overrun_error = 1UL;
2526     }
2527     else
2528     {
2529       /* Check DMA configuration */
2530 #if defined(ADC_MULTIMODE_SUPPORT)
2531       if (tmp_multimode_config != LL_ADC_MULTI_INDEPENDENT)
2532       {
2533         /* Multimode (when feature is available) is enabled,
2534            Common Control Register MDMA bits must be checked. */
2535         if (LL_ADC_GetMultiDMATransfer(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) != LL_ADC_MULTI_REG_DMA_EACH_ADC)
2536         {
2537           overrun_error = 1UL;
2538         }
2539       }
2540       else
2541 #endif /* ADC_MULTIMODE_SUPPORT */
2542       {
2543         /* Multimode not set or feature not available or ADC independent */
2544         if ((hadc->Instance->CFGR & ADC_CFGR_DMAEN) != 0UL)
2545         {
2546           overrun_error = 1UL;
2547         }
2548       }
2549     }
2550 
2551     if (overrun_error == 1UL)
2552     {
2553       /* Change ADC state to error state */
2554       SET_BIT(hadc->State, HAL_ADC_STATE_REG_OVR);
2555 
2556       /* Set ADC error code to overrun */
2557       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_OVR);
2558 
2559       /* Error callback */
2560       /* Note: In case of overrun, ADC conversion data is preserved until     */
2561       /*       flag OVR is reset.                                             */
2562       /*       Therefore, old ADC conversion data can be retrieved in         */
2563       /*       function "HAL_ADC_ErrorCallback()".                            */
2564 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2565       hadc->ErrorCallback(hadc);
2566 #else
2567       HAL_ADC_ErrorCallback(hadc);
2568 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2569     }
2570 
2571     /* Clear ADC overrun flag */
2572     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
2573   }
2574 
2575   /* ========== Check Injected context queue overflow flag ========== */
2576   if (((tmp_isr & ADC_FLAG_JQOVF) == ADC_FLAG_JQOVF) && ((tmp_ier & ADC_IT_JQOVF) == ADC_IT_JQOVF))
2577   {
2578     /* Change ADC state to overrun state */
2579     SET_BIT(hadc->State, HAL_ADC_STATE_INJ_JQOVF);
2580 
2581     /* Set ADC error code to Injected context queue overflow */
2582     SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_JQOVF);
2583 
2584     /* Clear the Injected context queue overflow flag */
2585     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JQOVF);
2586 
2587     /* Injected context queue overflow callback */
2588 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2589     hadc->InjectedQueueOverflowCallback(hadc);
2590 #else
2591     HAL_ADCEx_InjectedQueueOverflowCallback(hadc);
2592 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2593   }
2594 
2595 }
2596 
2597 /**
2598   * @brief  Conversion complete callback in non-blocking mode.
2599   * @param hadc ADC handle
2600   * @retval None
2601   */
HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef * hadc)2602 __weak void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
2603 {
2604   /* Prevent unused argument(s) compilation warning */
2605   UNUSED(hadc);
2606 
2607   /* NOTE : This function should not be modified. When the callback is needed,
2608             function HAL_ADC_ConvCpltCallback must be implemented in the user file.
2609    */
2610 }
2611 
2612 /**
2613   * @brief  Conversion DMA half-transfer callback in non-blocking mode.
2614   * @param hadc ADC handle
2615   * @retval None
2616   */
HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef * hadc)2617 __weak void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef *hadc)
2618 {
2619   /* Prevent unused argument(s) compilation warning */
2620   UNUSED(hadc);
2621 
2622   /* NOTE : This function should not be modified. When the callback is needed,
2623             function HAL_ADC_ConvHalfCpltCallback must be implemented in the user file.
2624   */
2625 }
2626 
2627 /**
2628   * @brief  Analog watchdog 1 callback in non-blocking mode.
2629   * @param hadc ADC handle
2630   * @retval None
2631   */
HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef * hadc)2632 __weak void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef *hadc)
2633 {
2634   /* Prevent unused argument(s) compilation warning */
2635   UNUSED(hadc);
2636 
2637   /* NOTE : This function should not be modified. When the callback is needed,
2638             function HAL_ADC_LevelOutOfWindowCallback must be implemented in the user file.
2639   */
2640 }
2641 
2642 /**
2643   * @brief  ADC error callback in non-blocking mode
2644   *         (ADC conversion with interruption or transfer by DMA).
2645   * @note   In case of error due to overrun when using ADC with DMA transfer
2646   *         (HAL ADC handle parameter "ErrorCode" to state "HAL_ADC_ERROR_OVR"):
2647   *         - Reinitialize the DMA using function "HAL_ADC_Stop_DMA()".
2648   *         - If needed, restart a new ADC conversion using function
2649   *           "HAL_ADC_Start_DMA()"
2650   *           (this function is also clearing overrun flag)
2651   * @param hadc ADC handle
2652   * @retval None
2653   */
HAL_ADC_ErrorCallback(ADC_HandleTypeDef * hadc)2654 __weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc)
2655 {
2656   /* Prevent unused argument(s) compilation warning */
2657   UNUSED(hadc);
2658 
2659   /* NOTE : This function should not be modified. When the callback is needed,
2660             function HAL_ADC_ErrorCallback must be implemented in the user file.
2661   */
2662 }
2663 
2664 /**
2665   * @}
2666   */
2667 
2668 /** @defgroup ADC_Exported_Functions_Group3 Peripheral Control functions
2669   * @brief    Peripheral Control functions
2670   *
2671 @verbatim
2672  ===============================================================================
2673              ##### Peripheral Control functions #####
2674  ===============================================================================
2675     [..]  This section provides functions allowing to:
2676       (+) Configure channels on regular group
2677       (+) Configure the analog watchdog
2678 
2679 @endverbatim
2680   * @{
2681   */
2682 
2683 /**
2684   * @brief  Configure a channel to be assigned to ADC group regular.
2685   * @note   In case of usage of internal measurement channels:
2686   *         Vbat/VrefInt/TempSensor.
2687   *         These internal paths can be disabled using function
2688   *         HAL_ADC_DeInit().
2689   * @note   Possibility to update parameters on the fly:
2690   *         This function initializes channel into ADC group regular,
2691   *         following calls to this function can be used to reconfigure
2692   *         some parameters of structure "ADC_ChannelConfTypeDef" on the fly,
2693   *         without resetting the ADC.
2694   *         The setting of these parameters is conditioned to ADC state:
2695   *         Refer to comments of structure "ADC_ChannelConfTypeDef".
2696   * @param hadc ADC handle
2697   * @param pConfig Structure of ADC channel assigned to ADC group regular.
2698   * @retval HAL status
2699   */
HAL_ADC_ConfigChannel(ADC_HandleTypeDef * hadc,const ADC_ChannelConfTypeDef * pConfig)2700 HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef *hadc, const ADC_ChannelConfTypeDef *pConfig)
2701 {
2702   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
2703   uint32_t tmpOffsetShifted;
2704   uint32_t tmp_config_internal_channel;
2705   __IO uint32_t wait_loop_index = 0UL;
2706   uint32_t tmp_adc_is_conversion_on_going_regular;
2707   uint32_t tmp_adc_is_conversion_on_going_injected;
2708 
2709   /* Check the parameters */
2710   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2711   assert_param(IS_ADC_REGULAR_RANK(pConfig->Rank));
2712   assert_param(IS_ADC_SAMPLE_TIME(pConfig->SamplingTime));
2713   assert_param(IS_ADC_SINGLE_DIFFERENTIAL(pConfig->SingleDiff));
2714   assert_param(IS_ADC_OFFSET_NUMBER(pConfig->OffsetNumber));
2715   assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), pConfig->Offset));
2716 
2717   /* if ROVSE is set, the value of the OFFSETy_EN bit in ADCx_OFRy register is
2718      ignored (considered as reset) */
2719   assert_param(!((pConfig->OffsetNumber != ADC_OFFSET_NONE) && (hadc->Init.OversamplingMode == ENABLE)));
2720 
2721   /* Verification of channel number */
2722   if (pConfig->SingleDiff != ADC_DIFFERENTIAL_ENDED)
2723   {
2724     assert_param(IS_ADC_CHANNEL(hadc, pConfig->Channel));
2725   }
2726   else
2727   {
2728     assert_param(IS_ADC_DIFF_CHANNEL(hadc, pConfig->Channel));
2729   }
2730 
2731   /* Process locked */
2732   __HAL_LOCK(hadc);
2733 
2734   /* Parameters update conditioned to ADC state:                              */
2735   /* Parameters that can be updated when ADC is disabled or enabled without   */
2736   /* conversion on going on regular group:                                    */
2737   /*  - Channel number                                                        */
2738   /*  - Channel rank                                                          */
2739   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
2740   {
2741     /* Set ADC group regular sequence: channel on the selected scan sequence rank */
2742     LL_ADC_REG_SetSequencerRanks(hadc->Instance, pConfig->Rank, pConfig->Channel);
2743 
2744     /* Parameters update conditioned to ADC state:                              */
2745     /* Parameters that can be updated when ADC is disabled or enabled without   */
2746     /* conversion on going on regular group:                                    */
2747     /*  - Channel sampling time                                                 */
2748     /*  - Channel offset                                                        */
2749     tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
2750     tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
2751     if ((tmp_adc_is_conversion_on_going_regular == 0UL)
2752         && (tmp_adc_is_conversion_on_going_injected == 0UL)
2753        )
2754     {
2755       /* Manage specific case of sampling time 3.5 cycles replacing 2.5 cyles */
2756       if (pConfig->SamplingTime == ADC_SAMPLETIME_3CYCLES_5)
2757       {
2758         /* Set sampling time of the selected ADC channel */
2759         LL_ADC_SetChannelSamplingTime(hadc->Instance, pConfig->Channel, LL_ADC_SAMPLINGTIME_2CYCLES_5);
2760 
2761         /* Set ADC sampling time common configuration */
2762         LL_ADC_SetSamplingTimeCommonConfig(hadc->Instance, LL_ADC_SAMPLINGTIME_COMMON_3C5_REPL_2C5);
2763       }
2764       else
2765       {
2766         /* Set sampling time of the selected ADC channel */
2767         LL_ADC_SetChannelSamplingTime(hadc->Instance, pConfig->Channel, pConfig->SamplingTime);
2768 
2769         /* Set ADC sampling time common configuration */
2770         LL_ADC_SetSamplingTimeCommonConfig(hadc->Instance, LL_ADC_SAMPLINGTIME_COMMON_DEFAULT);
2771       }
2772 
2773       /* Configure the offset: offset enable/disable, channel, offset value */
2774 
2775       /* Shift the offset with respect to the selected ADC resolution. */
2776       /* Offset has to be left-aligned on bit 11, the LSB (right bits) are set to 0 */
2777       tmpOffsetShifted = ADC_OFFSET_SHIFT_RESOLUTION(hadc, (uint32_t)pConfig->Offset);
2778 
2779       if (pConfig->OffsetNumber != ADC_OFFSET_NONE)
2780       {
2781         /* Set ADC selected offset number */
2782         LL_ADC_SetOffset(hadc->Instance, pConfig->OffsetNumber, pConfig->Channel, tmpOffsetShifted);
2783 
2784       }
2785       else
2786       {
2787         /* Scan each offset register to check if the selected channel is targeted. */
2788         /* If this is the case, the corresponding offset number is disabled.       */
2789         if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_1))
2790             == __LL_ADC_CHANNEL_TO_DECIMAL_NB(pConfig->Channel))
2791         {
2792           LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_1, LL_ADC_OFFSET_DISABLE);
2793         }
2794         if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_2))
2795             == __LL_ADC_CHANNEL_TO_DECIMAL_NB(pConfig->Channel))
2796         {
2797           LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_2, LL_ADC_OFFSET_DISABLE);
2798         }
2799         if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_3))
2800             == __LL_ADC_CHANNEL_TO_DECIMAL_NB(pConfig->Channel))
2801         {
2802           LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_3, LL_ADC_OFFSET_DISABLE);
2803         }
2804         if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_4))
2805             == __LL_ADC_CHANNEL_TO_DECIMAL_NB(pConfig->Channel))
2806         {
2807           LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_4, LL_ADC_OFFSET_DISABLE);
2808         }
2809       }
2810     }
2811 
2812     /* Parameters update conditioned to ADC state:                              */
2813     /* Parameters that can be updated only when ADC is disabled:                */
2814     /*  - Single or differential mode                                           */
2815     /*  - Internal measurement channels: Vbat/VrefInt/TempSensor                */
2816     if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
2817     {
2818       /* Set mode single-ended or differential input of the selected ADC channel */
2819       LL_ADC_SetChannelSingleDiff(hadc->Instance, pConfig->Channel, pConfig->SingleDiff);
2820 
2821       /* Configuration of differential mode */
2822       if (pConfig->SingleDiff == ADC_DIFFERENTIAL_ENDED)
2823       {
2824         /* Set sampling time of the selected ADC channel */
2825         /* Note: ADC channel number masked with value "0x1F" to ensure shift value within 32 bits range */
2826         LL_ADC_SetChannelSamplingTime(hadc->Instance,
2827                                       (uint32_t)(__LL_ADC_DECIMAL_NB_TO_CHANNEL(
2828                                                    (__LL_ADC_CHANNEL_TO_DECIMAL_NB((uint32_t)pConfig->Channel)
2829                                                     + 1UL) & 0x1FUL)),
2830                                       pConfig->SamplingTime);
2831       }
2832 
2833       /* Management of internal measurement channels: Vbat/VrefInt/TempSensor.  */
2834       /* If internal channel selected, enable dedicated internal buffers and    */
2835       /* paths.                                                                 */
2836       /* Note: these internal measurement paths can be disabled using           */
2837       /* HAL_ADC_DeInit().                                                      */
2838 
2839       if (__LL_ADC_IS_CHANNEL_INTERNAL(pConfig->Channel))
2840       {
2841         /* Configuration of common ADC parameters                                 */
2842 
2843         tmp_config_internal_channel = LL_ADC_GetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
2844 
2845         /* Software is allowed to change common parameters only when all ADCs   */
2846         /* of the common group are disabled.                                    */
2847         if (__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) == 0UL)
2848         {
2849           /* If the requested internal measurement path has already been enabled, */
2850           /* bypass the configuration processing.                                 */
2851           if ((pConfig->Channel == ADC_CHANNEL_TEMPSENSOR)
2852               && ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_TEMPSENSOR) == 0UL))
2853           {
2854             if (ADC_TEMPERATURE_SENSOR_INSTANCE(hadc))
2855             {
2856               LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
2857                                              LL_ADC_PATH_INTERNAL_TEMPSENSOR | tmp_config_internal_channel);
2858 
2859               /* Delay for temperature sensor stabilization time */
2860               /* Wait loop initialization and execution */
2861               /* Note: Variable divided by 2 to compensate partially              */
2862               /*       CPU processing cycles, scaling in us split to not          */
2863               /*       exceed 32 bits register capacity and handle low frequency. */
2864               wait_loop_index = ((LL_ADC_DELAY_TEMPSENSOR_STAB_US / 10UL)
2865                                  * ((SystemCoreClock / (100000UL * 2UL)) + 1UL));
2866               while(wait_loop_index != 0UL)
2867               {
2868                 wait_loop_index--;
2869               }
2870             }
2871           }
2872           else if ((pConfig->Channel == ADC_CHANNEL_VBAT)
2873                    && ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_VBAT) == 0UL))
2874           {
2875             if (ADC_BATTERY_VOLTAGE_INSTANCE(hadc))
2876             {
2877               LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
2878                                              LL_ADC_PATH_INTERNAL_VBAT | tmp_config_internal_channel);
2879             }
2880           }
2881           else if ((pConfig->Channel == ADC_CHANNEL_VREFINT)
2882                    && ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_VREFINT) == 0UL))
2883           {
2884             if (ADC_VREFINT_INSTANCE(hadc))
2885             {
2886               LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
2887                                              LL_ADC_PATH_INTERNAL_VREFINT | tmp_config_internal_channel);
2888             }
2889           }
2890           else
2891           {
2892             /* nothing to do */
2893           }
2894         }
2895         /* If the requested internal measurement path has already been          */
2896         /* enabled and other ADC of the common group are enabled, internal      */
2897         /* measurement paths cannot be enabled.                                 */
2898         else
2899         {
2900           /* Update ADC state machine to error */
2901           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
2902 
2903           tmp_hal_status = HAL_ERROR;
2904         }
2905       }
2906     }
2907   }
2908 
2909   /* If a conversion is on going on regular group, no update on regular       */
2910   /* channel could be done on neither of the channel configuration structure  */
2911   /* parameters.                                                              */
2912   else
2913   {
2914     /* Update ADC state machine to error */
2915     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
2916 
2917     tmp_hal_status = HAL_ERROR;
2918   }
2919 
2920   /* Process unlocked */
2921   __HAL_UNLOCK(hadc);
2922 
2923   /* Return function status */
2924   return tmp_hal_status;
2925 }
2926 
2927 /**
2928   * @brief  Configure the analog watchdog.
2929   * @note   Possibility to update parameters on the fly:
2930   *         This function initializes the selected analog watchdog, successive
2931   *         calls to this function can be used to reconfigure some parameters
2932   *         of structure "ADC_AnalogWDGConfTypeDef" on the fly, without resetting
2933   *         the ADC.
2934   *         The setting of these parameters is conditioned to ADC state.
2935   *         For parameters constraints, see comments of structure
2936   *         "ADC_AnalogWDGConfTypeDef".
2937   * @note   On this STM32 series, analog watchdog thresholds cannot be modified
2938   *         while ADC conversion is on going.
2939   * @param hadc ADC handle
2940   * @param pAnalogWDGConfig Structure of ADC analog watchdog configuration
2941   * @retval HAL status
2942   */
HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef * hadc,const ADC_AnalogWDGConfTypeDef * pAnalogWDGConfig)2943 HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef *hadc, const ADC_AnalogWDGConfTypeDef *pAnalogWDGConfig)
2944 {
2945   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
2946   uint32_t tmp_awd_high_threshold_shifted;
2947   uint32_t tmp_awd_low_threshold_shifted;
2948   uint32_t tmp_adc_is_conversion_on_going_regular;
2949   uint32_t tmp_adc_is_conversion_on_going_injected;
2950 
2951   /* Check the parameters */
2952   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2953   assert_param(IS_ADC_ANALOG_WATCHDOG_NUMBER(pAnalogWDGConfig->WatchdogNumber));
2954   assert_param(IS_ADC_ANALOG_WATCHDOG_MODE(pAnalogWDGConfig->WatchdogMode));
2955   assert_param(IS_FUNCTIONAL_STATE(pAnalogWDGConfig->ITMode));
2956 
2957   if ((pAnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG)     ||
2958       (pAnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC)   ||
2959       (pAnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC))
2960   {
2961     assert_param(IS_ADC_CHANNEL(hadc, pAnalogWDGConfig->Channel));
2962   }
2963 
2964   /* Verify thresholds range */
2965   if (hadc->Init.OversamplingMode == ENABLE)
2966   {
2967     /* Case of oversampling enabled: depending on ratio and shift configuration,
2968        analog watchdog thresholds can be higher than ADC resolution.
2969        Verify if thresholds are within maximum thresholds range. */
2970     assert_param(IS_ADC_RANGE(ADC_RESOLUTION_12B, pAnalogWDGConfig->HighThreshold));
2971     assert_param(IS_ADC_RANGE(ADC_RESOLUTION_12B, pAnalogWDGConfig->LowThreshold));
2972   }
2973   else
2974   {
2975     /* Verify if thresholds are within the selected ADC resolution */
2976     assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), pAnalogWDGConfig->HighThreshold));
2977     assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), pAnalogWDGConfig->LowThreshold));
2978   }
2979 
2980   /* Process locked */
2981   __HAL_LOCK(hadc);
2982 
2983   /* Parameters update conditioned to ADC state:                              */
2984   /* Parameters that can be updated when ADC is disabled or enabled without   */
2985   /* conversion on going on ADC groups regular and injected:                  */
2986   /*  - Analog watchdog channels                                              */
2987   /*  - Analog watchdog thresholds                                            */
2988   tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
2989   tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
2990   if ((tmp_adc_is_conversion_on_going_regular == 0UL)
2991       && (tmp_adc_is_conversion_on_going_injected == 0UL)
2992      )
2993   {
2994     /* Analog watchdog configuration */
2995     if (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_1)
2996     {
2997       /* Configuration of analog watchdog:                                    */
2998       /*  - Set the analog watchdog enable mode: one or overall group of      */
2999       /*    channels, on groups regular and-or injected.                      */
3000       switch (pAnalogWDGConfig->WatchdogMode)
3001       {
3002         case ADC_ANALOGWATCHDOG_SINGLE_REG:
3003           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1,
3004                                           __LL_ADC_ANALOGWD_CHANNEL_GROUP(pAnalogWDGConfig->Channel,
3005                                                                           LL_ADC_GROUP_REGULAR));
3006           break;
3007 
3008         case ADC_ANALOGWATCHDOG_SINGLE_INJEC:
3009           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1,
3010                                           __LL_ADC_ANALOGWD_CHANNEL_GROUP(pAnalogWDGConfig->Channel,
3011                                                                           LL_ADC_GROUP_INJECTED));
3012           break;
3013 
3014         case ADC_ANALOGWATCHDOG_SINGLE_REGINJEC:
3015           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1,
3016                                           __LL_ADC_ANALOGWD_CHANNEL_GROUP(pAnalogWDGConfig->Channel,
3017                                                                           LL_ADC_GROUP_REGULAR_INJECTED));
3018           break;
3019 
3020         case ADC_ANALOGWATCHDOG_ALL_REG:
3021           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_ALL_CHANNELS_REG);
3022           break;
3023 
3024         case ADC_ANALOGWATCHDOG_ALL_INJEC:
3025           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_ALL_CHANNELS_INJ);
3026           break;
3027 
3028         case ADC_ANALOGWATCHDOG_ALL_REGINJEC:
3029           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_ALL_CHANNELS_REG_INJ);
3030           break;
3031 
3032         default: /* ADC_ANALOGWATCHDOG_NONE */
3033           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_DISABLE);
3034           break;
3035       }
3036 
3037       /* Shift the offset in function of the selected ADC resolution:         */
3038       /* Thresholds have to be left-aligned on bit 11, the LSB (right bits)   */
3039       /* are set to 0                                                         */
3040       tmp_awd_high_threshold_shifted = ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(hadc, pAnalogWDGConfig->HighThreshold);
3041       tmp_awd_low_threshold_shifted  = ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(hadc, pAnalogWDGConfig->LowThreshold);
3042 
3043       /* Set ADC analog watchdog thresholds value of both thresholds high and low */
3044       LL_ADC_ConfigAnalogWDThresholds(hadc->Instance, pAnalogWDGConfig->WatchdogNumber, tmp_awd_high_threshold_shifted,
3045                                       tmp_awd_low_threshold_shifted);
3046 
3047       /* Update state, clear previous result related to AWD1 */
3048       CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD1);
3049 
3050       /* Clear flag ADC analog watchdog */
3051       /* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready  */
3052       /* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent()          */
3053       /* (in case left enabled by previous ADC operations).                 */
3054       LL_ADC_ClearFlag_AWD1(hadc->Instance);
3055 
3056       /* Configure ADC analog watchdog interrupt */
3057       if (pAnalogWDGConfig->ITMode == ENABLE)
3058       {
3059         LL_ADC_EnableIT_AWD1(hadc->Instance);
3060       }
3061       else
3062       {
3063         LL_ADC_DisableIT_AWD1(hadc->Instance);
3064       }
3065     }
3066     /* Case of ADC_ANALOGWATCHDOG_2 or ADC_ANALOGWATCHDOG_3 */
3067     else
3068     {
3069       switch (pAnalogWDGConfig->WatchdogMode)
3070       {
3071         case ADC_ANALOGWATCHDOG_SINGLE_REG:
3072         case ADC_ANALOGWATCHDOG_SINGLE_INJEC:
3073         case ADC_ANALOGWATCHDOG_SINGLE_REGINJEC:
3074           /* Update AWD by bitfield to keep the possibility to monitor        */
3075           /* several channels by successive calls of this function.           */
3076           if (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_2)
3077           {
3078             SET_BIT(hadc->Instance->AWD2CR,
3079                     (1UL << (__LL_ADC_CHANNEL_TO_DECIMAL_NB(pAnalogWDGConfig->Channel) & 0x1FUL)));
3080           }
3081           else
3082           {
3083             SET_BIT(hadc->Instance->AWD3CR,
3084                     (1UL << (__LL_ADC_CHANNEL_TO_DECIMAL_NB(pAnalogWDGConfig->Channel) & 0x1FUL)));
3085           }
3086           break;
3087 
3088         case ADC_ANALOGWATCHDOG_ALL_REG:
3089         case ADC_ANALOGWATCHDOG_ALL_INJEC:
3090         case ADC_ANALOGWATCHDOG_ALL_REGINJEC:
3091           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance,
3092                                           pAnalogWDGConfig->WatchdogNumber, LL_ADC_AWD_ALL_CHANNELS_REG_INJ);
3093           break;
3094 
3095         default: /* ADC_ANALOGWATCHDOG_NONE */
3096           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, pAnalogWDGConfig->WatchdogNumber, LL_ADC_AWD_DISABLE);
3097           break;
3098       }
3099 
3100       /* Shift the thresholds in function of the selected ADC resolution      */
3101       /* have to be left-aligned on bit 7, the LSB (right bits) are set to 0  */
3102       tmp_awd_high_threshold_shifted = ADC_AWD23THRESHOLD_SHIFT_RESOLUTION(hadc, pAnalogWDGConfig->HighThreshold);
3103       tmp_awd_low_threshold_shifted  = ADC_AWD23THRESHOLD_SHIFT_RESOLUTION(hadc, pAnalogWDGConfig->LowThreshold);
3104 
3105       /* Set ADC analog watchdog thresholds value of both thresholds high and low */
3106       LL_ADC_ConfigAnalogWDThresholds(hadc->Instance, pAnalogWDGConfig->WatchdogNumber, tmp_awd_high_threshold_shifted,
3107                                       tmp_awd_low_threshold_shifted);
3108 
3109       if (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_2)
3110       {
3111         /* Update state, clear previous result related to AWD2 */
3112         CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD2);
3113 
3114         /* Clear flag ADC analog watchdog */
3115         /* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready  */
3116         /* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent()          */
3117         /* (in case left enabled by previous ADC operations).                 */
3118         LL_ADC_ClearFlag_AWD2(hadc->Instance);
3119 
3120         /* Configure ADC analog watchdog interrupt */
3121         if (pAnalogWDGConfig->ITMode == ENABLE)
3122         {
3123           LL_ADC_EnableIT_AWD2(hadc->Instance);
3124         }
3125         else
3126         {
3127           LL_ADC_DisableIT_AWD2(hadc->Instance);
3128         }
3129       }
3130       /* (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_3) */
3131       else
3132       {
3133         /* Update state, clear previous result related to AWD3 */
3134         CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD3);
3135 
3136         /* Clear flag ADC analog watchdog */
3137         /* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready  */
3138         /* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent()          */
3139         /* (in case left enabled by previous ADC operations).                 */
3140         LL_ADC_ClearFlag_AWD3(hadc->Instance);
3141 
3142         /* Configure ADC analog watchdog interrupt */
3143         if (pAnalogWDGConfig->ITMode == ENABLE)
3144         {
3145           LL_ADC_EnableIT_AWD3(hadc->Instance);
3146         }
3147         else
3148         {
3149           LL_ADC_DisableIT_AWD3(hadc->Instance);
3150         }
3151       }
3152     }
3153 
3154   }
3155   /* If a conversion is on going on ADC group regular or injected, no update  */
3156   /* could be done on neither of the AWD configuration structure parameters.  */
3157   else
3158   {
3159     /* Update ADC state machine to error */
3160     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
3161 
3162     tmp_hal_status = HAL_ERROR;
3163   }
3164   /* Process unlocked */
3165   __HAL_UNLOCK(hadc);
3166 
3167   /* Return function status */
3168   return tmp_hal_status;
3169 }
3170 
3171 
3172 /**
3173   * @}
3174   */
3175 
3176 /** @defgroup ADC_Exported_Functions_Group4 Peripheral State functions
3177   *  @brief    ADC Peripheral State functions
3178   *
3179 @verbatim
3180  ===============================================================================
3181             ##### Peripheral state and errors functions #####
3182  ===============================================================================
3183     [..]
3184     This subsection provides functions to get in run-time the status of the
3185     peripheral.
3186       (+) Check the ADC state
3187       (+) Check the ADC error code
3188 
3189 @endverbatim
3190   * @{
3191   */
3192 
3193 /**
3194   * @brief  Return the ADC handle state.
3195   * @note   ADC state machine is managed by bitfields, ADC status must be
3196   *         compared with states bits.
3197   *         For example:
3198   *           " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_REG_BUSY) != 0UL) "
3199   *           " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD1) != 0UL) "
3200   * @param hadc ADC handle
3201   * @retval ADC handle state (bitfield on 32 bits)
3202   */
HAL_ADC_GetState(const ADC_HandleTypeDef * hadc)3203 uint32_t HAL_ADC_GetState(const ADC_HandleTypeDef *hadc)
3204 {
3205   /* Check the parameters */
3206   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
3207 
3208   /* Return ADC handle state */
3209   return hadc->State;
3210 }
3211 
3212 /**
3213   * @brief  Return the ADC error code.
3214   * @param hadc ADC handle
3215   * @retval ADC error code (bitfield on 32 bits)
3216   */
HAL_ADC_GetError(const ADC_HandleTypeDef * hadc)3217 uint32_t HAL_ADC_GetError(const ADC_HandleTypeDef *hadc)
3218 {
3219   /* Check the parameters */
3220   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
3221 
3222   return hadc->ErrorCode;
3223 }
3224 
3225 /**
3226   * @}
3227   */
3228 
3229 /**
3230   * @}
3231   */
3232 
3233 /** @defgroup ADC_Private_Functions ADC Private Functions
3234   * @{
3235   */
3236 
3237 /**
3238   * @brief  Stop ADC conversion.
3239   * @param hadc ADC handle
3240   * @param ConversionGroup ADC group regular and/or injected.
3241   *          This parameter can be one of the following values:
3242   *            @arg @ref ADC_REGULAR_GROUP           ADC regular conversion type.
3243   *            @arg @ref ADC_INJECTED_GROUP          ADC injected conversion type.
3244   *            @arg @ref ADC_REGULAR_INJECTED_GROUP  ADC regular and injected conversion type.
3245   * @retval HAL status.
3246   */
ADC_ConversionStop(ADC_HandleTypeDef * hadc,uint32_t ConversionGroup)3247 HAL_StatusTypeDef ADC_ConversionStop(ADC_HandleTypeDef *hadc, uint32_t ConversionGroup)
3248 {
3249   uint32_t tickstart;
3250   uint32_t Conversion_Timeout_CPU_cycles = 0UL;
3251   uint32_t conversion_group_reassigned = ConversionGroup;
3252   uint32_t tmp_ADC_CR_ADSTART_JADSTART;
3253   uint32_t tmp_adc_is_conversion_on_going_regular;
3254   uint32_t tmp_adc_is_conversion_on_going_injected;
3255 
3256   /* Check the parameters */
3257   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
3258   assert_param(IS_ADC_CONVERSION_GROUP(ConversionGroup));
3259 
3260   /* Verification if ADC is not already stopped (on regular and injected      */
3261   /* groups) to bypass this function if not needed.                           */
3262   tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
3263   tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
3264   if ((tmp_adc_is_conversion_on_going_regular != 0UL)
3265       || (tmp_adc_is_conversion_on_going_injected != 0UL)
3266      )
3267   {
3268     /* Particular case of continuous auto-injection mode combined with        */
3269     /* auto-delay mode.                                                       */
3270     /* In auto-injection mode, regular group stop ADC_CR_ADSTP is used (not   */
3271     /* injected group stop ADC_CR_JADSTP).                                    */
3272     /* Procedure to be followed: Wait until JEOS=1, clear JEOS, set ADSTP=1   */
3273     /* (see reference manual).                                                */
3274     if (((hadc->Instance->CFGR & ADC_CFGR_JAUTO) != 0UL)
3275         && (hadc->Init.ContinuousConvMode == ENABLE)
3276         && (hadc->Init.LowPowerAutoWait == ENABLE)
3277        )
3278     {
3279       /* Use stop of regular group */
3280       conversion_group_reassigned = ADC_REGULAR_GROUP;
3281 
3282       /* Wait until JEOS=1 (maximum Timeout: 4 injected conversions) */
3283       while (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOS) == 0UL)
3284       {
3285         if (Conversion_Timeout_CPU_cycles >= (ADC_CONVERSION_TIME_MAX_CPU_CYCLES * 4UL))
3286         {
3287           /* Update ADC state machine to error */
3288           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
3289 
3290           /* Set ADC error code to ADC peripheral internal error */
3291           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
3292 
3293           return HAL_ERROR;
3294         }
3295         Conversion_Timeout_CPU_cycles ++;
3296       }
3297 
3298       /* Clear JEOS */
3299       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOS);
3300     }
3301 
3302     /* Stop potential conversion on going on ADC group regular */
3303     if (conversion_group_reassigned != ADC_INJECTED_GROUP)
3304     {
3305       /* Software is allowed to set ADSTP only when ADSTART=1 and ADDIS=0 */
3306       if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) != 0UL)
3307       {
3308         if (LL_ADC_IsDisableOngoing(hadc->Instance) == 0UL)
3309         {
3310           /* Stop ADC group regular conversion */
3311           LL_ADC_REG_StopConversion(hadc->Instance);
3312         }
3313       }
3314     }
3315 
3316     /* Stop potential conversion on going on ADC group injected */
3317     if (conversion_group_reassigned != ADC_REGULAR_GROUP)
3318     {
3319       /* Software is allowed to set JADSTP only when JADSTART=1 and ADDIS=0 */
3320       if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) != 0UL)
3321       {
3322         if (LL_ADC_IsDisableOngoing(hadc->Instance) == 0UL)
3323         {
3324           /* Stop ADC group injected conversion */
3325           LL_ADC_INJ_StopConversion(hadc->Instance);
3326         }
3327       }
3328     }
3329 
3330     /* Selection of start and stop bits with respect to the regular or injected group */
3331     switch (conversion_group_reassigned)
3332     {
3333       case ADC_REGULAR_INJECTED_GROUP:
3334         tmp_ADC_CR_ADSTART_JADSTART = (ADC_CR_ADSTART | ADC_CR_JADSTART);
3335         break;
3336       case ADC_INJECTED_GROUP:
3337         tmp_ADC_CR_ADSTART_JADSTART = ADC_CR_JADSTART;
3338         break;
3339       /* Case ADC_REGULAR_GROUP only*/
3340       default:
3341         tmp_ADC_CR_ADSTART_JADSTART = ADC_CR_ADSTART;
3342         break;
3343     }
3344 
3345     /* Wait for conversion effectively stopped */
3346     tickstart = HAL_GetTick();
3347 
3348     while ((hadc->Instance->CR & tmp_ADC_CR_ADSTART_JADSTART) != 0UL)
3349     {
3350       if ((HAL_GetTick() - tickstart) > ADC_STOP_CONVERSION_TIMEOUT)
3351       {
3352         /* New check to avoid false timeout detection in case of preemption */
3353         if ((hadc->Instance->CR & tmp_ADC_CR_ADSTART_JADSTART) != 0UL)
3354         {
3355           /* Update ADC state machine to error */
3356           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
3357 
3358           /* Set ADC error code to ADC peripheral internal error */
3359           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
3360 
3361           return HAL_ERROR;
3362         }
3363       }
3364     }
3365 
3366   }
3367 
3368   /* Return HAL status */
3369   return HAL_OK;
3370 }
3371 
3372 /**
3373   * @brief  Enable the selected ADC.
3374   * @note   Prerequisite condition to use this function: ADC must be disabled
3375   *         and voltage regulator must be enabled (done into HAL_ADC_Init()).
3376   * @param hadc ADC handle
3377   * @retval HAL status.
3378   */
ADC_Enable(ADC_HandleTypeDef * hadc)3379 HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef *hadc)
3380 {
3381   uint32_t tickstart;
3382   __IO uint32_t wait_loop_index = 0UL;
3383 
3384   /* ADC enable and wait for ADC ready (in case of ADC is disabled or         */
3385   /* enabling phase not yet completed: flag ADC ready not yet set).           */
3386   /* Timeout implemented to not be stuck if ADC cannot be enabled (possible   */
3387   /* causes: ADC clock not running, ...).                                     */
3388   if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
3389   {
3390     /* Check if conditions to enable the ADC are fulfilled */
3391     if ((hadc->Instance->CR & (ADC_CR_ADCAL | ADC_CR_JADSTP | ADC_CR_ADSTP | ADC_CR_JADSTART | ADC_CR_ADSTART
3392                                | ADC_CR_ADDIS | ADC_CR_ADEN)) != 0UL)
3393     {
3394       /* Update ADC state machine to error */
3395       SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
3396 
3397       /* Set ADC error code to ADC peripheral internal error */
3398       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
3399 
3400       return HAL_ERROR;
3401     }
3402 
3403     /* Enable the ADC peripheral */
3404     LL_ADC_Enable(hadc->Instance);
3405 
3406     if ((LL_ADC_GetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance))
3407          & LL_ADC_PATH_INTERNAL_TEMPSENSOR) != 0UL)
3408     {
3409       /* Delay for temperature sensor buffer stabilization time */
3410       /* Note: Value LL_ADC_DELAY_TEMPSENSOR_STAB_US used instead of      */
3411       /*       LL_ADC_DELAY_TEMPSENSOR_BUFFER_STAB_US because needed      */
3412       /*       in case of ADC enable after a system wake up               */
3413       /*       from low power mode.                                       */
3414 
3415       /* Wait loop initialization and execution */
3416       /* Note: Variable divided by 2 to compensate partially              */
3417       /*       CPU processing cycles, scaling in us split to not          */
3418       /*       exceed 32 bits register capacity and handle low frequency. */
3419       wait_loop_index = ((LL_ADC_DELAY_TEMPSENSOR_STAB_US / 10UL) * ((SystemCoreClock / (100000UL * 2UL)) + 1UL));
3420       while (wait_loop_index != 0UL)
3421       {
3422         wait_loop_index--;
3423       }
3424     }
3425 
3426     /* Wait for ADC effectively enabled */
3427     tickstart = HAL_GetTick();
3428 
3429     while (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_RDY) == 0UL)
3430     {
3431       /*  If ADEN bit is set less than 4 ADC clock cycles after the ADCAL bit
3432           has been cleared (after a calibration), ADEN bit is reset by the
3433           calibration logic.
3434           The workaround is to continue setting ADEN until ADRDY is becomes 1.
3435           Additionally, ADC_ENABLE_TIMEOUT is defined to encompass this
3436           4 ADC clock cycle duration */
3437       /* Note: Test of ADC enabled required due to hardware constraint to     */
3438       /*       not enable ADC if already enabled.                             */
3439       if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
3440       {
3441         LL_ADC_Enable(hadc->Instance);
3442       }
3443 
3444       if ((HAL_GetTick() - tickstart) > ADC_ENABLE_TIMEOUT)
3445       {
3446         /* New check to avoid false timeout detection in case of preemption */
3447         if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_RDY) == 0UL)
3448         {
3449           /* Update ADC state machine to error */
3450           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
3451 
3452           /* Set ADC error code to ADC peripheral internal error */
3453           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
3454 
3455           return HAL_ERROR;
3456         }
3457       }
3458     }
3459   }
3460 
3461   /* Return HAL status */
3462   return HAL_OK;
3463 }
3464 
3465 /**
3466   * @brief  Disable the selected ADC.
3467   * @note   Prerequisite condition to use this function: ADC conversions must be
3468   *         stopped.
3469   * @param hadc ADC handle
3470   * @retval HAL status.
3471   */
ADC_Disable(ADC_HandleTypeDef * hadc)3472 HAL_StatusTypeDef ADC_Disable(ADC_HandleTypeDef *hadc)
3473 {
3474   uint32_t tickstart;
3475   const uint32_t tmp_adc_is_disable_on_going = LL_ADC_IsDisableOngoing(hadc->Instance);
3476 
3477   /* Verification if ADC is not already disabled:                             */
3478   /* Note: forbidden to disable ADC (set bit ADC_CR_ADDIS) if ADC is already  */
3479   /*       disabled.                                                          */
3480   if ((LL_ADC_IsEnabled(hadc->Instance) != 0UL)
3481       && (tmp_adc_is_disable_on_going == 0UL)
3482      )
3483   {
3484     /* Check if conditions to disable the ADC are fulfilled */
3485     if ((hadc->Instance->CR & (ADC_CR_JADSTART | ADC_CR_ADSTART | ADC_CR_ADEN)) == ADC_CR_ADEN)
3486     {
3487       /* Disable the ADC peripheral */
3488       LL_ADC_Disable(hadc->Instance);
3489       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOSMP | ADC_FLAG_RDY));
3490     }
3491     else
3492     {
3493       /* Update ADC state machine to error */
3494       SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
3495 
3496       /* Set ADC error code to ADC peripheral internal error */
3497       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
3498 
3499       return HAL_ERROR;
3500     }
3501 
3502     /* Wait for ADC effectively disabled */
3503     /* Get tick count */
3504     tickstart = HAL_GetTick();
3505 
3506     while ((hadc->Instance->CR & ADC_CR_ADEN) != 0UL)
3507     {
3508       if ((HAL_GetTick() - tickstart) > ADC_DISABLE_TIMEOUT)
3509       {
3510         /* New check to avoid false timeout detection in case of preemption */
3511         if ((hadc->Instance->CR & ADC_CR_ADEN) != 0UL)
3512         {
3513           /* Update ADC state machine to error */
3514           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
3515 
3516           /* Set ADC error code to ADC peripheral internal error */
3517           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
3518 
3519           return HAL_ERROR;
3520         }
3521       }
3522     }
3523   }
3524 
3525   /* Return HAL status */
3526   return HAL_OK;
3527 }
3528 
3529 /**
3530   * @brief  DMA transfer complete callback.
3531   * @param hdma pointer to DMA handle.
3532   * @retval None
3533   */
ADC_DMAConvCplt(DMA_HandleTypeDef * hdma)3534 void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma)
3535 {
3536   /* Retrieve ADC handle corresponding to current DMA handle */
3537   ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
3538 
3539   /* Update state machine on conversion status if not in error state */
3540   if ((hadc->State & (HAL_ADC_STATE_ERROR_INTERNAL | HAL_ADC_STATE_ERROR_DMA)) == 0UL)
3541   {
3542     /* Set ADC state */
3543     SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
3544 
3545     /* Determine whether any further conversion upcoming on group regular     */
3546     /* by external trigger, continuous mode or scan sequence on going         */
3547     /* to disable interruption.                                               */
3548     /* Is it the end of the regular sequence ? */
3549     if ((hadc->Instance->ISR & ADC_FLAG_EOS) != 0UL)
3550     {
3551       /* Are conversions software-triggered ? */
3552       if (LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
3553       {
3554         /* Is CONT bit set ? */
3555         if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_CONT) == 0UL)
3556         {
3557           /* CONT bit is not set, no more conversions expected */
3558           CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
3559           if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) == 0UL)
3560           {
3561             SET_BIT(hadc->State, HAL_ADC_STATE_READY);
3562           }
3563         }
3564       }
3565     }
3566     else
3567     {
3568       /* DMA End of Transfer interrupt was triggered but conversions sequence
3569          is not over. If DMACFG is set to 0, conversions are stopped. */
3570       if (READ_BIT(hadc->Instance->CFGR, ADC_CFGR_DMACFG) == 0UL)
3571       {
3572         /* DMACFG bit is not set, conversions are stopped. */
3573         CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
3574         if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) == 0UL)
3575         {
3576           SET_BIT(hadc->State, HAL_ADC_STATE_READY);
3577         }
3578       }
3579     }
3580 
3581     /* Conversion complete callback */
3582 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
3583     hadc->ConvCpltCallback(hadc);
3584 #else
3585     HAL_ADC_ConvCpltCallback(hadc);
3586 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
3587   }
3588   else /* DMA and-or internal error occurred */
3589   {
3590     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) != 0UL)
3591     {
3592       /* Call HAL ADC Error Callback function */
3593 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
3594       hadc->ErrorCallback(hadc);
3595 #else
3596       HAL_ADC_ErrorCallback(hadc);
3597 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
3598     }
3599     else
3600     {
3601       /* Call ADC DMA error callback */
3602       hadc->DMA_Handle->XferErrorCallback(hdma);
3603     }
3604   }
3605 }
3606 
3607 /**
3608   * @brief  DMA half transfer complete callback.
3609   * @param hdma pointer to DMA handle.
3610   * @retval None
3611   */
ADC_DMAHalfConvCplt(DMA_HandleTypeDef * hdma)3612 void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma)
3613 {
3614   /* Retrieve ADC handle corresponding to current DMA handle */
3615   ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
3616 
3617   /* Half conversion callback */
3618 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
3619   hadc->ConvHalfCpltCallback(hadc);
3620 #else
3621   HAL_ADC_ConvHalfCpltCallback(hadc);
3622 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
3623 }
3624 
3625 /**
3626   * @brief  DMA error callback.
3627   * @param hdma pointer to DMA handle.
3628   * @retval None
3629   */
ADC_DMAError(DMA_HandleTypeDef * hdma)3630 void ADC_DMAError(DMA_HandleTypeDef *hdma)
3631 {
3632   /* Retrieve ADC handle corresponding to current DMA handle */
3633   ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
3634 
3635   /* Set ADC state */
3636   SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
3637 
3638   /* Set ADC error code to DMA error */
3639   SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_DMA);
3640 
3641   /* Error callback */
3642 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
3643   hadc->ErrorCallback(hadc);
3644 #else
3645   HAL_ADC_ErrorCallback(hadc);
3646 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
3647 }
3648 
3649 /**
3650   * @}
3651   */
3652 
3653 #endif /* HAL_ADC_MODULE_ENABLED */
3654 /**
3655   * @}
3656   */
3657 
3658 /**
3659   * @}
3660   */
3661