1 /**
2   ******************************************************************************
3   * @file    stm32n6xx_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   *          "stm32n6xx_hal_adc_ex.c".
13   *
14   ******************************************************************************
15   * @attention
16   *
17   * Copyright (c) 2023 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 (channel wise)
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   (+) Configurable delay between conversions in Dual interleaved mode.
48 
49   (+) ADC channels selectable single/differential input.
50 
51   (+) ADC offset shared on 4 offset instances.
52 
53   (+) ADC gain compensation
54 
55   (+) ADC calibration
56 
57   (+) ADC conversion of regular group.
58 
59   (+) ADC supply requirements: 1.62 V to 3.6 V.
60 
61   (+) ADC input range: from Vref- (connected to Vssa) to Vref+ (connected to
62       Vdda or to an external voltage reference).
63 
64 
65                      ##### How to use this driver #####
66   ==============================================================================
67     [..]
68 
69      *** Configuration of top level parameters related to ADC ***
70      ============================================================
71      [..]
72 
73     (#) Enable the ADC interface
74         (++) As prerequisite, ADC clock must be configured at RCC top level.
75 
76         (++) Two clock settings are mandatory:
77              (+++) ADC clock (core clock, also possibly conversion clock).
78 
79              (+++) ADC clock (conversions clock).
80                    Two possible clock sources: synchronous clock derived from AHB clock
81                    or asynchronous clock derived from system clock, PLL2 or PLL3.
82 
83              (+++) Example:
84                    Into HAL_ADC_MspInit() (recommended code location) or with
85                    other device clock parameters configuration:
86                (+++) __HAL_RCC_ADC_CLK_ENABLE();                  (mandatory)
87 
88                RCC_ADCCLKSOURCE_PLL2 enable:                   (optional: if asynchronous clock selected)
89                (+++) RCC_PeriphClkInitTypeDef   RCC_PeriphClkInit;
90                (+++) PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
91                (+++) PeriphClkInit.AdcClockSelection    = RCC_ADCCLKSOURCE_PLL2;
92                (+++) HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit);
93 
94         (++) ADC clock source and clock prescaler are configured at ADC level with
95              parameter "ClockPrescaler" using function HAL_ADC_Init().
96 
97     (#) ADC pins configuration
98          (++) Enable the clock for the ADC GPIOs
99               using macro __HAL_RCC_GPIOx_CLK_ENABLE()
100          (++) Configure these ADC pins in analog mode
101               using function HAL_GPIO_Init()
102 
103     (#) Optionally, in case of usage of ADC with interruptions:
104          (++) Configure the NVIC for ADC
105               using function HAL_NVIC_EnableIRQ(ADCx_IRQn)
106          (++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
107               into the function of corresponding ADC interruption vector
108               ADCx_IRQHandler().
109 
110     (#) Optionally, in case of usage of DMA:
111          (++) Configure the DMA (DMA channel, mode normal or circular, ...)
112               using function HAL_DMA_Init().
113          (++) Configure the NVIC for DMA
114               using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
115          (++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
116               into the function of corresponding DMA interruption vector
117               DMAx_Channelx_IRQHandler().
118 
119      *** Configuration of ADC, group regular, channels parameters ***
120      ================================================================
121      [..]
122 
123     (#) Configure the ADC parameters (resolution, data alignment, ...)
124         and regular group parameters (conversion trigger, sequencer, ...)
125         using function HAL_ADC_Init().
126 
127     (#) Configure the channels for regular group parameters (channel number,
128         channel rank into sequencer, ..., into regular group)
129         using function HAL_ADC_ConfigChannel().
130 
131     (#) Optionally, configure the analog watchdog parameters (channels
132         monitored, thresholds, ...)
133         using function HAL_ADC_AnalogWDGConfig().
134 
135      *** Execution of ADC conversions ***
136      ====================================
137      [..]
138 
139     (#) Optionally, perform an automatic ADC calibration to improve the
140         conversion accuracy
141         using function HAL_ADCEx_Calibration_Start().
142 
143     (#) ADC driver can be used among three modes: polling, interruption,
144         transfer by DMA.
145 
146         (++) ADC conversion by polling:
147           (+++) Activate the ADC peripheral and start conversions
148                 using function HAL_ADC_Start()
149           (+++) Wait for ADC conversion completion
150                 using function HAL_ADC_PollForConversion()
151           (+++) Retrieve conversion results
152                 using function HAL_ADC_GetValue()
153           (+++) Stop conversion and disable the ADC peripheral
154                 using function HAL_ADC_Stop()
155 
156         (++) ADC conversion by interruption:
157           (+++) Activate the ADC peripheral and start conversions
158                 using function HAL_ADC_Start_IT()
159           (+++) Wait for ADC conversion completion by call of function
160                 HAL_ADC_ConvCpltCallback()
161                 (this function must be implemented in user program)
162           (+++) Retrieve conversion results
163                 using function HAL_ADC_GetValue()
164           (+++) Stop conversion and disable the ADC peripheral
165                 using function HAL_ADC_Stop_IT()
166 
167         (++) ADC conversion with transfer by DMA:
168           (+++) Activate the ADC peripheral and start conversions
169                 using function HAL_ADC_Start_DMA()
170           (+++) Wait for ADC conversion completion by call of function
171                 HAL_ADC_ConvCpltCallback() or HAL_ADC_ConvHalfCpltCallback()
172                 (these functions must be implemented in user program)
173           (+++) Conversion results are automatically transferred by DMA into
174                 destination variable address.
175           (+++) Stop conversion and disable the ADC peripheral
176                 using function HAL_ADC_Stop_DMA()
177 
178      [..]
179 
180     (@) Callback functions must be implemented in user program:
181       (+@) HAL_ADC_ErrorCallback()
182       (+@) HAL_ADC_LevelOutOfWindowCallback() (callback of analog watchdog)
183       (+@) HAL_ADC_ConvCpltCallback()
184       (+@) HAL_ADC_ConvHalfCpltCallback
185 
186      *** Deinitialization of ADC ***
187      ============================================================
188      [..]
189 
190     (#) Disable the ADC interface
191       (++) ADC clock can be hard reset and disabled at RCC top level.
192         (++) Hard reset of ADC peripherals
193              using macro __HAL_RCC_ADCx_FORCE_RESET(), __HAL_RCC_ADCx_RELEASE_RESET().
194         (++) ADC clock disable
195              using the equivalent macro/functions as configuration step.
196              (+++) Example:
197                    Into HAL_ADC_MspDeInit() (recommended code location) or with
198                    other device clock parameters configuration:
199                (+++) __HAL_RCC_ADC_CLK_DISABLE();                  (if not used anymore)
200                RCC_ADCCLKSOURCE_CLKP restore:                      (optional)
201                (+++) RCC_PeriphClkInitTypeDef   RCC_PeriphClkInit;
202                (+++) PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
203                (+++) PeriphClkInit.AdcClockSelection    = RCC_ADCCLKSOURCE_CLKP;
204                (+++) HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit);
205 
206     (#) ADC pins configuration
207          (++) Disable the clock for the ADC GPIOs
208               using macro __HAL_RCC_GPIOx_CLK_DISABLE()
209 
210     (#) Optionally, in case of usage of ADC with interruptions:
211          (++) Disable the NVIC for ADC
212               using function HAL_NVIC_EnableIRQ(ADCx_IRQn)
213 
214     (#) Optionally, in case of usage of DMA:
215          (++) Deinitialize the DMA
216               using function HAL_DMA_Init().
217          (++) Disable the NVIC for DMA
218               using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
219 
220     [..]
221 
222     *** Callback registration ***
223     =============================================
224     [..]
225 
226      The compilation flag USE_HAL_ADC_REGISTER_CALLBACKS, when set to 1,
227      allows the user to configure dynamically the driver callbacks.
228      Use Functions @ref HAL_ADC_RegisterCallback()
229      to register an interrupt callback.
230     [..]
231 
232      Function @ref HAL_ADC_RegisterCallback() allows to register following callbacks:
233        (+) ConvCpltCallback               : ADC conversion complete callback
234        (+) ConvHalfCpltCallback           : ADC conversion DMA half-transfer callback
235        (+) LevelOutOfWindowCallback       : ADC analog watchdog 1 callback
236        (+) ErrorCallback                  : ADC error callback
237        (+) InjectedConvCpltCallback       : ADC group injected conversion complete callback
238        (+) LevelOutOfWindow2Callback      : ADC analog watchdog 2 callback
239        (+) LevelOutOfWindow3Callback      : ADC analog watchdog 3 callback
240        (+) EndOfSamplingCallback          : ADC end of sampling callback
241        (+) MspInitCallback                : ADC Msp Init callback
242        (+) MspDeInitCallback              : ADC Msp DeInit callback
243      This function takes as parameters the HAL peripheral handle, the Callback ID
244      and a pointer to the user callback function.
245     [..]
246 
247      Use function @ref HAL_ADC_UnRegisterCallback to reset a callback to the default
248      weak function.
249     [..]
250 
251      @ref HAL_ADC_UnRegisterCallback takes as parameters the HAL peripheral handle,
252      and the Callback ID.
253      This function allows to reset following callbacks:
254        (+) ConvCpltCallback               : ADC conversion complete callback
255        (+) ConvHalfCpltCallback           : ADC conversion DMA half-transfer callback
256        (+) LevelOutOfWindowCallback       : ADC analog watchdog 1 callback
257        (+) ErrorCallback                  : ADC error callback
258        (+) InjectedConvCpltCallback       : ADC group injected conversion complete callback
259        (+) LevelOutOfWindow2Callback      : ADC analog watchdog 2 callback
260        (+) LevelOutOfWindow3Callback      : ADC analog watchdog 3 callback
261        (+) EndOfSamplingCallback          : ADC end of sampling callback
262        (+) MspInitCallback                : ADC Msp Init callback
263        (+) MspDeInitCallback              : ADC Msp DeInit callback
264      [..]
265 
266      By default, after the @ref HAL_ADC_Init() and when the state is @ref HAL_ADC_STATE_RESET
267      all callbacks are set to the corresponding weak functions:
268      examples @ref HAL_ADC_ConvCpltCallback(), @ref HAL_ADC_ErrorCallback().
269      Exception done for MspInit and MspDeInit functions that are
270      reset to the legacy weak functions in the @ref HAL_ADC_Init()/ @ref HAL_ADC_DeInit() only when
271      these callbacks are null (not registered beforehand).
272     [..]
273 
274      If MspInit or MspDeInit are not null, the @ref HAL_ADC_Init()/ @ref HAL_ADC_DeInit()
275      keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state.
276      [..]
277 
278      Callbacks can be registered/unregistered in @ref HAL_ADC_STATE_READY state only.
279      Exception done MspInit/MspDeInit functions that can be registered/unregistered
280      in @ref HAL_ADC_STATE_READY or @ref HAL_ADC_STATE_RESET state,
281      thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit.
282     [..]
283 
284      Then, the user first registers the MspInit/MspDeInit user callbacks
285      using @ref HAL_ADC_RegisterCallback() before calling @ref HAL_ADC_DeInit()
286      or @ref HAL_ADC_Init() function.
287      [..]
288 
289      When the compilation flag USE_HAL_ADC_REGISTER_CALLBACKS is set to 0 or
290      not defined, the callback registration feature is not available and all callbacks
291      are set to the corresponding weak functions.
292 
293   @endverbatim
294   ******************************************************************************
295   */
296 
297 /* Includes ------------------------------------------------------------------*/
298 #include "stm32n6xx_hal.h"
299 
300 /** @addtogroup STM32N6xx_HAL_Driver
301   * @{
302   */
303 
304 /** @defgroup ADC ADC
305   * @brief ADC HAL module driver
306   * @{
307   */
308 
309 #ifdef HAL_ADC_MODULE_ENABLED
310 
311 /* Private typedef -----------------------------------------------------------*/
312 /* Private define ------------------------------------------------------------*/
313 
314 /** @defgroup ADC_Private_Constants ADC Private Constants
315   * @{
316   */
317 #define ADC_CFGR1_FIELDS_1                 ((uint32_t)(ADC_CFGR1_RES    |\
318                                                        ADC_CFGR1_CONT   | ADC_CFGR1_OVRMOD  |\
319                                                        ADC_CFGR1_DISCEN | ADC_CFGR1_DISCNUM |\
320                                                        ADC_CFGR1_EXTEN  | ADC_CFGR1_EXTSEL)) /*!< ADC_CFGR1 fields of
321                                            parameters that can be updated when no regular conversion is on-going */
322 
323 #define ADC_CFGR2_FIELDS                   ((uint32_t)(ADC_CFGR2_ROVSE | ADC_CFGR2_OVSR  |\
324                                                        ADC_CFGR2_OVSS | ADC_CFGR2_TROVS |\
325                                                        ADC_CFGR2_ROVSM))                     /*!< ADC_CFGR2 fields of
326                                            parameters that can be updated when no conversion (neither regular
327                                            nor injected) is on-going  */
328 
329 /* Timeout values for ADC operations (enable settling time,                   */
330 /*   disable settling time, ...).                                             */
331 /*   Values defined to be higher than worst cases: low clock frequency,       */
332 /*   maximum prescalers.                                                      */
333 #define ADC_ENABLE_TIMEOUT              (2UL)    /*!< ADC enable time-out value  */
334 #define ADC_DISABLE_TIMEOUT             (2UL)    /*!< ADC disable time-out value */
335 
336 /* Timeout to wait for current conversion on going to be completed.           */
337 /* Timeout fixed to longest ADC conversion possible, for 1 channel:           */
338 /*   - maximum sampling time (640.5 adc_clk)                                  */
339 /*   - ADC resolution (Tsar 12 bits= 12.5 adc_clk)                            */
340 /*   - System clock / ADC clock <= 4096 (hypothesis of maximum clock ratio)   */
341 /*   - ADC oversampling ratio 256                                             */
342 /*   Calculation: 653 * 4096 * 256 CPU clock cycles max                       */
343 /* Unit: cycles of CPU clock.                                                 */
344 #define ADC_CONVERSION_TIME_MAX_CPU_CYCLES (653UL * 4096UL * 256UL)  /*!< ADC conversion completion time-out value */
345 
346 #define ADC_LDO_RDY_TIMEOUT             (1UL) /* Note: Timeout value independent of ADC clock frequency, for more
347                                                        accurate value refer to LL_ADC_DELAY_INTERNAL_REGUL_STAB_US */
348 /**
349   * @}
350   */
351 
352 /* Private macro -------------------------------------------------------------*/
353 /* Private variables ---------------------------------------------------------*/
354 /* Private function prototypes -----------------------------------------------*/
355 /* Exported functions --------------------------------------------------------*/
356 
357 /** @defgroup ADC_Exported_Functions ADC Exported Functions
358   * @{
359   */
360 
361 /** @defgroup ADC_Exported_Functions_Group1 Initialization and de-initialization functions
362   * @brief    ADC Initialization and Configuration functions
363   *
364 @verbatim
365  ===============================================================================
366               ##### Initialization and de-initialization functions #####
367  ===============================================================================
368     [..]  This section provides functions allowing to:
369       (+) Initialize and configure the ADC.
370       (+) De-initialize the ADC.
371 @endverbatim
372   * @{
373   */
374 
375 /**
376   * @brief  Initialize the ADC peripheral and regular group according to
377   *         parameters specified in structure "ADC_InitTypeDef".
378   * @note   As prerequisite, ADC clock must be configured at RCC top level
379   *         (refer to description of RCC configuration for ADC
380   *         in header of this file).
381   * @note   Possibility to update parameters on the fly:
382   *         This function initializes the ADC MSP (HAL_ADC_MspInit()) only when
383   *         coming from ADC state reset. Following calls to this function can
384   *         be used to reconfigure some parameters of ADC_InitTypeDef
385   *         structure on the fly, without modifying MSP configuration. If ADC
386   *         MSP has to be modified again, HAL_ADC_DeInit() must be called
387   *         before HAL_ADC_Init().
388   *         The setting of these parameters is conditioned to ADC state.
389   *         For parameters constraints, see comments of structure
390   *         "ADC_InitTypeDef".
391   * @note   This function configures the ADC within 2 scopes: scope of entire
392   *         ADC and scope of regular group. For parameters details, see comments
393   *         of structure "ADC_InitTypeDef".
394   * @note   Parameters related to common ADC registers (ADC clock mode) are set
395   *         only if all ADCs are disabled.
396   *         If this is not the case, these common parameters setting are
397   *         bypassed without error reporting: it can be the intended behaviour in
398   *         case of update of a parameter of ADC_InitTypeDef on the fly,
399   *         without disabling the other ADCs sharing the same ADC common instance.
400   * @param hadc ADC handle
401   * @retval HAL status
402   */
HAL_ADC_Init(ADC_HandleTypeDef * hadc)403 HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef *hadc)
404 {
405   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
406   uint32_t tmpCFGR1;
407   uint32_t tmp_adc_reg_is_conversion_on_going;
408   uint32_t tmp_adc_is_conversion_on_going_regular;
409   uint32_t tmp_adc_is_conversion_on_going_injected;
410 
411   /* Check ADC handle */
412   if (hadc == NULL)
413   {
414     return HAL_ERROR;
415   }
416 
417   /* Check the parameters */
418   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
419   assert_param(IS_ADC_RESOLUTION(hadc->Init.Resolution));
420   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
421   assert_param(IS_ADC_EXTTRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
422   assert_param(IS_ADC_SCAN_MODE(hadc->Init.ScanConvMode));
423   assert_param(IS_ADC_GAIN_COMPENSATION(hadc->Init.GainCompensation));
424   assert_param(IS_ADC_SAMPLINGMODE(hadc->Init.SamplingMode));
425   assert_param(IS_ADC_CONVERSIONDATAMGT(hadc->Init.ConversionDataManagement));
426   assert_param(IS_ADC_EXTTRIG(hadc->Instance, hadc->Init.ExternalTrigConv));
427   assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection));
428   assert_param(IS_ADC_OVERRUN(hadc->Init.Overrun));
429   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerAutoWait));
430   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.OversamplingMode));
431 
432   if (hadc->Init.ScanConvMode != ADC_SCAN_DISABLE)
433   {
434     assert_param(IS_ADC_REGULAR_NB_CONV(hadc->Init.NbrOfConversion));
435     assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DiscontinuousConvMode));
436 
437     if (hadc->Init.DiscontinuousConvMode == ENABLE)
438     {
439       assert_param(IS_ADC_REGULAR_DISCONT_NUMBER(hadc->Init.NbrOfDiscConversion));
440     }
441   }
442 
443   /* DISCEN and CONT bits cannot be set at the same time */
444   assert_param(!((hadc->Init.DiscontinuousConvMode == ENABLE) && (hadc->Init.ContinuousConvMode == ENABLE)));
445 
446   /* Actions performed only if ADC is coming from state reset:                */
447   /* - Initialization of ADC MSP                                              */
448   if (hadc->State == HAL_ADC_STATE_RESET)
449   {
450 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
451     /* Init the ADC Callback settings */
452     hadc->ConvCpltCallback              = HAL_ADC_ConvCpltCallback;                 /* Legacy weak callback */
453     hadc->ConvHalfCpltCallback          = HAL_ADC_ConvHalfCpltCallback;             /* Legacy weak callback */
454     hadc->LevelOutOfWindowCallback      = HAL_ADC_LevelOutOfWindowCallback;         /* Legacy weak callback */
455     hadc->ErrorCallback                 = HAL_ADC_ErrorCallback;                    /* Legacy weak callback */
456     hadc->InjectedConvCpltCallback      = HAL_ADCEx_InjectedConvCpltCallback;       /* Legacy weak callback */
457     hadc->LevelOutOfWindow2Callback     = HAL_ADCEx_LevelOutOfWindow2Callback;      /* Legacy weak callback */
458     hadc->LevelOutOfWindow3Callback     = HAL_ADCEx_LevelOutOfWindow3Callback;      /* Legacy weak callback */
459     hadc->EndOfSamplingCallback         = HAL_ADCEx_EndOfSamplingCallback;          /* Legacy weak callback */
460 
461     if (hadc->MspInitCallback == NULL)
462     {
463       hadc->MspInitCallback = HAL_ADC_MspInit; /* Legacy weak MspInit  */
464     }
465 
466     /* Init the low level hardware */
467     hadc->MspInitCallback(hadc);
468 #else
469     /* Init the low level hardware */
470     HAL_ADC_MspInit(hadc);
471 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
472 
473     /* Set ADC error code to none */
474     ADC_CLEAR_ERRORCODE(hadc);
475 
476     /* Initialize Lock */
477     hadc->Lock = HAL_UNLOCKED;
478   }
479 
480   /* ADC must be disabled to set configuration bits                            */
481   if (LL_ADC_IsEnabled(hadc->Instance) != 0UL)
482   {
483     return HAL_ERROR;
484   }
485 
486   /* - Exit from deep-power-down mode and ADC voltage regulator enable        */
487   if (LL_ADC_IsDeepPowerDownEnabled(hadc->Instance) != 0UL)
488   {
489     /* Disable ADC deep power down mode */
490     LL_ADC_DisableDeepPowerDown(hadc->Instance);
491 
492     /* System was in deep power down mode, calibration must
493      be relaunched or a previously saved calibration factor
494      re-applied once the ADC voltage regulator is enabled */
495   }
496   /* Configuration of ADC parameters if previous preliminary actions are      */
497   /* correctly completed and if there is no conversion on going on regular    */
498   /* group (ADC may already be enabled at this point if HAL_ADC_Init() is     */
499   /* called to update a parameter on the fly).                                */
500   tmp_adc_reg_is_conversion_on_going = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
501 
502   if (((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
503       && (tmp_adc_reg_is_conversion_on_going == 0UL)
504      )
505   {
506     /* Set ADC state */
507     ADC_STATE_CLR_SET(hadc->State,
508                       HAL_ADC_STATE_REG_BUSY,
509                       HAL_ADC_STATE_BUSY_INTERNAL);
510 
511     /* Configuration of common ADC parameters                                 */
512     /* (None) */
513 
514     /* Configuration of ADC instance:                                         */
515     /*  - resolution                               Init.Resolution            */
516     /*  - external trigger to start conversion     Init.ExternalTrigConv      */
517     /*  - external trigger polarity                Init.ExternalTrigConvEdge  */
518     /*  - continuous conversion mode               Init.ContinuousConvMode    */
519     /*  - overrun                                  Init.Overrun               */
520     /*  - discontinuous mode                       Init.DiscontinuousConvMode */
521     /*  - discontinuous mode channel count         Init.NbrOfDiscConversion   */
522 
523     tmpCFGR1 = (ADC_CFGR1_CONTINUOUS((uint32_t)hadc->Init.ContinuousConvMode)         |
524                 hadc->Init.Overrun                                                    |
525                 hadc->Init.Resolution                                                 |
526                 ADC_CFGR1_REG_DISCONTINUOUS((uint32_t)hadc->Init.DiscontinuousConvMode));
527 
528     if (hadc->Init.DiscontinuousConvMode == ENABLE)
529     {
530       tmpCFGR1 |= ADC_CFGR1_DISCONTINUOUS_NUM(hadc->Init.NbrOfDiscConversion);
531     }
532 
533     /* Enable external trigger if trigger selection is different of software  */
534     /* start.                                                                 */
535     /* Note: This configuration keeps the hardware feature of parameter       */
536     /*       ExternalTrigConvEdge "trigger edge none" equivalent to           */
537     /*       software start.                                                  */
538     if (hadc->Init.ExternalTrigConv != ADC_SOFTWARE_START)
539     {
540       tmpCFGR1 |= ((hadc->Init.ExternalTrigConv & ADC_CFGR1_EXTSEL)
541                    | hadc->Init.ExternalTrigConvEdge
542                   );
543     }
544 
545     /* Update Configuration Register CFGR */
546     MODIFY_REG(hadc->Instance->CFGR1, ADC_CFGR1_FIELDS_1, tmpCFGR1);
547 
548     /* Configuration of sampling mode */
549     MODIFY_REG(hadc->Instance->CFGR2, ADC_CFGR2_BULB | ADC_CFGR2_SMPTRIG, hadc->Init.SamplingMode);
550 
551     /* Parameters update conditioned to ADC state:                            */
552     /* Parameters that can be updated when ADC is disabled or enabled without */
553     /* conversion on going on regular and injected groups:                    */
554     /*  - Conversion data management      Init.ConversionDataManagement       */
555     /*  - LowPowerAutoWait feature        Init.LowPowerAutoWait               */
556     /*  - Oversampling parameters         Init.Oversampling                   */
557     tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
558     tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
559     if ((tmp_adc_is_conversion_on_going_regular == 0UL)
560         && (tmp_adc_is_conversion_on_going_injected == 0UL)
561        )
562     {
563       tmpCFGR1 = (
564                    ADC_CFGR1_AUTODELAY((uint32_t)hadc->Init.LowPowerAutoWait)        |
565                    ADC_CFGR1_DMACONTREQ((uint32_t)hadc->Init.ConversionDataManagement));
566 
567       MODIFY_REG(hadc->Instance->CFGR1, ADC_CFGR1_FIELDS_2, tmpCFGR1);
568 
569       LL_ADC_SetGainCompensation(hadc->Instance, hadc->Init.GainCompensation);
570 
571       if (hadc->Init.OversamplingMode == ENABLE)
572       {
573         assert_param(IS_ADC_OVERSAMPLING_RATIO(hadc->Init.Oversampling.Ratio));
574         assert_param(IS_ADC_RIGHT_BIT_SHIFT(hadc->Init.Oversampling.RightBitShift));
575         assert_param(IS_ADC_TRIGGERED_OVERSAMPLING_MODE(hadc->Init.Oversampling.TriggeredMode));
576         assert_param(IS_ADC_REGOVERSAMPLING_MODE(hadc->Init.Oversampling.OversamplingStopReset));
577 
578         if ((hadc->Init.ExternalTrigConv == ADC_SOFTWARE_START)
579             || (hadc->Init.ExternalTrigConvEdge == ADC_EXTERNALTRIGCONVEDGE_NONE))
580         {
581           /* Multi trigger is not applicable to software-triggered conversions */
582           assert_param((hadc->Init.Oversampling.TriggeredMode == ADC_TRIGGEREDMODE_SINGLE_TRIGGER));
583         }
584 
585         /* Configuration of Oversampler:                                       */
586         /*  - Oversampling Ratio                                               */
587         /*  - Right bit shift                                                  */
588         /*  - Left bit shift                                                   */
589         /*  - Triggered mode                                                   */
590         /*  - Oversampling mode (continued/resumed)                            */
591         MODIFY_REG(hadc->Instance->CFGR2, ADC_CFGR2_FIELDS,
592                    ADC_CFGR2_ROVSE                       |
593                    ((hadc->Init.Oversampling.Ratio - 1UL)  << ADC_CFGR2_OVSR_Pos) |
594                    hadc->Init.Oversampling.RightBitShift |
595                    hadc->Init.Oversampling.TriggeredMode |
596                    hadc->Init.Oversampling.OversamplingStopReset);
597 
598       }
599       else
600       {
601         /* Disable ADC oversampling scope on ADC group regular */
602         CLEAR_BIT(hadc->Instance->CFGR2, ADC_CFGR2_ROVSE);
603       }
604 
605       /* Set the LeftShift parameter: it is applied to the final result with or without oversampling */
606       MODIFY_REG(hadc->Instance->CFGR2, ADC_CFGR2_LSHIFT, hadc->Init.LeftBitShift);
607     }
608 
609     /* Configuration of regular group sequencer:                              */
610     /* - if scan mode is disabled, regular channels sequence length is set to */
611     /*   0x00: 1 channel converted (channel on regular rank 1)                */
612     /*   Parameter "NbrOfConversion" is discarded.                            */
613     /*   Note: Scan mode is not present by hardware on this device, but       */
614     /*   emulated by software for alignment over all STM32 devices.           */
615     /* - if scan mode is enabled, regular channels sequence length is set to  */
616     /*   parameter "NbrOfConversion".                                         */
617 
618     if (hadc->Init.ScanConvMode == ADC_SCAN_ENABLE)
619     {
620       /* Set number of ranks in regular group sequencer */
621       MODIFY_REG(hadc->Instance->SQR1, ADC_SQR1_L, (hadc->Init.NbrOfConversion - (uint8_t)1));
622     }
623     else
624     {
625       CLEAR_BIT(hadc->Instance->SQR1, ADC_SQR1_L);
626     }
627 
628     /* Initialize the ADC state */
629     /* Clear HAL_ADC_STATE_BUSY_INTERNAL bit, set HAL_ADC_STATE_READY bit */
630     ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL, HAL_ADC_STATE_READY);
631   }
632   else
633   {
634     /* Update ADC state machine to error */
635     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
636 
637     tmp_hal_status = HAL_ERROR;
638   }
639 
640   return tmp_hal_status;
641 }
642 
643 /**
644   * @brief  Deinitialize the ADC peripheral registers to their default reset
645   *         values, with deinitialization of the ADC MSP.
646   * @note   For devices with several ADCs: reset of ADC common registers is done
647   *         only if all ADCs sharing the same common group are disabled.
648   *         (function "HAL_ADC_MspDeInit()" is also called under the same conditions:
649   *         all ADC instances use the same core clock at RCC level, disabling
650   *         the core clock reset all ADC instances).
651   *         If this is not the case, reset of these common parameters reset is
652   *         bypassed without error reporting: it can be the intended behavior in
653   *         case of reset of a single ADC while the other ADCs sharing the same
654   *         common group is still running.
655   * @note   By default, HAL_ADC_DeInit() set ADC in mode deep power-down:
656   *         this saves more power by reducing leakage currents
657   *         and is particularly interesting before entering MCU low-power modes.
658   * @param hadc ADC handle
659   * @retval HAL status
660   */
HAL_ADC_DeInit(ADC_HandleTypeDef * hadc)661 HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc)
662 {
663   HAL_StatusTypeDef tmp_hal_status;
664 
665   /* Check ADC handle */
666   if (hadc == NULL)
667   {
668     return HAL_ERROR;
669   }
670 
671   /* Check the parameters */
672   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
673 
674   /* Set ADC state */
675   SET_BIT(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL);
676 
677   /* Stop potential conversion on going */
678   tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_INJECTED_GROUP);
679 
680   /* Disable ADC peripheral if conversions are effectively stopped */
681   if (tmp_hal_status == HAL_OK)
682   {
683     /* Disable the ADC peripheral */
684     tmp_hal_status = ADC_Disable(hadc);
685 
686     /* Check if ADC is effectively disabled */
687     if (tmp_hal_status == HAL_OK)
688     {
689       /* Change ADC state */
690       hadc->State = HAL_ADC_STATE_READY;
691     }
692   }
693 
694   /* Enable ADC deep power down mode */
695   LL_ADC_EnableDeepPowerDown(hadc->Instance);
696 
697   /* Note: HAL ADC deInit is done independently of ADC conversion stop        */
698   /*       and disable return status. In case of status fail, attempt to      */
699   /*       perform deinitialization anyway and it is up user code in          */
700   /*       in HAL_ADC_MspDeInit() to reset the ADC peripheral using           */
701   /*       system RCC hard reset.                                             */
702 
703   /* ========== Reset ADC registers ========== */
704   /* Reset register IER */
705   __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_AWD3  | ADC_IT_AWD2 | ADC_IT_AWD1 |
706                               ADC_IT_OVR   |
707                               ADC_IT_JEOS  | ADC_IT_JEOC |
708                               ADC_IT_EOS   | ADC_IT_EOC  |
709                               ADC_IT_EOSMP | ADC_IT_RDY));
710 
711   /* Reset register ISR */
712   __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD3  | ADC_FLAG_AWD2 | ADC_FLAG_AWD1 |
713                               ADC_FLAG_OVR   |
714                               ADC_FLAG_JEOS  | ADC_FLAG_JEOC |
715                               ADC_FLAG_EOS   | ADC_FLAG_EOC  |
716                               ADC_FLAG_EOSMP | ADC_FLAG_RDY));
717 
718   /* Reset register CR */
719   /* Bits ADC_CR_JADSTP, ADC_CR_ADSTP, ADC_CR_JADSTART, ADC_CR_ADSTART,
720      ADC_CR_ADCAL, ADC_CR_ADDIS and ADC_CR_ADEN are in access mode "read-set":
721      no direct reset applicable.
722      Update CR register to reset value where doable by software */
723   CLEAR_BIT(hadc->Instance->CR, ADC_CR_ADCALDIF);
724   SET_BIT(hadc->Instance->CR, ADC_CR_DEEPPWD);
725 
726   /* Reset register CFGR1 */
727   CLEAR_BIT(hadc->Instance->CFGR1, ADC_CFGR1_AWD1CH  | ADC_CFGR1_JAUTO |
728             ADC_CFGR1_JAWD1EN | ADC_CFGR1_AWD1EN  | ADC_CFGR1_AWD1SGL | ADC_CFGR1_JDISCEN |
729             ADC_CFGR1_DISCNUM | ADC_CFGR1_DISCEN  | ADC_CFGR1_AUTDLY  |
730             ADC_CFGR1_CONT    | ADC_CFGR1_OVRMOD  |
731             ADC_CFGR1_EXTEN   | ADC_CFGR1_EXTSEL  |
732             ADC_CFGR1_RES     | ADC_CFGR1_DMNGT);
733 
734   /* Reset register CFGR2 */
735   CLEAR_BIT(hadc->Instance->CFGR2, ADC_CFGR2_SMPTRIG |
736             ADC_CFGR2_SWTRIG  | ADC_CFGR2_BULB  |
737             ADC_CFGR2_ROVSM   | ADC_CFGR2_TROVS | ADC_CFGR2_OVSS |
738             ADC_CFGR2_OVSR    | ADC_CFGR2_JOVSE | ADC_CFGR2_ROVSE);
739 
740   /* Reset register SMPR1 */
741   CLEAR_BIT(hadc->Instance->SMPR1, ADC_SMPR1_FIELDS);
742 
743   /* Reset register SMPR2 */
744   CLEAR_BIT(hadc->Instance->SMPR2,
745             ADC_SMPR2_SMP18 | ADC_SMPR2_SMP17 | ADC_SMPR2_SMP16 |
746             ADC_SMPR2_SMP15 | ADC_SMPR2_SMP14 | ADC_SMPR2_SMP13 |
747             ADC_SMPR2_SMP12 | ADC_SMPR2_SMP11 | ADC_SMPR2_SMP10);
748 
749   /* Reset registers of AWD1 thresholds */
750   CLEAR_BIT(hadc->Instance->AWD1LTR, ADC_AWD1LTR_LTR);
751   SET_BIT(hadc->Instance->AWD1HTR, ADC_AWD1HTR_HTR);
752 
753   /* Reset registers of AWD2 thresholds */
754   CLEAR_BIT(hadc->Instance->AWD2LTR, ADC_AWD2LTR_LTR);
755   SET_BIT(hadc->Instance->AWD2HTR, ADC_AWD2HTR_HTR);
756 
757   /* Reset registers of AWD3 thresholds */
758   CLEAR_BIT(hadc->Instance->AWD3LTR, ADC_AWD3LTR_LTR);
759   SET_BIT(hadc->Instance->AWD3HTR, ADC_AWD3HTR_HTR);
760 
761   /* Reset register SQR1 */
762   CLEAR_BIT(hadc->Instance->SQR1, ADC_SQR1_SQ4 | ADC_SQR1_SQ3 | ADC_SQR1_SQ2 |
763             ADC_SQR1_SQ1 | ADC_SQR1_L);
764 
765   /* Reset register SQR2 */
766   CLEAR_BIT(hadc->Instance->SQR2, ADC_SQR2_SQ9 | ADC_SQR2_SQ8 | ADC_SQR2_SQ7 |
767             ADC_SQR2_SQ6 | ADC_SQR2_SQ5);
768 
769   /* Reset register SQR3 */
770   CLEAR_BIT(hadc->Instance->SQR3, ADC_SQR3_SQ14 | ADC_SQR3_SQ13 | ADC_SQR3_SQ12 |
771             ADC_SQR3_SQ11 | ADC_SQR3_SQ10);
772 
773   /* Reset register SQR4 */
774   CLEAR_BIT(hadc->Instance->SQR4, ADC_SQR4_SQ16 | ADC_SQR4_SQ15);
775 
776   /* Register JSQR was reset when the ADC was disabled */
777 
778   /* Reset register DR */
779   /* bits in access mode read only, no direct reset applicable*/
780 
781   /* Reset register OFR1 */
782   CLEAR_BIT(hadc->Instance->OFCFGR1, ADC_OFCFGR1_SSAT | ADC_OFCFGR1_OFFSET_CH);
783   CLEAR_BIT(hadc->Instance->OFR1, ADC_OFR1_OFFSET);
784   /* Reset register OFR2 */
785   CLEAR_BIT(hadc->Instance->OFCFGR2, ADC_OFCFGR2_SSAT | ADC_OFCFGR2_OFFSET_CH);
786   CLEAR_BIT(hadc->Instance->OFR2, ADC_OFR2_OFFSET);
787   /* Reset register OFR3 */
788   CLEAR_BIT(hadc->Instance->OFCFGR3, ADC_OFCFGR3_SSAT | ADC_OFCFGR3_OFFSET_CH);
789   CLEAR_BIT(hadc->Instance->OFR3, ADC_OFR3_OFFSET);
790   /* Reset register OFR4 */
791   CLEAR_BIT(hadc->Instance->OFCFGR4, ADC_OFCFGR4_SSAT | ADC_OFCFGR4_OFFSET_CH);
792   CLEAR_BIT(hadc->Instance->OFR4, ADC_OFR4_OFFSET);
793 
794   /* Reset register GCOMP */
795   CLEAR_BIT(hadc->Instance->GCOMP, ADC_GCOMP_GCOMP | ADC_GCOMP_GCOMPCOEFF);
796 
797   /* Reset registers JDR1, JDR2, JDR3, JDR4 */
798   /* bits in access mode read only, no direct reset applicable*/
799 
800   /* Reset register AWD2CR */
801   CLEAR_BIT(hadc->Instance->AWD2CR, ADC_AWD2CR_AWD2CH);
802 
803   /* Reset register AWD3CR */
804   CLEAR_BIT(hadc->Instance->AWD3CR, ADC_AWD3CR_AWD3CH);
805 
806   /* Reset register DIFSEL */
807   CLEAR_BIT(hadc->Instance->DIFSEL, ADC_DIFSEL_DIFSEL);
808 
809   /* Reset register PCSEL */
810   CLEAR_BIT(hadc->Instance->PCSEL, ADC_PCSEL_PCSEL);
811 
812   /* Reset register CALFACT */
813   CLEAR_BIT(hadc->Instance->CALFACT, ADC_CALFACT_CALFACT_D | ADC_CALFACT_CALFACT_S);
814 
815 
816   /* ========== Reset common ADC registers ========== */
817 
818   /* Software is allowed to change common parameters only when all the other
819      ADCs are disabled.   */
820   if (__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) == 0UL)
821   {
822     /* Reset configuration of ADC common register CCR:
823       - clock mode: CKMODE, PRESCEN
824       - multimode related parameters (when this feature is available): MDMA,
825         DMACFG, DELAY, DUAL (set by HAL_ADCEx_MultiModeConfigChannel() API)
826       - internal measurement paths: Vbat, temperature sensor, Vref (set into
827         HAL_ADC_ConfigChannel() or HAL_ADCEx_InjectedConfigChannel() )
828     */
829     ADC_CLEAR_COMMON_CONTROL_REGISTER(hadc);
830   }
831 
832   /* ========== Hard reset ADC peripheral ========== */
833   /* Performs a global reset of the entire ADC peripherals instances        */
834   /* sharing the same common ADC instance: ADC state is forced to           */
835   /* a similar state as after device power-on.                              */
836   /* Note: A possible implementation is to add RCC bus reset of ADC         */
837   /* (for example, using macro                                              */
838   /*  __HAL_RCC_ADC..._FORCE_RESET()/..._RELEASE_RESET()/..._CLK_DISABLE()) */
839   /* in function "void HAL_ADC_MspDeInit(ADC_HandleTypeDef *hadc)":         */
840 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
841   if (hadc->MspDeInitCallback == NULL)
842   {
843     hadc->MspDeInitCallback = HAL_ADC_MspDeInit; /* Legacy weak MspDeInit  */
844   }
845 
846   /* DeInit the low level hardware */
847   hadc->MspDeInitCallback(hadc);
848 #else
849   /* DeInit the low level hardware */
850   HAL_ADC_MspDeInit(hadc);
851 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
852 
853   /* Set ADC error code to none */
854   ADC_CLEAR_ERRORCODE(hadc);
855 
856   /* Set ADC state */
857   hadc->State = HAL_ADC_STATE_RESET;
858 
859   return tmp_hal_status;
860 }
861 
862 /**
863   * @brief  Initialize the ADC MSP.
864   * @param hadc ADC handle
865   * @retval None
866   */
HAL_ADC_MspInit(ADC_HandleTypeDef * hadc)867 __weak void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc)
868 {
869   /* Prevent unused argument(s) compilation warning */
870   UNUSED(hadc);
871 
872   /* NOTE : This function should not be modified. When the callback is needed,
873             function HAL_ADC_MspInit must be implemented in the user file.
874    */
875 }
876 
877 /**
878   * @brief  DeInitialize the ADC MSP.
879   * @param hadc ADC handle
880   * @note   All ADC instances use the same core clock at RCC level, disabling
881   *         the core clock reset all ADC instances).
882   * @retval None
883   */
HAL_ADC_MspDeInit(ADC_HandleTypeDef * hadc)884 __weak void HAL_ADC_MspDeInit(ADC_HandleTypeDef *hadc)
885 {
886   /* Prevent unused argument(s) compilation warning */
887   UNUSED(hadc);
888 
889   /* NOTE : This function should not be modified. When the callback is needed,
890             function HAL_ADC_MspDeInit must be implemented in the user file.
891    */
892 }
893 
894 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
895 /**
896   * @brief  Register a User ADC Callback
897   *         To be used instead of the weak predefined callback
898   * @param  hadc Pointer to a ADC_HandleTypeDef structure that contains
899   *                the configuration information for the specified ADC.
900   * @param  CallbackID ID of the callback to be registered
901   *         This parameter can be one of the following values:
902   *          @arg @ref HAL_ADC_CONVERSION_COMPLETE_CB_ID      ADC conversion complete callback ID
903   *          @arg @ref HAL_ADC_CONVERSION_HALF_CB_ID          ADC conversion DMA half-transfer callback ID
904   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID    ADC analog watchdog 1 callback ID
905   *          @arg @ref HAL_ADC_ERROR_CB_ID                    ADC error callback ID
906   *          @arg @ref HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID  ADC group injected conversion complete callback ID
907   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID    ADC analog watchdog 2 callback ID
908   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID    ADC analog watchdog 3 callback ID
909   *          @arg @ref HAL_ADC_END_OF_SAMPLING_CB_ID          ADC end of sampling callback ID
910   *          @arg @ref HAL_ADC_MSPINIT_CB_ID                  ADC Msp Init callback ID
911   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID                ADC Msp DeInit callback ID
912   *          @arg @ref HAL_ADC_MSPINIT_CB_ID MspInit callback ID
913   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID MspDeInit callback ID
914   * @param  pCallback pointer to the Callback function
915   * @retval HAL status
916   */
HAL_ADC_RegisterCallback(ADC_HandleTypeDef * hadc,HAL_ADC_CallbackIDTypeDef CallbackID,pADC_CallbackTypeDef pCallback)917 HAL_StatusTypeDef HAL_ADC_RegisterCallback(ADC_HandleTypeDef *hadc, HAL_ADC_CallbackIDTypeDef CallbackID,
918                                            pADC_CallbackTypeDef pCallback)
919 {
920   HAL_StatusTypeDef status = HAL_OK;
921 
922   if (pCallback == NULL)
923   {
924     /* Update the error code */
925     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
926 
927     return HAL_ERROR;
928   }
929 
930   if ((hadc->State & HAL_ADC_STATE_READY) != 0UL)
931   {
932     switch (CallbackID)
933     {
934       case HAL_ADC_CONVERSION_COMPLETE_CB_ID :
935         hadc->ConvCpltCallback = pCallback;
936         break;
937 
938       case HAL_ADC_CONVERSION_HALF_CB_ID :
939         hadc->ConvHalfCpltCallback = pCallback;
940         break;
941 
942       case HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID :
943         hadc->LevelOutOfWindowCallback = pCallback;
944         break;
945 
946       case HAL_ADC_ERROR_CB_ID :
947         hadc->ErrorCallback = pCallback;
948         break;
949 
950       case HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID :
951         hadc->InjectedConvCpltCallback = pCallback;
952         break;
953 
954       case HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID :
955         hadc->LevelOutOfWindow2Callback = pCallback;
956         break;
957 
958       case HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID :
959         hadc->LevelOutOfWindow3Callback = pCallback;
960         break;
961 
962       case HAL_ADC_END_OF_SAMPLING_CB_ID :
963         hadc->EndOfSamplingCallback = pCallback;
964         break;
965 
966       case HAL_ADC_MSPINIT_CB_ID :
967         hadc->MspInitCallback = pCallback;
968         break;
969 
970       case HAL_ADC_MSPDEINIT_CB_ID :
971         hadc->MspDeInitCallback = pCallback;
972         break;
973 
974       default :
975         /* Update the error code */
976         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
977 
978         /* Return error status */
979         status = HAL_ERROR;
980         break;
981     }
982   }
983   else if (HAL_ADC_STATE_RESET == hadc->State)
984   {
985     switch (CallbackID)
986     {
987       case HAL_ADC_MSPINIT_CB_ID :
988         hadc->MspInitCallback = pCallback;
989         break;
990 
991       case HAL_ADC_MSPDEINIT_CB_ID :
992         hadc->MspDeInitCallback = pCallback;
993         break;
994 
995       default :
996         /* Update the error code */
997         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
998 
999         /* Return error status */
1000         status = HAL_ERROR;
1001         break;
1002     }
1003   }
1004   else
1005   {
1006     /* Update the error code */
1007     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1008 
1009     /* Return error status */
1010     status =  HAL_ERROR;
1011   }
1012 
1013   return status;
1014 }
1015 
1016 /**
1017   * @brief  Unregister a ADC Callback
1018   *         ADC callback is redirected to the weak predefined callback
1019   * @param  hadc Pointer to a ADC_HandleTypeDef structure that contains
1020   *                the configuration information for the specified ADC.
1021   * @param  CallbackID ID of the callback to be unregistered
1022   *         This parameter can be one of the following values:
1023   *          @arg @ref HAL_ADC_CONVERSION_COMPLETE_CB_ID      ADC conversion complete callback ID
1024   *          @arg @ref HAL_ADC_CONVERSION_HALF_CB_ID          ADC conversion DMA half-transfer callback ID
1025   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID    ADC analog watchdog 1 callback ID
1026   *          @arg @ref HAL_ADC_ERROR_CB_ID                    ADC error callback ID
1027   *          @arg @ref HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID  ADC group injected conversion complete callback ID
1028   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID    ADC analog watchdog 2 callback ID
1029   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID    ADC analog watchdog 3 callback ID
1030   *          @arg @ref HAL_ADC_END_OF_SAMPLING_CB_ID          ADC end of sampling callback ID
1031   *          @arg @ref HAL_ADC_MSPINIT_CB_ID                  ADC Msp Init callback ID
1032   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID                ADC Msp DeInit callback ID
1033   *          @arg @ref HAL_ADC_MSPINIT_CB_ID MspInit callback ID
1034   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID MspDeInit callback ID
1035   * @retval HAL status
1036   */
HAL_ADC_UnRegisterCallback(ADC_HandleTypeDef * hadc,HAL_ADC_CallbackIDTypeDef CallbackID)1037 HAL_StatusTypeDef HAL_ADC_UnRegisterCallback(ADC_HandleTypeDef *hadc, HAL_ADC_CallbackIDTypeDef CallbackID)
1038 {
1039   HAL_StatusTypeDef status = HAL_OK;
1040 
1041   if ((hadc->State & HAL_ADC_STATE_READY) != 0UL)
1042   {
1043     switch (CallbackID)
1044     {
1045       case HAL_ADC_CONVERSION_COMPLETE_CB_ID :
1046         hadc->ConvCpltCallback = HAL_ADC_ConvCpltCallback;
1047         break;
1048 
1049       case HAL_ADC_CONVERSION_HALF_CB_ID :
1050         hadc->ConvHalfCpltCallback = HAL_ADC_ConvHalfCpltCallback;
1051         break;
1052 
1053       case HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID :
1054         hadc->LevelOutOfWindowCallback = HAL_ADC_LevelOutOfWindowCallback;
1055         break;
1056 
1057       case HAL_ADC_ERROR_CB_ID :
1058         hadc->ErrorCallback = HAL_ADC_ErrorCallback;
1059         break;
1060 
1061       case HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID :
1062         hadc->InjectedConvCpltCallback = HAL_ADCEx_InjectedConvCpltCallback;
1063         break;
1064 
1065       case HAL_ADC_LEVEL_OUT_OF_WINDOW_2_CB_ID :
1066         hadc->LevelOutOfWindow2Callback = HAL_ADCEx_LevelOutOfWindow2Callback;
1067         break;
1068 
1069       case HAL_ADC_LEVEL_OUT_OF_WINDOW_3_CB_ID :
1070         hadc->LevelOutOfWindow3Callback = HAL_ADCEx_LevelOutOfWindow3Callback;
1071         break;
1072 
1073       case HAL_ADC_END_OF_SAMPLING_CB_ID :
1074         hadc->EndOfSamplingCallback = HAL_ADCEx_EndOfSamplingCallback;
1075         break;
1076 
1077       case HAL_ADC_MSPINIT_CB_ID :
1078         hadc->MspInitCallback = HAL_ADC_MspInit; /* Legacy weak MspInit              */
1079         break;
1080 
1081       case HAL_ADC_MSPDEINIT_CB_ID :
1082         hadc->MspDeInitCallback = HAL_ADC_MspDeInit; /* Legacy weak MspDeInit            */
1083         break;
1084 
1085       default :
1086         /* Update the error code */
1087         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1088 
1089         /* Return error status */
1090         status =  HAL_ERROR;
1091         break;
1092     }
1093   }
1094   else if (HAL_ADC_STATE_RESET == hadc->State)
1095   {
1096     switch (CallbackID)
1097     {
1098       case HAL_ADC_MSPINIT_CB_ID :
1099         hadc->MspInitCallback = HAL_ADC_MspInit;                   /* Legacy weak MspInit              */
1100         break;
1101 
1102       case HAL_ADC_MSPDEINIT_CB_ID :
1103         hadc->MspDeInitCallback = HAL_ADC_MspDeInit;               /* Legacy weak MspDeInit            */
1104         break;
1105 
1106       default :
1107         /* Update the error code */
1108         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1109 
1110         /* Return error status */
1111         status =  HAL_ERROR;
1112         break;
1113     }
1114   }
1115   else
1116   {
1117     /* Update the error code */
1118     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
1119 
1120     /* Return error status */
1121     status =  HAL_ERROR;
1122   }
1123 
1124   return status;
1125 }
1126 
1127 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1128 
1129 /**
1130   * @}
1131   */
1132 
1133 /** @defgroup ADC_Exported_Functions_Group2 ADC Input and Output operation functions
1134   * @brief    ADC IO operation functions
1135   *
1136 @verbatim
1137  ===============================================================================
1138                       ##### IO operation functions #####
1139  ===============================================================================
1140     [..]  This section provides functions allowing to:
1141       (+) Start conversion of regular group.
1142       (+) Stop conversion of regular group.
1143       (+) Poll for conversion complete on regular group.
1144       (+) Poll for conversion event.
1145       (+) Get result of regular channel conversion.
1146       (+) Start conversion of regular group and enable interruptions.
1147       (+) Stop conversion of regular group and disable interruptions.
1148       (+) Handle ADC interrupt request
1149       (+) Start conversion of regular group and enable DMA transfer.
1150       (+) Stop conversion of regular group and disable ADC DMA transfer.
1151 @endverbatim
1152   * @{
1153   */
1154 
1155 /**
1156   * @brief  Enable ADC, start conversion of regular group.
1157   * @note   Interruptions enabled in this function: None.
1158   * @note   Case of multimode enabled (when multimode feature is available):
1159   *           if ADC is Slave, ADC is enabled but conversion is not started,
1160   *           if ADC is master, ADC is enabled and multimode conversion is started.
1161   * @param hadc ADC handle
1162   * @retval HAL status
1163   */
HAL_ADC_Start(ADC_HandleTypeDef * hadc)1164 HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef *hadc)
1165 {
1166   HAL_StatusTypeDef tmp_hal_status;
1167 #if defined(ADC_MULTIMODE_SUPPORT)
1168   const ADC_TypeDef *tmpADC_Master;
1169   uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
1170 #endif /* ADC_MULTIMODE_SUPPORT */
1171 
1172   /* Check the parameters */
1173   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1174 
1175   /* Perform ADC enable and conversion start if no conversion is on going */
1176   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1177   {
1178     /* Process locked */
1179     __HAL_LOCK(hadc);
1180 
1181     /* Enable the ADC peripheral */
1182     tmp_hal_status = ADC_Enable(hadc);
1183 
1184     /* Start conversion if ADC is effectively enabled */
1185     if (tmp_hal_status == HAL_OK)
1186     {
1187       /* Set ADC state                                                        */
1188       /* - Clear state bitfield related to regular group conversion results   */
1189       /* - Set state bitfield related to regular operation                    */
1190       ADC_STATE_CLR_SET(hadc->State,
1191                         HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
1192                         HAL_ADC_STATE_REG_BUSY);
1193 
1194 #if defined(ADC_MULTIMODE_SUPPORT)
1195       /* Reset HAL_ADC_STATE_MULTIMODE_SLAVE bit
1196         - if ADC instance is master or if multimode feature is not available
1197         - if multimode setting is disabled (ADC instance slave in independent mode) */
1198       if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
1199           || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
1200          )
1201       {
1202         CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
1203       }
1204 #endif /* ADC_MULTIMODE_SUPPORT */
1205 
1206       /* Set ADC error code */
1207       /* Check if a conversion is on going on ADC group injected */
1208       if (HAL_IS_BIT_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY))
1209       {
1210         /* Reset ADC error code fields related to regular conversions only */
1211         CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
1212       }
1213       else
1214       {
1215         /* Reset all ADC error code fields */
1216         ADC_CLEAR_ERRORCODE(hadc);
1217       }
1218 
1219       /* Clear ADC group regular conversion flag and overrun flag               */
1220       /* (To ensure of no unknown state from potential previous ADC operations) */
1221       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
1222 
1223       /* Unlock before starting ADC conversions: in case of potential         */
1224       /* interruption, to let the process to ADC IRQ Handler.                 */
1225       __HAL_UNLOCK(hadc);
1226 
1227       /* Enable conversion of regular group.                                  */
1228       /* If software start has been selected, conversion starts immediately.  */
1229       /* If external trigger has been selected, conversion will start at next */
1230       /* trigger event.                                                       */
1231       /* Case of multimode enabled (when multimode feature is available):     */
1232       /*  - if ADC is slave and dual regular conversions are enabled, ADC is  */
1233       /*    enabled only (conversion is not started),                         */
1234       /*  - if ADC is master, ADC is enabled and conversion is started.       */
1235 #if defined(ADC_MULTIMODE_SUPPORT)
1236       if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
1237           || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
1238           || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
1239           || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
1240          )
1241       {
1242         /* ADC instance is not a multimode slave instance with multimode regular conversions enabled */
1243         if (READ_BIT(hadc->Instance->CFGR1, ADC_CFGR1_JAUTO) != 0UL)
1244         {
1245           ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
1246         }
1247 
1248         /* Start ADC group regular conversion */
1249         LL_ADC_REG_StartConversion(hadc->Instance);
1250       }
1251       else
1252       {
1253         /* ADC instance is a multimode slave instance with multimode regular conversions enabled */
1254         SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
1255         /* if Master ADC JAUTO bit is set, update Slave State in setting
1256            HAL_ADC_STATE_INJ_BUSY bit and in resetting HAL_ADC_STATE_INJ_EOC bit */
1257         tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
1258         if (READ_BIT(tmpADC_Master->CFGR1, ADC_CFGR1_JAUTO) != 0UL)
1259         {
1260           ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
1261         }
1262 
1263       }
1264 #else
1265       if (READ_BIT(hadc->Instance->CFGR1, ADC_CFGR1_JAUTO) != 0UL)
1266       {
1267         ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
1268       }
1269 
1270       /* Start ADC group regular conversion */
1271       LL_ADC_REG_StartConversion(hadc->Instance);
1272 #endif /* ADC_MULTIMODE_SUPPORT */
1273     }
1274     else
1275     {
1276       __HAL_UNLOCK(hadc);
1277     }
1278   }
1279   else
1280   {
1281     tmp_hal_status = HAL_BUSY;
1282   }
1283 
1284   return tmp_hal_status;
1285 }
1286 
1287 /**
1288   * @brief  Stop ADC conversion of regular group (and injected channels in
1289   *         case of auto_injection mode), disable ADC peripheral.
1290   * @note:  ADC peripheral disable is forcing stop of potential
1291   *         conversion on injected group. If injected group is under use, it
1292   *         should be preliminarily stopped using HAL_ADCEx_InjectedStop function.
1293   * @param hadc ADC handle
1294   * @retval HAL status.
1295   */
HAL_ADC_Stop(ADC_HandleTypeDef * hadc)1296 HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef *hadc)
1297 {
1298   HAL_StatusTypeDef tmp_hal_status;
1299 
1300   /* Check the parameters */
1301   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1302 
1303   /* Process locked */
1304   __HAL_LOCK(hadc);
1305 
1306   /* 1. Stop potential conversion on going, on ADC groups regular and injected */
1307   tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_INJECTED_GROUP);
1308 
1309   /* Disable ADC peripheral if conversions are effectively stopped */
1310   if (tmp_hal_status == HAL_OK)
1311   {
1312     /* 2. Disable the ADC peripheral */
1313     tmp_hal_status = ADC_Disable(hadc);
1314 
1315     /* Check if ADC is effectively disabled */
1316     if (tmp_hal_status == HAL_OK)
1317     {
1318       /* Set ADC state */
1319       ADC_STATE_CLR_SET(hadc->State,
1320                         HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
1321                         HAL_ADC_STATE_READY);
1322     }
1323   }
1324 
1325   __HAL_UNLOCK(hadc);
1326 
1327   return tmp_hal_status;
1328 }
1329 
1330 /**
1331   * @brief  Wait for regular group conversion to be completed.
1332   * @note   ADC conversion flags EOS (end of sequence) and EOC (end of
1333   *         conversion) are cleared by this function, with an exception:
1334   *         if low power feature "LowPowerAutoWait" is enabled, flags are
1335   *         not cleared to not interfere with this feature until data register
1336   *         is read using function HAL_ADC_GetValue().
1337   * @note   This function cannot be used in a particular setup: ADC configured
1338   *         in DMA mode and polling for end of each conversion (ADC init
1339   *         parameter "EOCSelection" set to ADC_EOC_SINGLE_CONV).
1340   *         In this case, DMA resets the flag EOC and polling cannot be
1341   *         performed on each conversion. Nevertheless, polling can still
1342   *         be performed on the complete sequence (ADC init
1343   *         parameter "EOCSelection" set to ADC_EOC_SEQ_CONV).
1344   * @param hadc ADC handle
1345   * @param Timeout Timeout value in millisecond.
1346   * @retval HAL status
1347   */
HAL_ADC_PollForConversion(ADC_HandleTypeDef * hadc,uint32_t Timeout)1348 HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef *hadc, uint32_t Timeout)
1349 {
1350   uint32_t tickstart;
1351   uint32_t tmp_Flag_End;
1352   uint32_t tmp_cfgr;
1353 #if defined(ADC_MULTIMODE_SUPPORT)
1354   const ADC_TypeDef *tmpADC_Master;
1355   uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
1356 #endif /* ADC_MULTIMODE_SUPPORT */
1357 
1358   /* Check the parameters */
1359   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1360 
1361   /* If end of conversion selected to end of sequence conversions */
1362   if (hadc->Init.EOCSelection == ADC_EOC_SEQ_CONV)
1363   {
1364     tmp_Flag_End = ADC_FLAG_EOS;
1365   }
1366   /* If end of conversion selected to end of unitary conversion */
1367   else /* ADC_EOC_SINGLE_CONV */
1368   {
1369     /* Verification that ADC configuration is compliant with polling for      */
1370     /* each conversion:                                                       */
1371     /* Particular case is ADC configured in DMA mode and ADC sequencer with   */
1372     /* several ranks and polling for end of each conversion.                  */
1373     /* For code simplicity sake, this particular case is generalized to       */
1374     /* ADC configured in DMA mode and and polling for end of each conversion. */
1375 #if defined(ADC_MULTIMODE_SUPPORT)
1376     if ((tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
1377         || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
1378         || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
1379        )
1380     {
1381       /* Check ADC DMA mode in independent mode on ADC group regular */
1382       if (READ_BIT(hadc->Instance->CFGR1, ADC_CFGR1_DMNGT_0) != 0UL)
1383       {
1384         SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1385         return HAL_ERROR;
1386       }
1387       else
1388       {
1389         tmp_Flag_End = (ADC_FLAG_EOC);
1390       }
1391     }
1392     else
1393     {
1394       /* Check ADC DMA mode in multimode on ADC group regular */
1395       if (LL_ADC_GetMultiDataFormat(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) != LL_ADC_MULTI_REG_DATA_EACH_ADC)
1396       {
1397         SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1398         return HAL_ERROR;
1399       }
1400       else
1401       {
1402         tmp_Flag_End = (ADC_FLAG_EOC);
1403       }
1404     }
1405 #else
1406     /* Check ADC DMA mode */
1407     if (LL_ADC_REG_GetDMATransfer(hadc->Instance) != LL_ADC_REG_DMA_TRANSFER_NONE)
1408     {
1409       SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
1410       return HAL_ERROR;
1411     }
1412     else
1413     {
1414       tmp_Flag_End = (ADC_FLAG_EOC);
1415     }
1416 #endif /* ADC_MULTIMODE_SUPPORT */
1417   }
1418 
1419   /* Get tick count */
1420   tickstart = HAL_GetTick();
1421 
1422   /* Wait until End of unitary conversion or sequence conversions flag is raised */
1423   while ((hadc->Instance->ISR & tmp_Flag_End) == 0UL)
1424   {
1425     /* Check if timeout is disabled (set to infinite wait) */
1426     if (Timeout != HAL_MAX_DELAY)
1427     {
1428       if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
1429       {
1430         /* New check to avoid false timeout detection in case of preemption */
1431         if ((hadc->Instance->ISR & tmp_Flag_End) == 0UL)
1432         {
1433           /* Update ADC state machine to timeout */
1434           SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
1435 
1436           __HAL_UNLOCK(hadc);
1437 
1438           return HAL_TIMEOUT;
1439         }
1440       }
1441     }
1442   }
1443 
1444   /* Update ADC state machine */
1445   SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
1446 
1447   /* Determine whether any further conversion upcoming on group regular       */
1448   /* by external trigger, continuous mode or scan sequence on going.          */
1449   if ((LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
1450       && (hadc->Init.ContinuousConvMode == DISABLE)
1451      )
1452   {
1453     /* Check whether end of sequence is reached */
1454     if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS))
1455     {
1456       /* Set ADC state */
1457       CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
1458 
1459       if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) == 0UL)
1460       {
1461         SET_BIT(hadc->State, HAL_ADC_STATE_READY);
1462       }
1463     }
1464   }
1465 
1466   /* Get relevant register CFGR in ADC instance of ADC master or slave        */
1467   /* in function of multimode state (for devices with multimode               */
1468   /* available).                                                              */
1469 #if defined(ADC_MULTIMODE_SUPPORT)
1470   if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
1471       || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
1472       || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
1473       || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
1474      )
1475   {
1476     /* Retrieve ADC CFGR1 register */
1477     tmp_cfgr = READ_REG(hadc->Instance->CFGR1);
1478   }
1479   else
1480   {
1481     /* Retrieve Master ADC CFGR register */
1482     tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
1483     tmp_cfgr = READ_REG(tmpADC_Master->CFGR1);
1484   }
1485 #else
1486   /* Retrieve ADC CFGR1 register */
1487   tmp_cfgr = READ_REG(hadc->Instance->CFGR1);
1488 #endif /* ADC_MULTIMODE_SUPPORT */
1489 
1490   /* Clear polled flag */
1491   if (tmp_Flag_End == ADC_FLAG_EOS)
1492   {
1493     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOS);
1494   }
1495   else
1496   {
1497     /* Clear end of conversion EOC flag of regular group if low power feature */
1498     /* "LowPowerAutoWait " is disabled, to not interfere with this feature    */
1499     /* until data register is read using function HAL_ADC_GetValue().         */
1500     if (READ_BIT(tmp_cfgr, ADC_CFGR1_AUTDLY) == 0UL)
1501     {
1502       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS));
1503     }
1504   }
1505 
1506   return HAL_OK;
1507 }
1508 
1509 /**
1510   * @brief  Poll for ADC event.
1511   * @param hadc ADC handle
1512   * @param EventType the ADC event type.
1513   *          This parameter can be one of the following values:
1514   *            @arg @ref ADC_EOSMP_EVENT  ADC End of Sampling event
1515   *            @arg @ref ADC_AWD1_EVENT   ADC Analog watchdog 1 event (main analog watchdog, present on
1516   *                                       all STM32 series)
1517   *            @arg @ref ADC_AWD2_EVENT   ADC Analog watchdog 2 event (additional analog watchdog, not present on
1518   *                                       all STM32 series)
1519   *            @arg @ref ADC_AWD3_EVENT   ADC Analog watchdog 3 event (additional analog watchdog, not present on
1520   *                                       all STM32 series)
1521   *            @arg @ref ADC_OVR_EVENT    ADC Overrun event
1522   * @param Timeout Timeout value in millisecond.
1523   * @note   The relevant flag is cleared if found to be set, except for ADC_FLAG_OVR.
1524   *         Indeed, the latter is reset only if hadc->Init.Overrun field is set
1525   *         to ADC_OVR_DATA_OVERWRITTEN. Otherwise, data register may be potentially overwritten
1526   *         by a new converted data as soon as OVR is cleared.
1527   *         To reset OVR flag once the preserved data is retrieved, the user can resort
1528   *         to macro __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1529   * @retval HAL status
1530   */
HAL_ADC_PollForEvent(ADC_HandleTypeDef * hadc,uint32_t EventType,uint32_t Timeout)1531 HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef *hadc, uint32_t EventType, uint32_t Timeout)
1532 {
1533   uint32_t tickstart;
1534 
1535   /* Check the parameters */
1536   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1537   assert_param(IS_ADC_EVENT_TYPE(EventType));
1538 
1539   /* Get tick count */
1540   tickstart = HAL_GetTick();
1541 
1542   /* Check selected event flag */
1543   while (__HAL_ADC_GET_FLAG(hadc, EventType) == 0UL)
1544   {
1545     /* Check if timeout is disabled (set to infinite wait) */
1546     if (Timeout != HAL_MAX_DELAY)
1547     {
1548       if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
1549       {
1550         /* New check to avoid false timeout detection in case of preemption */
1551         if (__HAL_ADC_GET_FLAG(hadc, EventType) == 0UL)
1552         {
1553           /* Update ADC state machine to timeout */
1554           SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
1555 
1556           __HAL_UNLOCK(hadc);
1557 
1558           return HAL_TIMEOUT;
1559         }
1560       }
1561     }
1562   }
1563 
1564   switch (EventType)
1565   {
1566     /* End Of Sampling event */
1567     case ADC_EOSMP_EVENT:
1568       /* Set ADC state */
1569       SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOSMP);
1570 
1571       /* Clear the End Of Sampling flag */
1572       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP);
1573 
1574       break;
1575 
1576     /* Analog watchdog (level out of window) event */
1577     /* Note: In case of several analog watchdog enabled, if needed to know      */
1578     /* which one triggered and on which ADCx, test ADC state of analog watchdog */
1579     /* flags HAL_ADC_STATE_AWD1/2/3 using function "HAL_ADC_GetState()".        */
1580     /* For example:                                                             */
1581     /*  " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD1) != 0UL) "          */
1582     /*  " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD2) != 0UL) "          */
1583     /*  " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD3) != 0UL) "          */
1584 
1585     /* Check analog watchdog 1 flag */
1586     case ADC_AWD_EVENT:
1587       /* Set ADC state */
1588       SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
1589 
1590       /* Clear ADC analog watchdog flag */
1591       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD1);
1592 
1593       break;
1594 
1595     /* Check analog watchdog 2 flag */
1596     case ADC_AWD2_EVENT:
1597       /* Set ADC state */
1598       SET_BIT(hadc->State, HAL_ADC_STATE_AWD2);
1599 
1600       /* Clear ADC analog watchdog flag */
1601       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD2);
1602 
1603       break;
1604 
1605     /* Check analog watchdog 3 flag */
1606     case ADC_AWD3_EVENT:
1607       /* Set ADC state */
1608       SET_BIT(hadc->State, HAL_ADC_STATE_AWD3);
1609 
1610       /* Clear ADC analog watchdog flag */
1611       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD3);
1612 
1613       break;
1614 
1615     /* Overrun event */
1616     default: /* Case ADC_OVR_EVENT */
1617       /* If overrun is set to overwrite previous data, overrun event is not     */
1618       /* considered as an error.                                                */
1619       /* (cf ref manual "Managing conversions without using the DMA and without */
1620       /* overrun ")                                                             */
1621       if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
1622       {
1623         /* Set ADC state */
1624         SET_BIT(hadc->State, HAL_ADC_STATE_REG_OVR);
1625 
1626         /* Set ADC error code to overrun */
1627         SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_OVR);
1628       }
1629       else
1630       {
1631         /* Clear ADC Overrun flag only if Overrun is set to ADC_OVR_DATA_OVERWRITTEN
1632            otherwise, data register is potentially overwritten by new converted data as soon
1633            as OVR is cleared. */
1634         __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1635       }
1636       break;
1637   }
1638 
1639   return HAL_OK;
1640 }
1641 
1642 /**
1643   * @brief  Enable ADC, start conversion of regular group with interruption.
1644   * @note   Interruptions enabled in this function according to initialization
1645   *         setting : EOC (end of conversion), EOS (end of sequence),
1646   *         OVR overrun.
1647   *         Each of these interruptions has its dedicated callback function.
1648   * @note   Case of multimode enabled (when multimode feature is available):
1649   *         HAL_ADC_Start_IT() must be called for ADC Slave first, then for
1650   *         ADC Master.
1651   *         For ADC Slave, ADC is enabled only (conversion is not started).
1652   *         For ADC Master, ADC is enabled and multimode conversion is started.
1653   * @note   To guarantee a proper reset of all interruptions once all the needed
1654   *         conversions are obtained, HAL_ADC_Stop_IT() must be called to ensure
1655   *         a correct stop of the IT-based conversions.
1656   * @note   By default, HAL_ADC_Start_IT() does not enable the End Of Sampling
1657   *         interruption. If required (e.g. in case of oversampling with trigger
1658   *         mode), the user must:
1659   *          1. first clear the EOSMP flag if set with macro __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP)
1660   *          2. then enable the EOSMP interrupt with macro __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOSMP)
1661   *          before calling HAL_ADC_Start_IT().
1662   * @param hadc ADC handle
1663   * @retval HAL status
1664   */
HAL_ADC_Start_IT(ADC_HandleTypeDef * hadc)1665 HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef *hadc)
1666 {
1667   HAL_StatusTypeDef tmp_hal_status;
1668 #if defined(ADC_MULTIMODE_SUPPORT)
1669   const ADC_TypeDef *tmpADC_Master;
1670   uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
1671 #endif /* ADC_MULTIMODE_SUPPORT */
1672 
1673   /* Check the parameters */
1674   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1675 
1676   /* Perform ADC enable and conversion start if no conversion is on going */
1677   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1678   {
1679     /* Process locked */
1680     __HAL_LOCK(hadc);
1681 
1682     /* Enable the ADC peripheral */
1683     tmp_hal_status = ADC_Enable(hadc);
1684 
1685     /* Start conversion if ADC is effectively enabled */
1686     if (tmp_hal_status == HAL_OK)
1687     {
1688       /* Set ADC state                                                        */
1689       /* - Clear state bitfield related to regular group conversion results   */
1690       /* - Set state bitfield related to regular operation                    */
1691       ADC_STATE_CLR_SET(hadc->State,
1692                         HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
1693                         HAL_ADC_STATE_REG_BUSY);
1694 
1695 #if defined(ADC_MULTIMODE_SUPPORT)
1696       /* Reset HAL_ADC_STATE_MULTIMODE_SLAVE bit
1697         - if ADC instance is master or if multimode feature is not available
1698         - if multimode setting is disabled (ADC instance slave in independent mode) */
1699       if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
1700           || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
1701          )
1702       {
1703         CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
1704       }
1705 #endif /* ADC_MULTIMODE_SUPPORT */
1706 
1707       /* Set ADC error code */
1708       /* Check if a conversion is on going on ADC group injected */
1709       if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) != 0UL)
1710       {
1711         /* Reset ADC error code fields related to regular conversions only */
1712         CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
1713       }
1714       else
1715       {
1716         /* Reset all ADC error code fields */
1717         ADC_CLEAR_ERRORCODE(hadc);
1718       }
1719 
1720       /* Clear ADC group regular conversion flag and overrun flag               */
1721       /* (To ensure of no unknown state from potential previous ADC operations) */
1722       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
1723 
1724       /* Unlock before starting ADC conversions: in case of potential         */
1725       /* interruption, to let the process to ADC IRQ Handler.                 */
1726       __HAL_UNLOCK(hadc);
1727 
1728       /* Disable all interruptions before enabling the desired ones */
1729       __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR));
1730 
1731       /* Enable ADC end of conversion interrupt */
1732       switch (hadc->Init.EOCSelection)
1733       {
1734         case ADC_EOC_SEQ_CONV:
1735           __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOS);
1736           break;
1737         /* case ADC_EOC_SINGLE_CONV */
1738         default:
1739           __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOC);
1740           break;
1741       }
1742 
1743       /* Enable ADC overrun interrupt */
1744       /* If hadc->Init.Overrun is set to ADC_OVR_DATA_PRESERVED, only then is
1745          ADC_IT_OVR enabled; otherwise data overwrite is considered as normal
1746          behavior and no CPU time is lost for a non-processed interruption */
1747       if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
1748       {
1749         __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
1750       }
1751 
1752       /* Enable conversion of regular group.                                  */
1753       /* If software start has been selected, conversion starts immediately.  */
1754       /* If external trigger has been selected, conversion will start at next */
1755       /* trigger event.                                                       */
1756       /* Case of multimode enabled (when multimode feature is available):     */
1757       /*  - if ADC is slave and dual regular conversions are enabled, ADC is  */
1758       /*    enabled only (conversion is not started),                         */
1759       /*  - if ADC is master, ADC is enabled and conversion is started.       */
1760 #if defined(ADC_MULTIMODE_SUPPORT)
1761       if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
1762           || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
1763           || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
1764           || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
1765          )
1766       {
1767         /* ADC instance is not a multimode slave instance with multimode regular conversions enabled */
1768         if (READ_BIT(hadc->Instance->CFGR1, ADC_CFGR1_JAUTO) != 0UL)
1769         {
1770           ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
1771 
1772           /* Enable as well injected interruptions in case
1773            HAL_ADCEx_InjectedStart_IT() has not been called beforehand. This
1774            allows to start regular and injected conversions when JAUTO is
1775            set with a single call to HAL_ADC_Start_IT() */
1776           switch (hadc->Init.EOCSelection)
1777           {
1778             case ADC_EOC_SEQ_CONV:
1779               __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
1780               __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOS);
1781               break;
1782             /* case ADC_EOC_SINGLE_CONV */
1783             default:
1784               __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOS);
1785               __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC);
1786               break;
1787           }
1788         }
1789 
1790         /* Start ADC group regular conversion */
1791         LL_ADC_REG_StartConversion(hadc->Instance);
1792       }
1793       else
1794       {
1795         /* ADC instance is a multimode slave instance with multimode regular conversions enabled */
1796         SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
1797         /* if Master ADC JAUTO bit is set, Slave injected interruptions
1798            are enabled nevertheless (for same reason as above) */
1799         tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
1800         if (READ_BIT(tmpADC_Master->CFGR1, ADC_CFGR1_JAUTO) != 0UL)
1801         {
1802           /* First, update Slave State in setting HAL_ADC_STATE_INJ_BUSY bit
1803              and in resetting HAL_ADC_STATE_INJ_EOC bit */
1804           ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
1805           /* Next, set Slave injected interruptions */
1806           switch (hadc->Init.EOCSelection)
1807           {
1808             case ADC_EOC_SEQ_CONV:
1809               __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
1810               __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOS);
1811               break;
1812             /* case ADC_EOC_SINGLE_CONV */
1813             default:
1814               __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOS);
1815               __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC);
1816               break;
1817           }
1818         }
1819       }
1820 #else
1821       /* ADC instance is not a multimode slave instance with multimode regular conversions enabled */
1822       if (READ_BIT(hadc->Instance->CFGR1, ADC_CFGR1_JAUTO) != 0UL)
1823       {
1824         ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
1825 
1826         /* Enable as well injected interruptions in case
1827          HAL_ADCEx_InjectedStart_IT() has not been called beforehand. This
1828          allows to start regular and injected conversions when JAUTO is
1829          set with a single call to HAL_ADC_Start_IT() */
1830         switch (hadc->Init.EOCSelection)
1831         {
1832           case ADC_EOC_SEQ_CONV:
1833             __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
1834             __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOS);
1835             break;
1836           /* case ADC_EOC_SINGLE_CONV */
1837           default:
1838             __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOS);
1839             __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC);
1840             break;
1841         }
1842       }
1843 
1844       /* Start ADC group regular conversion */
1845       LL_ADC_REG_StartConversion(hadc->Instance);
1846 #endif /* ADC_MULTIMODE_SUPPORT */
1847     }
1848     else
1849     {
1850       __HAL_UNLOCK(hadc);
1851     }
1852 
1853   }
1854   else
1855   {
1856     tmp_hal_status = HAL_BUSY;
1857   }
1858 
1859   return tmp_hal_status;
1860 }
1861 
1862 /**
1863   * @brief  Stop ADC conversion of regular group (and injected group in
1864   *         case of auto_injection mode), disable interrution of
1865   *         end-of-conversion, disable ADC peripheral.
1866   * @param hadc ADC handle
1867   * @retval HAL status.
1868   */
HAL_ADC_Stop_IT(ADC_HandleTypeDef * hadc)1869 HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef *hadc)
1870 {
1871   HAL_StatusTypeDef tmp_hal_status;
1872 
1873   /* Check the parameters */
1874   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1875 
1876   /* Process locked */
1877   __HAL_LOCK(hadc);
1878 
1879   /* 1. Stop potential conversion on going, on ADC groups regular and injected */
1880   tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_INJECTED_GROUP);
1881 
1882   /* Disable ADC peripheral if conversions are effectively stopped */
1883   if (tmp_hal_status == HAL_OK)
1884   {
1885     /* Disable ADC end of conversion interrupt for regular group */
1886     /* Disable ADC overrun interrupt */
1887     __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR));
1888 
1889     /* 2. Disable the ADC peripheral */
1890     tmp_hal_status = ADC_Disable(hadc);
1891 
1892     /* Check if ADC is effectively disabled */
1893     if (tmp_hal_status == HAL_OK)
1894     {
1895       /* Set ADC state */
1896       ADC_STATE_CLR_SET(hadc->State,
1897                         HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
1898                         HAL_ADC_STATE_READY);
1899     }
1900   }
1901 
1902   __HAL_UNLOCK(hadc);
1903 
1904   return tmp_hal_status;
1905 }
1906 
1907 /**
1908   * @brief  Enable ADC, start conversion of regular group and transfer result through DMA.
1909   * @note   Interruptions enabled in this function:
1910   *         overrun (if applicable), DMA half transfer, DMA transfer complete.
1911   *         Each of these interruptions has its dedicated callback function.
1912   * @note   Case of multimode enabled (when multimode feature is available): HAL_ADC_Start_DMA()
1913   *         is designed for single-ADC mode only. For multimode, the dedicated
1914   *         HAL_ADCEx_MultiModeStart_DMA() function must be used.
1915   * @param hadc ADC handle
1916   * @param pData Destination Buffer address.
1917   * @param Length Number of data to be transferred from ADC peripheral to memory
1918   * @retval HAL status.
1919   */
HAL_ADC_Start_DMA(ADC_HandleTypeDef * hadc,const uint32_t * pData,uint32_t Length)1920 HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef *hadc, const uint32_t *pData, uint32_t Length)
1921 {
1922   HAL_StatusTypeDef tmp_hal_status;
1923 #if defined(ADC_MULTIMODE_SUPPORT)
1924   uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
1925 #endif /* ADC_MULTIMODE_SUPPORT */
1926   uint32_t LengthInBytes;
1927   DMA_NodeConfTypeDef node_conf;
1928 
1929   /* Check the parameters */
1930   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1931 
1932   /* Perform ADC enable and conversion start if no conversion is on going */
1933   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
1934   {
1935     /* Process locked */
1936     __HAL_LOCK(hadc);
1937 
1938 #if defined(ADC_MULTIMODE_SUPPORT)
1939     /* Ensure that multimode regular conversions are not enabled.   */
1940     /* Otherwise, dedicated API HAL_ADCEx_MultiModeStart_DMA() must be used.  */
1941     if ((tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
1942         || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
1943         || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
1944        )
1945 #endif /* ADC_MULTIMODE_SUPPORT */
1946     {
1947       /* Enable the ADC peripheral */
1948       tmp_hal_status = ADC_Enable(hadc);
1949 
1950       /* Start conversion if ADC is effectively enabled */
1951       if (tmp_hal_status == HAL_OK)
1952       {
1953         /* Set ADC state                                                        */
1954         /* - Clear state bitfield related to regular group conversion results   */
1955         /* - Set state bitfield related to regular operation                    */
1956         ADC_STATE_CLR_SET(hadc->State,
1957                           HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
1958                           HAL_ADC_STATE_REG_BUSY);
1959 
1960 #if defined(ADC_MULTIMODE_SUPPORT)
1961         /* Reset HAL_ADC_STATE_MULTIMODE_SLAVE bit
1962           - if ADC instance is master or if multimode feature is not available
1963           - if multimode setting is disabled (ADC instance slave in independent mode) */
1964         if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
1965             || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
1966            )
1967         {
1968           CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
1969         }
1970 #endif /* ADC_MULTIMODE_SUPPORT */
1971 
1972         /* Check if a conversion is on going on ADC group injected */
1973         if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) != 0UL)
1974         {
1975           /* Reset ADC error code fields related to regular conversions only */
1976           CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
1977         }
1978         else
1979         {
1980           /* Reset all ADC error code fields */
1981           ADC_CLEAR_ERRORCODE(hadc);
1982         }
1983 
1984         /* Set the DMA transfer complete callback */
1985         hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt;
1986 
1987         /* Set the DMA half transfer complete callback */
1988         hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt;
1989 
1990         /* Set the DMA error callback */
1991         hadc->DMA_Handle->XferErrorCallback = ADC_DMAError;
1992 
1993 
1994         /* Manage ADC and DMA start: ADC overrun interruption, DMA start,     */
1995         /* ADC start (in case of SW start):                                   */
1996 
1997         /* Clear regular group conversion flag and overrun flag               */
1998         /* (To ensure of no unknown state from potential previous ADC         */
1999         /* operations)                                                        */
2000         __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR));
2001 
2002         /* Unlock before starting ADC conversions: in case of potential         */
2003         /* interruption, to let the process to ADC IRQ Handler.                 */
2004         __HAL_UNLOCK(hadc);
2005 
2006         /* With DMA, overrun event is always considered as an error even if
2007            hadc->Init.Overrun is set to ADC_OVR_DATA_OVERWRITTEN. Therefore,
2008            ADC_IT_OVR is enabled. */
2009         __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
2010 
2011         /* Start the DMA channel */
2012         /* Check linkedlist mode */
2013         if ((hadc->DMA_Handle->Mode & DMA_LINKEDLIST) == DMA_LINKEDLIST)
2014         {
2015           if ((hadc->DMA_Handle->LinkedListQueue != NULL) && (hadc->DMA_Handle->LinkedListQueue->Head != NULL))
2016           {
2017             /* Length should be converted to number of bytes */
2018             if (HAL_DMAEx_List_GetNodeConfig(&node_conf, hadc->DMA_Handle->LinkedListQueue->Head) != HAL_OK)
2019             {
2020               return HAL_ERROR;
2021             }
2022 
2023             /* Length should be converted to number of bytes */
2024             if (node_conf.Init.SrcDataWidth == DMA_SRC_DATAWIDTH_WORD)
2025             {
2026               /* Word -> Bytes */
2027               LengthInBytes = Length * 4U;
2028             }
2029             else if (node_conf.Init.SrcDataWidth == DMA_SRC_DATAWIDTH_HALFWORD)
2030             {
2031               /* Halfword -> Bytes */
2032               LengthInBytes = Length * 2U;
2033             }
2034             else /* Bytes */
2035             {
2036               /* Same size already expressed in Bytes */
2037               LengthInBytes = Length;
2038             }
2039 
2040             hadc->DMA_Handle->LinkedListQueue->Head->LinkRegisters[NODE_CBR1_DEFAULT_OFFSET] = (uint32_t)LengthInBytes;
2041             hadc->DMA_Handle->LinkedListQueue->Head->LinkRegisters[NODE_CSAR_DEFAULT_OFFSET] =                  \
2042                 (uint32_t)&hadc->Instance->DR;
2043             hadc->DMA_Handle->LinkedListQueue->Head->LinkRegisters[NODE_CDAR_DEFAULT_OFFSET] = (uint32_t)pData;
2044             tmp_hal_status = HAL_DMAEx_List_Start_IT(hadc->DMA_Handle);
2045           }
2046           else
2047           {
2048             tmp_hal_status = HAL_ERROR;
2049           }
2050         }
2051         else
2052         {
2053           /* Length should be converted to number of bytes */
2054           if (hadc->DMA_Handle->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_WORD)
2055           {
2056             /* Word -> Bytes */
2057             LengthInBytes = Length * 4U;
2058           }
2059           else if (hadc->DMA_Handle->Init.SrcDataWidth == DMA_SRC_DATAWIDTH_HALFWORD)
2060           {
2061             /* Halfword -> Bytes */
2062             LengthInBytes = Length * 2U;
2063           }
2064           else /* Bytes */
2065           {
2066             /* Same size already expressed in Bytes */
2067             LengthInBytes = Length;
2068           }
2069 
2070           /* Start the DMA channel */
2071           tmp_hal_status = HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->DR, (uint32_t)pData,        \
2072                                             LengthInBytes);
2073         }
2074 
2075         if (tmp_hal_status != HAL_ERROR)
2076         {
2077           /* Enable conversion of regular group.                                  */
2078           /* If software start has been selected, conversion starts immediately.  */
2079           /* If external trigger has been selected, conversion will start at next */
2080           /* trigger event.                                                       */
2081           /* Start ADC group regular conversion */
2082           LL_ADC_REG_StartConversion(hadc->Instance);
2083         }
2084       }
2085       else
2086       {
2087         __HAL_UNLOCK(hadc);
2088       }
2089     }
2090 #if defined(ADC_MULTIMODE_SUPPORT)
2091     else
2092     {
2093       tmp_hal_status = HAL_ERROR;
2094       __HAL_UNLOCK(hadc);
2095     }
2096 #endif /* ADC_MULTIMODE_SUPPORT */
2097   }
2098   else
2099   {
2100     tmp_hal_status = HAL_BUSY;
2101   }
2102 
2103   return tmp_hal_status;
2104 }
2105 
2106 /**
2107   * @brief  Stop ADC conversion of regular group (and injected group in
2108   *         case of auto_injection mode), disable ADC DMA transfer, disable
2109   *         ADC peripheral.
2110   * @note:  ADC peripheral disable is forcing stop of potential
2111   *         conversion on ADC group injected. If ADC group injected is under use, it
2112   *         should be preliminarily stopped using HAL_ADCEx_InjectedStop function.
2113   * @note   Case of multimode enabled (when multimode feature is available):
2114   *         HAL_ADC_Stop_DMA() function is dedicated to single-ADC mode only.
2115   *         For multimode, the dedicated HAL_ADCEx_MultiModeStop_DMA() API must be used.
2116   * @param hadc ADC handle
2117   * @retval HAL status.
2118   */
HAL_ADC_Stop_DMA(ADC_HandleTypeDef * hadc)2119 HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef *hadc)
2120 {
2121   HAL_StatusTypeDef tmp_hal_status;
2122 
2123   /* Check the parameters */
2124   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2125 
2126   /* Process locked */
2127   __HAL_LOCK(hadc);
2128 
2129   /* 1. Stop potential ADC group regular conversion on going */
2130   tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_INJECTED_GROUP);
2131 
2132   /* Disable ADC peripheral if conversions are effectively stopped */
2133   if (tmp_hal_status == HAL_OK)
2134   {
2135     /* Disable ADC DMA (ADC DMA configuration of continuous requests is kept) */
2136     MODIFY_REG(hadc->Instance->CFGR1, ADC_CFGR1_DMNGT_0 | ADC_CFGR1_DMNGT_1, 0UL);
2137 
2138     /* Disable the DMA channel (in case of DMA in circular mode or stop       */
2139     /* while DMA transfer is on going)                                        */
2140     if (hadc->DMA_Handle->State == HAL_DMA_STATE_BUSY)
2141     {
2142       tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle);
2143 
2144       /* Check if DMA channel effectively disabled */
2145       if (tmp_hal_status != HAL_OK)
2146       {
2147         /* Update ADC state machine to error */
2148         SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
2149       }
2150     }
2151 
2152     /* Disable ADC overrun interrupt */
2153     __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
2154 
2155     /* 2. Disable the ADC peripheral */
2156     /* Update "tmp_hal_status" only if DMA channel disabling passed,          */
2157     /* to keep in memory a potential failing status.                          */
2158     if (tmp_hal_status == HAL_OK)
2159     {
2160       tmp_hal_status = ADC_Disable(hadc);
2161     }
2162     else
2163     {
2164       (void)ADC_Disable(hadc);
2165     }
2166 
2167     /* Check if ADC is effectively disabled */
2168     if (tmp_hal_status == HAL_OK)
2169     {
2170       /* Set ADC state */
2171       ADC_STATE_CLR_SET(hadc->State,
2172                         HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
2173                         HAL_ADC_STATE_READY);
2174     }
2175 
2176   }
2177 
2178   __HAL_UNLOCK(hadc);
2179 
2180   return tmp_hal_status;
2181 }
2182 
2183 /**
2184   * @brief  Get ADC regular group conversion result.
2185   * @note   Reading register DR automatically clears ADC flag EOC
2186   *         (ADC group regular end of unitary conversion).
2187   * @note   This function returns an unsigned value. Using the ADC offset
2188   *         feature can result in negative conversion data.
2189   *         To read conversion data with ADC offset enabled
2190   *         use function @ref HAL_ADC_GetSignedValue.
2191   * @note   This function does not clear ADC flag EOS
2192   *         (ADC group regular end of sequence conversion).
2193   *         Occurrence of flag EOS rising:
2194   *          - If sequencer is composed of 1 rank, flag EOS is equivalent
2195   *            to flag EOC.
2196   *          - If sequencer is composed of several ranks, during the scan
2197   *            sequence flag EOC only is raised, at the end of the scan sequence
2198   *            both flags EOC and EOS are raised.
2199   *         To clear this flag, either use function:
2200   *         in programming model IT: @ref HAL_ADC_IRQHandler(), in programming
2201   *         model polling: @ref HAL_ADC_PollForConversion()
2202   *         or @ref __HAL_ADC_CLEAR_FLAG(&hadc, ADC_FLAG_EOS).
2203   * @param hadc ADC handle
2204   * @retval ADC group regular conversion data
2205   */
HAL_ADC_GetValue(const ADC_HandleTypeDef * hadc)2206 uint32_t HAL_ADC_GetValue(const ADC_HandleTypeDef *hadc)
2207 {
2208   /* Check the parameters */
2209   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2210 
2211   /* Note: EOC flag is not cleared here by software because automatically     */
2212   /*       cleared by hardware when reading register DR.                      */
2213 
2214   /* Return ADC converted value */
2215   return hadc->Instance->DR;
2216 }
2217 
2218 /**
2219   * @brief  Get ADC regular group conversion result.
2220   * @note   Reading register DR automatically clears ADC flag EOC
2221   *         (ADC group regular end of unitary conversion).
2222   * @note   This function does not clear ADC flag EOS
2223   *         (ADC group regular end of sequence conversion).
2224   *         Occurrence of flag EOS rising:
2225   *          - If sequencer is composed of 1 rank, flag EOS is equivalent
2226   *            to flag EOC.
2227   *          - If sequencer is composed of several ranks, during the scan
2228   *            sequence flag EOC only is raised, at the end of the scan sequence
2229   *            both flags EOC and EOS are raised.
2230   *         To clear this flag, either use function:
2231   *         in programming model IT: @ref HAL_ADC_IRQHandler(), in programming
2232   *         model polling: @ref HAL_ADC_PollForConversion()
2233   *         or @ref __HAL_ADC_CLEAR_FLAG(&hadc, ADC_FLAG_EOS).
2234   * @param hadc ADC handle
2235   * @retval ADC group regular conversion data
2236   */
HAL_ADC_GetSignedValue(const ADC_HandleTypeDef * hadc)2237 int32_t HAL_ADC_GetSignedValue(const ADC_HandleTypeDef *hadc)
2238 {
2239   /* Check the parameters */
2240   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2241 
2242   /* Note: EOC flag is not cleared here by software because automatically     */
2243   /*       cleared by hardware when reading register DR.                      */
2244 
2245   /* Return ADC converted value */
2246   return (int32_t)(hadc->Instance->DR);
2247 }
2248 
2249 /**
2250   * @brief  Start ADC conversion sampling phase of regular group
2251   * @note:  This function should only be called to start sampling when
2252   *         - @ref ADC_SAMPLING_MODE_TRIGGER_CONTROLED sampling
2253   *         mode has been selected
2254   *         - @ref ADC_SOFTWARE_START has been selected as trigger source
2255   * @param hadc ADC handle
2256   * @retval HAL status.
2257   */
HAL_ADC_StartSampling(ADC_HandleTypeDef * hadc)2258 HAL_StatusTypeDef HAL_ADC_StartSampling(ADC_HandleTypeDef *hadc)
2259 {
2260   /* Check the parameters */
2261   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2262 
2263   /* Start sampling */
2264   SET_BIT(hadc->Instance->CFGR2, ADC_CFGR2_SWTRIG);
2265 
2266   /* Return function status */
2267   return HAL_OK;
2268 }
2269 
2270 /**
2271   * @brief  Stop ADC conversion sampling phase of regular group and start conversion
2272   * @note:  This function should only be called to stop sampling when
2273   *         - @ref ADC_SAMPLING_MODE_TRIGGER_CONTROLED sampling
2274   *         mode has been selected
2275   *         - @ref ADC_SOFTWARE_START has been selected as trigger source
2276   *         - after sampling has been started using @ref HAL_ADC_StartSampling.
2277   * @param hadc ADC handle
2278   * @retval HAL status.
2279   */
HAL_ADC_StopSampling(ADC_HandleTypeDef * hadc)2280 HAL_StatusTypeDef HAL_ADC_StopSampling(ADC_HandleTypeDef *hadc)
2281 {
2282   /* Check the parameters */
2283   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2284 
2285   /* Start sampling */
2286   CLEAR_BIT(hadc->Instance->CFGR2, ADC_CFGR2_SWTRIG);
2287 
2288   /* Return function status */
2289   return HAL_OK;
2290 }
2291 
2292 /**
2293   * @brief  Handle ADC interrupt request.
2294   * @param hadc ADC handle
2295   * @retval None
2296   */
HAL_ADC_IRQHandler(ADC_HandleTypeDef * hadc)2297 void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc)
2298 {
2299   uint32_t overrun_error = 0UL; /* flag set if overrun occurrence has to be considered as an error */
2300   uint32_t tmp_isr = hadc->Instance->ISR;
2301   uint32_t tmp_ier = hadc->Instance->IER;
2302   uint32_t tmp_adc_inj_is_trigger_source_sw_start;
2303   uint32_t tmp_adc_reg_is_trigger_source_sw_start;
2304   uint32_t tmp_cfgr;
2305 #if defined(ADC_MULTIMODE_SUPPORT)
2306   const ADC_TypeDef *tmpADC_Master;
2307   uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
2308 #endif /* ADC_MULTIMODE_SUPPORT */
2309 
2310   /* Check the parameters */
2311   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2312   assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection));
2313 
2314   /* ========== Check End of Sampling flag for ADC group regular ========== */
2315   if (((tmp_isr & ADC_FLAG_EOSMP) == ADC_FLAG_EOSMP) && ((tmp_ier & ADC_IT_EOSMP) == ADC_IT_EOSMP))
2316   {
2317     /* Update state machine on end of sampling status if not in error state */
2318     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
2319     {
2320       /* Set ADC state */
2321       SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOSMP);
2322     }
2323 
2324     /* End Of Sampling callback */
2325 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2326     hadc->EndOfSamplingCallback(hadc);
2327 #else
2328     HAL_ADCEx_EndOfSamplingCallback(hadc);
2329 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2330 
2331     /* Clear regular group conversion flag */
2332     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOSMP);
2333   }
2334 
2335   /* ====== Check ADC group regular end of unitary conversion sequence conversions ===== */
2336   if ((((tmp_isr & ADC_FLAG_EOC) == ADC_FLAG_EOC) && ((tmp_ier & ADC_IT_EOC) == ADC_IT_EOC)) ||
2337       (((tmp_isr & ADC_FLAG_EOS) == ADC_FLAG_EOS) && ((tmp_ier & ADC_IT_EOS) == ADC_IT_EOS)))
2338   {
2339     /* Update state machine on conversion status if not in error state */
2340     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
2341     {
2342       /* Set ADC state */
2343       SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
2344     }
2345 
2346     /* Determine whether any further conversion upcoming on group regular     */
2347     /* by external trigger, continuous mode or scan sequence on going         */
2348     /* to disable interruption.                                               */
2349     if (LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
2350     {
2351       /* Get relevant register CFGR in ADC instance of ADC master or slave    */
2352       /* in function of multimode state (for devices with multimode           */
2353       /* available).                                                          */
2354 #if defined(ADC_MULTIMODE_SUPPORT)
2355       if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
2356           || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
2357           || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_SIMULT)
2358           || (tmp_multimode_config == LL_ADC_MULTI_DUAL_INJ_ALTERN)
2359          )
2360       {
2361         /* check CONT bit directly in handle ADC CFGR register */
2362         tmp_cfgr = READ_REG(hadc->Instance->CFGR1);
2363       }
2364       else
2365       {
2366         /* else need to check Master ADC CONT bit */
2367         tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
2368         tmp_cfgr = READ_REG(tmpADC_Master->CFGR1);
2369       }
2370 #else
2371       tmp_cfgr = READ_REG(hadc->Instance->CFGR1);
2372 #endif /* ADC_MULTIMODE_SUPPORT */
2373 
2374       /* Carry on if continuous mode is disabled */
2375       if (READ_BIT(tmp_cfgr, ADC_CFGR1_CONT) != ADC_CFGR1_CONT)
2376       {
2377         /* If End of Sequence is reached, disable interrupts */
2378         if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS))
2379         {
2380           /* Allowed to modify bits ADC_IT_EOC/ADC_IT_EOS only if bit         */
2381           /* ADSTART==0 (no conversion on going)                              */
2382           if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
2383           {
2384             /* Disable ADC end of sequence conversion interrupt */
2385             /* Note: Overrun interrupt was enabled with EOC interrupt in      */
2386             /* HAL_Start_IT(), but is not disabled here because can be used   */
2387             /* by overrun IRQ process below.                                  */
2388             __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_EOS);
2389 
2390             /* Set ADC state */
2391             CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
2392 
2393             if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) == 0UL)
2394             {
2395               SET_BIT(hadc->State, HAL_ADC_STATE_READY);
2396             }
2397           }
2398           else
2399           {
2400             /* Change ADC state to error state */
2401             SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
2402 
2403             /* Set ADC error code to ADC peripheral internal error */
2404             SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
2405           }
2406         }
2407       }
2408     }
2409 
2410     /* Conversion complete callback */
2411     /* Note: Into callback function "HAL_ADC_ConvCpltCallback()",             */
2412     /*       to determine if conversion has been triggered from EOC or EOS,   */
2413     /*       possibility to use:                                              */
2414     /*        " if ( __HAL_ADC_GET_FLAG(&hadc, ADC_FLAG_EOS)) "               */
2415 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2416     hadc->ConvCpltCallback(hadc);
2417 #else
2418     HAL_ADC_ConvCpltCallback(hadc);
2419 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2420 
2421     /* Clear regular group conversion flag */
2422     /* Note: in case of overrun set to ADC_OVR_DATA_PRESERVED, end of         */
2423     /*       conversion flags clear induces the release of the preserved data.*/
2424     /*       Therefore, if the preserved data value is needed, it must be     */
2425     /*       read preliminarily into HAL_ADC_ConvCpltCallback().              */
2426     __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS));
2427   }
2428 
2429   /* ====== Check ADC group injected end of unitary conversion sequence conversions ===== */
2430   if ((((tmp_isr & ADC_FLAG_JEOC) == ADC_FLAG_JEOC) && ((tmp_ier & ADC_IT_JEOC) == ADC_IT_JEOC)) ||
2431       (((tmp_isr & ADC_FLAG_JEOS) == ADC_FLAG_JEOS) && ((tmp_ier & ADC_IT_JEOS) == ADC_IT_JEOS)))
2432   {
2433     /* Update state machine on conversion status if not in error state */
2434     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) == 0UL)
2435     {
2436       /* Set ADC state */
2437       SET_BIT(hadc->State, HAL_ADC_STATE_INJ_EOC);
2438     }
2439 
2440     /* Retrieve ADC configuration */
2441     tmp_adc_inj_is_trigger_source_sw_start = LL_ADC_INJ_IsTriggerSourceSWStart(hadc->Instance);
2442     tmp_adc_reg_is_trigger_source_sw_start = LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance);
2443     /* Get relevant register CFGR in ADC instance of ADC master or slave  */
2444     /* in function of multimode state (for devices with multimode         */
2445     /* available).                                                        */
2446 #if defined(ADC_MULTIMODE_SUPPORT)
2447     if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance)
2448         || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT)
2449         || (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_SIMULT)
2450         || (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_INTERL)
2451        )
2452     {
2453       tmp_cfgr = READ_REG(hadc->Instance->CFGR1);
2454     }
2455     else
2456     {
2457       tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance);
2458       tmp_cfgr = READ_REG(tmpADC_Master->CFGR1);
2459     }
2460 #else
2461     tmp_cfgr = READ_REG(hadc->Instance->CFGR1);
2462 #endif /* ADC_MULTIMODE_SUPPORT */
2463 
2464     /* Disable interruption if no further conversion upcoming by injected     */
2465     /* external trigger or by automatic injected conversion with regular      */
2466     /* group having no further conversion upcoming (same conditions as        */
2467     /* regular group interruption disabling above),                           */
2468     /* and if injected scan sequence is completed.                            */
2469     if (tmp_adc_inj_is_trigger_source_sw_start != 0UL)
2470     {
2471       if (((READ_BIT(tmp_cfgr, ADC_CFGR1_JAUTO) == 0UL) ||
2472            ((tmp_adc_reg_is_trigger_source_sw_start != 0UL)  &&
2473             (READ_BIT(tmp_cfgr, ADC_CFGR1_CONT) == 0UL))))
2474       {
2475         /* If End of Sequence is reached, disable interrupts */
2476         if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOS))
2477         {
2478           if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) == 0UL)
2479           {
2480             /* Disable ADC end of sequence conversion interrupt  */
2481             __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC | ADC_IT_JEOS);
2482 
2483             /* Set ADC state */
2484             CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY);
2485 
2486             if ((hadc->State & HAL_ADC_STATE_REG_BUSY) == 0UL)
2487             {
2488               SET_BIT(hadc->State, HAL_ADC_STATE_READY);
2489             }
2490           }
2491         }
2492       }
2493     }
2494 
2495     /* Injected Conversion complete callback */
2496     /* Note:  HAL_ADCEx_InjectedConvCpltCallback can resort to
2497               if (__HAL_ADC_GET_FLAG(&hadc, ADC_FLAG_JEOS)) or
2498               if (__HAL_ADC_GET_FLAG(&hadc, ADC_FLAG_JEOC)) to determine whether
2499               interruption has been triggered by end of conversion or end of
2500               sequence.    */
2501 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2502     hadc->InjectedConvCpltCallback(hadc);
2503 #else
2504     HAL_ADCEx_InjectedConvCpltCallback(hadc);
2505 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2506 
2507     /* Clear injected group conversion flag */
2508     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOC | ADC_FLAG_JEOS);
2509   }
2510 
2511   /* ========== Check Analog watchdog 1 flag ========== */
2512   if (((tmp_isr & ADC_FLAG_AWD1) == ADC_FLAG_AWD1) && ((tmp_ier & ADC_IT_AWD1) == ADC_IT_AWD1))
2513   {
2514     /* Set ADC state */
2515     SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
2516 
2517     /* Level out of window 1 callback */
2518 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2519     hadc->LevelOutOfWindowCallback(hadc);
2520 #else
2521     HAL_ADC_LevelOutOfWindowCallback(hadc);
2522 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2523 
2524     /* Clear ADC analog watchdog flag */
2525     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD1);
2526   }
2527 
2528   /* ========== Check analog watchdog 2 flag ========== */
2529   if (((tmp_isr & ADC_FLAG_AWD2) == ADC_FLAG_AWD2) && ((tmp_ier & ADC_IT_AWD2) == ADC_IT_AWD2))
2530   {
2531     /* Set ADC state */
2532     SET_BIT(hadc->State, HAL_ADC_STATE_AWD2);
2533 
2534     /* Level out of window 2 callback */
2535 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2536     hadc->LevelOutOfWindow2Callback(hadc);
2537 #else
2538     HAL_ADCEx_LevelOutOfWindow2Callback(hadc);
2539 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2540 
2541     /* Clear ADC analog watchdog flag */
2542     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD2);
2543   }
2544 
2545   /* ========== Check analog watchdog 3 flag ========== */
2546   if (((tmp_isr & ADC_FLAG_AWD3) == ADC_FLAG_AWD3) && ((tmp_ier & ADC_IT_AWD3) == ADC_IT_AWD3))
2547   {
2548     /* Set ADC state */
2549     SET_BIT(hadc->State, HAL_ADC_STATE_AWD3);
2550 
2551     /* Level out of window 3 callback */
2552 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2553     hadc->LevelOutOfWindow3Callback(hadc);
2554 #else
2555     HAL_ADCEx_LevelOutOfWindow3Callback(hadc);
2556 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2557 
2558     /* Clear ADC analog watchdog flag */
2559     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD3);
2560   }
2561 
2562   /* ========== Check Overrun flag ========== */
2563   if (((tmp_isr & ADC_FLAG_OVR) == ADC_FLAG_OVR) && ((tmp_ier & ADC_IT_OVR) == ADC_IT_OVR))
2564   {
2565     /* If overrun is set to overwrite previous data (default setting),        */
2566     /* overrun event is not considered as an error.                           */
2567     /* (cf ref manual "Managing conversions without using the DMA and without */
2568     /* overrun ")                                                             */
2569     /* Exception for usage with DMA overrun event always considered as an     */
2570     /* error.                                                                 */
2571     if (hadc->Init.Overrun == ADC_OVR_DATA_PRESERVED)
2572     {
2573       overrun_error = 1UL;
2574     }
2575     else
2576     {
2577       /* Check DMA configuration */
2578 #if defined(ADC_MULTIMODE_SUPPORT)
2579       if (tmp_multimode_config != LL_ADC_MULTI_INDEPENDENT)
2580       {
2581         overrun_error = 1UL;
2582 
2583         /* Multimode (when feature is available) is enabled,
2584            Common Control Register MDMA bits must be checked. */
2585         if (LL_ADC_GetMultiDataFormat(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) != LL_ADC_MULTI_REG_DATA_EACH_ADC)
2586         {
2587           overrun_error = 1UL;
2588         }
2589       }
2590       else
2591 #endif /* ADC_MULTIMODE_SUPPORT */
2592       {
2593         /* Multimode not set or feature not available or ADC independent */
2594         if ((hadc->Instance->CFGR1 & ADC_CFGR1_DMNGT) != 0UL)
2595         {
2596           overrun_error = 1UL;
2597         }
2598       }
2599     }
2600 
2601     if (overrun_error == 1UL)
2602     {
2603       /* Change ADC state to error state */
2604       SET_BIT(hadc->State, HAL_ADC_STATE_REG_OVR);
2605 
2606       /* Set ADC error code to overrun */
2607       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_OVR);
2608 
2609       /* Error callback */
2610       /* Note: In case of overrun, ADC conversion data is preserved until     */
2611       /*       flag OVR is reset.                                             */
2612       /*       Therefore, old ADC conversion data can be retrieved in         */
2613       /*       function "HAL_ADC_ErrorCallback()".                            */
2614 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2615       hadc->ErrorCallback(hadc);
2616 #else
2617       HAL_ADC_ErrorCallback(hadc);
2618 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2619     }
2620 
2621     /* Clear ADC overrun flag */
2622     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
2623   }
2624 
2625 }
2626 
2627 
2628 /**
2629   * @brief  Conversion complete callback in non-blocking mode.
2630   * @param hadc ADC handle
2631   * @retval None
2632   */
HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef * hadc)2633 __weak void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
2634 {
2635   /* Prevent unused argument(s) compilation warning */
2636   UNUSED(hadc);
2637 
2638   /* NOTE : This function should not be modified. When the callback is needed,
2639             function HAL_ADC_ConvCpltCallback must be implemented in the user file.
2640    */
2641 }
2642 
2643 /**
2644   * @brief  Conversion DMA half-transfer callback in non-blocking mode.
2645   * @param hadc ADC handle
2646   * @retval None
2647   */
HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef * hadc)2648 __weak void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef *hadc)
2649 {
2650   /* Prevent unused argument(s) compilation warning */
2651   UNUSED(hadc);
2652 
2653   /* NOTE : This function should not be modified. When the callback is needed,
2654             function HAL_ADC_ConvHalfCpltCallback must be implemented in the user file.
2655   */
2656 }
2657 
2658 /**
2659   * @brief  Analog watchdog 1 callback in non-blocking mode.
2660   * @param hadc ADC handle
2661   * @retval None
2662   */
HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef * hadc)2663 __weak void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef *hadc)
2664 {
2665   /* Prevent unused argument(s) compilation warning */
2666   UNUSED(hadc);
2667 
2668   /* NOTE : This function should not be modified. When the callback is needed,
2669             function HAL_ADC_LevelOutOfWindowCallback must be implemented in the user file.
2670   */
2671 }
2672 
2673 /**
2674   * @brief  ADC error callback in non-blocking mode
2675   *         (ADC conversion with interruption or transfer by DMA).
2676   * @note   In case of error due to overrun when using ADC with DMA transfer
2677   *         (HAL ADC handle parameter "ErrorCode" to state "HAL_ADC_ERROR_OVR"):
2678   *         - Reinitialize the DMA using function "HAL_ADC_Stop_DMA()".
2679   *         - If needed, restart a new ADC conversion using function
2680   *           "HAL_ADC_Start_DMA()"
2681   *           (this function is also clearing overrun flag)
2682   * @param hadc ADC handle
2683   * @retval None
2684   */
HAL_ADC_ErrorCallback(ADC_HandleTypeDef * hadc)2685 __weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc)
2686 {
2687   /* Prevent unused argument(s) compilation warning */
2688   UNUSED(hadc);
2689 
2690   /* NOTE : This function should not be modified. When the callback is needed,
2691             function HAL_ADC_ErrorCallback must be implemented in the user file.
2692   */
2693 }
2694 
2695 /**
2696   * @}
2697   */
2698 
2699 /** @defgroup ADC_Exported_Functions_Group3 Peripheral Control functions
2700   * @brief    Peripheral Control functions
2701   *
2702 @verbatim
2703  ===============================================================================
2704              ##### Peripheral Control functions #####
2705  ===============================================================================
2706     [..]  This section provides functions allowing to:
2707       (+) Configure channels on regular group
2708       (+) Configure the analog watchdog
2709 
2710 @endverbatim
2711   * @{
2712   */
2713 
2714 /**
2715   * @brief  Configure a channel to be assigned to ADC group regular.
2716   * @note   In case of usage of internal measurement channels (VrefInt, ...):
2717   *         These internal paths can be disabled using function
2718   *         HAL_ADC_DeInit().
2719   * @note   Possibility to update parameters on the fly:
2720   *         This function initializes channel into ADC group regular,
2721   *         following calls to this function can be used to reconfigure
2722   *         some parameters of structure "ADC_ChannelConfTypeDef" on the fly,
2723   *         without resetting the ADC.
2724   *         The setting of these parameters is conditioned to ADC state:
2725   *         Refer to comments of structure "ADC_ChannelConfTypeDef".
2726   * @param hadc ADC handle
2727   * @param pConfig Structure of ADC channel assigned to ADC group regular.
2728   * @retval HAL status
2729   */
HAL_ADC_ConfigChannel(ADC_HandleTypeDef * hadc,const ADC_ChannelConfTypeDef * pConfig)2730 HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef *hadc, const ADC_ChannelConfTypeDef *pConfig)
2731 {
2732   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
2733   uint32_t tmpOffsetShifted;
2734   uint32_t tmp_config_common_path_internal_channel;
2735   uint32_t tmp_config_path_internal_channel;
2736   uint32_t tmp_adc_is_conversion_on_going_regular;
2737   uint32_t tmp_adc_is_conversion_on_going_injected;
2738 
2739   /* Check the parameters */
2740   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2741   assert_param(IS_ADC_REGULAR_RANK(pConfig->Rank));
2742   assert_param(IS_ADC_SAMPLING_TIME(pConfig->SamplingTime));
2743   assert_param(IS_ADC_SINGLE_DIFFERENTIAL(pConfig->SingleDiff));
2744   assert_param(IS_ADC_OFFSET_NUMBER(pConfig->OffsetNumber));
2745   assert_param(IS_ADC_OFFSET(pConfig->Offset));
2746   /* if ROVSE is set, the value of the OFFSETy_EN bit in ADCx_OFRy register is
2747      ignored (considered as reset) */
2748   assert_param(!((pConfig->OffsetNumber != ADC_OFFSET_NONE) && (hadc->Init.OversamplingMode == ENABLE)));
2749 
2750   /* Verification of channel number */
2751   if (pConfig->SingleDiff != ADC_DIFFERENTIAL_ENDED)
2752   {
2753     assert_param(IS_ADC_CHANNEL(hadc, pConfig->Channel));
2754   }
2755   else
2756   {
2757     assert_param(IS_ADC_DIFF_CHANNEL(hadc, pConfig->Channel));
2758   }
2759 
2760   /* ADC must be disabled to set configuration bits                           */
2761   if (LL_ADC_IsEnabled(hadc->Instance) != 0UL)
2762   {
2763     return HAL_ERROR;
2764   }
2765 
2766   /* Process locked */
2767   __HAL_LOCK(hadc);
2768 
2769   /* Parameters update conditioned to ADC state:                              */
2770   /* Parameters that can be updated when ADC is disabled or enabled without   */
2771   /* conversion on going on regular group:                                    */
2772   /*  - Channel number                                                        */
2773   /*  - Channel rank                                                          */
2774   if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL)
2775   {
2776     /* ADC channels preselection */
2777     LL_ADC_SetChannelPreselection(hadc->Instance, pConfig->Channel);
2778 
2779     /* Set ADC group regular sequence: channel on the selected scan sequence rank */
2780     LL_ADC_REG_SetSequencerRanks(hadc->Instance, pConfig->Rank, pConfig->Channel);
2781 
2782     /* Parameters update conditioned to ADC state:                              */
2783     /* Parameters that can be updated when ADC is disabled or enabled without   */
2784     /* conversion on going on regular group:                                    */
2785     /*  - Channel sampling time                                                 */
2786     /*  - Channel offset                                                        */
2787     tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
2788     tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
2789     if ((tmp_adc_is_conversion_on_going_regular == 0UL)
2790         && (tmp_adc_is_conversion_on_going_injected == 0UL)
2791        )
2792     {
2793       /* Set sampling time of the selected ADC channel */
2794       LL_ADC_SetChannelSamplingTime(hadc->Instance, pConfig->Channel, pConfig->SamplingTime);
2795 
2796       /* Configure the offset: offset enable/disable, channel, offset value */
2797 
2798       /* Shift the offset with respect to the selected ADC resolution. */
2799       /* Offset has to be left-aligned on bit 11, the LSB (right bits) are set to 0 */
2800       tmpOffsetShifted = ADC_OFFSET_SHIFT_RESOLUTION(hadc, (uint32_t)pConfig->Offset);
2801 
2802       if (pConfig->OffsetNumber != ADC_OFFSET_NONE)
2803       {
2804         /* Set ADC selected offset number */
2805         LL_ADC_SetOffsetChannel(hadc->Instance, pConfig->OffsetNumber, pConfig->Channel);
2806         LL_ADC_SetOffsetLevel(hadc->Instance, pConfig->OffsetNumber, tmpOffsetShifted);
2807 
2808         assert_param(IS_ADC_OFFSET_SIGN(pConfig->OffsetSign));
2809         assert_param(IS_FUNCTIONAL_STATE(pConfig->OffsetSignedSaturation));
2810         assert_param(IS_FUNCTIONAL_STATE(pConfig->OffsetSaturation));
2811         /* Signed and unsigned saturation cannot be set at the same time */
2812         assert_param(!((pConfig->OffsetSignedSaturation == ENABLE) && (pConfig->OffsetSaturation == ENABLE)));
2813 
2814 
2815         /* Set ADC offset sign */
2816         LL_ADC_SetOffsetSign(hadc->Instance, pConfig->OffsetNumber, pConfig->OffsetSign);
2817         /* Set ADC offset signed saturation */
2818         LL_ADC_SetOffsetSignedSaturation(hadc->Instance, pConfig->OffsetNumber,      \
2819                                          (pConfig->OffsetSignedSaturation == ENABLE) \
2820                                          ? LL_ADC_OFFSET_SIGNED_SAT_ENABLE           \
2821                                          : LL_ADC_OFFSET_SIGNED_SAT_DISABLE);
2822         /* Set ADC offset unsigned saturation */
2823         LL_ADC_SetOffsetUnsignedSaturation(hadc->Instance, pConfig->OffsetNumber,    \
2824                                            (pConfig->OffsetSaturation == ENABLE)     \
2825                                            ? LL_ADC_OFFSET_UNSIGNED_SAT_ENABLE       \
2826                                            : LL_ADC_OFFSET_UNSIGNED_SAT_DISABLE);
2827       }
2828       else
2829       {
2830         /* Scan each offset register to check if the selected channel is targeted.
2831            If this is the case, the corresponding offset number is disabled.       */
2832         if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_1))
2833             == __HAL_ADC_CHANNEL_TO_DECIMAL_NB(pConfig->Channel))
2834         {
2835           LL_ADC_SetOffsetLevel(hadc->Instance, LL_ADC_OFFSET_1, 0UL);
2836         }
2837         if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_2))
2838             == __HAL_ADC_CHANNEL_TO_DECIMAL_NB(pConfig->Channel))
2839         {
2840           LL_ADC_SetOffsetLevel(hadc->Instance, LL_ADC_OFFSET_2, 0UL);
2841         }
2842         if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_3))
2843             == __HAL_ADC_CHANNEL_TO_DECIMAL_NB(pConfig->Channel))
2844         {
2845           LL_ADC_SetOffsetLevel(hadc->Instance, LL_ADC_OFFSET_3, 0UL);
2846         }
2847         if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_4))
2848             == __HAL_ADC_CHANNEL_TO_DECIMAL_NB(pConfig->Channel))
2849         {
2850           LL_ADC_SetOffsetLevel(hadc->Instance, LL_ADC_OFFSET_4, 0UL);
2851         }
2852       }
2853     }
2854 
2855     /* Parameters update conditioned to ADC state:                              */
2856     /* Parameters that can be updated only when ADC is disabled:                */
2857     /*  - Single or differential mode                                           */
2858     /*  - Internal measurement channels: Vbat/VrefInt/TempSensor                */
2859     if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
2860     {
2861       /* Set mode single-ended or differential input of the selected ADC channel */
2862       LL_ADC_SetChannelSingleDiff(hadc->Instance, pConfig->Channel, pConfig->SingleDiff);
2863 
2864       /* Configuration of differential mode */
2865       if (pConfig->SingleDiff == ADC_DIFFERENTIAL_ENDED)
2866       {
2867         /* Set ADC channel preselection of corresponding negative channel */
2868         LL_ADC_SetChannelPreselection(hadc->Instance,
2869                                       __HAL_ADC_CHANNEL_DIFF_NEG_INPUT(hadc, pConfig->Channel));
2870       }
2871 
2872     }
2873     /* Management of internal measurement channels: Vbat/VrefInt/TempSensor.  */
2874     /* If internal channel selected, enable dedicated internal buffers and    */
2875     /* paths.                                                                 */
2876     /* Note: these internal measurement paths can be disabled using           */
2877     /* HAL_ADC_DeInit().                                                      */
2878 
2879     if (__LL_ADC_IS_CHANNEL_INTERNAL(pConfig->Channel))
2880     {
2881       tmp_config_common_path_internal_channel =
2882         LL_ADC_GetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance));
2883       tmp_config_path_internal_channel = LL_ADC_GetPathInternalCh(hadc->Instance);
2884       /* If the requested internal measurement path has already been enabled, */
2885       /* bypass the configuration processing.                                 */
2886       if ((pConfig->Channel == ADC_CHANNEL_VREFINT)
2887           && ((tmp_config_common_path_internal_channel & LL_ADC_PATH_INTERNAL_VREFINT) == 0UL))
2888       {
2889         if (ADC_VREFINT_INSTANCE(hadc))
2890         {
2891           LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
2892                                          LL_ADC_PATH_INTERNAL_VREFINT | tmp_config_common_path_internal_channel);
2893         }
2894       }
2895       else if ((pConfig->Channel == ADC_CHANNEL_VBAT)
2896                && ((tmp_config_common_path_internal_channel & LL_ADC_PATH_INTERNAL_VBAT) == 0UL))
2897       {
2898         if (ADC_BATTERY_VOLTAGE_INSTANCE(hadc))
2899         {
2900           LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance),
2901                                          LL_ADC_PATH_INTERNAL_VBAT | tmp_config_common_path_internal_channel);
2902         }
2903       }
2904       else if (((pConfig->Channel == ADC_CHANNEL_VDDCORE)
2905                 && ((tmp_config_path_internal_channel & LL_ADC_PATH_INTERNAL_VDDCORE) == 0UL)))
2906       {
2907         if (ADC_VDDCORE_INSTANCE(hadc))
2908         {
2909           LL_ADC_SetPathInternalCh(hadc->Instance, LL_ADC_PATH_INTERNAL_VDDCORE | tmp_config_path_internal_channel);
2910         }
2911       }
2912       else
2913       {
2914         /* nothing to do */
2915       }
2916     }
2917   }
2918 
2919   /* If a conversion is on going on regular group, no update on regular       */
2920   /* channel could be done on neither of the channel configuration structure  */
2921   /* parameters.                                                              */
2922   else
2923   {
2924     /* Update ADC state machine to error */
2925     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
2926 
2927     tmp_hal_status = HAL_ERROR;
2928   }
2929 
2930   __HAL_UNLOCK(hadc);
2931 
2932   return tmp_hal_status;
2933 }
2934 
2935 /**
2936   * @brief  Configure the analog watchdog.
2937   * @note   Possibility to update parameters on the fly:
2938   *         This function initializes the selected analog watchdog, successive
2939   *         calls to this function can be used to reconfigure some parameters
2940   *         of structure "ADC_AnalogWDGConfTypeDef" on the fly, without resetting
2941   *         the ADC.
2942   *         The setting of these parameters is conditioned to ADC state.
2943   *         For parameters constraints, see comments of structure
2944   *         "ADC_AnalogWDGConfTypeDef".
2945   * @note   On this STM32 series, analog watchdog thresholds can be modified
2946   *         while ADC conversion is on going.
2947   *         In this case, some constraints must be taken into account:
2948   *         the programmed threshold values are effective from the next
2949   *         ADC EOC (end of unitary conversion).
2950   *         Considering that registers write delay may happen due to
2951   *         bus activity, this might cause an uncertainty on the
2952   *         effective timing of the new programmed threshold values.
2953   * @param hadc ADC handle
2954   * @param pAnalogWDGConfig Structure of ADC analog watchdog configuration
2955   * @retval HAL status
2956   */
HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef * hadc,const ADC_AnalogWDGConfTypeDef * pAnalogWDGConfig)2957 HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef *hadc, const ADC_AnalogWDGConfTypeDef *pAnalogWDGConfig)
2958 {
2959   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
2960   uint32_t tmp_awd_high_threshold_shifted;
2961   uint32_t tmp_awd_low_threshold_shifted;
2962   uint32_t tmp_adc_resolution;
2963   uint32_t tmp_adc_is_conversion_on_going_regular;
2964   uint32_t tmp_adc_is_conversion_on_going_injected;
2965 
2966   /* Check the parameters */
2967   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
2968   assert_param(IS_ADC_ANALOG_WATCHDOG_NUMBER(pAnalogWDGConfig->WatchdogNumber));
2969   assert_param(IS_ADC_ANALOG_WATCHDOG_MODE(pAnalogWDGConfig->WatchdogMode));
2970   assert_param(IS_FUNCTIONAL_STATE(pAnalogWDGConfig->ITMode));
2971 
2972   if ((pAnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG)     ||
2973       (pAnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC)   ||
2974       (pAnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC))
2975   {
2976     assert_param(IS_ADC_CHANNEL(hadc, pAnalogWDGConfig->Channel));
2977   }
2978 
2979   /* Verify thresholds range */
2980   if (hadc->Init.OversamplingMode == ENABLE)
2981   {
2982     /* Case of oversampling enabled: thresholds are compared to oversampling
2983        intermediate computation (after ratio, before shift application) */
2984     assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc),
2985                               pAnalogWDGConfig->HighThreshold / (hadc->Init.Oversampling.Ratio + 1UL)));
2986     assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc),
2987                               pAnalogWDGConfig->LowThreshold / (hadc->Init.Oversampling.Ratio + 1UL)));
2988   }
2989   else
2990   {
2991     /* Verify if thresholds are within the selected ADC resolution */
2992     assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), pAnalogWDGConfig->HighThreshold));
2993     assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), pAnalogWDGConfig->LowThreshold));
2994   }
2995 
2996   /* ADC must be disabled to set configuration bits                           */
2997   if (LL_ADC_IsEnabled(hadc->Instance) != 0UL)
2998   {
2999     return HAL_ERROR;
3000   }
3001 
3002   /* Process locked */
3003   __HAL_LOCK(hadc);
3004 
3005   /* Parameters update conditioned to ADC state:                              */
3006   /* Parameters that can be updated when ADC is disabled or enabled without   */
3007   /* conversion on going on ADC groups regular and injected:                  */
3008   /*  - Analog watchdog channels                                              */
3009   /*  - Analog watchdog thresholds                                            */
3010   tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
3011   tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
3012 
3013   if ((tmp_adc_is_conversion_on_going_regular == 0UL)
3014       && (tmp_adc_is_conversion_on_going_injected == 0UL)
3015      )
3016   {
3017     /* Format analog watchdog thresholds data in function of the selected ADC resolution */
3018     tmp_adc_resolution = LL_ADC_GetResolution(hadc->Instance);
3019     tmp_awd_high_threshold_shifted = __LL_ADC_ANALOGWD_SET_THRESHOLD_RESOLUTION(tmp_adc_resolution,
3020                                                                                 pAnalogWDGConfig->HighThreshold);
3021     tmp_awd_low_threshold_shifted = __LL_ADC_ANALOGWD_SET_THRESHOLD_RESOLUTION(tmp_adc_resolution,
3022                                                                                pAnalogWDGConfig->LowThreshold);
3023 
3024     /* Analog watchdog configuration */
3025     if (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_1)
3026     {
3027       /* Configuration of analog watchdog:                                    */
3028       /*  - Set the analog watchdog enable mode: one or overall group of      */
3029       /*    channels, on groups regular and-or injected.                      */
3030       switch (pAnalogWDGConfig->WatchdogMode)
3031       {
3032         case ADC_ANALOGWATCHDOG_SINGLE_REG:
3033           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1,
3034                                           __LL_ADC_ANALOGWD_CHANNEL_GROUP(pAnalogWDGConfig->Channel,
3035                                                                           LL_ADC_GROUP_REGULAR));
3036           break;
3037 
3038         case ADC_ANALOGWATCHDOG_SINGLE_INJEC:
3039           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1,
3040                                           __LL_ADC_ANALOGWD_CHANNEL_GROUP(pAnalogWDGConfig->Channel,
3041                                                                           LL_ADC_GROUP_INJECTED));
3042           break;
3043 
3044         case ADC_ANALOGWATCHDOG_SINGLE_REGINJEC:
3045           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1,
3046                                           __LL_ADC_ANALOGWD_CHANNEL_GROUP(pAnalogWDGConfig->Channel,
3047                                                                           LL_ADC_GROUP_REGULAR_INJECTED));
3048           break;
3049 
3050         case ADC_ANALOGWATCHDOG_ALL_REG:
3051           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_ALL_CHANNELS_REG);
3052           break;
3053 
3054         case ADC_ANALOGWATCHDOG_ALL_INJEC:
3055           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_ALL_CHANNELS_INJ);
3056           break;
3057 
3058         case ADC_ANALOGWATCHDOG_ALL_REGINJEC:
3059           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_ALL_CHANNELS_REG_INJ);
3060           break;
3061 
3062         default: /* ADC_ANALOGWATCHDOG_NONE */
3063           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, LL_ADC_AWD1, LL_ADC_AWD_DISABLE);
3064           break;
3065       }
3066 
3067       /* Set the filtering configuration */
3068       assert_param(IS_ADC_ANALOG_WATCHDOG_FILTERING_MODE(pAnalogWDGConfig->FilteringConfig));
3069       LL_ADC_SetAWDFilteringConfiguration(hadc->Instance, hadc->Instance->AWD1HTR, pAnalogWDGConfig->FilteringConfig);
3070 
3071       /* Set ADC analog watchdog thresholds value of both thresholds high and low */
3072       LL_ADC_SetAnalogWDThresholds(hadc->Instance, pAnalogWDGConfig->WatchdogNumber,
3073                                    LL_ADC_AWD_THRESHOLD_HIGH, tmp_awd_high_threshold_shifted);
3074       LL_ADC_SetAnalogWDThresholds(hadc->Instance, pAnalogWDGConfig->WatchdogNumber,
3075                                    LL_ADC_AWD_THRESHOLD_LOW, tmp_awd_low_threshold_shifted);
3076 
3077       /* Update state, clear previous result related to AWD1 */
3078       CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD1);
3079 
3080       /* Clear flag ADC analog watchdog */
3081       /* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready  */
3082       /* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent()          */
3083       /* (in case left enabled by previous ADC operations).                 */
3084       LL_ADC_ClearFlag_AWD1(hadc->Instance);
3085 
3086       /* Configure ADC analog watchdog interrupt */
3087       if (pAnalogWDGConfig->ITMode == ENABLE)
3088       {
3089         LL_ADC_EnableIT_AWD1(hadc->Instance);
3090       }
3091       else
3092       {
3093         LL_ADC_DisableIT_AWD1(hadc->Instance);
3094       }
3095     }
3096     /* Case of ADC_ANALOGWATCHDOG_2 or ADC_ANALOGWATCHDOG_3 */
3097     else
3098     {
3099       switch (pAnalogWDGConfig->WatchdogMode)
3100       {
3101         case ADC_ANALOGWATCHDOG_SINGLE_REG:
3102         case ADC_ANALOGWATCHDOG_SINGLE_INJEC:
3103         case ADC_ANALOGWATCHDOG_SINGLE_REGINJEC:
3104           /* Update AWD by bitfield to keep the possibility to monitor        */
3105           /* several channels by successive calls of this function.           */
3106           if (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_2)
3107           {
3108             SET_BIT(hadc->Instance->AWD2CR, (1UL                                                       \
3109                                              << (__LL_ADC_CHANNEL_TO_DECIMAL_NB(pAnalogWDGConfig->Channel) & 0x1FUL)));
3110           }
3111           else
3112           {
3113             SET_BIT(hadc->Instance->AWD3CR, (1UL                                                      \
3114                                              << (__LL_ADC_CHANNEL_TO_DECIMAL_NB(pAnalogWDGConfig->Channel) & 0x1FUL)));
3115           }
3116           break;
3117 
3118         case ADC_ANALOGWATCHDOG_ALL_REG:
3119         case ADC_ANALOGWATCHDOG_ALL_INJEC:
3120         case ADC_ANALOGWATCHDOG_ALL_REGINJEC:
3121           /* Update AWD by bitfield to keep the possibility to monitor        */
3122           /* several channels by successive calls of this function.           */
3123           if (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_2)
3124           {
3125             SET_BIT(hadc->Instance->AWD2CR, (1UL                                                           \
3126                                              << (__LL_ADC_CHANNEL_TO_DECIMAL_NB(pAnalogWDGConfig->Channel) & 0x1FUL)));
3127           }
3128           else
3129           {
3130             SET_BIT(hadc->Instance->AWD3CR, (1UL                                                        \
3131                                              << (__LL_ADC_CHANNEL_TO_DECIMAL_NB(pAnalogWDGConfig->Channel) & 0x1FUL)));
3132           }
3133           break;
3134 
3135         default: /* ADC_ANALOGWATCHDOG_NONE */
3136           LL_ADC_SetAnalogWDMonitChannels(hadc->Instance, pAnalogWDGConfig->WatchdogNumber, LL_ADC_AWD_DISABLE);
3137           break;
3138       }
3139 
3140       if (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_2)
3141       {
3142         /* Set ADC analog watchdog thresholds value of both thresholds high and low */
3143         MODIFY_REG(hadc->Instance->AWD2LTR, ADC_AWD2LTR_LTR, tmp_awd_low_threshold_shifted);
3144         MODIFY_REG(hadc->Instance->AWD2HTR, ADC_AWD2HTR_HTR, tmp_awd_high_threshold_shifted);
3145       }
3146       else
3147       {
3148         /* Set ADC analog watchdog thresholds value of both thresholds high and low */
3149         MODIFY_REG(hadc->Instance->AWD3LTR, ADC_AWD3LTR_LTR, tmp_awd_low_threshold_shifted);
3150         MODIFY_REG(hadc->Instance->AWD3HTR, ADC_AWD3HTR_HTR, tmp_awd_high_threshold_shifted);
3151       }
3152 
3153       if (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_2)
3154       {
3155         /* Update state, clear previous result related to AWD2 */
3156         CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD2);
3157 
3158         /* Clear flag ADC analog watchdog */
3159         /* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready  */
3160         /* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent()          */
3161         /* (in case left enabled by previous ADC operations).                 */
3162         LL_ADC_ClearFlag_AWD2(hadc->Instance);
3163 
3164         /* Configure ADC analog watchdog interrupt */
3165         if (pAnalogWDGConfig->ITMode == ENABLE)
3166         {
3167           LL_ADC_EnableIT_AWD2(hadc->Instance);
3168         }
3169         else
3170         {
3171           LL_ADC_DisableIT_AWD2(hadc->Instance);
3172         }
3173       }
3174       /* (pAnalogWDGConfig->WatchdogNumber == ADC_ANALOGWATCHDOG_3) */
3175       else
3176       {
3177         /* Update state, clear previous result related to AWD3 */
3178         CLEAR_BIT(hadc->State, HAL_ADC_STATE_AWD3);
3179 
3180         /* Clear flag ADC analog watchdog */
3181         /* Note: Flag cleared Clear the ADC Analog watchdog flag to be ready  */
3182         /* to use for HAL_ADC_IRQHandler() or HAL_ADC_PollForEvent()          */
3183         /* (in case left enabled by previous ADC operations).                 */
3184         LL_ADC_ClearFlag_AWD3(hadc->Instance);
3185 
3186         /* Configure ADC analog watchdog interrupt */
3187         if (pAnalogWDGConfig->ITMode == ENABLE)
3188         {
3189           LL_ADC_EnableIT_AWD3(hadc->Instance);
3190         }
3191         else
3192         {
3193           LL_ADC_DisableIT_AWD3(hadc->Instance);
3194         }
3195       }
3196     }
3197 
3198   }
3199   /* If a conversion is on going on ADC group regular or injected, no update  */
3200   /* could be done on neither of the AWD configuration structure parameters.  */
3201   else
3202   {
3203     /* Update ADC state machine to error */
3204     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
3205 
3206     tmp_hal_status = HAL_ERROR;
3207   }
3208 
3209   __HAL_UNLOCK(hadc);
3210 
3211   return tmp_hal_status;
3212 }
3213 
3214 
3215 /**
3216   * @}
3217   */
3218 
3219 /** @defgroup ADC_Exported_Functions_Group4 Peripheral State functions
3220   *  @brief    ADC Peripheral State functions
3221   *
3222 @verbatim
3223  ===============================================================================
3224             ##### Peripheral state and errors functions #####
3225  ===============================================================================
3226     [..]
3227     This subsection provides functions to get in run-time the status of the
3228     peripheral.
3229       (+) Check the ADC state
3230       (+) Check the ADC error code
3231 
3232 @endverbatim
3233   * @{
3234   */
3235 
3236 /**
3237   * @brief  Return the ADC handle state.
3238   * @note   ADC state machine is managed by bitfields, ADC status must be
3239   *         compared with states bits.
3240   *         For example:
3241   *           " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_REG_BUSY) != 0UL) "
3242   *           " if ((HAL_ADC_GetState(hadc1) & HAL_ADC_STATE_AWD1) != 0UL) "
3243   * @param hadc ADC handle
3244   * @retval ADC handle state (bitfield on 32 bits)
3245   */
HAL_ADC_GetState(const ADC_HandleTypeDef * hadc)3246 uint32_t HAL_ADC_GetState(const ADC_HandleTypeDef *hadc)
3247 {
3248   /* Check the parameters */
3249   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
3250 
3251   /* Return ADC handle state */
3252   return hadc->State;
3253 }
3254 
3255 /**
3256   * @brief  Return the ADC error code.
3257   * @param hadc ADC handle
3258   * @retval ADC error code (bitfield on 32 bits)
3259   */
HAL_ADC_GetError(const ADC_HandleTypeDef * hadc)3260 uint32_t HAL_ADC_GetError(const ADC_HandleTypeDef *hadc)
3261 {
3262   /* Check the parameters */
3263   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
3264 
3265   return hadc->ErrorCode;
3266 }
3267 
3268 /**
3269   * @}
3270   */
3271 
3272 /**
3273   * @}
3274   */
3275 
3276 /** @defgroup ADC_Private_Functions ADC Private Functions
3277   * @{
3278   */
3279 
3280 /**
3281   * @brief  Stop ADC conversion.
3282   * @param hadc ADC handle
3283   * @param ConversionGroup ADC group regular and/or injected.
3284   *          This parameter can be one of the following values:
3285   *            @arg @ref ADC_REGULAR_GROUP           ADC regular conversion type.
3286   *            @arg @ref ADC_INJECTED_GROUP          ADC injected conversion type.
3287   *            @arg @ref ADC_REGULAR_INJECTED_GROUP  ADC regular and injected conversion type.
3288   * @retval HAL status.
3289   */
ADC_ConversionStop(ADC_HandleTypeDef * hadc,uint32_t ConversionGroup)3290 HAL_StatusTypeDef ADC_ConversionStop(ADC_HandleTypeDef *hadc, uint32_t ConversionGroup)
3291 {
3292   uint32_t tickstart;
3293   uint32_t conversion_timeout_cpu_cycles = 0UL;
3294   uint32_t conversion_group_reassigned = ConversionGroup;
3295   uint32_t tmp_ADC_CR_ADSTART_JADSTART;
3296   uint32_t tmp_adc_is_conversion_on_going_regular;
3297   uint32_t tmp_adc_is_conversion_on_going_injected;
3298 
3299   /* Check the parameters */
3300   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
3301   assert_param(IS_ADC_CONVERSION_GROUP(ConversionGroup));
3302 
3303   /* Verification if ADC is not already stopped (on regular and injected      */
3304   /* groups) to bypass this function if not needed.                           */
3305   tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance);
3306   tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance);
3307   if ((tmp_adc_is_conversion_on_going_regular != 0UL)
3308       || (tmp_adc_is_conversion_on_going_injected != 0UL)
3309      )
3310   {
3311     /* Particular case of continuous auto-injection mode combined with        */
3312     /* auto-delay mode.                                                       */
3313     /* In auto-injection mode, regular group stop ADC_CR_ADSTP is used (not   */
3314     /* injected group stop ADC_CR_JADSTP).                                    */
3315     /* Procedure to be followed: Wait until JEOS=1, clear JEOS, set ADSTP=1   */
3316     /* (see reference manual).                                                */
3317     if (((hadc->Instance->CFGR1 & ADC_CFGR1_JAUTO) != 0UL)
3318         && (hadc->Init.ContinuousConvMode == ENABLE)
3319         && (hadc->Init.LowPowerAutoWait == ENABLE)
3320        )
3321     {
3322       /* Use stop of regular group */
3323       conversion_group_reassigned = ADC_REGULAR_GROUP;
3324 
3325       /* Wait until JEOS=1 (maximum Timeout: 4 injected conversions) */
3326       while (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOS) == 0UL)
3327       {
3328         if (conversion_timeout_cpu_cycles >= (ADC_CONVERSION_TIME_MAX_CPU_CYCLES * 4UL))
3329         {
3330           /* Update ADC state machine to error */
3331           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
3332 
3333           /* Set ADC error code to ADC peripheral internal error */
3334           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
3335 
3336           return HAL_ERROR;
3337         }
3338         conversion_timeout_cpu_cycles ++;
3339       }
3340 
3341       /* Clear JEOS */
3342       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOS);
3343     }
3344 
3345     /* Stop potential conversion on going on ADC group regular */
3346     if (conversion_group_reassigned != ADC_INJECTED_GROUP)
3347     {
3348       /* Software is allowed to set ADSTP only when ADSTART=1 and ADDIS=0 */
3349       if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) != 0UL)
3350       {
3351         if (LL_ADC_IsDisableOngoing(hadc->Instance) == 0UL)
3352         {
3353           /* Stop ADC group regular conversion */
3354           LL_ADC_REG_StopConversion(hadc->Instance);
3355         }
3356       }
3357     }
3358 
3359     /* Stop potential conversion on going on ADC group injected */
3360     if (conversion_group_reassigned != ADC_REGULAR_GROUP)
3361     {
3362       /* Software is allowed to set JADSTP only when JADSTART=1 and ADDIS=0 */
3363       if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) != 0UL)
3364       {
3365         if (LL_ADC_IsDisableOngoing(hadc->Instance) == 0UL)
3366         {
3367           /* Stop ADC group injected conversion */
3368           LL_ADC_INJ_StopConversion(hadc->Instance);
3369         }
3370       }
3371     }
3372 
3373     /* Selection of start and stop bits with respect to the regular or injected group */
3374     switch (conversion_group_reassigned)
3375     {
3376       case ADC_REGULAR_INJECTED_GROUP:
3377         tmp_ADC_CR_ADSTART_JADSTART = (ADC_CR_ADSTART | ADC_CR_JADSTART);
3378         break;
3379       case ADC_INJECTED_GROUP:
3380         tmp_ADC_CR_ADSTART_JADSTART = ADC_CR_JADSTART;
3381         break;
3382       /* Case ADC_REGULAR_GROUP only*/
3383       default:
3384         tmp_ADC_CR_ADSTART_JADSTART = ADC_CR_ADSTART;
3385         break;
3386     }
3387 
3388     /* Wait for conversion effectively stopped */
3389     tickstart = HAL_GetTick();
3390 
3391     while ((hadc->Instance->CR & tmp_ADC_CR_ADSTART_JADSTART) != 0UL)
3392     {
3393       if ((HAL_GetTick() - tickstart) > ADC_STOP_CONVERSION_TIMEOUT)
3394       {
3395         /* New check to avoid false timeout detection in case of preemption */
3396         if ((hadc->Instance->CR & tmp_ADC_CR_ADSTART_JADSTART) != 0UL)
3397         {
3398           /* Update ADC state machine to error */
3399           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
3400 
3401           /* Set ADC error code to ADC peripheral internal error */
3402           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
3403 
3404           return HAL_ERROR;
3405         }
3406       }
3407     }
3408 
3409   }
3410 
3411   /* Return HAL status */
3412   return HAL_OK;
3413 }
3414 
3415 /**
3416   * @brief  Enable the selected ADC.
3417   * @note   Prerequisite condition to use this function: ADC must be disabled
3418   *         and voltage regulator must be enabled (done into HAL_ADC_Init()).
3419   * @param hadc ADC handle
3420   * @retval HAL status.
3421   */
ADC_Enable(ADC_HandleTypeDef * hadc)3422 HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef *hadc)
3423 {
3424   uint32_t tickstart;
3425 
3426   /* ADC enable and wait for ADC ready (in case of ADC is disabled or         */
3427   /* enabling phase not yet completed: flag ADC ready not yet set).           */
3428   /* Timeout implemented to not be stuck if ADC cannot be enabled (possible   */
3429   /* causes: ADC clock not running, ...).                                     */
3430   if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
3431   {
3432     /* Check if conditions to enable the ADC are fulfilled */
3433     if ((hadc->Instance->CR & (ADC_CR_ADCAL | ADC_CR_JADSTP | ADC_CR_ADSTP | ADC_CR_JADSTART | ADC_CR_ADSTART
3434                                | ADC_CR_ADDIS | ADC_CR_ADEN)) != 0UL)
3435     {
3436       /* Update ADC state machine to error */
3437       SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
3438 
3439       /* Set ADC error code to ADC peripheral internal error */
3440       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
3441 
3442       return HAL_ERROR;
3443     }
3444 
3445     /* Enable the ADC peripheral */
3446     LL_ADC_Enable(hadc->Instance);
3447 
3448     /* Wait for ADC effectively enabled */
3449     tickstart = HAL_GetTick();
3450 
3451     while (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_RDY) == 0UL)
3452     {
3453       /*  If ADEN bit is set less than 4 ADC clock cycles after the ADCAL bit
3454           has been cleared (after a calibration), ADEN bit is reset by the
3455           calibration logic.
3456           The workaround is to continue setting ADEN until ADRDY is becomes 1.
3457           Additionally, ADC_ENABLE_TIMEOUT is defined to encompass this
3458           4 ADC clock cycle duration */
3459       /* Note: Test of ADC enabled required due to hardware constraint to     */
3460       /*       not enable ADC if already enabled.                             */
3461       if (LL_ADC_IsEnabled(hadc->Instance) == 0UL)
3462       {
3463         LL_ADC_Enable(hadc->Instance);
3464       }
3465 
3466       if ((HAL_GetTick() - tickstart) > ADC_ENABLE_TIMEOUT)
3467       {
3468         /* New check to avoid false timeout detection in case of preemption */
3469         if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_RDY) == 0UL)
3470         {
3471           /* Update ADC state machine to error */
3472           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
3473 
3474           /* Set ADC error code to ADC peripheral internal error */
3475           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
3476 
3477           return HAL_ERROR;
3478         }
3479       }
3480     }
3481   }
3482 
3483   /* Return HAL status */
3484   return HAL_OK;
3485 }
3486 
3487 /**
3488   * @brief  Disable the selected ADC.
3489   * @note   Prerequisite condition to use this function: ADC conversions must be
3490   *         stopped.
3491   * @param hadc ADC handle
3492   * @retval HAL status.
3493   */
ADC_Disable(ADC_HandleTypeDef * hadc)3494 HAL_StatusTypeDef ADC_Disable(ADC_HandleTypeDef *hadc)
3495 {
3496   uint32_t tickstart;
3497   const uint32_t tmp_adc_is_disable_on_going = LL_ADC_IsDisableOngoing(hadc->Instance);
3498 
3499   /* Verification if ADC is not already disabled:                             */
3500   /* Note: forbidden to disable ADC (set bit ADC_CR_ADDIS) if ADC is already  */
3501   /*       disabled.                                                          */
3502   if ((LL_ADC_IsEnabled(hadc->Instance) != 0UL)
3503       && (tmp_adc_is_disable_on_going == 0UL)
3504      )
3505   {
3506     /* Check if conditions to disable the ADC are fulfilled */
3507     if ((hadc->Instance->CR & (ADC_CR_JADSTART | ADC_CR_ADSTART | ADC_CR_ADEN)) == ADC_CR_ADEN)
3508     {
3509       /* Disable the ADC peripheral */
3510       LL_ADC_Disable(hadc->Instance);
3511       __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOSMP | ADC_FLAG_RDY));
3512     }
3513     else
3514     {
3515       /* Update ADC state machine to error */
3516       SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
3517 
3518       /* Set ADC error code to ADC peripheral internal error */
3519       SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
3520 
3521       return HAL_ERROR;
3522     }
3523 
3524     /* Wait for ADC effectively disabled */
3525     /* Get tick count */
3526     tickstart = HAL_GetTick();
3527 
3528     while ((hadc->Instance->CR & ADC_CR_ADEN) != 0UL)
3529     {
3530       if ((HAL_GetTick() - tickstart) > ADC_DISABLE_TIMEOUT)
3531       {
3532         /* New check to avoid false timeout detection in case of preemption */
3533         if ((hadc->Instance->CR & ADC_CR_ADEN) != 0UL)
3534         {
3535           /* Update ADC state machine to error */
3536           SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
3537 
3538           /* Set ADC error code to ADC peripheral internal error */
3539           SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
3540 
3541           return HAL_ERROR;
3542         }
3543       }
3544     }
3545   }
3546 
3547   /* Return HAL status */
3548   return HAL_OK;
3549 }
3550 
3551 /**
3552   * @brief  DMA transfer complete callback.
3553   * @param hdma pointer to DMA handle.
3554   * @retval None
3555   */
ADC_DMAConvCplt(DMA_HandleTypeDef * hdma)3556 void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma)
3557 {
3558   /* Retrieve ADC handle corresponding to current DMA handle */
3559   ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
3560 
3561   /* Update state machine on conversion status if not in error state */
3562   if ((hadc->State & (HAL_ADC_STATE_ERROR_INTERNAL | HAL_ADC_STATE_ERROR_DMA)) == 0UL)
3563   {
3564     /* Set ADC state */
3565     SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
3566 
3567     /* Determine whether any further conversion upcoming on group regular     */
3568     /* by external trigger, continuous mode or scan sequence on going         */
3569     /* to disable interruption.                                               */
3570     /* Is it the end of the regular sequence ? */
3571     if ((hadc->Instance->ISR & ADC_FLAG_EOS) != 0UL)
3572     {
3573       /* Are conversions software-triggered ? */
3574       if (LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance) != 0UL)
3575       {
3576         /* Is CONT bit set ? */
3577         if (READ_BIT(hadc->Instance->CFGR1, ADC_CFGR1_CONT) == 0UL)
3578         {
3579           /* CONT bit is not set, no more conversions expected */
3580           CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
3581           if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) == 0UL)
3582           {
3583             SET_BIT(hadc->State, HAL_ADC_STATE_READY);
3584           }
3585         }
3586       }
3587     }
3588     else
3589     {
3590       /* DMA End of Transfer interrupt was triggered but conversions sequence
3591          is not over. If DMACFG is set to 0, conversions are stopped. */
3592       if (READ_BIT(hadc->Instance->CFGR1, ADC_CFGR1_DMNGT) == 0UL)
3593       {
3594         /* DMACFG bit is not set, conversions are stopped. */
3595         CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
3596         if ((hadc->State & HAL_ADC_STATE_INJ_BUSY) == 0UL)
3597         {
3598           SET_BIT(hadc->State, HAL_ADC_STATE_READY);
3599         }
3600       }
3601     }
3602 
3603     /* Conversion complete callback */
3604 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
3605     hadc->ConvCpltCallback(hadc);
3606 #else
3607     HAL_ADC_ConvCpltCallback(hadc);
3608 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
3609   }
3610   else /* DMA and-or internal error occurred */
3611   {
3612     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) != 0UL)
3613     {
3614       /* Call HAL ADC Error Callback function */
3615 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
3616       hadc->ErrorCallback(hadc);
3617 #else
3618       HAL_ADC_ErrorCallback(hadc);
3619 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
3620     }
3621     else
3622     {
3623       /* Call ADC DMA error callback */
3624       hadc->DMA_Handle->XferErrorCallback(hdma);
3625     }
3626   }
3627 }
3628 
3629 /**
3630   * @brief  DMA half transfer complete callback.
3631   * @param hdma pointer to DMA handle.
3632   * @retval None
3633   */
ADC_DMAHalfConvCplt(DMA_HandleTypeDef * hdma)3634 void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma)
3635 {
3636   /* Retrieve ADC handle corresponding to current DMA handle */
3637   ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
3638 
3639   /* Half conversion callback */
3640 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
3641   hadc->ConvHalfCpltCallback(hadc);
3642 #else
3643   HAL_ADC_ConvHalfCpltCallback(hadc);
3644 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
3645 }
3646 
3647 /**
3648   * @brief  DMA error callback.
3649   * @param hdma pointer to DMA handle.
3650   * @retval None
3651   */
ADC_DMAError(DMA_HandleTypeDef * hdma)3652 void ADC_DMAError(DMA_HandleTypeDef *hdma)
3653 {
3654   /* Retrieve ADC handle corresponding to current DMA handle */
3655   ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
3656 
3657   /* Set ADC state */
3658   SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
3659 
3660   /* Set ADC error code to DMA error */
3661   SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_DMA);
3662 
3663   /* Error callback */
3664 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
3665   hadc->ErrorCallback(hadc);
3666 #else
3667   HAL_ADC_ErrorCallback(hadc);
3668 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
3669 }
3670 
3671 /**
3672   * @}
3673   */
3674 
3675 #endif /* HAL_ADC_MODULE_ENABLED */
3676 /**
3677   * @}
3678   */
3679 
3680 /**
3681   * @}
3682   */
3683