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