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