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