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