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