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