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