1 /**
2   ******************************************************************************
3   * @file    stm32wbaxx_hal_adc.c
4   * @author  MCD Application Team
5   * @brief   This file provides firmware functions to manage the following
6   *          functionalities of the Analog to Digital Converter (ADC)
7   *          peripheral:
8   *           + Initialization and de-initialization functions
9   *           + Peripheral Control functions
10   *           + Peripheral State functions
11   *          Other functions (extended functions) are available in file
12   *          "stm32wbaxx_hal_adc_ex.c".
13   *
14   ******************************************************************************
15   * @attention
16   *
17   * Copyright (c) 2022 STMicroelectronics.
18   * All rights reserved.
19   *
20   * This software is licensed under terms that can be found in the LICENSE file
21   * in the root directory of this software component.
22   * If no LICENSE file comes with this software, it is provided AS-IS.
23   *
24   ******************************************************************************
25   @verbatim
26   ==============================================================================
27                      ##### ADC peripheral features #####
28   ==============================================================================
29   [..]
30   (+) 12-bit, 10-bit, 8-bit or 6-bit configurable resolution.
31 
32   (+) Interrupt generation at the end of regular conversion and in case of
33       analog watchdog or overrun events.
34 
35   (+) Single and continuous conversion modes.
36 
37   (+) Scan mode for conversion of several channels sequentially.
38 
39   (+) Data alignment with in-built data coherency.
40 
41   (+) Programmable sampling time (common to group of channels)
42 
43   (+) External trigger (timer or EXTI) with configurable polarity
44 
45   (+) DMA request generation for transfer of conversions data of regular group.
46 
47   (+) ADC calibration
48 
49   (+) ADC conversion of regular group.
50 
51   (+) ADC supply requirements: 1.62 V to 3.6 V.
52 
53   (+) ADC input range: from Vref- (connected to Vssa) to Vref+ (connected to
54       Vdda or to an external voltage reference).
55 
56 
57                      ##### How to use this driver #####
58   ==============================================================================
59     [..]
60 
61      *** Configuration of top level parameters related to ADC ***
62      ============================================================
63      [..]
64 
65     (#) Enable the ADC interface
66         (++) As prerequisite, ADC clock must be configured at RCC top level.
67              Caution: On this series, ADC clock frequency max is 35MHz (refer
68                       to device datasheet).
69                       Therefore, ADC clock source from RCC and ADC clock
70                       prescaler must be configured to remain below
71                       this maximum frequency.
72 
73         (++) Two clock settings are mandatory:
74              (+++) ADC clock (core clock, also possibly conversion clock).
75 
76              (+++) ADC clock (conversions clock).
77                    Five possible clock sources from RCC level: HCLK1, SYSCLK, SYSCLK, HSE32, HSI16, PLL1PCLK.
78 
79              (+++) Example:
80                    Into HAL_ADC_MspInit() (recommended code location) or with
81                    other device clock parameters configuration:
82                (+++) __HAL_RCC_ADC_CLK_ENABLE();                  (mandatory: core clock)
83 
84         (++) ADC clock source and clock prescaler are configured at ADC level with
85              parameter "ClockPrescaler" using function HAL_ADC_Init().
86 
87     (#) ADC pins configuration
88          (++) Enable the clock for the ADC GPIOs
89               using macro __HAL_RCC_GPIOx_CLK_ENABLE()
90          (++) Configure these ADC pins in analog mode
91               using function HAL_GPIO_Init()
92 
93     (#) Optionally, in case of usage of ADC with interruptions:
94          (++) Configure the NVIC for ADC
95               using function HAL_NVIC_EnableIRQ(ADCx_IRQn)
96          (++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
97               into the function of corresponding ADC interruption vector
98               ADCx_IRQHandler().
99 
100     (#) Optionally, in case of usage of DMA:
101          (++) Configure the DMA (DMA channel, mode normal or circular, ...)
102               using function HAL_DMA_Init().
103          (++) Configure the NVIC for DMA
104               using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
105          (++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
106               into the function of corresponding DMA interruption vector
107               DMAx_Channelx_IRQHandler().
108 
109      *** Configuration of ADC, group regular, channels parameters ***
110      ================================================================
111      [..]
112 
113     (#) Configure the ADC parameters (resolution, data alignment, ...)
114         and regular group parameters (conversion trigger, sequencer, ...)
115         using function HAL_ADC_Init().
116 
117     (#) Configure the channels for regular group parameters (channel number,
118         channel rank into sequencer, ..., into regular group)
119         using function HAL_ADC_ConfigChannel().
120 
121     (#) Optionally, configure the analog watchdog parameters (channels
122         monitored, thresholds, ...)
123         using function HAL_ADC_AnalogWDGConfig().
124 
125      *** Execution of ADC conversions ***
126      ====================================
127      [..]
128 
129     (#) Optionally, perform an automatic ADC calibration to improve the
130         conversion accuracy
131         using function HAL_ADCEx_Calibration_Start().
132 
133     (#) ADC driver can be used among three modes: polling, interruption,
134         transfer by DMA.
135 
136         (++) ADC conversion by polling:
137           (+++) Activate the ADC peripheral and start conversions
138                 using function HAL_ADC_Start()
139           (+++) Wait for ADC conversion completion
140                 using function HAL_ADC_PollForConversion()
141           (+++) Retrieve conversion results
142                 using function HAL_ADC_GetValue()
143           (+++) Stop conversion and disable the ADC peripheral
144                 using function HAL_ADC_Stop()
145 
146         (++) ADC conversion by interruption:
147           (+++) Activate the ADC peripheral and start conversions
148                 using function HAL_ADC_Start_IT()
149           (+++) Wait for ADC conversion completion by call of function
150                 HAL_ADC_ConvCpltCallback()
151                 (this function must be implemented in user program)
152           (+++) Retrieve conversion results
153                 using function HAL_ADC_GetValue()
154           (+++) Stop conversion and disable the ADC peripheral
155                 using function HAL_ADC_Stop_IT()
156 
157         (++) ADC conversion with transfer by DMA:
158           (+++) Activate the ADC peripheral and start conversions
159                 using function HAL_ADC_Start_DMA()
160           (+++) Wait for ADC conversion completion by call of function
161                 HAL_ADC_ConvCpltCallback() or HAL_ADC_ConvHalfCpltCallback()
162                 (these functions must be implemented in user program)
163           (+++) Conversion results are automatically transferred by DMA into
164                 destination variable address.
165           (+++) Stop conversion and disable the ADC peripheral
166                 using function HAL_ADC_Stop_DMA()
167 
168      [..]
169 
170     (@) Callback functions must be implemented in user program:
171       (+@) HAL_ADC_ErrorCallback()
172       (+@) HAL_ADC_LevelOutOfWindowCallback() (callback of analog watchdog)
173       (+@) HAL_ADC_ConvCpltCallback()
174       (+@) HAL_ADC_ConvHalfCpltCallback
175 
176      *** Deinitialization of ADC ***
177      ============================================================
178      [..]
179 
180     (#) Disable the ADC interface
181       (++) ADC clock can be hard reset and disabled at RCC top level.
182         (++) Hard reset of ADC peripherals
183              using macro __ADCx_FORCE_RESET(), __ADCx_RELEASE_RESET().
184         (++) ADC clock disable
185              using the equivalent macro/functions as configuration step.
186              (+++) Example:
187                    Into HAL_ADC_MspDeInit() (recommended code location) or with
188                    other device clock parameters configuration:
189                (+++) RCC_OscInitStructure.OscillatorType = RCC_OSCILLATORTYPE_HSI14;
190                (+++) RCC_OscInitStructure.HSI14State = RCC_HSI14_OFF; (if not used for system clock)
191                (+++) HAL_RCC_OscConfig(&RCC_OscInitStructure);
192 
193     (#) ADC pins configuration
194          (++) Disable the clock for the ADC GPIOs
195               using macro __HAL_RCC_GPIOx_CLK_DISABLE()
196 
197     (#) Optionally, in case of usage of ADC with interruptions:
198          (++) Disable the NVIC for ADC
199               using function HAL_NVIC_EnableIRQ(ADCx_IRQn)
200 
201     (#) Optionally, in case of usage of DMA:
202          (++) Deinitialize the DMA
203               using function HAL_DMA_Init().
204          (++) Disable the NVIC for DMA
205               using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
206 
207     [..]
208 
209     *** Callback registration ***
210     =============================================
211     [..]
212 
213      The compilation flag USE_HAL_ADC_REGISTER_CALLBACKS, when set to 1,
214      allows the user to configure dynamically the driver callbacks.
215      Use Functions HAL_ADC_RegisterCallback()
216      to register an interrupt callback.
217     [..]
218 
219      Function HAL_ADC_RegisterCallback() allows to register following callbacks:
220        (+) ConvCpltCallback               : ADC conversion complete callback
221        (+) ConvHalfCpltCallback           : ADC conversion DMA half-transfer callback
222        (+) LevelOutOfWindowCallback       : ADC analog watchdog 1 callback
223        (+) ErrorCallback                  : ADC error callback
224        (+) LevelOutOfWindow2Callback      : ADC analog watchdog 2 callback
225        (+) LevelOutOfWindow3Callback      : ADC analog watchdog 3 callback
226        (+) EndOfSamplingCallback          : ADC end of sampling callback
227        (+) MspInitCallback                : ADC Msp Init callback
228        (+) MspDeInitCallback              : ADC Msp DeInit callback
229      This function takes as parameters the HAL peripheral handle, the Callback ID
230      and a pointer to the user callback function.
231     [..]
232 
233      Use function HAL_ADC_UnRegisterCallback to reset a callback to the default
234      weak function.
235     [..]
236 
237      HAL_ADC_UnRegisterCallback takes as parameters the HAL peripheral handle,
238      and the Callback ID.
239      This function allows to reset following callbacks:
240        (+) ConvCpltCallback               : ADC conversion complete callback
241        (+) ConvHalfCpltCallback           : ADC conversion DMA half-transfer callback
242        (+) LevelOutOfWindowCallback       : ADC analog watchdog 1 callback
243        (+) ErrorCallback                  : ADC error 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      [..]
250 
251      By default, after the HAL_ADC_Init() and when the state is HAL_ADC_STATE_RESET
252      all callbacks are set to the corresponding weak functions:
253      examples HAL_ADC_ConvCpltCallback(), HAL_ADC_ErrorCallback().
254      Exception done for MspInit and MspDeInit functions that are
255      reset to the legacy weak functions in the HAL_ADC_Init()/ HAL_ADC_DeInit() only when
256      these callbacks are null (not registered beforehand).
257     [..]
258 
259      If MspInit or MspDeInit are not null, the HAL_ADC_Init()/ HAL_ADC_DeInit()
260      keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state.
261      [..]
262 
263      Callbacks can be registered/unregistered in HAL_ADC_STATE_READY state only.
264      Exception done MspInit/MspDeInit functions that can be registered/unregistered
265      in HAL_ADC_STATE_READY or HAL_ADC_STATE_RESET state,
266      thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit.
267     [..]
268 
269      Then, the user first registers the MspInit/MspDeInit user callbacks
270      using HAL_ADC_RegisterCallback() before calling HAL_ADC_DeInit()
271      or HAL_ADC_Init() function.
272      [..]
273 
274      When the compilation flag USE_HAL_ADC_REGISTER_CALLBACKS is set to 0 or
275      not defined, the callback registration feature is not available and all callbacks
276      are set to the corresponding weak functions.
277 
278   @endverbatim
279   ******************************************************************************
280   */
281 
282 /* Includes ------------------------------------------------------------------*/
283 #include "stm32wbaxx_hal.h"
284 
285 /** @addtogroup STM32WBAxx_HAL_Driver
286   * @{
287   */
288 
289 /** @defgroup ADC ADC
290   * @brief ADC HAL module driver
291   * @{
292   */
293 
294 #ifdef HAL_ADC_MODULE_ENABLED
295 
296 /* Private typedef -----------------------------------------------------------*/
297 /* Private define ------------------------------------------------------------*/
298 
299 /** @defgroup ADC_Private_Constants ADC Private Constants
300   * @{
301   */
302 
303 /* Fixed timeout values for ADC calibration, enable settling time, disable  */
304 /* settling time.                                                           */
305 /* Values defined to be higher than worst cases: low clock frequency,       */
306 /* maximum prescaler.                                                       */
307 /* Ex of profile low frequency : Clock source at 0.1 MHz, ADC clock         */
308 /* prescaler 4, sampling time 7.5 ADC clock cycles, resolution 12 bits.     */
309 /* Unit: ms                                                                 */
310 #define ADC_ENABLE_TIMEOUT              (2UL)
311 #define ADC_DISABLE_TIMEOUT             (2UL)
312 #define ADC_STOP_CONVERSION_TIMEOUT     (2UL)
313 #define ADC_LDO_RDY_TIMEOUT             (1UL) /* Note: Timeout value independent of ADC clock frequency, for more
314                                                        accurate value refer to LL_ADC_DELAY_INTERNAL_REGUL_STAB_US */
315 
316 /* Register CHSELR bits corresponding to ranks 2 to 8 .                     */
317 #define ADC_CHSELR_SQ2_TO_SQ8           (ADC_CHSELR_SQ2 | ADC_CHSELR_SQ3 | ADC_CHSELR_SQ4 | \
318                                          ADC_CHSELR_SQ5 | ADC_CHSELR_SQ6 | ADC_CHSELR_SQ7 | ADC_CHSELR_SQ8)
319 
320 /**
321   * @}
322   */
323 
324 /* Private macro -------------------------------------------------------------*/
325 /* Private variables ---------------------------------------------------------*/
326 /* Private function prototypes -----------------------------------------------*/
327 /** @defgroup ADC_Private_Functions ADC Private Functions
328   * @{
329   */
330 static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma);
331 static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma);
332 static void ADC_DMAError(DMA_HandleTypeDef *hdma);
333 /**
334   * @}
335   */
336 
337 /* Exported functions ---------------------------------------------------------*/
338 
339 /** @defgroup ADC_Exported_Functions ADC Exported Functions
340   * @{
341   */
342 
343 /** @defgroup ADC_Exported_Functions_Group1 Initialization and de-initialization functions
344   * @brief    ADC Initialization and Configuration functions
345   *
346 @verbatim
347  ===============================================================================
348               ##### Initialization and de-initialization functions #####
349  ===============================================================================
350     [..]  This section provides functions allowing to:
351       (+) Initialize and configure the ADC.
352       (+) De-initialize the ADC.
353 @endverbatim
354   * @{
355   */
356 
357 /**
358   * @brief  Initialize the ADC peripheral and regular group according to
359   *         parameters specified in structure "ADC_InitTypeDef".
360   * @note   As prerequisite, ADC clock must be configured at RCC top level
361   *         (refer to description of RCC configuration for ADC
362   *         in header of this file).
363   * @note   Possibility to update parameters on the fly:
364   *         This function initializes the ADC MSP (HAL_ADC_MspInit()) only when
365   *         coming from ADC state reset. Following calls to this function can
366   *         be used to reconfigure some parameters of ADC_InitTypeDef
367   *         structure on the fly, without modifying MSP configuration. If ADC
368   *         MSP has to be modified again, HAL_ADC_DeInit() must be called
369   *         before HAL_ADC_Init().
370   *         The setting of these parameters is conditioned to ADC state.
371   *         For parameters constraints, see comments of structure
372   *         "ADC_InitTypeDef".
373   * @note   This function configures the ADC within 2 scopes: scope of entire
374   *         ADC and scope of regular group. For parameters details, see comments
375   *         of structure "ADC_InitTypeDef".
376   * @param hadc ADC handle
377   * @retval HAL status
378   */
HAL_ADC_Init(ADC_HandleTypeDef * hadc)379 HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef *hadc)
380 {
381   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
382   uint32_t tmp_cfgr1 = 0UL;
383   uint32_t tmp_cfgr2 = 0UL;
384   uint32_t tmp_adc_reg_is_conversion_on_going;
385   uint32_t tickstart;
386 
387   /* Check ADC handle */
388   if (hadc == NULL)
389   {
390     return HAL_ERROR;
391   }
392 
393   /* Check the parameters */
394   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
395   assert_param(IS_ADC_CLOCKPRESCALER(hadc->Init.ClockPrescaler));
396   assert_param(IS_ADC_RESOLUTION(hadc->Init.Resolution));
397   assert_param(IS_ADC_DATA_ALIGN(hadc->Init.DataAlign));
398   assert_param(IS_ADC_SCAN_MODE(hadc->Init.ScanConvMode));
399   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
400   assert_param(IS_ADC_EXTTRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
401   assert_param(IS_ADC_EXTTRIG(hadc->Init.ExternalTrigConv));
402   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests));
403   assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection));
404   assert_param(IS_ADC_OVERRUN(hadc->Init.Overrun));
405   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerAutoWait));
406   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerAutoPowerOff));
407   assert_param(IS_ADC_AUTONOMOUS_DPD(hadc->Init.LowPowerAutonomousDPD));
408   assert_param(IS_ADC_SAMPLE_TIME(hadc->Init.SamplingTimeCommon1));
409   assert_param(IS_ADC_SAMPLE_TIME(hadc->Init.SamplingTimeCommon2));
410   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.OversamplingMode));
411   if (hadc->Init.OversamplingMode == ENABLE)
412   {
413     assert_param(IS_ADC_OVERSAMPLING_RATIO(hadc->Init.Oversampling.Ratio));
414     assert_param(IS_ADC_RIGHT_BIT_SHIFT(hadc->Init.Oversampling.RightBitShift));
415     assert_param(IS_ADC_TRIGGERED_OVERSAMPLING_MODE(hadc->Init.Oversampling.TriggeredMode));
416   }
417   assert_param(IS_ADC_TRIGGER_FREQ(hadc->Init.TriggerFrequencyMode));
418 
419   if (hadc->Init.ScanConvMode != ADC_SCAN_DISABLE)
420   {
421     assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DiscontinuousConvMode));
422 
423     if (hadc->Init.ScanConvMode == ADC_SCAN_ENABLE)
424     {
425       assert_param(IS_ADC_REGULAR_NB_CONV(hadc->Init.NbrOfConversion));
426     }
427   }
428 
429   /* ADC group regular discontinuous mode can be enabled only if              */
430   /* continuous mode is disabled.                                             */
431   assert_param(!((hadc->Init.DiscontinuousConvMode == ENABLE) && (hadc->Init.ContinuousConvMode == ENABLE)));
432 
433   /* Actions performed only if ADC is coming from state reset:                */
434   /* - Initialization of ADC MSP                                              */
435   if (hadc->State == HAL_ADC_STATE_RESET)
436   {
437 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
438     /* Init the ADC Callback settings */
439     hadc->ConvCpltCallback              = HAL_ADC_ConvCpltCallback;                 /* Legacy weak callback */
440     hadc->ConvHalfCpltCallback          = HAL_ADC_ConvHalfCpltCallback;             /* Legacy weak callback */
441     hadc->LevelOutOfWindowCallback      = HAL_ADC_LevelOutOfWindowCallback;         /* Legacy weak callback */
442     hadc->ErrorCallback                 = HAL_ADC_ErrorCallback;                    /* Legacy weak callback */
443     hadc->LevelOutOfWindow2Callback     = HAL_ADCEx_LevelOutOfWindow2Callback;      /* Legacy weak callback */
444     hadc->LevelOutOfWindow3Callback     = HAL_ADCEx_LevelOutOfWindow3Callback;      /* Legacy weak callback */
445     hadc->EndOfSamplingCallback         = HAL_ADCEx_EndOfSamplingCallback;          /* Legacy weak callback */
446 
447     if (hadc->MspInitCallback == NULL)
448     {
449       hadc->MspInitCallback = HAL_ADC_MspInit; /* Legacy weak MspInit  */
450     }
451 
452     /* Init the low level hardware */
453     hadc->MspInitCallback(hadc);
454 #else
455     /* Init the low level hardware */
456     HAL_ADC_MspInit(hadc);
457 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
458 
459     /* Set ADC error code to none */
460     ADC_CLEAR_ERRORCODE(hadc);
461 
462     /* Initialize Lock */
463     hadc->Lock = HAL_UNLOCKED;
464   }
465 
466   if (LL_ADC_IsInternalRegulatorEnabled(hadc->Instance) == 0UL)
467   {
468     /* Clear flag ADC internal voltage regulator ready */
469     LL_ADC_ClearFlag_LDORDY(hadc->Instance);
470 
471     /* Enable ADC internal voltage regulator */
472     LL_ADC_EnableInternalRegulator(hadc->Instance);
473 
474     /* Get tick count */
475     tickstart = HAL_GetTick();
476 
477     /* Delay for ADC stabilization time */
478     while (LL_ADC_IsActiveFlag_LDORDY(hadc->Instance) == 0UL)
479     {
480       if ((HAL_GetTick() - tickstart) > ADC_LDO_RDY_TIMEOUT)
481       {
482         /* New check to avoid false timeout detection in case of preemption */
483         if (LL_ADC_IsActiveFlag_LDORDY(hadc->Instance) == 0UL)
484         {
485           /* Update ADC state machine to error */
486           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
487 
488           /* Set ADC error code to ADC peripheral internal error */
489           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
490 
491           return HAL_ERROR;
492         }
493       }
494     }
495   }
496 
497   /* Verification that ADC voltage regulator is correctly enabled, whether    */
498   /* or not ADC is coming from state reset (if any potential problem of       */
499   /* clocking, voltage regulator would not be enabled).                       */
500   if (LL_ADC_IsInternalRegulatorEnabled(hadc->Instance) == 0UL)
501   {
502     /* Update ADC state machine to error */
503     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
504 
505     /* Set ADC error code to ADC peripheral internal error */
506     SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
507 
508     tmp_hal_status = HAL_ERROR;
509   }
510 
511   /* Configuration of ADC parameters if previous preliminary actions are      */
512   /* correctly completed and if there is no conversion on going on regular    */
513   /* group (ADC may already be enabled at this point if HAL_ADC_Init() is     */
514   /* called to update a parameter on the fly).                                */
515   tmp_adc_reg_is_conversion_on_going = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
516 
517   if (((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
518       && (tmp_adc_reg_is_conversion_on_going == 0UL)
519      )
520   {
521     /* Set ADC state */
522     ADC_STATE_CLR_SET(hadc->State,
523                       HAL_ADC_STATE_REG_BUSY,
524                       HAL_ADC_STATE_BUSY_INTERNAL);
525 
526     /* Configuration of common ADC parameters                                 */
527 
528     /* Parameters update conditioned to ADC state:                            */
529     /* Parameters that can be updated only when ADC is disabled:              */
530     /*  - Internal voltage regulator (no parameter in HAL ADC init structure) */
531     /*  - Clock configuration                                                 */
532     /*  - ADC resolution                                                      */
533     /*  - Oversampling                                                        */
534     /*  - Trigger frequency mode                                              */
535     /* Note: If low power mode AutoPowerOff is enabled, ADC enable            */
536     /*       and disable phases are performed automatically by hardware       */
537     /*       (in this case, flag ADC_FLAG_RDY is not set).                    */
538     if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
539     {
540       /* Some parameters of this register are not reset, since they are set   */
541       /* by other functions and must be kept in case of usage of this         */
542       /* function on the fly (update of a parameter of ADC_InitTypeDef        */
543       /* without needing to reconfigure all other ADC groups/channels         */
544       /* parameters):                                                         */
545       /*   - internal measurement paths (VrefInt, ...)                        */
546       /*     (set into HAL_ADC_ConfigChannel() )                              */
547 
548       /* Configuration of ADC resolution                                      */
549       MODIFY_REG(hadc->Instance->CFGR1,
550                  ADC_CFGR1_RES,
551                  hadc->Init.Resolution);
552 
553       tmp_cfgr2 |= (hadc->Init.TriggerFrequencyMode);
554 
555       if (hadc->Init.OversamplingMode == ENABLE)
556       {
557         tmp_cfgr2 |= (ADC_CFGR2_OVSE |
558                       hadc->Init.Oversampling.Ratio         |
559                       hadc->Init.Oversampling.RightBitShift |
560                       hadc->Init.Oversampling.TriggeredMode
561                      );
562       }
563 
564       MODIFY_REG(hadc->Instance->CFGR2,
565                  ADC_CFGR2_LFTRIG |
566                  ADC_CFGR2_OVSE   |
567                  ADC_CFGR2_OVSR   |
568                  ADC_CFGR2_OVSS   |
569                  ADC_CFGR2_TOVS,
570                  tmp_cfgr2);
571 
572       MODIFY_REG(ADC4_COMMON->CCR,
573                  ADC_CCR_PRESC,
574                  hadc->Init.ClockPrescaler & ADC_CCR_PRESC);
575     }
576 
577     /* Configuration of ADC:                                                  */
578     /*  - discontinuous mode                                                  */
579     /*  - LowPowerAutoWait mode                                               */
580     /*  - LowPowerAutoPowerOff mode                                           */
581     /*  - continuous conversion mode                                          */
582     /*  - overrun                                                             */
583     /*  - external trigger to start conversion                                */
584     /*  - external trigger polarity                                           */
585     /*  - data alignment                                                      */
586     /*  - resolution                                                          */
587     /*  - scan direction                                                      */
588     /*  - DMA continuous request                                              */
589     tmp_cfgr1 |= (ADC_CFGR1_AUTOWAIT((uint32_t)hadc->Init.LowPowerAutoWait)      |
590                   ADC_CFGR1_CONTINUOUS((uint32_t)hadc->Init.ContinuousConvMode)  |
591                   ADC_CFGR1_OVERRUN(hadc->Init.Overrun)                          |
592                   hadc->Init.DataAlign                                           |
593                   ADC_SCAN_SEQ_MODE(hadc->Init.ScanConvMode)                     |
594                   ADC_CFGR1_DMACONTREQ((uint32_t)hadc->Init.DMAContinuousRequests));
595 
596     /* Update setting of discontinuous mode only if continuous mode is disabled */
597     if (hadc->Init.DiscontinuousConvMode == ENABLE)
598     {
599       if (hadc->Init.ContinuousConvMode == DISABLE)
600       {
601         /* Enable the selected ADC group regular discontinuous mode */
602         tmp_cfgr1 |= ADC_CFGR1_DISCEN;
603       }
604       else
605       {
606         /* ADC regular group discontinuous was intended to be enabled,        */
607         /* but ADC regular group modes continuous and sequencer discontinuous */
608         /* cannot be enabled simultaneously.                                  */
609 
610         /* Update ADC state machine to error */
611         SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
612 
613         /* Set ADC error code to ADC peripheral internal error */
614         SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
615       }
616     }
617 
618     /* Enable external trigger if trigger selection is different of software  */
619     /* start.                                                                 */
620     /* Note: This configuration keeps the hardware feature of parameter       */
621     /*       ExternalTrigConvEdge "trigger edge none" equivalent to           */
622     /*       software start.                                                  */
623     if (hadc->Init.ExternalTrigConv != ADC_SOFTWARE_START)
624     {
625       tmp_cfgr1 |= ((hadc->Init.ExternalTrigConv & ADC_CFGR1_EXTSEL) |
626                     hadc->Init.ExternalTrigConvEdge);
627     }
628 
629     /* Update ADC configuration register with previous settings */
630     MODIFY_REG(hadc->Instance->CFGR1,
631                ADC_CFGR1_DISCEN  |
632                ADC_CFGR1_CHSELRMOD |
633                ADC_CFGR1_WAIT    |
634                ADC_CFGR1_CONT    |
635                ADC_CFGR1_OVRMOD  |
636                ADC_CFGR1_EXTSEL  |
637                ADC_CFGR1_EXTEN   |
638                ADC_CFGR1_ALIGN   |
639                ADC_CFGR1_SCANDIR |
640                ADC_CFGR1_DMACFG,
641                tmp_cfgr1);
642 
643     MODIFY_REG(hadc->Instance->CFGR2,
644                ADC_CFGR2_LFTRIG |
645                ADC_CFGR2_OVSE   |
646                ADC_CFGR2_OVSR   |
647                ADC_CFGR2_OVSS   |
648                ADC_CFGR2_TOVS,
649                tmp_cfgr2);
650 
651     /* Low power mode configuration */
652     MODIFY_REG(hadc->Instance->PWRR,
653                ADC_PWRR_AUTOFF  |
654                ADC_PWRR_DPD,
655                ((uint32_t) hadc->Init.LowPowerAutoPowerOff) |
656                hadc->Init.LowPowerAutonomousDPD);
657 
658     /* Channel sampling time configuration */
659     LL_ADC_SetSamplingTimeCommonChannels(hadc->Instance, LL_ADC_SAMPLINGTIME_COMMON_1, hadc->Init.SamplingTimeCommon1);
660     LL_ADC_SetSamplingTimeCommonChannels(hadc->Instance, LL_ADC_SAMPLINGTIME_COMMON_2, hadc->Init.SamplingTimeCommon2);
661 
662     /* Configuration of regular group sequencer:                              */
663     /* - if scan mode is disabled, regular channels sequence length is set to */
664     /*   0x00: 1 channel converted (channel on regular rank 1)                */
665     /*   Parameter "NbrOfConversion" is discarded.                            */
666     /*   Note: Scan mode is not present by hardware on this device, but       */
667     /*   emulated by software for alignment over all STM32 devices.           */
668     /* - if scan mode is enabled, regular channels sequence length is set to  */
669     /*   parameter "NbrOfConversion".                                         */
670     /*   Channels must be configured into each rank using function            */
671     /*   "HAL_ADC_ConfigChannel()".                                           */
672     if (hadc->Init.ScanConvMode == ADC_SCAN_DISABLE)
673     {
674       /* Set sequencer scan length by clearing ranks above rank 1             */
675       /* and do not modify rank 1 value.                                      */
676       SET_BIT(hadc->Instance->CHSELR,
677               ADC_CHSELR_SQ2_TO_SQ8);
678     }
679     else if (hadc->Init.ScanConvMode == ADC_SCAN_ENABLE)
680     {
681       /* Set ADC group regular sequencer:                                   */
682       /*  - Set ADC group regular sequencer to value memorized              */
683       /*    in HAL ADC handle                                               */
684       /*    Note: This value maybe be initialized at a unknown value,       */
685       /*          therefore after the first call of "HAL_ADC_Init()",       */
686       /*          each rank corresponding to parameter "NbrOfConversion"    */
687       /*          must be set using "HAL_ADC_ConfigChannel()".              */
688       /*  - Set sequencer scan length by clearing ranks above maximum rank  */
689       /*    and do not modify other ranks value.                            */
690       MODIFY_REG(hadc->Instance->CHSELR,
691                  ADC_CHSELR_SQ_ALL,
692                  (ADC_CHSELR_SQ2_TO_SQ8 << (((hadc->Init.NbrOfConversion - 1UL) * ADC_REGULAR_RANK_2) & 0x1FUL))
693                  | (hadc->ADCGroupRegularSequencerRanks)
694                 );
695     }
696     else
697     {
698       /* Nothing to do */
699     }
700 
701     /* Check back that ADC registers have effectively been configured to      */
702     /* ensure of no potential problem of ADC core peripheral clocking.        */
703     /* Check through register CFGR1 (excluding analog watchdog configuration: */
704     /* set into separate dedicated function, and bits of ADC resolution set   */
705     /* out of temporary variable 'tmp_cfgr1').                                 */
706     if ((hadc->Instance->CFGR1 & ~(ADC_CFGR1_AWD1CH | ADC_CFGR1_AWD1EN | ADC_CFGR1_AWD1SGL | ADC_CFGR1_RES))
707         == tmp_cfgr1)
708     {
709       /* Set ADC error code to none */
710       ADC_CLEAR_ERRORCODE(hadc);
711 
712       /* Set the ADC state */
713       ADC_STATE_CLR_SET(hadc->State,
714                         HAL_ADC_STATE_BUSY_INTERNAL,
715                         HAL_ADC_STATE_READY);
716     }
717     else
718     {
719       /* Update ADC state machine to error */
720       ADC_STATE_CLR_SET(hadc->State,
721                         HAL_ADC_STATE_BUSY_INTERNAL,
722                         HAL_ADC_STATE_ERROR_INTERNAL);
723 
724       /* Set ADC error code to ADC peripheral internal error */
725       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
726 
727       tmp_hal_status = HAL_ERROR;
728     }
729 
730   }
731   else
732   {
733     /* Update ADC state machine to error */
734     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
735 
736     tmp_hal_status = HAL_ERROR;
737   }
738 
739   return tmp_hal_status;
740 }
741 
742 /**
743   * @brief  Deinitialize the ADC peripheral registers to their default reset
744   *         values, with deinitialization of the ADC MSP.
745   * @note   For devices with several ADCs: reset of ADC common registers is done
746   *         only if all ADCs sharing the same common group are disabled.
747   *         (function "HAL_ADC_MspDeInit()" is also called under the same conditions:
748   *         all ADC instances use the same core clock at RCC level, disabling
749   *         the core clock reset all ADC instances).
750   *         If this is not the case, reset of these common parameters reset is
751   *         bypassed without error reporting: it can be the intended behavior in
752   *         case of reset of a single ADC while the other ADCs sharing the same
753   *         common group is still running.
754   * @note   By default, HAL_ADC_DeInit() set ADC in mode deep power-down:
755   *         this saves more power by reducing leakage currents
756   *         and is particularly interesting before entering MCU low-power modes.
757   * @param hadc ADC handle
758   * @retval HAL status
759   */
HAL_ADC_DeInit(ADC_HandleTypeDef * hadc)760 HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc)
761 {
762   HAL_StatusTypeDef tmp_hal_status;
763 
764   /* Check ADC handle */
765   if (hadc == NULL)
766   {
767     return HAL_ERROR;
768   }
769 
770   /* Check the parameters */
771   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
772 
773   /* Set ADC state */
774   SET_BIT(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL);
775 
776   /* Stop potential conversion on going, on regular group */
777   tmp_hal_status = ADC_ConversionStop(hadc);
778 
779   /* Disable ADC peripheral if conversions are effectively stopped */
780   if (tmp_hal_status == HAL_OK)
781   {
782     /* Disable the ADC peripheral */
783     tmp_hal_status = ADC_Disable(hadc);
784 
785     /* Check if ADC is effectively disabled */
786     if (tmp_hal_status == HAL_OK)
787     {
788       /* Change ADC state */
789       hadc->State = HAL_ADC_STATE_READY;
790     }
791 
792     /* Disable ADC internal voltage regulator */
793     LL_ADC_DisableInternalRegulator(hadc->Instance);
794   }
795 
796   /* Note: HAL ADC deInit is done independently of ADC conversion stop        */
797   /*       and disable return status. In case of status fail, attempt to      */
798   /*       perform deinitialization anyway and it is up user code in          */
799   /*       in HAL_ADC_MspDeInit() to reset the ADC peripheral using           */
800   /*       system RCC hard reset.                                             */
801 
802   /* ========== Reset ADC registers ========== */
803   /* Reset register IER */
804   __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_AWD3  | ADC_IT_AWD2 |
805                               ADC_IT_AWD1  | ADC_IT_OVR  |
806                               ADC_IT_EOS   | ADC_IT_EOC  |
807                               ADC_IT_EOSMP | ADC_IT_RDY));
808 
809   /* Reset register ISR */
810   __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD3  | ADC_FLAG_AWD2 |
811                               ADC_FLAG_AWD1  | ADC_FLAG_OVR  |
812                               ADC_FLAG_EOS   | ADC_FLAG_EOC  |
813                               ADC_FLAG_EOSMP | ADC_FLAG_RDY));
814 
815   /* Reset register CR */
816   /* Bits ADC_CR_ADCAL, ADC_CR_ADSTP, ADC_CR_ADSTART are in access mode     */
817   /* "read-set": no direct reset applicable.                                */
818 
819   /* Reset register CFGR1 */
820   hadc->Instance->CFGR1 &= ~(ADC_CFGR1_AWD1CH   | ADC_CFGR1_AWD1EN  | ADC_CFGR1_AWD1SGL | ADC_CFGR1_DISCEN |
821                              ADC_CFGR1_CHSELRMOD | ADC_CFGR1_WAIT   | ADC_CFGR1_CONT   | ADC_CFGR1_OVRMOD |
822                              ADC_CFGR1_EXTEN   | ADC_CFGR1_EXTSEL | ADC_CFGR1_ALIGN  | ADC_CFGR1_RES    |
823                              ADC_CFGR1_SCANDIR | ADC_CFGR1_DMACFG | ADC_CFGR1_DMAEN);
824 
825   /* Reset register SMPR */
826   hadc->Instance->SMPR &= ~ADC_SMPR_SMP1;
827 
828   /* Reset registers AWDxTR */
829   hadc->Instance->AWD1TR &= ~(ADC_AWD1TR_HT1 | ADC_AWD1TR_LT1);
830   hadc->Instance->AWD2TR &= ~(ADC_AWD2TR_HT2 | ADC_AWD2TR_LT2);
831   hadc->Instance->AWD3TR &= ~(ADC_AWD3TR_HT3 | ADC_AWD3TR_LT3);
832 
833   /* Reset register CHSELR */
834   hadc->Instance->CHSELR &= ~(ADC_CHSELR_SQ_ALL);
835 
836   /* Reset register DR */
837   /* bits in access mode read only, no direct reset applicable */
838 
839   /* Reset register PWRR */
840   /* Note: Bit of deep power down mode already updated previously */
841   hadc->Instance->PWRR &= ~(ADC_PWRR_AUTOFF);
842 
843   /* Reset register CCR */
844   ADC4_COMMON->CCR &= ~(ADC_CCR_TSEN | ADC_CCR_VREFEN | ADC_CCR_PRESC);
845 
846   /* ========== Hard reset ADC peripheral ========== */
847   /* Performs a global reset of the entire ADC peripheral: ADC state is     */
848   /* forced to a similar state after device power-on.                       */
849   /* Note: A possible implementation is to add RCC bus reset of ADC         */
850   /* (for example, using macro                                              */
851   /*  __HAL_RCC_ADC..._FORCE_RESET()/..._RELEASE_RESET()/..._CLK_DISABLE()) */
852   /* in function "void HAL_ADC_MspDeInit(ADC_HandleTypeDef *hadc)":         */
853 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
854   if (hadc->MspDeInitCallback == NULL)
855   {
856     hadc->MspDeInitCallback = HAL_ADC_MspDeInit; /* Legacy weak MspDeInit  */
857   }
858 
859   /* DeInit the low level hardware */
860   hadc->MspDeInitCallback(hadc);
861 #else
862   /* DeInit the low level hardware */
863   HAL_ADC_MspDeInit(hadc);
864 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
865 
866   /* Reset HAL ADC handle variable */
867   hadc->ADCGroupRegularSequencerRanks = 0x00000000UL;
868 
869   /* Set ADC error code to none */
870   ADC_CLEAR_ERRORCODE(hadc);
871 
872   /* Set ADC state */
873   hadc->State = HAL_ADC_STATE_RESET;
874 
875   __HAL_UNLOCK(hadc);
876 
877   return tmp_hal_status;
878 }
879 
880 /**
881   * @brief  Initialize the ADC MSP.
882   * @param hadc ADC handle
883   * @retval None
884   */
HAL_ADC_MspInit(ADC_HandleTypeDef * hadc)885 __weak void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc)
886 {
887   /* Prevent unused argument(s) compilation warning */
888   UNUSED(hadc);
889 
890   /* NOTE : This function should not be modified. When the callback is needed,
891             function HAL_ADC_MspInit must be implemented in the user file.
892    */
893 }
894 
895 /**
896   * @brief  DeInitialize the ADC MSP.
897   * @param hadc ADC handle
898   * @note   All ADC instances use the same core clock at RCC level, disabling
899   *         the core clock reset all ADC instances).
900   * @retval None
901   */
HAL_ADC_MspDeInit(ADC_HandleTypeDef * hadc)902 __weak void HAL_ADC_MspDeInit(ADC_HandleTypeDef *hadc)
903 {
904   /* Prevent unused argument(s) compilation warning */
905   UNUSED(hadc);
906 
907   /* NOTE : This function should not be modified. When the callback is needed,
908             function HAL_ADC_MspDeInit must be implemented in the user file.
909    */
910 }
911 
912 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
913 /**
914   * @brief  Register a User ADC Callback
915   *         To be used instead of the weak predefined callback
916   * @param  hadc Pointer to a ADC_HandleTypeDef structure that contains
917   *                the configuration information for the specified ADC.
918   * @param  CallbackID ID of the callback to be registered
919   *         This parameter can be one of the following values:
920   *          @arg @ref HAL_ADC_CONVERSION_COMPLETE_CB_ID      ADC conversion complete callback ID
921   *          @arg @ref HAL_ADC_CONVERSION_HALF_CB_ID          ADC conversion DMA half-transfer callback ID
922   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID    ADC analog watchdog 1 callback ID
923   *          @arg @ref HAL_ADC_ERROR_CB_ID                    ADC error callback ID
924   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID    ADC analog watchdog 2 callback ID
925   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID    ADC analog watchdog 3 callback ID
926   *          @arg @ref HAL_ADC_END_OF_SAMPLING_CB_ID          ADC end of sampling callback ID
927   *          @arg @ref HAL_ADC_MSPINIT_CB_ID                  ADC Msp Init callback ID
928   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID                ADC Msp DeInit callback ID
929   *          @arg @ref HAL_ADC_MSPINIT_CB_ID MspInit callback ID
930   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID MspDeInit callback ID
931   * @param  pCallback pointer to the Callback function
932   * @retval HAL status
933   */
HAL_ADC_RegisterCallback(ADC_HandleTypeDef * hadc,HAL_ADC_CallbackIDTypeDef CallbackID,pADC_CallbackTypeDef pCallback)934 HAL_StatusTypeDef HAL_ADC_RegisterCallback(ADC_HandleTypeDef *hadc, HAL_ADC_CallbackIDTypeDef CallbackID,
935                                            pADC_CallbackTypeDef pCallback)
936 {
937   HAL_StatusTypeDef status = HAL_OK;
938 
939   if (pCallback == NULL)
940   {
941     /* Update the error code */
942     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
943 
944     return HAL_ERROR;
945   }
946 
947   if ((hadc->State & HAL_ADC_STATE_READY) != 0UL)
948   {
949     switch (CallbackID)
950     {
951       case HAL_ADC_CONVERSION_COMPLETE_CB_ID :
952         hadc->ConvCpltCallback = pCallback;
953         break;
954 
955       case HAL_ADC_CONVERSION_HALF_CB_ID :
956         hadc->ConvHalfCpltCallback = pCallback;
957         break;
958 
959       case HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID :
960         hadc->LevelOutOfWindowCallback = pCallback;
961         break;
962 
963       case HAL_ADC_ERROR_CB_ID :
964         hadc->ErrorCallback = pCallback;
965         break;
966 
967       case HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID :
968         hadc->LevelOutOfWindow2Callback = pCallback;
969         break;
970 
971       case HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID :
972         hadc->LevelOutOfWindow3Callback = pCallback;
973         break;
974 
975       case HAL_ADC_END_OF_SAMPLING_CB_ID :
976         hadc->EndOfSamplingCallback = pCallback;
977         break;
978 
979       case HAL_ADC_MSPINIT_CB_ID :
980         hadc->MspInitCallback = pCallback;
981         break;
982 
983       case HAL_ADC_MSPDEINIT_CB_ID :
984         hadc->MspDeInitCallback = pCallback;
985         break;
986 
987       default :
988         /* Update the error code */
989         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
990 
991         /* Return error status */
992         status = HAL_ERROR;
993         break;
994     }
995   }
996   else if (HAL_ADC_STATE_RESET == hadc->State)
997   {
998     switch (CallbackID)
999     {
1000       case HAL_ADC_MSPINIT_CB_ID :
1001         hadc->MspInitCallback = pCallback;
1002         break;
1003 
1004       case HAL_ADC_MSPDEINIT_CB_ID :
1005         hadc->MspDeInitCallback = pCallback;
1006         break;
1007 
1008       default :
1009         /* Update the error code */
1010         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1011 
1012         /* Return error status */
1013         status = HAL_ERROR;
1014         break;
1015     }
1016   }
1017   else
1018   {
1019     /* Update the error code */
1020     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1021 
1022     /* Return error status */
1023     status =  HAL_ERROR;
1024   }
1025 
1026   return status;
1027 }
1028 
1029 /**
1030   * @brief  Unregister a ADC Callback
1031   *         ADC callback is redirected to the weak predefined callback
1032   * @param  hadc Pointer to a ADC_HandleTypeDef structure that contains
1033   *                the configuration information for the specified ADC.
1034   * @param  CallbackID ID of the callback to be unregistered
1035   *         This parameter can be one of the following values:
1036   *          @arg @ref HAL_ADC_CONVERSION_COMPLETE_CB_ID      ADC conversion complete callback ID
1037   *          @arg @ref HAL_ADC_CONVERSION_HALF_CB_ID          ADC conversion DMA half-transfer callback ID
1038   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID    ADC analog watchdog 1 callback ID
1039   *          @arg @ref HAL_ADC_ERROR_CB_ID                    ADC error callback ID
1040   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID    ADC analog watchdog 2 callback ID
1041   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID    ADC analog watchdog 3 callback ID
1042   *          @arg @ref HAL_ADC_END_OF_SAMPLING_CB_ID          ADC end of sampling callback ID
1043   *          @arg @ref HAL_ADC_MSPINIT_CB_ID                  ADC Msp Init callback ID
1044   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID                ADC Msp DeInit callback ID
1045   *          @arg @ref HAL_ADC_MSPINIT_CB_ID MspInit callback ID
1046   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID MspDeInit callback ID
1047   * @retval HAL status
1048   */
HAL_ADC_UnRegisterCallback(ADC_HandleTypeDef * hadc,HAL_ADC_CallbackIDTypeDef CallbackID)1049 HAL_StatusTypeDef HAL_ADC_UnRegisterCallback(ADC_HandleTypeDef *hadc, HAL_ADC_CallbackIDTypeDef CallbackID)
1050 {
1051   HAL_StatusTypeDef status = HAL_OK;
1052 
1053   if ((hadc->State & HAL_ADC_STATE_READY) != 0UL)
1054   {
1055     switch (CallbackID)
1056     {
1057       case HAL_ADC_CONVERSION_COMPLETE_CB_ID :
1058         hadc->ConvCpltCallback = HAL_ADC_ConvCpltCallback;
1059         break;
1060 
1061       case HAL_ADC_CONVERSION_HALF_CB_ID :
1062         hadc->ConvHalfCpltCallback = HAL_ADC_ConvHalfCpltCallback;
1063         break;
1064 
1065       case HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID :
1066         hadc->LevelOutOfWindowCallback = HAL_ADC_LevelOutOfWindowCallback;
1067         break;
1068 
1069       case HAL_ADC_ERROR_CB_ID :
1070         hadc->ErrorCallback = HAL_ADC_ErrorCallback;
1071         break;
1072 
1073       case HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID :
1074         hadc->LevelOutOfWindow2Callback = HAL_ADCEx_LevelOutOfWindow2Callback;
1075         break;
1076 
1077       case HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID :
1078         hadc->LevelOutOfWindow3Callback = HAL_ADCEx_LevelOutOfWindow3Callback;
1079         break;
1080 
1081       case HAL_ADC_END_OF_SAMPLING_CB_ID :
1082         hadc->EndOfSamplingCallback = HAL_ADCEx_EndOfSamplingCallback;
1083         break;
1084 
1085       case HAL_ADC_MSPINIT_CB_ID :
1086         hadc->MspInitCallback = HAL_ADC_MspInit; /* Legacy weak MspInit              */
1087         break;
1088 
1089       case HAL_ADC_MSPDEINIT_CB_ID :
1090         hadc->MspDeInitCallback = HAL_ADC_MspDeInit; /* Legacy weak MspDeInit            */
1091         break;
1092 
1093       default :
1094         /* Update the error code */
1095         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1096 
1097         /* Return error status */
1098         status =  HAL_ERROR;
1099         break;
1100     }
1101   }
1102   else if (HAL_ADC_STATE_RESET == hadc->State)
1103   {
1104     switch (CallbackID)
1105     {
1106       case HAL_ADC_MSPINIT_CB_ID :
1107         hadc->MspInitCallback = HAL_ADC_MspInit;                   /* Legacy weak MspInit              */
1108         break;
1109 
1110       case HAL_ADC_MSPDEINIT_CB_ID :
1111         hadc->MspDeInitCallback = HAL_ADC_MspDeInit;               /* Legacy weak MspDeInit            */
1112         break;
1113 
1114       default :
1115         /* Update the error code */
1116         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1117 
1118         /* Return error status */
1119         status =  HAL_ERROR;
1120         break;
1121     }
1122   }
1123   else
1124   {
1125     /* Update the error code */
1126     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1127 
1128     /* Return error status */
1129     status =  HAL_ERROR;
1130   }
1131 
1132   return status;
1133 }
1134 
1135 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1136 
1137 /**
1138   * @}
1139   */
1140 
1141 /** @defgroup ADC_Exported_Functions_Group2 ADC Input and Output operation functions
1142   * @brief    ADC IO operation functions
1143   *
1144 @verbatim
1145  ===============================================================================
1146                       ##### IO operation functions #####
1147  ===============================================================================
1148     [..]  This section provides functions allowing to:
1149       (+) Start conversion of regular group.
1150       (+) Stop conversion of regular group.
1151       (+) Poll for conversion complete on regular group.
1152       (+) Poll for conversion event.
1153       (+) Get result of regular channel conversion.
1154       (+) Start conversion of regular group and enable interruptions.
1155       (+) Stop conversion of regular group and disable interruptions.
1156       (+) Handle ADC interrupt request
1157       (+) Start conversion of regular group and enable DMA transfer.
1158       (+) Stop conversion of regular group and disable ADC DMA transfer.
1159 @endverbatim
1160   * @{
1161   */
1162 
1163 /**
1164   * @brief  Enable ADC, start conversion of regular group.
1165   * @note   Interruptions enabled in this function: None.
1166   * @param hadc ADC handle
1167   * @retval HAL status
1168   */
HAL_ADC_Start(ADC_HandleTypeDef * hadc)1169 HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef *hadc)
1170 {
1171   HAL_StatusTypeDef tmp_hal_status;
1172 
1173   /* Check the parameters */
1174   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1175 
1176   /* Perform ADC enable and conversion start if no conversion is on going */
1177   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1178   {
1179     __HAL_LOCK(hadc);
1180 
1181     /* Enable the ADC peripheral */
1182     tmp_hal_status = ADC_Enable(hadc);
1183 
1184     /* Start conversion if ADC is effectively enabled */
1185     if (tmp_hal_status == HAL_OK)
1186     {
1187       /* Set ADC state                                                        */
1188       /* - Clear state bitfield related to regular group conversion results   */
1189       /* - Set state bitfield related to regular operation                    */
1190       ADC_STATE_CLR_SET(hadc->State,
1191                         HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
1192                         HAL_ADC_STATE_REG_BUSY);
1193 
1194       /* Set ADC error code */
1195       /* Reset all ADC error code fields */
1196       ADC_CLEAR_ERRORCODE(hadc);
1197 
1198       /* Clear ADC group regular conversion flag and overrun flag               */
1199       /* (To ensure of no unknown state from potential previous ADC operations) */
1200       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
1201 
1202       /* Process unlocked */
1203       /* Unlock before starting ADC conversions: in case of potential         */
1204       /* interruption, to let the process to ADC IRQ Handler.                 */
1205       __HAL_UNLOCK(hadc);
1206 
1207       /* Enable conversion of regular group.                                  */
1208       /* If software start has been selected, conversion starts immediately.  */
1209       /* If external trigger has been selected, conversion will start at next */
1210       /* trigger event.                                                       */
1211       /* Start ADC group regular conversion */
1212       LL_ADC_REG_StartConversion(hadc->Instance);
1213     }
1214     else
1215     {
1216       __HAL_UNLOCK(hadc);
1217     }
1218   }
1219   else
1220   {
1221     tmp_hal_status = HAL_BUSY;
1222   }
1223 
1224   return tmp_hal_status;
1225 }
1226 
1227 /**
1228   * @brief  Stop ADC conversion of regular group (and injected channels in
1229   *         case of auto_injection mode), disable ADC peripheral.
1230   * @note:  ADC peripheral disable is forcing stop of potential
1231   *         conversion on injected group. If injected group is under use, it
1232   *         should be preliminarily stopped using HAL_ADCEx_InjectedStop function.
1233   * @param hadc ADC handle
1234   * @retval HAL status.
1235   */
HAL_ADC_Stop(ADC_HandleTypeDef * hadc)1236 HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef *hadc)
1237 {
1238   HAL_StatusTypeDef tmp_hal_status;
1239 
1240   /* Check the parameters */
1241   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1242 
1243   __HAL_LOCK(hadc);
1244 
1245   /* 1. Stop potential conversion on going, on ADC group regular */
1246   tmp_hal_status = ADC_ConversionStop(hadc);
1247 
1248   /* Disable ADC peripheral if conversions are effectively stopped */
1249   if (tmp_hal_status == HAL_OK)
1250   {
1251     /* 2. Disable the ADC peripheral */
1252     tmp_hal_status = ADC_Disable(hadc);
1253 
1254     /* Check if ADC is effectively disabled */
1255     if (tmp_hal_status == HAL_OK)
1256     {
1257       /* Set ADC state */
1258       ADC_STATE_CLR_SET(hadc->State,
1259                         HAL_ADC_STATE_REG_BUSY,
1260                         HAL_ADC_STATE_READY);
1261     }
1262   }
1263 
1264   __HAL_UNLOCK(hadc);
1265 
1266   return tmp_hal_status;
1267 }
1268 
1269 /**
1270   * @brief  Wait for regular group conversion to be completed.
1271   * @note   ADC conversion flags EOS (end of sequence) and EOC (end of
1272   *         conversion) are cleared by this function, with an exception:
1273   *         if low power feature "LowPowerAutoWait" is enabled, flags are
1274   *         not cleared to not interfere with this feature until data register
1275   *         is read using function HAL_ADC_GetValue().
1276   * @note   This function cannot be used in a particular setup: ADC configured
1277   *         in DMA mode and polling for end of each conversion (ADC init
1278   *         parameter "EOCSelection" set to ADC_EOC_SINGLE_CONV).
1279   *         In this case, DMA resets the flag EOC and polling cannot be
1280   *         performed on each conversion. Nevertheless, polling can still
1281   *         be performed on the complete sequence (ADC init
1282   *         parameter "EOCSelection" set to ADC_EOC_SEQ_CONV).
1283   * @param hadc ADC handle
1284   * @param Timeout Timeout value in millisecond.
1285   * @retval HAL status
1286   */
HAL_ADC_PollForConversion(ADC_HandleTypeDef * hadc,uint32_t Timeout)1287 HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef *hadc, uint32_t Timeout)
1288 {
1289   uint32_t tickstart;
1290   uint32_t tmp_flag_end;
1291 
1292   /* Check the parameters */
1293   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1294 
1295   /* If end of conversion selected to end of sequence conversions */
1296   if (hadc->Init.EOCSelection == ADC_EOC_SEQ_CONV)
1297   {
1298     tmp_flag_end = ADC_FLAG_EOS;
1299   }
1300   /* If end of conversion selected to end of unitary conversion */
1301   else /* ADC_EOC_SINGLE_CONV */
1302   {
1303     /* Verification that ADC configuration is compliant with polling for      */
1304     /* each conversion:                                                       */
1305     /* Particular case is ADC configured in DMA mode and ADC sequencer with   */
1306     /* several ranks and polling for end of each conversion.                  */
1307     /* For code simplicity sake, this particular case is generalized to       */
1308     /* ADC configured in DMA mode and and polling for end of each conversion. */
1309     if ((hadc->Instance->CFGR1 & ADC_CFGR1_DMAEN) != 0UL)
1310     {
1311       /* Update ADC state machine to error */
1312       SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1313 
1314       return HAL_ERROR;
1315     }
1316     else
1317     {
1318       tmp_flag_end = (ADC_FLAG_EOC);
1319     }
1320   }
1321 
1322   /* Get tick count */
1323   tickstart = HAL_GetTick();
1324 
1325   /* Wait until End of unitary conversion or sequence conversions flag is raised */
1326   while ((hadc->Instance->ISR & tmp_flag_end) == 0UL)
1327   {
1328     /* Check if timeout is disabled (set to infinite wait) */
1329     if (Timeout != HAL_MAX_DELAY)
1330     {
1331       if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
1332       {
1333         /* New check to avoid false timeout detection in case of preemption */
1334         if ((hadc->Instance->ISR & tmp_flag_end) == 0UL)
1335         {
1336           /* Update ADC state machine to timeout */
1337           SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
1338 
1339           __HAL_UNLOCK(hadc);
1340 
1341           return HAL_TIMEOUT;
1342         }
1343       }
1344     }
1345   }
1346 
1347   /* Update ADC state machine */
1348   SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
1349 
1350   /* Determine whether any further conversion upcoming on group regular       */
1351   /* by external trigger, continuous mode or scan sequence on going.          */
1352   if ((LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
1353       && (hadc->Init.ContinuousConvMode == DISABLE)
1354      )
1355   {
1356     /* Check whether end of sequence is reached */
1357     if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS))
1358     {
1359       /* Allowed to modify bits ADC_IT_EOC/ADC_IT_EOS only if bit             */
1360       /* ADSTART==0 (no conversion on going)                                  */
1361       if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1362       {
1363         /* Disable ADC end of single conversion interrupt on group regular */
1364         /* Note: Overrun interrupt was enabled with EOC interrupt in          */
1365         /* HAL_Start_IT(), but is not disabled here because can be used       */
1366         /* by overrun IRQ process below.                                      */
1367         __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_EOS);
1368 
1369         /* Set ADC state */
1370         ADC_STATE_CLR_SET(hadc->State,
1371                           HAL_ADC_STATE_REG_BUSY,
1372                           HAL_ADC_STATE_READY);
1373       }
1374       else
1375       {
1376         /* Change ADC state to error state */
1377         SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1378 
1379         /* Set ADC error code to ADC peripheral internal error */
1380         SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
1381       }
1382     }
1383   }
1384 
1385   /* Clear end of conversion flag of regular group if low power feature       */
1386   /* "LowPowerAutoWait " is disabled, to not interfere with this feature      */
1387   /* until data register is read using function HAL_ADC_GetValue().           */
1388   if (hadc->Init.LowPowerAutoWait == DISABLE)
1389   {
1390     /* Clear regular group conversion flag */
1391     __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS));
1392   }
1393 
1394   /* Return function status */
1395   return HAL_OK;
1396 }
1397 
1398 /**
1399   * @brief  Poll for ADC event.
1400   * @param hadc ADC handle
1401   * @param EventType the ADC event type.
1402   *          This parameter can be one of the following values:
1403   *            @arg @ref ADC_EOSMP_EVENT  ADC End of Sampling event
1404   *            @arg @ref ADC_AWD1_EVENT   ADC Analog watchdog 1 event (main analog watchdog, present on
1405   *                                       all STM32 series)
1406   *            @arg @ref ADC_AWD2_EVENT   ADC Analog watchdog 2 event (additional analog watchdog, not present on
1407   *                                       all STM32 series)
1408   *            @arg @ref ADC_AWD3_EVENT   ADC Analog watchdog 3 event (additional analog watchdog, not present on
1409   *                                       all STM32 series)
1410   *            @arg @ref ADC_OVR_EVENT    ADC Overrun event
1411   * @param Timeout Timeout value in millisecond.
1412   * @note   The relevant flag is cleared if found to be set, except for ADC_FLAG_OVR.
1413   *         Indeed, the latter is reset only if hadc->Init.Overrun field is set
1414   *         to ADC_OVR_DATA_OVERWRITTEN. Otherwise, data register may be potentially overwritten
1415   *         by a new converted data as soon as OVR is cleared.
1416   *         To reset OVR flag once the preserved data is retrieved, the user can resort
1417   *         to macro __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1418   * @retval HAL status
1419   */
HAL_ADC_PollForEvent(ADC_HandleTypeDef * hadc,uint32_t EventType,uint32_t Timeout)1420 HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef *hadc, uint32_t EventType, uint32_t Timeout)
1421 {
1422   uint32_t tickstart;
1423 
1424   /* Check the parameters */
1425   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1426   assert_param(IS_ADC_EVENT_TYPE(EventType));
1427 
1428   /* Get tick count */
1429   tickstart = HAL_GetTick();
1430 
1431   /* Check selected event flag */
1432   while (__HAL_ADC_GET_FLAG(hadc, EventType) == 0UL)
1433   {
1434     /* Check if timeout is disabled (set to infinite wait) */
1435     if (Timeout != HAL_MAX_DELAY)
1436     {
1437       if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
1438       {
1439         /* New check to avoid false timeout detection in case of preemption */
1440         if (__HAL_ADC_GET_FLAG(hadc, EventType) == 0UL)
1441         {
1442           /* Update ADC state machine to timeout */
1443           SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
1444 
1445           __HAL_UNLOCK(hadc);
1446 
1447           return HAL_TIMEOUT;
1448         }
1449       }
1450     }
1451   }
1452 
1453   switch (EventType)
1454   {
1455     /* End Of Sampling event */
1456     case ADC_EOSMP_EVENT:
1457       /* Set ADC state */
1458       SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOSMP);
1459 
1460       /* Clear the End Of Sampling flag */
1461       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP);
1462 
1463       break;
1464 
1465     /* Analog watchdog (level out of window) event */
1466     /* Note: In case of several analog watchdog enabled, if needed to know      */
1467     /* which one triggered and on which ADCx, test ADC state of analog watchdog */
1468     /* flags HAL_ADC_STATE_AWD1/2/3 using function "HAL_ADC_GetState()".        */
1469     /* For example:                                                             */
1470     /*  " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD1) != 0UL) "          */
1471     /*  " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD2) != 0UL) "          */
1472     /*  " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD3) != 0UL) "          */
1473 
1474     /* Check analog watchdog 1 flag */
1475     case ADC_AWD_EVENT:
1476       /* Set ADC state */
1477       SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
1478 
1479       /* Clear ADC analog watchdog flag */
1480       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD1);
1481 
1482       break;
1483 
1484     /* Check analog watchdog 2 flag */
1485     case ADC_AWD2_EVENT:
1486       /* Set ADC state */
1487       SET_BIT(hadc->State, HAL_ADC_STATE_AWD2);
1488 
1489       /* Clear ADC analog watchdog flag */
1490       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD2);
1491 
1492       break;
1493 
1494     /* Check analog watchdog 3 flag */
1495     case ADC_AWD3_EVENT:
1496       /* Set ADC state */
1497       SET_BIT(hadc->State, HAL_ADC_STATE_AWD3);
1498 
1499       /* Clear ADC analog watchdog flag */
1500       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD3);
1501 
1502       break;
1503 
1504     /* Overrun event */
1505     default: /* Case ADC_OVR_EVENT */
1506       /* If overrun is set to overwrite previous data, overrun event is not     */
1507       /* considered as an error.                                                */
1508       /* (cf ref manual "Managing conversions without using the DMA and without */
1509       /* overrun ")                                                             */
1510       if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
1511       {
1512         /* Set ADC state */
1513         SET_BIT(hadc->State, HAL_ADC_STATE_REG_OVR);
1514 
1515         /* Set ADC error code to overrun */
1516         SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_OVR);
1517       }
1518       else
1519       {
1520         /* Clear ADC Overrun flag only if Overrun is set to ADC_OVR_DATA_OVERWRITTEN
1521            otherwise, data register is potentially overwritten by new converted data as soon
1522            as OVR is cleared. */
1523         __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1524       }
1525       break;
1526   }
1527 
1528   /* Return function status */
1529   return HAL_OK;
1530 }
1531 
1532 /**
1533   * @brief  Enable ADC, start conversion of regular group with interruption.
1534   * @note   Interruptions enabled in this function according to initialization
1535   *         setting : EOC (end of conversion), EOS (end of sequence),
1536   *         OVR overrun.
1537   *         Each of these interruptions has its dedicated callback function.
1538   * @note   To guarantee a proper reset of all interruptions once all the needed
1539   *         conversions are obtained, HAL_ADC_Stop_IT() must be called to ensure
1540   *         a correct stop of the IT-based conversions.
1541   * @note   By default, HAL_ADC_Start_IT() does not enable the End Of Sampling
1542   *         interruption. If required (e.g. in case of oversampling with trigger
1543   *         mode), the user must:
1544   *          1. first clear the EOSMP flag if set with macro __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP)
1545   *          2. then enable the EOSMP interrupt with macro __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOSMP)
1546   *          before calling HAL_ADC_Start_IT().
1547   * @param hadc ADC handle
1548   * @retval HAL status
1549   */
HAL_ADC_Start_IT(ADC_HandleTypeDef * hadc)1550 HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef *hadc)
1551 {
1552   HAL_StatusTypeDef tmp_hal_status;
1553 
1554   /* Check the parameters */
1555   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1556 
1557   /* Perform ADC enable and conversion start if no conversion is on going */
1558   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1559   {
1560     __HAL_LOCK(hadc);
1561 
1562     /* Enable the ADC peripheral */
1563     tmp_hal_status = ADC_Enable(hadc);
1564 
1565     /* Start conversion if ADC is effectively enabled */
1566     if (tmp_hal_status == HAL_OK)
1567     {
1568       /* Set ADC state                                                        */
1569       /* - Clear state bitfield related to regular group conversion results   */
1570       /* - Set state bitfield related to regular operation                    */
1571       ADC_STATE_CLR_SET(hadc->State,
1572                         HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
1573                         HAL_ADC_STATE_REG_BUSY);
1574 
1575 
1576       /* Set ADC error code */
1577       /* Reset all ADC error code fields */
1578       ADC_CLEAR_ERRORCODE(hadc);
1579 
1580       /* Clear ADC group regular conversion flag and overrun flag               */
1581       /* (To ensure of no unknown state from potential previous ADC operations) */
1582       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
1583 
1584       /* Process unlocked */
1585       /* Unlock before starting ADC conversions: in case of potential         */
1586       /* interruption, to let the process to ADC IRQ Handler.                 */
1587       __HAL_UNLOCK(hadc);
1588 
1589       /* Disable all interruptions before enabling the desired ones */
1590       __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR));
1591 
1592       /* Enable ADC end of conversion interrupt */
1593       switch (hadc->Init.EOCSelection)
1594       {
1595         case ADC_EOC_SEQ_CONV:
1596           __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOS);
1597           break;
1598         /* case ADC_EOC_SINGLE_CONV */
1599         default:
1600           __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOC);
1601           break;
1602       }
1603 
1604       /* Enable ADC overrun interrupt */
1605       /* If hadc->Init.Overrun is set to ADC_OVR_DATA_PRESERVED, only then is
1606          ADC_IT_OVR enabled; otherwise data overwrite is considered as normal
1607          behavior and no CPU time is lost for a non-processed interruption */
1608       if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
1609       {
1610         __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
1611       }
1612 
1613       /* Enable conversion of regular group.                                  */
1614       /* If software start has been selected, conversion starts immediately.  */
1615       /* If external trigger has been selected, conversion will start at next */
1616       /* trigger event.                                                       */
1617       /* Start ADC group regular conversion */
1618       LL_ADC_REG_StartConversion(hadc->Instance);
1619     }
1620     else
1621     {
1622       __HAL_UNLOCK(hadc);
1623     }
1624 
1625   }
1626   else
1627   {
1628     tmp_hal_status = HAL_BUSY;
1629   }
1630 
1631   return tmp_hal_status;
1632 }
1633 
1634 /**
1635   * @brief  Stop ADC conversion of regular group (and injected group in
1636   *         case of auto_injection mode), disable interrution of
1637   *         end-of-conversion, disable ADC peripheral.
1638   * @param hadc ADC handle
1639   * @retval HAL status.
1640   */
HAL_ADC_Stop_IT(ADC_HandleTypeDef * hadc)1641 HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef *hadc)
1642 {
1643   HAL_StatusTypeDef tmp_hal_status;
1644 
1645   /* Check the parameters */
1646   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1647 
1648   __HAL_LOCK(hadc);
1649 
1650   /* 1. Stop potential conversion on going, on ADC group regular */
1651   tmp_hal_status = ADC_ConversionStop(hadc);
1652 
1653   /* Disable ADC peripheral if conversions are effectively stopped */
1654   if (tmp_hal_status == HAL_OK)
1655   {
1656     /* Disable ADC end of conversion interrupt for regular group */
1657     /* Disable ADC overrun interrupt */
1658     __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR));
1659 
1660     /* 2. Disable the ADC peripheral */
1661     tmp_hal_status = ADC_Disable(hadc);
1662 
1663     /* Check if ADC is effectively disabled */
1664     if (tmp_hal_status == HAL_OK)
1665     {
1666       /* Set ADC state */
1667       ADC_STATE_CLR_SET(hadc->State,
1668                         HAL_ADC_STATE_REG_BUSY,
1669                         HAL_ADC_STATE_READY);
1670     }
1671   }
1672 
1673   __HAL_UNLOCK(hadc);
1674 
1675   return tmp_hal_status;
1676 }
1677 
1678 /**
1679   * @brief  Enable ADC, start conversion of regular group and transfer result through DMA.
1680   * @note   Interruptions enabled in this function:
1681   *         overrun (if applicable), DMA half transfer, DMA transfer complete.
1682   *         Each of these interruptions has its dedicated callback function.
1683   * @param hadc ADC handle
1684   * @param pData Destination Buffer address.
1685   * @param Length Number of data to be transferred from ADC peripheral to memory
1686   * @retval HAL status.
1687   */
HAL_ADC_Start_DMA(ADC_HandleTypeDef * hadc,uint32_t * pData,uint32_t Length)1688 HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef *hadc, uint32_t *pData, uint32_t Length)
1689 {
1690   HAL_StatusTypeDef tmp_hal_status;
1691   uint32_t LengthInBytes;
1692 
1693   /* Check the parameters */
1694   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1695 
1696   /* Perform ADC enable and conversion start if no conversion is on going */
1697   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1698   {
1699     __HAL_LOCK(hadc);
1700 
1701     /* Specific case for first call occurrence of this function (DMA transfer */
1702     /* not activated and ADC disabled), DMA transfer must be activated        */
1703     /* with ADC disabled.                                                     */
1704     if ((hadc->Instance->CFGR1 & ADC_CFGR1_DMAEN) == 0UL)
1705     {
1706       if (LL_ADC_IsEnabled(hadc->Instance) != 0UL)
1707       {
1708         /* Disable ADC */
1709         LL_ADC_Disable(hadc->Instance);
1710       }
1711 
1712       /* Enable ADC DMA mode */
1713       hadc->Instance->CFGR1 |= ADC_CFGR1_DMAEN;
1714     }
1715 
1716     /* Enable the ADC peripheral */
1717     tmp_hal_status = ADC_Enable(hadc);
1718 
1719     /* Start conversion if ADC is effectively enabled */
1720     if (tmp_hal_status == HAL_OK)
1721     {
1722       /* Set ADC state                                                        */
1723       /* - Clear state bitfield related to regular group conversion results   */
1724       /* - Set state bitfield related to regular operation                    */
1725       ADC_STATE_CLR_SET(hadc->State,
1726                         HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
1727                         HAL_ADC_STATE_REG_BUSY);
1728 
1729       /* Set ADC error code */
1730       /* Reset all ADC error code fields */
1731       ADC_CLEAR_ERRORCODE(hadc);
1732 
1733       /* Set the DMA transfer complete callback */
1734       hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt;
1735 
1736       /* Set the DMA half transfer complete callback */
1737       hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt;
1738 
1739       /* Set the DMA error callback */
1740       hadc->DMA_Handle->XferErrorCallback = ADC_DMAError;
1741 
1742 
1743       /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC   */
1744       /* start (in case of SW start):                                         */
1745 
1746       /* Clear regular group conversion flag and overrun flag */
1747       /* (To ensure of no unknown state from potential previous ADC           */
1748       /* operations)                                                          */
1749       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
1750 
1751       /* Process unlocked */
1752       /* Unlock before starting ADC conversions: in case of potential         */
1753       /* interruption, to let the process to ADC IRQ Handler.                 */
1754       __HAL_UNLOCK(hadc);
1755 
1756       /* Enable ADC overrun interrupt */
1757       __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
1758 
1759       /* Length should be converted to number of bytes */
1760       LengthInBytes = Length * 4U;
1761 
1762       /* Start the DMA channel */
1763       if ((hadc->DMA_Handle->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
1764       {
1765         if ((hadc->DMA_Handle->LinkedListQueue != NULL) && (hadc->DMA_Handle->LinkedListQueue->Head != NULL))
1766         {
1767           hadc->DMA_Handle->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = (uint32_t)LengthInBytes;
1768           hadc->DMA_Handle->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] = \
1769               (uint32_t)&hadc->Instance->DR;
1770           hadc->DMA_Handle->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData;
1771           tmp_hal_status = HAL_DMAEx_List_Start_IT(hadc->DMA_Handle);
1772         }
1773         else
1774         {
1775           tmp_hal_status = HAL_ERROR;
1776         }
1777       }
1778       else
1779       {
1780         tmp_hal_status = HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->DR, (uint32_t)pData, \
1781                                           LengthInBytes);
1782       }
1783 
1784       /* Enable conversion of regular group.                                  */
1785       /* If software start has been selected, conversion starts immediately.  */
1786       /* If external trigger has been selected, conversion will start at next */
1787       /* trigger event.                                                       */
1788       /* Start ADC group regular conversion */
1789       LL_ADC_REG_StartConversion(hadc->Instance);
1790     }
1791   }
1792   else
1793   {
1794     tmp_hal_status = HAL_BUSY;
1795   }
1796 
1797   return tmp_hal_status;
1798 }
1799 
1800 /**
1801   * @brief  Stop ADC conversion of regular group (and injected group in
1802   *         case of auto_injection mode), disable ADC DMA transfer, disable
1803   *         ADC peripheral.
1804   * @param hadc ADC handle
1805   * @retval HAL status.
1806   */
HAL_ADC_Stop_DMA(ADC_HandleTypeDef * hadc)1807 HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef *hadc)
1808 {
1809   HAL_StatusTypeDef tmp_hal_status;
1810 
1811   /* Check the parameters */
1812   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1813 
1814   __HAL_LOCK(hadc);
1815 
1816   /* 1. Stop potential ADC group regular conversion on going */
1817   tmp_hal_status = ADC_ConversionStop(hadc);
1818 
1819   /* Disable ADC peripheral if conversions are effectively stopped */
1820   if (tmp_hal_status == HAL_OK)
1821   {
1822     /* Disable the DMA channel (in case of DMA in circular mode or stop       */
1823     /* while DMA transfer is on going)                                        */
1824     if (hadc->DMA_Handle->State == HAL_DMA_STATE_BUSY)
1825     {
1826       tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle);
1827 
1828       /* Check if DMA channel effectively disabled */
1829       if (tmp_hal_status != HAL_OK)
1830       {
1831         /* Update ADC state machine to error */
1832         SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
1833       }
1834     }
1835 
1836     /* Disable ADC overrun interrupt */
1837     __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
1838 
1839     /* 2. Disable the ADC peripheral */
1840     /* Update "tmp_hal_status" only if DMA channel disabling passed,          */
1841     /* to keep in memory a potential failing status.                          */
1842     if (tmp_hal_status == HAL_OK)
1843     {
1844       tmp_hal_status = ADC_Disable(hadc);
1845     }
1846     else
1847     {
1848       (void)ADC_Disable(hadc);
1849     }
1850 
1851     /* Check if ADC is effectively disabled */
1852     if (tmp_hal_status == HAL_OK)
1853     {
1854       /* Set ADC state */
1855       ADC_STATE_CLR_SET(hadc->State,
1856                         HAL_ADC_STATE_REG_BUSY,
1857                         HAL_ADC_STATE_READY);
1858     }
1859 
1860     /* Disable ADC DMA (ADC DMA configuration of continuous requests is kept) */
1861     CLEAR_BIT(hadc->Instance->CFGR1, ADC_CFGR1_DMAEN);
1862   }
1863 
1864   __HAL_UNLOCK(hadc);
1865 
1866   return tmp_hal_status;
1867 }
1868 
1869 /**
1870   * @brief  Get ADC regular group conversion result.
1871   * @note   Reading register DR automatically clears ADC flag EOC
1872   *         (ADC group regular end of unitary conversion).
1873   * @note   This function does not clear ADC flag EOS
1874   *         (ADC group regular end of sequence conversion).
1875   *         Occurrence of flag EOS rising:
1876   *          - If sequencer is composed of 1 rank, flag EOS is equivalent
1877   *            to flag EOC.
1878   *          - If sequencer is composed of several ranks, during the scan
1879   *            sequence flag EOC only is raised, at the end of the scan sequence
1880   *            both flags EOC and EOS are raised.
1881   *         To clear this flag, either use function:
1882   *         in programming model IT: @ref HAL_ADC_IRQHandler(), in programming
1883   *         model polling: @ref HAL_ADC_PollForConversion()
1884   *         or @ref __HAL_ADC_CLEAR_FLAG(&hadc, ADC_FLAG_EOS).
1885   * @param hadc ADC handle
1886   * @retval ADC group regular conversion data
1887   */
HAL_ADC_GetValue(const ADC_HandleTypeDef * hadc)1888 uint32_t HAL_ADC_GetValue(const ADC_HandleTypeDef *hadc)
1889 {
1890   /* Check the parameters */
1891   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1892 
1893   /* Note: EOC flag is not cleared here by software because automatically     */
1894   /*       cleared by hardware when reading register DR.                      */
1895 
1896   /* Return ADC converted value */
1897   return hadc->Instance->DR;
1898 }
1899 
1900 /**
1901   * @brief  Handle ADC interrupt request.
1902   * @param hadc ADC handle
1903   * @retval None
1904   */
HAL_ADC_IRQHandler(ADC_HandleTypeDef * hadc)1905 void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc)
1906 {
1907   uint32_t overrun_error = 0UL; /* flag set if overrun occurrence has to be considered as an error */
1908   uint32_t tmp_isr = hadc->Instance->ISR;
1909   uint32_t tmp_ier = hadc->Instance->IER;
1910 
1911   /* Check the parameters */
1912   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1913   assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection));
1914 
1915   /* ========== Check End of Sampling flag for ADC group regular ========== */
1916   if (((tmp_isr & ADC_FLAG_EOSMP) == ADC_FLAG_EOSMP) && ((tmp_ier & ADC_IT_EOSMP) == ADC_IT_EOSMP))
1917   {
1918     /* Update state machine on end of sampling status if not in error state */
1919     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
1920     {
1921       /* Set ADC state */
1922       SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOSMP);
1923     }
1924 
1925     /* End Of Sampling callback */
1926 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
1927     hadc->EndOfSamplingCallback(hadc);
1928 #else
1929     HAL_ADCEx_EndOfSamplingCallback(hadc);
1930 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1931 
1932     /* Clear regular group conversion flag */
1933     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP);
1934   }
1935 
1936   /* ====== Check ADC group regular end of unitary conversion sequence conversions ===== */
1937   if ((((tmp_isr & ADC_FLAG_EOC) == ADC_FLAG_EOC) && ((tmp_ier & ADC_IT_EOC) == ADC_IT_EOC)) ||
1938       (((tmp_isr & ADC_FLAG_EOS) == ADC_FLAG_EOS) && ((tmp_ier & ADC_IT_EOS) == ADC_IT_EOS)))
1939   {
1940     /* Update state machine on conversion status if not in error state */
1941     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
1942     {
1943       /* Set ADC state */
1944       SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
1945     }
1946 
1947     /* Determine whether any further conversion upcoming on group regular     */
1948     /* by external trigger, continuous mode or scan sequence on going         */
1949     /* to disable interruption.                                               */
1950     if ((LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
1951         && (hadc->Init.ContinuousConvMode == DISABLE)
1952        )
1953     {
1954       /* If End of Sequence is reached, disable interrupts */
1955       if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS))
1956       {
1957         /* Allowed to modify bits ADC_IT_EOC/ADC_IT_EOS only if bit           */
1958         /* ADSTART==0 (no conversion on going)                                */
1959         if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1960         {
1961           /* Disable ADC end of single conversion interrupt on group regular */
1962           /* Note: Overrun interrupt was enabled with EOC interrupt in        */
1963           /* HAL_Start_IT(), but is not disabled here because can be used     */
1964           /* by overrun IRQ process below.                                    */
1965           __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_EOS);
1966 
1967           /* Set ADC state */
1968           ADC_STATE_CLR_SET(hadc->State,
1969                             HAL_ADC_STATE_REG_BUSY,
1970                             HAL_ADC_STATE_READY);
1971         }
1972         else
1973         {
1974           /* Change ADC state to error state */
1975           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1976 
1977           /* Set ADC error code to ADC peripheral internal error */
1978           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
1979         }
1980       }
1981     }
1982 
1983     /* Conversion complete callback */
1984     /* Note: Into callback function "HAL_ADC_ConvCpltCallback()",             */
1985     /*       to determine if conversion has been triggered from EOC or EOS,   */
1986     /*       possibility to use:                                              */
1987     /*        " if ( __HAL_ADC_GET_FLAG(&hadc, ADC_FLAG_EOS)) "               */
1988 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
1989     hadc->ConvCpltCallback(hadc);
1990 #else
1991     HAL_ADC_ConvCpltCallback(hadc);
1992 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1993 
1994     /* Clear regular group conversion flag */
1995     /* Note: in case of overrun set to ADC_OVR_DATA_PRESERVED, end of         */
1996     /*       conversion flags clear induces the release of the preserved data.*/
1997     /*       Therefore, if the preserved data value is needed, it must be     */
1998     /*       read preliminarily into HAL_ADC_ConvCpltCallback().              */
1999     __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS));
2000   }
2001 
2002   /* ========== Check Analog watchdog 1 flag ========== */
2003   if (((tmp_isr & ADC_FLAG_AWD1) == ADC_FLAG_AWD1) && ((tmp_ier & ADC_IT_AWD1) == ADC_IT_AWD1))
2004   {
2005     /* Set ADC state */
2006     SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
2007 
2008     /* Level out of window 1 callback */
2009 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2010     hadc->LevelOutOfWindowCallback(hadc);
2011 #else
2012     HAL_ADC_LevelOutOfWindowCallback(hadc);
2013 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2014 
2015     /* Clear ADC analog watchdog flag */
2016     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD1);
2017   }
2018 
2019   /* ========== Check analog watchdog 2 flag ========== */
2020   if (((tmp_isr & ADC_FLAG_AWD2) == ADC_FLAG_AWD2) && ((tmp_ier & ADC_IT_AWD2) == ADC_IT_AWD2))
2021   {
2022     /* Set ADC state */
2023     SET_BIT(hadc->State, HAL_ADC_STATE_AWD2);
2024 
2025     /* Level out of window 2 callback */
2026 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2027     hadc->LevelOutOfWindow2Callback(hadc);
2028 #else
2029     HAL_ADCEx_LevelOutOfWindow2Callback(hadc);
2030 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2031 
2032     /* Clear ADC analog watchdog flag */
2033     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD2);
2034   }
2035 
2036   /* ========== Check analog watchdog 3 flag ========== */
2037   if (((tmp_isr & ADC_FLAG_AWD3) == ADC_FLAG_AWD3) && ((tmp_ier & ADC_IT_AWD3) == ADC_IT_AWD3))
2038   {
2039     /* Set ADC state */
2040     SET_BIT(hadc->State, HAL_ADC_STATE_AWD3);
2041 
2042     /* Level out of window 3 callback */
2043 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2044     hadc->LevelOutOfWindow3Callback(hadc);
2045 #else
2046     HAL_ADCEx_LevelOutOfWindow3Callback(hadc);
2047 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2048 
2049     /* Clear ADC analog watchdog flag */
2050     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD3);
2051   }
2052 
2053   /* ========== Check Overrun flag ========== */
2054   if (((tmp_isr & ADC_FLAG_OVR) == ADC_FLAG_OVR) && ((tmp_ier & ADC_IT_OVR) == ADC_IT_OVR))
2055   {
2056     /* If overrun is set to overwrite previous data (default setting),        */
2057     /* overrun event is not considered as an error.                           */
2058     /* (cf ref manual "Managing conversions without using the DMA and without */
2059     /* overrun ")                                                             */
2060     /* Exception for usage with DMA overrun event always considered as an     */
2061     /* error.                                                                 */
2062     if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
2063     {
2064       overrun_error = 1UL;
2065     }
2066     else
2067     {
2068       /* Check DMA configuration */
2069       if (LL_ADC_REG_GetDMATransfer(hadc->Instance) != LL_ADC_REG_DMA_TRANSFER_NONE)
2070       {
2071         overrun_error = 1UL;
2072       }
2073     }
2074 
2075     if (overrun_error == 1UL)
2076     {
2077       /* Change ADC state to error state */
2078       SET_BIT(hadc->State, HAL_ADC_STATE_REG_OVR);
2079 
2080       /* Set ADC error code to overrun */
2081       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_OVR);
2082 
2083       /* Error callback */
2084       /* Note: In case of overrun, ADC conversion data is preserved until     */
2085       /*       flag OVR is reset.                                             */
2086       /*       Therefore, old ADC conversion data can be retrieved in         */
2087       /*       function "HAL_ADC_ErrorCallback()".                            */
2088 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2089       hadc->ErrorCallback(hadc);
2090 #else
2091       HAL_ADC_ErrorCallback(hadc);
2092 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2093     }
2094 
2095     /* Clear ADC overrun flag */
2096     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
2097   }
2098 
2099   /* ========== Check channel configuration ready flag ========== */
2100   if (((tmp_isr & ADC_FLAG_LDORDY) == ADC_FLAG_LDORDY) && ((tmp_ier & ADC_IT_LDORDY) == ADC_IT_LDORDY))
2101   {
2102     /* Internal voltage regulator callback */
2103     HAL_ADCEx_LDOReadyCallback(hadc);
2104 
2105     /* Clear ADC analog watchdog flag */
2106     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_LDORDY);
2107   }
2108 }
2109 
2110 /**
2111   * @brief  Conversion complete callback in non-blocking mode.
2112   * @param hadc ADC handle
2113   * @retval None
2114   */
HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef * hadc)2115 __weak void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
2116 {
2117   /* Prevent unused argument(s) compilation warning */
2118   UNUSED(hadc);
2119 
2120   /* NOTE : This function should not be modified. When the callback is needed,
2121             function HAL_ADC_ConvCpltCallback must be implemented in the user file.
2122    */
2123 }
2124 
2125 /**
2126   * @brief  Conversion DMA half-transfer callback in non-blocking mode.
2127   * @param hadc ADC handle
2128   * @retval None
2129   */
HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef * hadc)2130 __weak void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef *hadc)
2131 {
2132   /* Prevent unused argument(s) compilation warning */
2133   UNUSED(hadc);
2134 
2135   /* NOTE : This function should not be modified. When the callback is needed,
2136             function HAL_ADC_ConvHalfCpltCallback must be implemented in the user file.
2137   */
2138 }
2139 
2140 /**
2141   * @brief  Analog watchdog 1 callback in non-blocking mode.
2142   * @param hadc ADC handle
2143   * @retval None
2144   */
HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef * hadc)2145 __weak void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef *hadc)
2146 {
2147   /* Prevent unused argument(s) compilation warning */
2148   UNUSED(hadc);
2149 
2150   /* NOTE : This function should not be modified. When the callback is needed,
2151             function HAL_ADC_LevelOutOfWindowCallback must be implemented in the user file.
2152   */
2153 }
2154 
2155 /**
2156   * @brief  ADC error callback in non-blocking mode
2157   *         (ADC conversion with interruption or transfer by DMA).
2158   * @note   In case of error due to overrun when using ADC with DMA transfer
2159   *         (HAL ADC handle parameter "ErrorCode" to state "HAL_ADC_ERROR_OVR"):
2160   *         - Reinitialize the DMA using function "HAL_ADC_Stop_DMA()".
2161   *         - If needed, restart a new ADC conversion using function
2162   *           "HAL_ADC_Start_DMA()"
2163   *           (this function is also clearing overrun flag)
2164   * @param hadc ADC handle
2165   * @retval None
2166   */
HAL_ADC_ErrorCallback(ADC_HandleTypeDef * hadc)2167 __weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc)
2168 {
2169   /* Prevent unused argument(s) compilation warning */
2170   UNUSED(hadc);
2171 
2172   /* NOTE : This function should not be modified. When the callback is needed,
2173             function HAL_ADC_ErrorCallback must be implemented in the user file.
2174   */
2175 }
2176 
2177 /**
2178   * @}
2179   */
2180 
2181 /** @defgroup ADC_Exported_Functions_Group3 Peripheral Control functions
2182   * @brief    Peripheral Control functions
2183   *
2184 @verbatim
2185  ===============================================================================
2186              ##### Peripheral Control functions #####
2187  ===============================================================================
2188     [..]  This section provides functions allowing to:
2189       (+) Configure channels on regular group
2190       (+) Configure the analog watchdog
2191 
2192 @endverbatim
2193   * @{
2194   */
2195 
2196 /**
2197   * @brief  Configure a channel to be assigned to ADC group regular.
2198   * @note   In case of usage of internal measurement channels:
2199   *         Vbat/VrefInt/TempSensor.
2200   *         These internal paths can be disabled using function
2201   *         HAL_ADC_DeInit().
2202   * @note   Possibility to update parameters on the fly:
2203   *         This function initializes channel into ADC group regular,
2204   *         following calls to this function can be used to reconfigure
2205   *         some parameters of structure "ADC_ChannelConfTypeDef" on the fly,
2206   *         without resetting the ADC.
2207   *         The setting of these parameters is conditioned to ADC state:
2208   *         Refer to comments of structure "ADC_ChannelConfTypeDef".
2209   * @param hadc ADC handle
2210   * @param pConfig Structure of ADC channel assigned to ADC group regular.
2211   * @retval HAL status
2212   */
HAL_ADC_ConfigChannel(ADC_HandleTypeDef * hadc,const ADC_ChannelConfTypeDef * pConfig)2213 HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef *hadc, const ADC_ChannelConfTypeDef *pConfig)
2214 {
2215   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
2216   uint32_t tmp_config_internal_channel;
2217   __IO uint32_t wait_loop_index = 0UL;
2218 
2219   /* Check the parameters */
2220   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2221   assert_param(IS_ADC_CHANNEL(pConfig->Channel));
2222   assert_param(IS_ADC_SAMPLING_TIME_COMMON(pConfig->SamplingTime));
2223 
2224   if ((hadc->Init.ScanConvMode == ADC_SCAN_SEQ_FIXED)       ||
2225       (hadc->Init.ScanConvMode == ADC_SCAN_SEQ_FIXED_BACKWARD))
2226   {
2227     assert_param(IS_ADC_REGULAR_RANK_SEQ_FIXED(pConfig->Rank));
2228   }
2229   else
2230   {
2231     assert_param(IS_ADC_REGULAR_NB_CONV(hadc->Init.NbrOfConversion));
2232 
2233     assert_param(IS_ADC_REGULAR_RANK(pConfig->Rank));
2234   }
2235 
2236   __HAL_LOCK(hadc);
2237 
2238   /* Parameters update conditioned to ADC state:                              */
2239   /* Parameters that can be updated when ADC is disabled or enabled without   */
2240   /* conversion on going on regular group:                                    */
2241   /*  - Channel number                                                        */
2242   /*  - Channel sampling time                                                 */
2243   /*  - Management of internal measurement channels: VrefInt/TempSensor/Vbat  */
2244   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
2245   {
2246     /* Configure channel: depending on rank setting, add it or remove it from */
2247     /* ADC sequencer.                                                         */
2248     /* If sequencer set to not fully configurable with channel rank set to    */
2249     /* none, remove the channel from the sequencer.                           */
2250     /* Otherwise (sequencer set to fully configurable or to to not fully      */
2251     /* configurable with channel rank to be set), configure the selected      */
2252     /* channel.                                                               */
2253     if (pConfig->Rank != ADC_RANK_NONE)
2254     {
2255       /* Regular sequence configuration */
2256       /* Note: ADC channel configuration requires few ADC clock cycles        */
2257       /*       to be ready. Processing of ADC settings in this function       */
2258       /*       induce that a specific wait time is not necessary.             */
2259       /*       For more details on ADC channel configuration ready,           */
2260       /*       refer to function "LL_ADC_IsActiveFlag_CCRDY()".               */
2261       if ((hadc->Init.ScanConvMode == ADC_SCAN_SEQ_FIXED)       ||
2262           (hadc->Init.ScanConvMode == ADC_SCAN_SEQ_FIXED_BACKWARD))
2263       {
2264         /* Sequencer set to not fully configurable:                           */
2265         /* Set the channel by enabling the corresponding bitfield.            */
2266         LL_ADC_REG_SetSequencerChAdd(hadc->Instance, pConfig->Channel);
2267       }
2268       else
2269       {
2270         /* Sequencer set to fully configurable:                               */
2271         /* Set the channel by entering it into the selected rank.             */
2272 
2273         /* Memorize the channel set into variable in HAL ADC handle */
2274         MODIFY_REG(hadc->ADCGroupRegularSequencerRanks,
2275                    ADC_CHSELR_SQ1 << (pConfig->Rank & 0x1FUL),
2276                    __LL_ADC_CHANNEL_TO_DECIMAL_NB(pConfig->Channel) << (pConfig->Rank & 0x1FUL));
2277 
2278         /* If the selected rank is below ADC group regular sequencer length,  */
2279         /* apply the configuration in ADC register.                           */
2280         /* Note: Otherwise, configuration is not applied.                     */
2281         /*       To apply it, parameter'NbrOfConversion' must be increased.   */
2282         if (((pConfig->Rank >> 2UL) + 1UL) <= hadc->Init.NbrOfConversion)
2283         {
2284           LL_ADC_REG_SetSequencerRanks(hadc->Instance, pConfig->Rank, pConfig->Channel);
2285         }
2286       }
2287 
2288       /* Set sampling time of the selected ADC channel */
2289       LL_ADC_SetChannelSamplingTime(hadc->Instance, pConfig->Channel, pConfig->SamplingTime);
2290 
2291       /* Management of internal measurement channels: VrefInt/TempSensor/Vbat */
2292       /* internal measurement paths enable: If internal channel selected,     */
2293       /* enable dedicated internal buffers and path.                          */
2294       /* Note: these internal measurement paths can be disabled using         */
2295       /*       HAL_ADC_DeInit() or removing the channel from sequencer with   */
2296       /*       channel configuration parameter "Rank".                        */
2297       if (__LL_ADC_IS_CHANNEL_INTERNAL(pConfig->Channel))
2298       {
2299         tmp_config_internal_channel = LL_ADC_GetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
2300 
2301         /* If the requested internal measurement path has already been enabled,   */
2302         /* bypass the configuration processing.                                   */
2303         if ((pConfig->Channel == ADC_CHANNEL_TEMPSENSOR) &&
2304             ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_TEMPSENSOR) == 0UL))
2305         {
2306           LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
2307                                          LL_ADC_PATH_INTERNAL_TEMPSENSOR | tmp_config_internal_channel);
2308 
2309           /* Delay for temperature sensor stabilization time */
2310           /* Wait loop initialization and execution */
2311           /* Note: Variable divided by 2 to compensate partially              */
2312           /*       CPU processing cycles, scaling in us split to not          */
2313           /*       exceed 32 bits register capacity and handle low frequency. */
2314           wait_loop_index = ((LL_ADC_DELAY_TEMPSENSOR_STAB_US / 10UL) * ((SystemCoreClock / (100000UL * 2UL)) + 1UL));
2315           while (wait_loop_index != 0UL)
2316           {
2317             wait_loop_index--;
2318           }
2319         }
2320         else if ((pConfig->Channel == ADC_CHANNEL_VREFINT) &&
2321                  ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_VREFINT) == 0UL))
2322         {
2323           LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
2324                                          LL_ADC_PATH_INTERNAL_VREFINT | tmp_config_internal_channel);
2325         }
2326         else
2327         {
2328           /* nothing to do */
2329         }
2330       }
2331     }
2332     else
2333     {
2334       /* Regular sequencer configuration */
2335       /* Note: Case of sequencer set to fully configurable:                   */
2336       /*       Sequencer rank cannot be disabled, only affected to            */
2337       /*       another channel.                                               */
2338       /*       To remove a rank, use parameter 'NbrOfConversion".             */
2339       if ((hadc->Init.ScanConvMode == ADC_SCAN_SEQ_FIXED)       ||
2340           (hadc->Init.ScanConvMode == ADC_SCAN_SEQ_FIXED_BACKWARD))
2341       {
2342         /* Sequencer set to not fully configurable:                           */
2343         /* Reset the channel by disabling the corresponding bitfield.         */
2344         LL_ADC_REG_SetSequencerChRem(hadc->Instance, pConfig->Channel);
2345       }
2346 
2347       /* Management of internal measurement channels: Vbat/VrefInt/TempSensor.  */
2348       /* If internal channel selected, enable dedicated internal buffers and    */
2349       /* paths.                                                                 */
2350       if (__LL_ADC_IS_CHANNEL_INTERNAL(pConfig->Channel))
2351       {
2352         tmp_config_internal_channel = LL_ADC_GetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
2353 
2354         if (pConfig->Channel == ADC_CHANNEL_TEMPSENSOR)
2355         {
2356           LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
2357                                          ~LL_ADC_PATH_INTERNAL_TEMPSENSOR & tmp_config_internal_channel);
2358         }
2359         else if (pConfig->Channel == ADC_CHANNEL_VREFINT)
2360         {
2361           LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
2362                                          ~LL_ADC_PATH_INTERNAL_VREFINT & tmp_config_internal_channel);
2363         }
2364         else
2365         {
2366           /* nothing to do */
2367         }
2368       }
2369     }
2370   }
2371 
2372   /* If a conversion is on going on regular group, no update on regular       */
2373   /* channel could be done on neither of the channel configuration structure  */
2374   /* parameters.                                                              */
2375   else
2376   {
2377     /* Update ADC state machine to error */
2378     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
2379 
2380     tmp_hal_status = HAL_ERROR;
2381   }
2382 
2383   __HAL_UNLOCK(hadc);
2384 
2385   return tmp_hal_status;
2386 }
2387 
2388 /**
2389   * @brief  Configure the analog watchdog.
2390   * @note   Possibility to update parameters on the fly:
2391   *         This function initializes the selected analog watchdog, successive
2392   *         calls to this function can be used to reconfigure some parameters
2393   *         of structure "ADC_AnalogWDGConfTypeDef" on the fly, without resetting
2394   *         the ADC.
2395   *         The setting of these parameters is conditioned to ADC state.
2396   *         For parameters constraints, see comments of structure
2397   *         "ADC_AnalogWDGConfTypeDef".
2398   * @note   On this STM32 series, analog watchdog thresholds can be modified
2399   *         while ADC conversion is on going.
2400   *         In this case, some constraints must be taken into account:
2401   *         the programmed threshold values are effective from the next
2402   *         ADC EOC (end of unitary conversion).
2403   *         Considering that registers write delay may happen due to
2404   *         bus activity, this might cause an uncertainty on the
2405   *         effective timing of the new programmed threshold values.
2406   * @param hadc ADC handle
2407   * @param pAnalogWDGConfig Structure of ADC analog watchdog configuration
2408   * @retval HAL status
2409   */
HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef * hadc,const ADC_AnalogWDGConfTypeDef * pAnalogWDGConfig)2410 HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef *hadc, const ADC_AnalogWDGConfTypeDef *pAnalogWDGConfig)
2411 {
2412   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
2413   uint32_t tmp_awd_high_threshold_shifted;
2414   uint32_t tmp_awd_low_threshold_shifted;
2415 
2416   /* Check the parameters */
2417   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2418   assert_param(IS_ADC_ANALOG_WATCHDOG_NUMBER(pAnalogWDGConfig->WatchdogNumber));
2419   assert_param(IS_ADC_ANALOG_WATCHDOG_MODE(pAnalogWDGConfig->WatchdogMode));
2420   assert_param(IS_FUNCTIONAL_STATE(pAnalogWDGConfig->ITMode));
2421 
2422   if (pAnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG)
2423   {
2424     assert_param(IS_ADC_CHANNEL(pAnalogWDGConfig->Channel));
2425   }
2426 
2427   /* Verify thresholds range */
2428   if (hadc->Init.OversamplingMode == ENABLE)
2429   {
2430     /* Case of oversampling enabled: depending on ratio and shift configuration,
2431        analog watchdog thresholds can be higher than ADC resolution.
2432        Verify if thresholds are within maximum thresholds range. */
2433     assert_param(IS_ADC_RANGE(ADC_RESOLUTION_12B, pAnalogWDGConfig->HighThreshold));
2434     assert_param(IS_ADC_RANGE(ADC_RESOLUTION_12B, pAnalogWDGConfig->LowThreshold));
2435   }
2436   else
2437   {
2438     /* Verify if thresholds are within the selected ADC resolution */
2439     assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), pAnalogWDGConfig->HighThreshold));
2440     assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), pAnalogWDGConfig->LowThreshold));
2441   }
2442 
2443   __HAL_LOCK(hadc);
2444 
2445   /* Parameters update conditioned to ADC state:                              */
2446   /* Parameters that can be updated when ADC is disabled or enabled without   */
2447   /* conversion on going on ADC group regular:                                */
2448   /*  - Analog watchdog channels                                              */
2449   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
2450   {
2451     /* Analog watchdog configuration */
2452     if (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_1)
2453     {
2454       /* Configuration of analog watchdog:                                    */
2455       /*  - Set the analog watchdog enable mode: one or overall group of      */
2456       /*    channels.                                                         */
2457       switch (pAnalogWDGConfig->WatchdogMode)
2458       {
2459         case ADC_ANALOGWATCHDOG_SINGLE_REG:
2460           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1,
2461                                           __LL_ADC_ANALOGWD_CHANNEL_GROUP(pAnalogWDGConfig->Channel,
2462                                                                           LL_ADC_GROUP_REGULAR));
2463           break;
2464 
2465         case ADC_ANALOGWATCHDOG_ALL_REG:
2466           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_ALL_CHANNELS_REG);
2467           break;
2468 
2469         default: /* ADC_ANALOGWATCHDOG_NONE */
2470           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_DISABLE);
2471           break;
2472       }
2473 
2474       /* Update state, clear previous result related to AWD1 */
2475       CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD1);
2476 
2477       /* Clear flag ADC analog watchdog */
2478       /* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready  */
2479       /* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent()          */
2480       /* (in case left enabled by previous ADC operations).                 */
2481       LL_ADC_ClearFlag_AWD1(hadc->Instance);
2482 
2483       /* Configure ADC analog watchdog interrupt */
2484       if (pAnalogWDGConfig->ITMode == ENABLE)
2485       {
2486         LL_ADC_EnableIT_AWD1(hadc->Instance);
2487       }
2488       else
2489       {
2490         LL_ADC_DisableIT_AWD1(hadc->Instance);
2491       }
2492     }
2493     /* Case of ADC_ANALOGWATCHDOG_2 or ADC_ANALOGWATCHDOG_3 */
2494     else
2495     {
2496       switch (pAnalogWDGConfig->WatchdogMode)
2497       {
2498         case ADC_ANALOGWATCHDOG_SINGLE_REG:
2499           /* Update AWD by bitfield to keep the possibility to monitor        */
2500           /* several channels by successive calls of this function.           */
2501           if (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_2)
2502           {
2503             SET_BIT(hadc->Instance->AWD2CR, (1UL << __LL_ADC_CHANNEL_TO_DECIMAL_NB(pAnalogWDGConfig->Channel)));
2504           }
2505           else
2506           {
2507             SET_BIT(hadc->Instance->AWD3CR, (1UL << __LL_ADC_CHANNEL_TO_DECIMAL_NB(pAnalogWDGConfig->Channel)));
2508           }
2509           break;
2510 
2511         case ADC_ANALOGWATCHDOG_ALL_REG:
2512           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance,
2513                                           pAnalogWDGConfig->WatchdogNumber,
2514                                           LL_ADC_AWD_ALL_CHANNELS_REG);
2515           break;
2516 
2517         default: /* ADC_ANALOGWATCHDOG_NONE */
2518           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, pAnalogWDGConfig->WatchdogNumber, LL_ADC_AWD_DISABLE);
2519           break;
2520       }
2521 
2522       if (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_2)
2523       {
2524         /* Update state, clear previous result related to AWD2 */
2525         CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD2);
2526 
2527         /* Clear flag ADC analog watchdog */
2528         /* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready  */
2529         /* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent()          */
2530         /* (in case left enabled by previous ADC operations).                 */
2531         LL_ADC_ClearFlag_AWD2(hadc->Instance);
2532 
2533         /* Configure ADC analog watchdog interrupt */
2534         if (pAnalogWDGConfig->ITMode == ENABLE)
2535         {
2536           LL_ADC_EnableIT_AWD2(hadc->Instance);
2537         }
2538         else
2539         {
2540           LL_ADC_DisableIT_AWD2(hadc->Instance);
2541         }
2542       }
2543       /* (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_3) */
2544       else
2545       {
2546         /* Update state, clear previous result related to AWD3 */
2547         CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD3);
2548 
2549         /* Clear flag ADC analog watchdog */
2550         /* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready  */
2551         /* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent()          */
2552         /* (in case left enabled by previous ADC operations).                 */
2553         LL_ADC_ClearFlag_AWD3(hadc->Instance);
2554 
2555         /* Configure ADC analog watchdog interrupt */
2556         if (pAnalogWDGConfig->ITMode == ENABLE)
2557         {
2558           LL_ADC_EnableIT_AWD3(hadc->Instance);
2559         }
2560         else
2561         {
2562           LL_ADC_DisableIT_AWD3(hadc->Instance);
2563         }
2564       }
2565     }
2566 
2567   }
2568 
2569   /* Analog watchdog thresholds configuration */
2570   if (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_1)
2571   {
2572     /* Shift the offset with respect to the selected ADC resolution:        */
2573     /* Thresholds have to be left-aligned on bit 11, the LSB (right bits)   */
2574     /* are set to 0.                                                        */
2575     tmp_awd_high_threshold_shifted = ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(hadc, pAnalogWDGConfig->HighThreshold);
2576     tmp_awd_low_threshold_shifted  = ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(hadc, pAnalogWDGConfig->LowThreshold);
2577   }
2578   /* Case of ADC_ANALOGWATCHDOG_2 and ADC_ANALOGWATCHDOG_3 */
2579   else
2580   {
2581     /* No need to shift the offset with respect to the selected ADC resolution: */
2582     /* Thresholds have to be left-aligned on bit 11, the LSB (right bits)   */
2583     /* are set to 0.                                                        */
2584     tmp_awd_high_threshold_shifted = pAnalogWDGConfig->HighThreshold;
2585     tmp_awd_low_threshold_shifted  = pAnalogWDGConfig->LowThreshold;
2586   }
2587 
2588   /* Set ADC analog watchdog thresholds value of both thresholds high and low */
2589   LL_ADC_ConfigAnalogWDThresholds(hadc->Instance, pAnalogWDGConfig->WatchdogNumber, tmp_awd_high_threshold_shifted,
2590                                   tmp_awd_low_threshold_shifted);
2591 
2592   __HAL_UNLOCK(hadc);
2593 
2594   return tmp_hal_status;
2595 }
2596 
2597 
2598 /**
2599   * @}
2600   */
2601 
2602 /** @defgroup ADC_Exported_Functions_Group4 Peripheral State functions
2603   *  @brief    ADC Peripheral State functions
2604   *
2605 @verbatim
2606  ===============================================================================
2607             ##### Peripheral state and errors functions #####
2608  ===============================================================================
2609     [..]
2610     This subsection provides functions to get in run-time the status of the
2611     peripheral.
2612       (+) Check the ADC state
2613       (+) Check the ADC error code
2614 
2615 @endverbatim
2616   * @{
2617   */
2618 
2619 /**
2620   * @brief  Return the ADC handle state.
2621   * @note   ADC state machine is managed by bitfields, ADC status must be
2622   *         compared with states bits.
2623   *         For example:
2624   *           " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_REG_BUSY) != 0UL) "
2625   *           " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD1) != 0UL) "
2626   * @param hadc ADC handle
2627   * @retval ADC handle state (bitfield on 32 bits)
2628   */
HAL_ADC_GetState(const ADC_HandleTypeDef * hadc)2629 uint32_t HAL_ADC_GetState(const ADC_HandleTypeDef *hadc)
2630 {
2631   /* Check the parameters */
2632   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2633 
2634   /* Return ADC handle state */
2635   return hadc->State;
2636 }
2637 
2638 /**
2639   * @brief  Return the ADC error code.
2640   * @param hadc ADC handle
2641   * @retval ADC error code (bitfield on 32 bits)
2642   */
HAL_ADC_GetError(const ADC_HandleTypeDef * hadc)2643 uint32_t HAL_ADC_GetError(const ADC_HandleTypeDef *hadc)
2644 {
2645   /* Check the parameters */
2646   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2647 
2648   return hadc->ErrorCode;
2649 }
2650 
2651 /**
2652   * @}
2653   */
2654 
2655 /**
2656   * @}
2657   */
2658 
2659 /** @defgroup ADC_Private_Functions ADC Private Functions
2660   * @{
2661   */
2662 
2663 /**
2664   * @brief  Stop ADC conversion.
2665   * @note   Prerequisite condition to use this function: ADC conversions must be
2666   *         stopped to disable the ADC.
2667   * @param  hadc ADC handle
2668   * @retval HAL status.
2669   */
ADC_ConversionStop(ADC_HandleTypeDef * hadc)2670 HAL_StatusTypeDef ADC_ConversionStop(ADC_HandleTypeDef *hadc)
2671 {
2672   uint32_t tickstart;
2673 
2674   /* Check the parameters */
2675   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2676 
2677   /* Verification if ADC is not already stopped on regular group to bypass    */
2678   /* this function if not needed.                                             */
2679   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) != 0UL)
2680   {
2681     /* Stop potential conversion on going on regular group */
2682     /* Software is allowed to set ADSTP only when ADSTART=1 and ADDIS=0 */
2683     if (LL_ADC_IsDisableOngoing(hadc->Instance) == 0UL)
2684     {
2685       /* Stop ADC group regular conversion */
2686       LL_ADC_REG_StopConversion(hadc->Instance);
2687     }
2688 
2689     /* Wait for conversion effectively stopped */
2690     /* Get tick count */
2691     tickstart = HAL_GetTick();
2692 
2693     while ((hadc->Instance->CR & ADC_CR_ADSTART) != 0UL)
2694     {
2695       if ((HAL_GetTick() - tickstart) > ADC_STOP_CONVERSION_TIMEOUT)
2696       {
2697         /* New check to avoid false timeout detection in case of preemption */
2698         if ((hadc->Instance->CR & ADC_CR_ADSTART) != 0UL)
2699         {
2700           /* Update ADC state machine to error */
2701           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2702 
2703           /* Set ADC error code to ADC peripheral internal error */
2704           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2705 
2706           return HAL_ERROR;
2707         }
2708       }
2709     }
2710 
2711   }
2712 
2713   /* Return HAL status */
2714   return HAL_OK;
2715 }
2716 
2717 /**
2718   * @brief  Enable the selected ADC.
2719   * @note   Prerequisite condition to use this function: ADC must be disabled
2720   *         and voltage regulator must be enabled (done into HAL_ADC_Init()).
2721   * @param hadc ADC handle
2722   * @retval HAL status.
2723   */
ADC_Enable(ADC_HandleTypeDef * hadc)2724 HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef *hadc)
2725 {
2726   uint32_t tickstart;
2727   __IO uint32_t wait_loop_index = 0UL;
2728 
2729   /* ADC enable and wait for ADC ready (in case of ADC is disabled or         */
2730   /* enabling phase not yet completed: flag ADC ready not yet set).           */
2731   /* Timeout implemented to not be stuck if ADC cannot be enabled (possible   */
2732   /* causes: ADC clock not running, ...).                                     */
2733   if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
2734   {
2735     /* Check if conditions to enable the ADC are fulfilled */
2736     if ((hadc->Instance->CR & (ADC_CR_ADCAL | ADC_CR_ADSTP | ADC_CR_ADSTART | ADC_CR_ADDIS | ADC_CR_ADEN)) != 0UL)
2737     {
2738       /* Update ADC state machine to error */
2739       SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2740 
2741       /* Set ADC error code to ADC peripheral internal error */
2742       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2743 
2744       return HAL_ERROR;
2745     }
2746 
2747     /* Enable the ADC peripheral */
2748     LL_ADC_Enable(hadc->Instance);
2749 
2750     if ((LL_ADC_GetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) & LL_ADC_PATH_INTERNAL_TEMPSENSOR)
2751         != 0UL)
2752     {
2753       /* Delay for temperature sensor buffer stabilization time */
2754       /* Wait loop initialization and execution */
2755       /* Note: Variable divided by 2 to compensate partially              */
2756       /*       CPU processing cycles, scaling in us split to not          */
2757       /*       exceed 32 bits register capacity and handle low frequency. */
2758       wait_loop_index = ((LL_ADC_DELAY_TEMPSENSOR_BUFFER_STAB_US / 10UL)
2759                          * ((SystemCoreClock / (100000UL * 2UL)) + 1UL));
2760       while (wait_loop_index != 0UL)
2761       {
2762         wait_loop_index--;
2763       }
2764     }
2765 
2766     /* If low power mode AutoPowerOff is enabled, power-on/off phases are     */
2767     /* performed automatically by hardware and flag ADC ready is not set.     */
2768     if (hadc->Init.LowPowerAutoPowerOff != ENABLE)
2769     {
2770       /* Wait for ADC effectively enabled */
2771       tickstart = HAL_GetTick();
2772 
2773       while (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_RDY) == 0UL)
2774       {
2775         /*  If ADEN bit is set less than 4 ADC clock cycles after the ADCAL bit
2776             has been cleared (after a calibration), ADEN bit is reset by the
2777             calibration logic.
2778             The workaround is to continue setting ADEN until ADRDY is becomes 1.
2779             Additionally, ADC_ENABLE_TIMEOUT is defined to encompass this
2780             4 ADC clock cycle duration */
2781         /* Note: Test of ADC enabled required due to hardware constraint to     */
2782         /*       not enable ADC if already enabled.                             */
2783         if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
2784         {
2785           LL_ADC_Enable(hadc->Instance);
2786         }
2787 
2788         if ((HAL_GetTick() - tickstart) > ADC_ENABLE_TIMEOUT)
2789         {
2790           /* New check to avoid false timeout detection in case of preemption */
2791           if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_RDY) == 0UL)
2792           {
2793             /* Update ADC state machine to error */
2794             SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2795 
2796             /* Set ADC error code to ADC peripheral internal error */
2797             SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2798 
2799             return HAL_ERROR;
2800           }
2801         }
2802       }
2803     }
2804   }
2805 
2806   /* Return HAL status */
2807   return HAL_OK;
2808 }
2809 
2810 /**
2811   * @brief  Disable the selected ADC.
2812   * @note   Prerequisite condition to use this function: ADC conversions must be
2813   *         stopped.
2814   * @param hadc ADC handle
2815   * @retval HAL status.
2816   */
ADC_Disable(ADC_HandleTypeDef * hadc)2817 HAL_StatusTypeDef ADC_Disable(ADC_HandleTypeDef *hadc)
2818 {
2819   uint32_t tickstart;
2820   const uint32_t tmp_adc_is_disable_on_going = LL_ADC_IsDisableOngoing(hadc->Instance);
2821 
2822   /* Verification if ADC is not already disabled:                             */
2823   /* Note: forbidden to disable ADC (set bit ADC_CR_ADDIS) if ADC is already  */
2824   /*       disabled.                                                          */
2825   if ((LL_ADC_IsEnabled(hadc->Instance) != 0UL)
2826       && (tmp_adc_is_disable_on_going == 0UL)
2827      )
2828   {
2829     /* Check if conditions to disable the ADC are fulfilled */
2830     if ((hadc->Instance->CR & (ADC_CR_ADSTART | ADC_CR_ADEN)) == ADC_CR_ADEN)
2831     {
2832       /* Disable the ADC peripheral */
2833       LL_ADC_Disable(hadc->Instance);
2834       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOSMP | ADC_FLAG_RDY));
2835     }
2836     else
2837     {
2838       /* Update ADC state machine to error */
2839       SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2840 
2841       /* Set ADC error code to ADC peripheral internal error */
2842       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2843 
2844       return HAL_ERROR;
2845     }
2846 
2847     /* Wait for ADC effectively disabled */
2848     /* Get tick count */
2849     tickstart = HAL_GetTick();
2850 
2851     while ((hadc->Instance->CR & ADC_CR_ADEN) != 0UL)
2852     {
2853       if ((HAL_GetTick() - tickstart) > ADC_DISABLE_TIMEOUT)
2854       {
2855         /* New check to avoid false timeout detection in case of preemption */
2856         if ((hadc->Instance->CR & ADC_CR_ADEN) != 0UL)
2857         {
2858           /* Update ADC state machine to error */
2859           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2860 
2861           /* Set ADC error code to ADC peripheral internal error */
2862           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2863 
2864           return HAL_ERROR;
2865         }
2866       }
2867     }
2868   }
2869 
2870   /* Return HAL status */
2871   return HAL_OK;
2872 }
2873 
2874 /**
2875   * @brief  DMA transfer complete callback.
2876   * @param hdma pointer to DMA handle.
2877   * @retval None
2878   */
ADC_DMAConvCplt(DMA_HandleTypeDef * hdma)2879 static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma)
2880 {
2881   /* Retrieve ADC handle corresponding to current DMA handle */
2882   ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
2883 
2884   /* Update state machine on conversion status if not in error state */
2885   if ((hadc->State & (HAL_ADC_STATE_ERROR_INTERNAL | HAL_ADC_STATE_ERROR_DMA)) == 0UL)
2886   {
2887     /* Set ADC state */
2888     SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
2889 
2890     /* Determine whether any further conversion upcoming on group regular     */
2891     /* by external trigger, continuous mode or scan sequence on going         */
2892     /* to disable interruption.                                               */
2893     if ((LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
2894         && (hadc->Init.ContinuousConvMode == DISABLE)
2895        )
2896     {
2897       /* If End of Sequence is reached, disable interrupts */
2898       if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS))
2899       {
2900         /* Allowed to modify bits ADC_IT_EOC/ADC_IT_EOS only if bit           */
2901         /* ADSTART==0 (no conversion on going)                                */
2902         if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
2903         {
2904           /* Disable ADC end of single conversion interrupt on group regular */
2905           /* Note: Overrun interrupt was enabled with EOC interrupt in        */
2906           /* HAL_Start_IT(), but is not disabled here because can be used     */
2907           /* by overrun IRQ process below.                                    */
2908           __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_EOS);
2909 
2910           /* Set ADC state */
2911           ADC_STATE_CLR_SET(hadc->State,
2912                             HAL_ADC_STATE_REG_BUSY,
2913                             HAL_ADC_STATE_READY);
2914         }
2915         else
2916         {
2917           /* Change ADC state to error state */
2918           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
2919 
2920           /* Set ADC error code to ADC peripheral internal error */
2921           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2922         }
2923       }
2924     }
2925 
2926     /* Conversion complete callback */
2927 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2928     hadc->ConvCpltCallback(hadc);
2929 #else
2930     HAL_ADC_ConvCpltCallback(hadc);
2931 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2932   }
2933   else /* DMA and-or internal error occurred */
2934   {
2935     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) != 0UL)
2936     {
2937       /* Call HAL ADC Error Callback function */
2938 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2939       hadc->ErrorCallback(hadc);
2940 #else
2941       HAL_ADC_ErrorCallback(hadc);
2942 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2943     }
2944     else
2945     {
2946       /* Call ADC DMA error callback */
2947       hadc->DMA_Handle->XferErrorCallback(hdma);
2948     }
2949   }
2950 }
2951 
2952 /**
2953   * @brief  DMA half transfer complete callback.
2954   * @param hdma pointer to DMA handle.
2955   * @retval None
2956   */
ADC_DMAHalfConvCplt(DMA_HandleTypeDef * hdma)2957 static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma)
2958 {
2959   /* Retrieve ADC handle corresponding to current DMA handle */
2960   ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
2961 
2962   /* Half conversion callback */
2963 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2964   hadc->ConvHalfCpltCallback(hadc);
2965 #else
2966   HAL_ADC_ConvHalfCpltCallback(hadc);
2967 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2968 }
2969 
2970 /**
2971   * @brief  DMA error callback.
2972   * @param hdma pointer to DMA handle.
2973   * @retval None
2974   */
ADC_DMAError(DMA_HandleTypeDef * hdma)2975 static void ADC_DMAError(DMA_HandleTypeDef *hdma)
2976 {
2977   /* Retrieve ADC handle corresponding to current DMA handle */
2978   ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
2979 
2980   /* Set ADC state */
2981   SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
2982 
2983   /* Set ADC error code to DMA error */
2984   SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_DMA);
2985 
2986   /* Error callback */
2987 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2988   hadc->ErrorCallback(hadc);
2989 #else
2990   HAL_ADC_ErrorCallback(hadc);
2991 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2992 }
2993 
2994 /**
2995   * @}
2996   */
2997 
2998 #endif /* HAL_ADC_MODULE_ENABLED */
2999 /**
3000   * @}
3001   */
3002 
3003 /**
3004   * @}
3005   */
3006