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