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