1 /**
2   ******************************************************************************
3   * @file    stm32f2xx_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) peripheral:
7   *           + Initialization and de-initialization functions
8   *           + Peripheral Control functions
9   *           + Peripheral State functions
10   *
11   ******************************************************************************
12   * @attention
13   *
14   * Copyright (c) 2016 STMicroelectronics.
15   * All rights reserved.
16   *
17   * This software is licensed under terms that can be found in the LICENSE file
18   * in the root directory of this software component.
19   * If no LICENSE file comes with this software, it is provided AS-IS.
20   *
21   ******************************************************************************
22   @verbatim
23   ==============================================================================
24                     ##### ADC Peripheral features #####
25   ==============================================================================
26   [..]
27   (#) 12-bit, 10-bit, 8-bit or 6-bit configurable resolution.
28   (#) Interrupt generation at the end of conversion, end of injected conversion,
29       and in case of analog watchdog or overrun events
30   (#) Single and continuous conversion modes.
31   (#) Scan mode for automatic conversion of channel 0 to channel x.
32   (#) Data alignment with in-built data coherency.
33   (#) Channel-wise programmable sampling time.
34   (#) External trigger option with configurable polarity for both regular and
35       injected conversion.
36   (#) Dual/Triple mode (on devices with 2 ADCs or more).
37   (#) Configurable DMA data storage in Dual/Triple ADC mode.
38   (#) Configurable delay between conversions in Dual/Triple interleaved mode.
39   (#) ADC conversion type (refer to the datasheets).
40   (#) ADC supply requirements: 2.4 V to 3.6 V at full speed and down to 1.8 V at
41       slower speed.
42   (#) ADC input range: VREF(minus) = VIN = VREF(plus).
43   (#) DMA request generation during regular channel conversion.
44 
45 
46                      ##### How to use this driver #####
47   ==============================================================================
48   [..]
49   (#)Initialize the ADC low level resources by implementing the HAL_ADC_MspInit():
50        (##) Enable the ADC interface clock using __HAL_RCC_ADC_CLK_ENABLE()
51        (##) ADC pins configuration
52              (+++) Enable the clock for the ADC GPIOs using the following function:
53                    __HAL_RCC_GPIOx_CLK_ENABLE()
54              (+++) Configure these ADC pins in analog mode using HAL_GPIO_Init()
55        (##) In case of using interrupts (e.g. HAL_ADC_Start_IT())
56              (+++) Configure the ADC interrupt priority using HAL_NVIC_SetPriority()
57              (+++) Enable the ADC IRQ handler using HAL_NVIC_EnableIRQ()
58              (+++) In ADC IRQ handler, call HAL_ADC_IRQHandler()
59        (##) In case of using DMA to control data transfer (e.g. HAL_ADC_Start_DMA())
60              (+++) Enable the DMAx interface clock using __HAL_RCC_DMAx_CLK_ENABLE()
61              (+++) Configure and enable two DMA streams stream for managing data
62                  transfer from peripheral to memory (output stream)
63              (+++) Associate the initialized DMA handle to the CRYP DMA handle
64                  using  __HAL_LINKDMA()
65              (+++) Configure the priority and enable the NVIC for the transfer complete
66                  interrupt on the two DMA Streams. The output stream should have higher
67                  priority than the input stream.
68 
69     *** Configuration of ADC, groups regular/injected, channels parameters ***
70   ==============================================================================
71   [..]
72   (#) Configure the ADC parameters (resolution, data alignment, ...)
73       and regular group parameters (conversion trigger, sequencer, ...)
74       using function HAL_ADC_Init().
75 
76   (#) Configure the channels for regular group parameters (channel number,
77       channel rank into sequencer, ..., into regular group)
78       using function HAL_ADC_ConfigChannel().
79 
80   (#) Optionally, configure the injected group parameters (conversion trigger,
81       sequencer, ..., of injected group)
82       and the channels for injected group parameters (channel number,
83       channel rank into sequencer, ..., into injected group)
84       using function HAL_ADCEx_InjectedConfigChannel().
85 
86   (#) Optionally, configure the analog watchdog parameters (channels
87       monitored, thresholds, ...) using function HAL_ADC_AnalogWDGConfig().
88 
89   (#) Optionally, for devices with several ADC instances: configure the
90       multimode parameters using function HAL_ADCEx_MultiModeConfigChannel().
91 
92                        *** Execution of ADC conversions ***
93   ==============================================================================
94   [..]
95   (#) ADC driver can be used among three modes: polling, interruption,
96       transfer by DMA.
97 
98      *** Polling mode IO operation ***
99      =================================
100      [..]
101        (+) Start the ADC peripheral using HAL_ADC_Start()
102        (+) Wait for end of conversion using HAL_ADC_PollForConversion(), at this stage
103            user can specify the value of timeout according to his end application
104        (+) To read the ADC converted values, use the HAL_ADC_GetValue() function.
105        (+) Stop the ADC peripheral using HAL_ADC_Stop()
106 
107      *** Interrupt mode IO operation ***
108      ===================================
109      [..]
110        (+) Start the ADC peripheral using HAL_ADC_Start_IT()
111        (+) Use HAL_ADC_IRQHandler() called under ADC_IRQHandler() Interrupt subroutine
112        (+) At ADC end of conversion HAL_ADC_ConvCpltCallback() function is executed and user can
113            add his own code by customization of function pointer HAL_ADC_ConvCpltCallback
114        (+) In case of ADC Error, HAL_ADC_ErrorCallback() function is executed and user can
115            add his own code by customization of function pointer HAL_ADC_ErrorCallback
116        (+) Stop the ADC peripheral using HAL_ADC_Stop_IT()
117 
118      *** DMA mode IO operation ***
119      ==============================
120      [..]
121        (+) Start the ADC peripheral using HAL_ADC_Start_DMA(), at this stage the user specify the length
122            of data to be transferred at each end of conversion
123        (+) At The end of data transfer by HAL_ADC_ConvCpltCallback() function is executed and user can
124            add his own code by customization of function pointer HAL_ADC_ConvCpltCallback
125        (+) In case of transfer Error, HAL_ADC_ErrorCallback() function is executed and user can
126            add his own code by customization of function pointer HAL_ADC_ErrorCallback
127        (+) Stop the ADC peripheral using HAL_ADC_Stop_DMA()
128 
129      *** ADC HAL driver macros list ***
130      =============================================
131      [..]
132        Below the list of most used macros in ADC HAL driver.
133 
134       (+) __HAL_ADC_ENABLE : Enable the ADC peripheral
135       (+) __HAL_ADC_DISABLE : Disable the ADC peripheral
136       (+) __HAL_ADC_ENABLE_IT: Enable the ADC end of conversion interrupt
137       (+) __HAL_ADC_DISABLE_IT: Disable the ADC end of conversion interrupt
138       (+) __HAL_ADC_GET_IT_SOURCE: Check if the specified ADC interrupt source is enabled or disabled
139       (+) __HAL_ADC_CLEAR_FLAG: Clear the ADC's pending flags
140       (+) __HAL_ADC_GET_FLAG: Get the selected ADC's flag status
141       (+) ADC_GET_RESOLUTION: Return resolution bits in CR1 register
142 
143      [..]
144        (@) You can refer to the ADC HAL driver header file for more useful macros
145 
146                       *** Deinitialization of ADC ***
147   ==============================================================================
148   [..]
149   (#) Disable the ADC interface
150      (++) ADC clock can be hard reset and disabled at RCC top level.
151      (++) Hard reset of ADC peripherals
152           using macro __HAL_RCC_ADC_FORCE_RESET(), __HAL_RCC_ADC_RELEASE_RESET().
153      (++) ADC clock disable using the equivalent macro/functions as configuration step.
154                (+++) Example:
155                    Into HAL_ADC_MspDeInit() (recommended code location) or with
156                    other device clock parameters configuration:
157                (+++) HAL_RCC_GetOscConfig(&RCC_OscInitStructure);
158                (+++) RCC_OscInitStructure.OscillatorType = RCC_OSCILLATORTYPE_HSI;
159                (+++) RCC_OscInitStructure.HSIState = RCC_HSI_OFF; (if not used for system clock)
160                (+++) HAL_RCC_OscConfig(&RCC_OscInitStructure);
161 
162   (#) ADC pins configuration
163      (++) Disable the clock for the ADC GPIOs using macro __HAL_RCC_GPIOx_CLK_DISABLE()
164 
165   (#) Optionally, in case of usage of ADC with interruptions:
166      (++) Disable the NVIC for ADC using function HAL_NVIC_DisableIRQ(ADCx_IRQn)
167 
168   (#) Optionally, in case of usage of DMA:
169         (++) Deinitialize the DMA using function HAL_DMA_DeInit().
170         (++) Disable the NVIC for DMA using function HAL_NVIC_DisableIRQ(DMAx_Channelx_IRQn)
171                       *** Callback registration ***
172   ==============================================================================
173     [..]
174 
175      The compilation flag USE_HAL_ADC_REGISTER_CALLBACKS, when set to 1,
176      allows the user to configure dynamically the driver callbacks.
177      Use Functions HAL_ADC_RegisterCallback()
178      to register an interrupt callback.
179     [..]
180 
181      Function HAL_ADC_RegisterCallback() allows to register following callbacks:
182        (+) ConvCpltCallback               : ADC conversion complete callback
183        (+) ConvHalfCpltCallback           : ADC conversion DMA half-transfer callback
184        (+) LevelOutOfWindowCallback       : ADC analog watchdog 1 callback
185        (+) ErrorCallback                  : ADC error callback
186        (+) InjectedConvCpltCallback       : ADC group injected conversion complete callback
187        (+) InjectedQueueOverflowCallback  : ADC group injected context queue overflow callback
188        (+) LevelOutOfWindow2Callback      : ADC analog watchdog 2 callback
189        (+) LevelOutOfWindow3Callback      : ADC analog watchdog 3 callback
190        (+) EndOfSamplingCallback          : ADC end of sampling callback
191        (+) MspInitCallback                : ADC Msp Init callback
192        (+) MspDeInitCallback              : ADC Msp DeInit callback
193      This function takes as parameters the HAL peripheral handle, the Callback ID
194      and a pointer to the user callback function.
195     [..]
196 
197      Use function HAL_ADC_UnRegisterCallback to reset a callback to the default
198      weak function.
199     [..]
200 
201      HAL_ADC_UnRegisterCallback takes as parameters the HAL peripheral handle,
202      and the Callback ID.
203      This function allows to reset following callbacks:
204        (+) ConvCpltCallback               : ADC conversion complete callback
205        (+) ConvHalfCpltCallback           : ADC conversion DMA half-transfer callback
206        (+) LevelOutOfWindowCallback       : ADC analog watchdog 1 callback
207        (+) ErrorCallback                  : ADC error callback
208        (+) InjectedConvCpltCallback       : ADC group injected conversion complete callback
209        (+) InjectedQueueOverflowCallback  : ADC group injected context queue overflow callback
210        (+) LevelOutOfWindow2Callback      : ADC analog watchdog 2 callback
211        (+) LevelOutOfWindow3Callback      : ADC analog watchdog 3 callback
212        (+) EndOfSamplingCallback          : ADC end of sampling callback
213        (+) MspInitCallback                : ADC Msp Init callback
214        (+) MspDeInitCallback              : ADC Msp DeInit callback
215      [..]
216 
217      By default, after the HAL_ADC_Init() and when the state is HAL_ADC_STATE_RESET
218      all callbacks are set to the corresponding weak functions:
219      examples HAL_ADC_ConvCpltCallback(), HAL_ADC_ErrorCallback().
220      Exception done for MspInit and MspDeInit functions that are
221      reset to the legacy weak functions in the HAL_ADC_Init()/ HAL_ADC_DeInit() only when
222      these callbacks are null (not registered beforehand).
223     [..]
224 
225      If MspInit or MspDeInit are not null, the HAL_ADC_Init()/ HAL_ADC_DeInit()
226      keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state.
227      [..]
228 
229      Callbacks can be registered/unregistered in HAL_ADC_STATE_READY state only.
230      Exception done MspInit/MspDeInit functions that can be registered/unregistered
231      in HAL_ADC_STATE_READY or HAL_ADC_STATE_RESET state,
232      thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit.
233     [..]
234 
235      Then, the user first registers the MspInit/MspDeInit user callbacks
236      using HAL_ADC_RegisterCallback() before calling HAL_ADC_DeInit()
237      or HAL_ADC_Init() function.
238      [..]
239 
240      When the compilation flag USE_HAL_ADC_REGISTER_CALLBACKS is set to 0 or
241      not defined, the callback registration feature is not available and all callbacks
242      are set to the corresponding weak functions.
243 
244   @endverbatim
245   ******************************************************************************
246   */
247 
248 /* Includes ------------------------------------------------------------------*/
249 #include "stm32f2xx_hal.h"
250 
251 /** @addtogroup STM32F2xx_HAL_Driver
252   * @{
253   */
254 
255 /** @defgroup ADC ADC
256   * @brief ADC driver modules
257   * @{
258   */
259 
260 #ifdef HAL_ADC_MODULE_ENABLED
261 
262 /* Private typedef -----------------------------------------------------------*/
263 /* Private define ------------------------------------------------------------*/
264 /* Private macro -------------------------------------------------------------*/
265 /* Private variables ---------------------------------------------------------*/
266 /** @addtogroup ADC_Private_Functions
267   * @{
268   */
269 /* Private function prototypes -----------------------------------------------*/
270 static void ADC_Init(ADC_HandleTypeDef* hadc);
271 static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma);
272 static void ADC_DMAError(DMA_HandleTypeDef *hdma);
273 static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma);
274 /**
275   * @}
276   */
277 /* Exported functions --------------------------------------------------------*/
278 /** @defgroup ADC_Exported_Functions ADC Exported Functions
279   * @{
280   */
281 
282 /** @defgroup ADC_Exported_Functions_Group1 Initialization and de-initialization functions
283  *  @brief    Initialization and Configuration functions
284  *
285 @verbatim
286  ===============================================================================
287               ##### Initialization and de-initialization functions #####
288  ===============================================================================
289     [..]  This section provides functions allowing to:
290       (+) Initialize and configure the ADC.
291       (+) De-initialize the ADC.
292 
293 @endverbatim
294   * @{
295   */
296 
297 /**
298   * @brief  Initializes the ADCx peripheral according to the specified parameters
299   *         in the ADC_InitStruct and initializes the ADC MSP.
300   *
301   * @note   This function is used to configure the global features of the ADC (
302   *         ClockPrescaler, Resolution, Data Alignment and number of conversion), however,
303   *         the rest of the configuration parameters are specific to the regular
304   *         channels group (scan mode activation, continuous mode activation,
305   *         External trigger source and edge, DMA continuous request after the
306   *         last transfer and End of conversion selection).
307   *
308   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
309   *         the configuration information for the specified ADC.
310   * @retval HAL status
311   */
HAL_ADC_Init(ADC_HandleTypeDef * hadc)312 HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc)
313 {
314   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
315 
316   /* Check ADC handle */
317   if(hadc == NULL)
318   {
319     return HAL_ERROR;
320   }
321 
322   /* Check the parameters */
323   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
324   assert_param(IS_ADC_CLOCKPRESCALER(hadc->Init.ClockPrescaler));
325   assert_param(IS_ADC_RESOLUTION(hadc->Init.Resolution));
326   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ScanConvMode));
327   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
328   assert_param(IS_ADC_EXT_TRIG(hadc->Init.ExternalTrigConv));
329   assert_param(IS_ADC_DATA_ALIGN(hadc->Init.DataAlign));
330   assert_param(IS_ADC_REGULAR_LENGTH(hadc->Init.NbrOfConversion));
331   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests));
332   assert_param(IS_ADC_EOCSelection(hadc->Init.EOCSelection));
333   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DiscontinuousConvMode));
334 
335   if(hadc->Init.ExternalTrigConv != ADC_SOFTWARE_START)
336   {
337     assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
338   }
339 
340   if(hadc->State == HAL_ADC_STATE_RESET)
341   {
342 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
343     /* Init the ADC Callback settings */
344     hadc->ConvCpltCallback              = HAL_ADC_ConvCpltCallback;                 /* Legacy weak callback */
345     hadc->ConvHalfCpltCallback          = HAL_ADC_ConvHalfCpltCallback;             /* Legacy weak callback */
346     hadc->LevelOutOfWindowCallback      = HAL_ADC_LevelOutOfWindowCallback;         /* Legacy weak callback */
347     hadc->ErrorCallback                 = HAL_ADC_ErrorCallback;                    /* Legacy weak callback */
348     hadc->InjectedConvCpltCallback      = HAL_ADCEx_InjectedConvCpltCallback;       /* Legacy weak callback */
349     if (hadc->MspInitCallback == NULL)
350     {
351       hadc->MspInitCallback = HAL_ADC_MspInit; /* Legacy weak MspInit  */
352     }
353 
354     /* Init the low level hardware */
355     hadc->MspInitCallback(hadc);
356 #else
357     /* Init the low level hardware */
358     HAL_ADC_MspInit(hadc);
359 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
360 
361     /* Initialize ADC error code */
362     ADC_CLEAR_ERRORCODE(hadc);
363 
364     /* Allocate lock resource and initialize it */
365     hadc->Lock = HAL_UNLOCKED;
366   }
367 
368   /* Configuration of ADC parameters if previous preliminary actions are      */
369   /* correctly completed.                                                     */
370   if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL))
371   {
372     /* Set ADC state */
373     ADC_STATE_CLR_SET(hadc->State,
374                       HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
375                       HAL_ADC_STATE_BUSY_INTERNAL);
376 
377     /* Set ADC parameters */
378     ADC_Init(hadc);
379 
380     /* Set ADC error code to none */
381     ADC_CLEAR_ERRORCODE(hadc);
382 
383     /* Set the ADC state */
384     ADC_STATE_CLR_SET(hadc->State,
385                       HAL_ADC_STATE_BUSY_INTERNAL,
386                       HAL_ADC_STATE_READY);
387   }
388   else
389   {
390     tmp_hal_status = HAL_ERROR;
391   }
392 
393   /* Release Lock */
394   __HAL_UNLOCK(hadc);
395 
396   /* Return function status */
397   return tmp_hal_status;
398 }
399 
400 /**
401   * @brief  Deinitializes the ADCx peripheral registers to their default reset values.
402   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
403   *         the configuration information for the specified ADC.
404   * @retval HAL status
405   */
HAL_ADC_DeInit(ADC_HandleTypeDef * hadc)406 HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef* hadc)
407 {
408   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
409 
410   /* Check ADC handle */
411   if(hadc == NULL)
412   {
413     return HAL_ERROR;
414   }
415 
416   /* Check the parameters */
417   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
418 
419   /* Set ADC state */
420   SET_BIT(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL);
421 
422   /* Stop potential conversion on going, on regular and injected groups */
423   /* Disable ADC peripheral */
424   __HAL_ADC_DISABLE(hadc);
425 
426   /* Configuration of ADC parameters if previous preliminary actions are      */
427   /* correctly completed.                                                     */
428   if(HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_ADON))
429   {
430 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
431   if (hadc->MspDeInitCallback == NULL)
432   {
433     hadc->MspDeInitCallback = HAL_ADC_MspDeInit; /* Legacy weak MspDeInit  */
434   }
435 
436   /* DeInit the low level hardware: RCC clock, NVIC */
437   hadc->MspDeInitCallback(hadc);
438 #else
439   /* DeInit the low level hardware: RCC clock, NVIC */
440   HAL_ADC_MspDeInit(hadc);
441 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
442 
443     /* Set ADC error code to none */
444     ADC_CLEAR_ERRORCODE(hadc);
445 
446     /* Set ADC state */
447     hadc->State = HAL_ADC_STATE_RESET;
448   }
449 
450   /* Process unlocked */
451   __HAL_UNLOCK(hadc);
452 
453   /* Return function status */
454   return tmp_hal_status;
455 }
456 
457 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
458 /**
459   * @brief  Register a User ADC Callback
460   *         To be used instead of the weak predefined callback
461   * @param  hadc Pointer to a ADC_HandleTypeDef structure that contains
462   *                the configuration information for the specified ADC.
463   * @param  CallbackID ID of the callback to be registered
464   *         This parameter can be one of the following values:
465   *          @arg @ref HAL_ADC_CONVERSION_COMPLETE_CB_ID      ADC conversion complete callback ID
466   *          @arg @ref HAL_ADC_CONVERSION_HALF_CB_ID          ADC conversion DMA half-transfer callback ID
467   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID    ADC analog watchdog 1 callback ID
468   *          @arg @ref HAL_ADC_ERROR_CB_ID                    ADC error callback ID
469   *          @arg @ref HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID  ADC group injected conversion complete callback ID
470   *          @arg @ref HAL_ADC_INJ_QUEUE_OVEFLOW_CB_ID        ADC group injected context queue overflow callback ID
471   *          @arg @ref HAL_ADC_MSPINIT_CB_ID                  ADC Msp Init callback ID
472   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID                ADC Msp DeInit callback ID
473   * @param  pCallback pointer to the Callback function
474   * @retval HAL status
475   */
HAL_ADC_RegisterCallback(ADC_HandleTypeDef * hadc,HAL_ADC_CallbackIDTypeDef CallbackID,pADC_CallbackTypeDef pCallback)476 HAL_StatusTypeDef HAL_ADC_RegisterCallback(ADC_HandleTypeDef *hadc, HAL_ADC_CallbackIDTypeDef CallbackID, pADC_CallbackTypeDef pCallback)
477 {
478   HAL_StatusTypeDef status = HAL_OK;
479 
480   if (pCallback == NULL)
481   {
482     /* Update the error code */
483     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
484 
485     return HAL_ERROR;
486   }
487 
488   if ((hadc->State & HAL_ADC_STATE_READY) != 0UL)
489   {
490     switch (CallbackID)
491     {
492       case HAL_ADC_CONVERSION_COMPLETE_CB_ID :
493         hadc->ConvCpltCallback = pCallback;
494         break;
495 
496       case HAL_ADC_CONVERSION_HALF_CB_ID :
497         hadc->ConvHalfCpltCallback = pCallback;
498         break;
499 
500       case HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID :
501         hadc->LevelOutOfWindowCallback = pCallback;
502         break;
503 
504       case HAL_ADC_ERROR_CB_ID :
505         hadc->ErrorCallback = pCallback;
506         break;
507 
508       case HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID :
509         hadc->InjectedConvCpltCallback = pCallback;
510         break;
511 
512       case HAL_ADC_MSPINIT_CB_ID :
513         hadc->MspInitCallback = pCallback;
514         break;
515 
516       case HAL_ADC_MSPDEINIT_CB_ID :
517         hadc->MspDeInitCallback = pCallback;
518         break;
519 
520       default :
521         /* Update the error code */
522         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
523 
524         /* Return error status */
525         status = HAL_ERROR;
526         break;
527     }
528   }
529   else if (HAL_ADC_STATE_RESET == hadc->State)
530   {
531     switch (CallbackID)
532     {
533       case HAL_ADC_MSPINIT_CB_ID :
534         hadc->MspInitCallback = pCallback;
535         break;
536 
537       case HAL_ADC_MSPDEINIT_CB_ID :
538         hadc->MspDeInitCallback = pCallback;
539         break;
540 
541       default :
542         /* Update the error code */
543         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
544 
545         /* Return error status */
546         status = HAL_ERROR;
547         break;
548     }
549   }
550   else
551   {
552     /* Update the error code */
553     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
554 
555     /* Return error status */
556     status =  HAL_ERROR;
557   }
558 
559   return status;
560 }
561 
562 /**
563   * @brief  Unregister a ADC Callback
564   *         ADC callback is redirected to the weak predefined callback
565   * @param  hadc Pointer to a ADC_HandleTypeDef structure that contains
566   *                the configuration information for the specified ADC.
567   * @param  CallbackID ID of the callback to be unregistered
568   *         This parameter can be one of the following values:
569   *          @arg @ref HAL_ADC_CONVERSION_COMPLETE_CB_ID      ADC conversion complete callback ID
570   *          @arg @ref HAL_ADC_CONVERSION_HALF_CB_ID          ADC conversion DMA half-transfer callback ID
571   *          @arg @ref HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID    ADC analog watchdog 1 callback ID
572   *          @arg @ref HAL_ADC_ERROR_CB_ID                    ADC error callback ID
573   *          @arg @ref HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID  ADC group injected conversion complete callback ID
574   *          @arg @ref HAL_ADC_INJ_QUEUE_OVEFLOW_CB_ID        ADC group injected context queue overflow callback ID
575   *          @arg @ref HAL_ADC_MSPINIT_CB_ID                  ADC Msp Init callback ID
576   *          @arg @ref HAL_ADC_MSPDEINIT_CB_ID                ADC Msp DeInit callback ID
577   * @retval HAL status
578   */
HAL_ADC_UnRegisterCallback(ADC_HandleTypeDef * hadc,HAL_ADC_CallbackIDTypeDef CallbackID)579 HAL_StatusTypeDef HAL_ADC_UnRegisterCallback(ADC_HandleTypeDef *hadc, HAL_ADC_CallbackIDTypeDef CallbackID)
580 {
581   HAL_StatusTypeDef status = HAL_OK;
582 
583   if ((hadc->State & HAL_ADC_STATE_READY) != 0UL)
584   {
585     switch (CallbackID)
586     {
587       case HAL_ADC_CONVERSION_COMPLETE_CB_ID :
588         hadc->ConvCpltCallback = HAL_ADC_ConvCpltCallback;
589         break;
590 
591       case HAL_ADC_CONVERSION_HALF_CB_ID :
592         hadc->ConvHalfCpltCallback = HAL_ADC_ConvHalfCpltCallback;
593         break;
594 
595       case HAL_ADC_LEVEL_OUT_OF_WINDOW_1_CB_ID :
596         hadc->LevelOutOfWindowCallback = HAL_ADC_LevelOutOfWindowCallback;
597         break;
598 
599       case HAL_ADC_ERROR_CB_ID :
600         hadc->ErrorCallback = HAL_ADC_ErrorCallback;
601         break;
602 
603       case HAL_ADC_INJ_CONVERSION_COMPLETE_CB_ID :
604         hadc->InjectedConvCpltCallback = HAL_ADCEx_InjectedConvCpltCallback;
605         break;
606 
607       case HAL_ADC_MSPINIT_CB_ID :
608         hadc->MspInitCallback = HAL_ADC_MspInit; /* Legacy weak MspInit              */
609         break;
610 
611       case HAL_ADC_MSPDEINIT_CB_ID :
612         hadc->MspDeInitCallback = HAL_ADC_MspDeInit; /* Legacy weak MspDeInit            */
613         break;
614 
615       default :
616         /* Update the error code */
617         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
618 
619         /* Return error status */
620         status =  HAL_ERROR;
621         break;
622     }
623   }
624   else if (HAL_ADC_STATE_RESET == hadc->State)
625   {
626     switch (CallbackID)
627     {
628       case HAL_ADC_MSPINIT_CB_ID :
629         hadc->MspInitCallback = HAL_ADC_MspInit;                   /* Legacy weak MspInit              */
630         break;
631 
632       case HAL_ADC_MSPDEINIT_CB_ID :
633         hadc->MspDeInitCallback = HAL_ADC_MspDeInit;               /* Legacy weak MspDeInit            */
634         break;
635 
636       default :
637         /* Update the error code */
638         hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
639 
640         /* Return error status */
641         status =  HAL_ERROR;
642         break;
643     }
644   }
645   else
646   {
647     /* Update the error code */
648     hadc->ErrorCode |= HAL_ADC_ERROR_INVALID_CALLBACK;
649 
650     /* Return error status */
651     status =  HAL_ERROR;
652   }
653 
654   return status;
655 }
656 
657 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
658 
659 /**
660   * @brief  Initializes the ADC MSP.
661   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
662   *         the configuration information for the specified ADC.
663   * @retval None
664   */
HAL_ADC_MspInit(ADC_HandleTypeDef * hadc)665 __weak void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc)
666 {
667   /* Prevent unused argument(s) compilation warning */
668   UNUSED(hadc);
669   /* NOTE : This function Should not be modified, when the callback is needed,
670             the HAL_ADC_MspInit could be implemented in the user file
671    */
672 }
673 
674 /**
675   * @brief  DeInitializes the ADC MSP.
676   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
677   *         the configuration information for the specified ADC.
678   * @retval None
679   */
HAL_ADC_MspDeInit(ADC_HandleTypeDef * hadc)680 __weak void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc)
681 {
682   /* Prevent unused argument(s) compilation warning */
683   UNUSED(hadc);
684   /* NOTE : This function Should not be modified, when the callback is needed,
685             the HAL_ADC_MspDeInit could be implemented in the user file
686    */
687 }
688 
689 /**
690   * @}
691   */
692 
693 /** @defgroup ADC_Exported_Functions_Group2 IO operation functions
694  *  @brief    IO operation functions
695  *
696 @verbatim
697  ===============================================================================
698              ##### IO operation functions #####
699  ===============================================================================
700     [..]  This section provides functions allowing to:
701       (+) Start conversion of regular channel.
702       (+) Stop conversion of regular channel.
703       (+) Start conversion of regular channel and enable interrupt.
704       (+) Stop conversion of regular channel and disable interrupt.
705       (+) Start conversion of regular channel and enable DMA transfer.
706       (+) Stop conversion of regular channel and disable DMA transfer.
707       (+) Handle ADC interrupt request.
708 
709 @endverbatim
710   * @{
711   */
712 
713 /**
714   * @brief  Enables ADC and starts conversion of the regular channels.
715   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
716   *         the configuration information for the specified ADC.
717   * @retval HAL status
718   */
HAL_ADC_Start(ADC_HandleTypeDef * hadc)719 HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc)
720 {
721   __IO uint32_t counter = 0U;
722 
723   /* Check the parameters */
724   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
725   assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
726 
727   /* Process locked */
728   __HAL_LOCK(hadc);
729 
730   /* Enable the ADC peripheral */
731   /* Check if ADC peripheral is disabled in order to enable it and wait during
732   Tstab time the ADC's stabilization */
733   if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON)
734   {
735     /* Enable the Peripheral */
736     __HAL_ADC_ENABLE(hadc);
737 
738     /* Delay for ADC stabilization time */
739     /* Compute number of CPU cycles to wait for */
740     counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000U));
741     while(counter != 0U)
742     {
743       counter--;
744     }
745   }
746 
747   /* Start conversion if ADC is effectively enabled */
748   if(HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_ADON))
749   {
750     /* Set ADC state                                                          */
751     /* - Clear state bitfield related to regular group conversion results     */
752     /* - Set state bitfield related to regular group operation                */
753     ADC_STATE_CLR_SET(hadc->State,
754                       HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR,
755                       HAL_ADC_STATE_REG_BUSY);
756 
757     /* If conversions on group regular are also triggering group injected,    */
758     /* update ADC state.                                                      */
759     if (READ_BIT(hadc->Instance->CR1, ADC_CR1_JAUTO) != RESET)
760     {
761       ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
762     }
763 
764     /* State machine update: Check if an injected conversion is ongoing */
765     if (HAL_IS_BIT_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY))
766     {
767       /* Reset ADC error code fields related to conversions on group regular */
768       CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
769     }
770     else
771     {
772       /* Reset ADC all error code fields */
773       ADC_CLEAR_ERRORCODE(hadc);
774     }
775 
776     /* Process unlocked */
777     /* Unlock before starting ADC conversions: in case of potential           */
778     /* interruption, to let the process to ADC IRQ Handler.                   */
779     __HAL_UNLOCK(hadc);
780 
781     /* Clear regular group conversion flag and overrun flag */
782     /* (To ensure of no unknown state from potential previous ADC operations) */
783     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOC | ADC_FLAG_OVR);
784 
785     /* Check if Multimode enabled */
786     if(HAL_IS_BIT_CLR(ADC->CCR, ADC_CCR_MULTI))
787     {
788       /* if no external trigger present enable software conversion of regular channels */
789       if((hadc->Instance->CR2 & ADC_CR2_EXTEN) == RESET)
790       {
791         /* Enable the selected ADC software conversion for regular group */
792         hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
793       }
794     }
795     else
796     {
797       /* if instance of handle correspond to ADC1 and  no external trigger present enable software conversion of regular channels */
798       if((hadc->Instance == ADC1) && ((hadc->Instance->CR2 & ADC_CR2_EXTEN) == RESET))
799       {
800         /* Enable the selected ADC software conversion for regular group */
801           hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
802       }
803     }
804   }
805   else
806   {
807     /* Update ADC state machine to error */
808     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
809 
810     /* Set ADC error code to ADC IP internal error */
811     SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
812   }
813 
814   /* Return function status */
815   return HAL_OK;
816 }
817 
818 /**
819   * @brief  Disables ADC and stop conversion of regular channels.
820   *
821   * @note   Caution: This function will stop also injected channels.
822   *
823   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
824   *         the configuration information for the specified ADC.
825   *
826   * @retval HAL status.
827   */
HAL_ADC_Stop(ADC_HandleTypeDef * hadc)828 HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc)
829 {
830   /* Check the parameters */
831   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
832 
833   /* Process locked */
834   __HAL_LOCK(hadc);
835 
836   /* Stop potential conversion on going, on regular and injected groups */
837   /* Disable ADC peripheral */
838   __HAL_ADC_DISABLE(hadc);
839 
840   /* Check if ADC is effectively disabled */
841   if(HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_ADON))
842   {
843     /* Set ADC state */
844     ADC_STATE_CLR_SET(hadc->State,
845                       HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
846                       HAL_ADC_STATE_READY);
847   }
848 
849   /* Process unlocked */
850   __HAL_UNLOCK(hadc);
851 
852   /* Return function status */
853   return HAL_OK;
854 }
855 
856 /**
857   * @brief  Poll for regular conversion complete
858   * @note   ADC conversion flags EOS (end of sequence) and EOC (end of
859   *         conversion) are cleared by this function.
860   * @note   This function cannot be used in a particular setup: ADC configured
861   *         in DMA mode and polling for end of each conversion (ADC init
862   *         parameter "EOCSelection" set to ADC_EOC_SINGLE_CONV).
863   *         In this case, DMA resets the flag EOC and polling cannot be
864   *         performed on each conversion. Nevertheless, polling can still
865   *         be performed on the complete sequence.
866   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
867   *         the configuration information for the specified ADC.
868   * @param  Timeout Timeout value in millisecond.
869   * @retval HAL status
870   */
HAL_ADC_PollForConversion(ADC_HandleTypeDef * hadc,uint32_t Timeout)871 HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout)
872 {
873   uint32_t tickstart = 0U;
874 
875   /* Verification that ADC configuration is compliant with polling for      */
876   /* each conversion:                                                       */
877   /* Particular case is ADC configured in DMA mode and ADC sequencer with   */
878   /* several ranks and polling for end of each conversion.                  */
879   /* For code simplicity sake, this particular case is generalized to       */
880   /* ADC configured in DMA mode and polling for end of each conversion.     */
881   if (HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_EOCS) &&
882       HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_DMA)    )
883   {
884     /* Update ADC state machine to error */
885     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
886 
887     /* Process unlocked */
888     __HAL_UNLOCK(hadc);
889 
890     return HAL_ERROR;
891   }
892 
893   /* Get tick */
894   tickstart = HAL_GetTick();
895 
896   /* Check End of conversion flag */
897   while(!(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC)))
898   {
899     /* Check if timeout is disabled (set to infinite wait) */
900     if(Timeout != HAL_MAX_DELAY)
901     {
902       if((Timeout == 0U) || ((HAL_GetTick() - tickstart ) > Timeout))
903       {
904         /* Update ADC state machine to timeout */
905         SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
906 
907         /* Process unlocked */
908         __HAL_UNLOCK(hadc);
909 
910         return HAL_TIMEOUT;
911       }
912     }
913   }
914 
915   /* Clear regular group conversion flag */
916   __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_STRT | ADC_FLAG_EOC);
917 
918   /* Update ADC state machine */
919   SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
920 
921   /* Determine whether any further conversion upcoming on group regular       */
922   /* by external trigger, continuous mode or scan sequence on going.          */
923   /* Note: On STM32F2, there is no independent flag of end of sequence.       */
924   /*       The test of scan sequence on going is done either with scan        */
925   /*       sequence disabled or with end of conversion flag set to            */
926   /*       of end of sequence.                                                */
927   if(ADC_IS_SOFTWARE_START_REGULAR(hadc)                   &&
928      (hadc->Init.ContinuousConvMode == DISABLE)            &&
929      (HAL_IS_BIT_CLR(hadc->Instance->SQR1, ADC_SQR1_L) ||
930       HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_EOCS)  )   )
931   {
932     /* Set ADC state */
933     CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
934 
935     if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_INJ_BUSY))
936     {
937       SET_BIT(hadc->State, HAL_ADC_STATE_READY);
938     }
939   }
940 
941   /* Return ADC state */
942   return HAL_OK;
943 }
944 
945 /**
946   * @brief  Poll for conversion event
947   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
948   *         the configuration information for the specified ADC.
949   * @param  EventType the ADC event type.
950   *          This parameter can be one of the following values:
951   *            @arg ADC_AWD_EVENT: ADC Analog watch Dog event.
952   *            @arg ADC_OVR_EVENT: ADC Overrun event.
953   * @param  Timeout Timeout value in millisecond.
954   * @retval HAL status
955   */
HAL_ADC_PollForEvent(ADC_HandleTypeDef * hadc,uint32_t EventType,uint32_t Timeout)956 HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout)
957 {
958   uint32_t tickstart = 0U;
959 
960   /* Check the parameters */
961   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
962   assert_param(IS_ADC_EVENT_TYPE(EventType));
963 
964   /* Get tick */
965   tickstart = HAL_GetTick();
966 
967   /* Check selected event flag */
968   while(!(__HAL_ADC_GET_FLAG(hadc,EventType)))
969   {
970     /* Check for the Timeout */
971     if(Timeout != HAL_MAX_DELAY)
972     {
973       if((Timeout == 0U) || ((HAL_GetTick() - tickstart ) > Timeout))
974       {
975         /* Update ADC state machine to timeout */
976         SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
977 
978         /* Process unlocked */
979         __HAL_UNLOCK(hadc);
980 
981         return HAL_TIMEOUT;
982       }
983     }
984   }
985 
986   /* Analog watchdog (level out of window) event */
987   if(EventType == ADC_AWD_EVENT)
988   {
989     /* Set ADC state */
990     SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
991 
992     /* Clear ADC analog watchdog flag */
993     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD);
994   }
995   /* Overrun event */
996   else
997   {
998     /* Set ADC state */
999     SET_BIT(hadc->State, HAL_ADC_STATE_REG_OVR);
1000     /* Set ADC error code to overrun */
1001     SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_OVR);
1002 
1003     /* Clear ADC overrun flag */
1004     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1005   }
1006 
1007   /* Return ADC state */
1008   return HAL_OK;
1009 }
1010 
1011 
1012 /**
1013   * @brief  Enables the interrupt and starts ADC conversion of regular channels.
1014   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1015   *         the configuration information for the specified ADC.
1016   * @retval HAL status.
1017   */
HAL_ADC_Start_IT(ADC_HandleTypeDef * hadc)1018 HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc)
1019 {
1020   __IO uint32_t counter = 0U;
1021 
1022   /* Check the parameters */
1023   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
1024   assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
1025 
1026   /* Process locked */
1027   __HAL_LOCK(hadc);
1028 
1029   /* Enable the ADC peripheral */
1030   /* Check if ADC peripheral is disabled in order to enable it and wait during
1031   Tstab time the ADC's stabilization */
1032   if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON)
1033   {
1034     /* Enable the Peripheral */
1035     __HAL_ADC_ENABLE(hadc);
1036 
1037     /* Delay for ADC stabilization time */
1038     /* Compute number of CPU cycles to wait for */
1039     counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000U));
1040     while(counter != 0U)
1041     {
1042       counter--;
1043     }
1044   }
1045 
1046   /* Start conversion if ADC is effectively enabled */
1047   if(HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_ADON))
1048   {
1049     /* Set ADC state                                                          */
1050     /* - Clear state bitfield related to regular group conversion results     */
1051     /* - Set state bitfield related to regular group operation                */
1052     ADC_STATE_CLR_SET(hadc->State,
1053                       HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR,
1054                       HAL_ADC_STATE_REG_BUSY);
1055 
1056     /* If conversions on group regular are also triggering group injected,    */
1057     /* update ADC state.                                                      */
1058     if (READ_BIT(hadc->Instance->CR1, ADC_CR1_JAUTO) != RESET)
1059     {
1060       ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
1061     }
1062 
1063     /* State machine update: Check if an injected conversion is ongoing */
1064     if (HAL_IS_BIT_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY))
1065     {
1066       /* Reset ADC error code fields related to conversions on group regular */
1067       CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
1068     }
1069     else
1070     {
1071       /* Reset ADC all error code fields */
1072       ADC_CLEAR_ERRORCODE(hadc);
1073     }
1074 
1075     /* Process unlocked */
1076     /* Unlock before starting ADC conversions: in case of potential           */
1077     /* interruption, to let the process to ADC IRQ Handler.                   */
1078     __HAL_UNLOCK(hadc);
1079 
1080     /* Clear regular group conversion flag and overrun flag */
1081     /* (To ensure of no unknown state from potential previous ADC operations) */
1082     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOC | ADC_FLAG_OVR);
1083 
1084     /* Enable end of conversion interrupt for regular group */
1085     __HAL_ADC_ENABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_OVR));
1086 
1087     /* Check if Multimode enabled */
1088     if(HAL_IS_BIT_CLR(ADC->CCR, ADC_CCR_MULTI))
1089     {
1090       /* if no external trigger present enable software conversion of regular channels */
1091       if((hadc->Instance->CR2 & ADC_CR2_EXTEN) == RESET)
1092       {
1093         /* Enable the selected ADC software conversion for regular group */
1094         hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
1095       }
1096     }
1097     else
1098     {
1099       /* if instance of handle correspond to ADC1 and  no external trigger present enable software conversion of regular channels */
1100       if((hadc->Instance == ADC1) && ((hadc->Instance->CR2 & ADC_CR2_EXTEN) == RESET))
1101       {
1102         /* Enable the selected ADC software conversion for regular group */
1103           hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
1104       }
1105     }
1106   }
1107   else
1108   {
1109     /* Update ADC state machine to error */
1110     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
1111 
1112     /* Set ADC error code to ADC IP internal error */
1113     SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
1114   }
1115 
1116   /* Return function status */
1117   return HAL_OK;
1118 }
1119 
1120 /**
1121   * @brief  Disables the interrupt and stop ADC conversion of regular channels.
1122   *
1123   * @note   Caution: This function will stop also injected channels.
1124   *
1125   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1126   *         the configuration information for the specified ADC.
1127   * @retval HAL status.
1128   */
HAL_ADC_Stop_IT(ADC_HandleTypeDef * hadc)1129 HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc)
1130 {
1131   /* Check the parameters */
1132   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1133 
1134   /* Process locked */
1135   __HAL_LOCK(hadc);
1136 
1137   /* Stop potential conversion on going, on regular and injected groups */
1138   /* Disable ADC peripheral */
1139   __HAL_ADC_DISABLE(hadc);
1140 
1141   /* Check if ADC is effectively disabled */
1142   if(HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_ADON))
1143   {
1144   	/* Disable ADC end of conversion interrupt for regular group */
1145     __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_OVR));
1146 
1147     /* Set ADC state */
1148     ADC_STATE_CLR_SET(hadc->State,
1149                       HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
1150                       HAL_ADC_STATE_READY);
1151   }
1152 
1153   /* Process unlocked */
1154   __HAL_UNLOCK(hadc);
1155 
1156   /* Return function status */
1157   return HAL_OK;
1158 }
1159 
1160 /**
1161   * @brief  Handles ADC interrupt request
1162   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1163   *         the configuration information for the specified ADC.
1164   * @retval None
1165   */
HAL_ADC_IRQHandler(ADC_HandleTypeDef * hadc)1166 void HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc)
1167 {
1168   uint32_t tmp1 = 0U, tmp2 = 0U;
1169 
1170   uint32_t tmp_sr = hadc->Instance->SR;
1171   uint32_t tmp_cr1 = hadc->Instance->CR1;
1172 
1173   /* Check the parameters */
1174   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
1175   assert_param(IS_ADC_REGULAR_LENGTH(hadc->Init.NbrOfConversion));
1176   assert_param(IS_ADC_EOCSelection(hadc->Init.EOCSelection));
1177 
1178   tmp1 = tmp_sr & ADC_FLAG_EOC;
1179   tmp2 = tmp_cr1 & ADC_IT_EOC;
1180   /* Check End of conversion flag for regular channels */
1181   if(tmp1 && tmp2)
1182   {
1183     /* Update state machine on conversion status if not in error state */
1184     if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL))
1185     {
1186       /* Set ADC state */
1187       SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
1188     }
1189 
1190     /* Determine whether any further conversion upcoming on group regular   */
1191     /* by external trigger, continuous mode or scan sequence on going.      */
1192     /* Note: On STM32F2, there is no independent flag of end of sequence.   */
1193     /*       The test of scan sequence on going is done either with scan    */
1194     /*       sequence disabled or with end of conversion flag set to        */
1195     /*       of end of sequence.                                            */
1196     if(ADC_IS_SOFTWARE_START_REGULAR(hadc)                   &&
1197        (hadc->Init.ContinuousConvMode == DISABLE)            &&
1198        (HAL_IS_BIT_CLR(hadc->Instance->SQR1, ADC_SQR1_L) ||
1199         HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_EOCS)  )   )
1200     {
1201       /* Disable ADC end of single conversion interrupt on group regular */
1202       /* Note: Overrun interrupt was enabled with EOC interrupt in          */
1203       /* HAL_ADC_Start_IT(), but is not disabled here because can be used   */
1204       /* by overrun IRQ process below.                                      */
1205       __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC);
1206 
1207       /* Set ADC state */
1208       CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
1209 
1210       if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_INJ_BUSY))
1211       {
1212         SET_BIT(hadc->State, HAL_ADC_STATE_READY);
1213       }
1214     }
1215 
1216     /* Conversion complete callback */
1217 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
1218     hadc->ConvCpltCallback(hadc);
1219 #else
1220     HAL_ADC_ConvCpltCallback(hadc);
1221 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1222 
1223     /* Clear regular group conversion flag */
1224     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_STRT | ADC_FLAG_EOC);
1225   }
1226 
1227   tmp1 = tmp_sr & ADC_FLAG_JEOC;
1228   tmp2 = tmp_cr1 & ADC_IT_JEOC;
1229   /* Check End of conversion flag for injected channels */
1230   if(tmp1 && tmp2)
1231   {
1232     /* Update state machine on conversion status if not in error state */
1233     if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL))
1234     {
1235       /* Set ADC state */
1236       SET_BIT(hadc->State, HAL_ADC_STATE_INJ_EOC);
1237     }
1238 
1239     /* Determine whether any further conversion upcoming on group injected  */
1240     /* by external trigger, scan sequence on going or by automatic injected */
1241     /* conversion from group regular (same conditions as group regular      */
1242     /* interruption disabling above).                                       */
1243     if(ADC_IS_SOFTWARE_START_INJECTED(hadc)                    &&
1244        (HAL_IS_BIT_CLR(hadc->Instance->JSQR, ADC_JSQR_JL)  ||
1245         HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_EOCS)    ) &&
1246        (HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO) &&
1247         (ADC_IS_SOFTWARE_START_REGULAR(hadc)       &&
1248         (hadc->Init.ContinuousConvMode == DISABLE)   )       )   )
1249     {
1250       /* Disable ADC end of single conversion interrupt on group injected */
1251       __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
1252 
1253       /* Set ADC state */
1254       CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY);
1255 
1256       if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_REG_BUSY))
1257       {
1258         SET_BIT(hadc->State, HAL_ADC_STATE_READY);
1259       }
1260     }
1261 
1262     /* Conversion complete callback */
1263 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
1264       hadc->InjectedConvCpltCallback(hadc);
1265 #else
1266       HAL_ADCEx_InjectedConvCpltCallback(hadc);
1267 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1268 
1269     /* Clear injected group conversion flag */
1270     __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_JSTRT | ADC_FLAG_JEOC));
1271   }
1272 
1273   tmp1 = tmp_sr & ADC_FLAG_AWD;
1274   tmp2 = tmp_cr1 & ADC_IT_AWD;
1275   /* Check Analog watchdog flag */
1276   if(tmp1 && tmp2)
1277   {
1278     if(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_AWD))
1279     {
1280       /* Set ADC state */
1281       SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
1282 
1283       /* Level out of window callback */
1284 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
1285       hadc->LevelOutOfWindowCallback(hadc);
1286 #else
1287       HAL_ADC_LevelOutOfWindowCallback(hadc);
1288 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1289 
1290       /* Clear the ADC analog watchdog flag */
1291       __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD);
1292     }
1293   }
1294 
1295   tmp1 = tmp_sr & ADC_FLAG_OVR;
1296   tmp2 = tmp_cr1 & ADC_IT_OVR;
1297   /* Check Overrun flag */
1298   if(tmp1 && tmp2)
1299   {
1300     /* Note: On STM32F2, ADC overrun can be set through other parameters    */
1301     /*       refer to description of parameter "EOCSelection" for more      */
1302     /*       details.                                                       */
1303 
1304     /* Set ADC error code to overrun */
1305     SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_OVR);
1306 
1307     /* Clear ADC overrun flag */
1308     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1309 
1310     /* Error callback */
1311 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
1312       hadc->ErrorCallback(hadc);
1313 #else
1314       HAL_ADC_ErrorCallback(hadc);
1315 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1316 
1317     /* Clear the Overrun flag */
1318     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
1319   }
1320 }
1321 
1322 /**
1323   * @brief  Enables ADC DMA request after last transfer (Single-ADC mode) and enables ADC peripheral
1324   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1325   *         the configuration information for the specified ADC.
1326   * @param  pData The destination Buffer address.
1327   * @param  Length The length of data to be transferred from ADC peripheral to memory.
1328   * @retval HAL status
1329   */
HAL_ADC_Start_DMA(ADC_HandleTypeDef * hadc,uint32_t * pData,uint32_t Length)1330 HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length)
1331 {
1332   __IO uint32_t counter = 0U;
1333 
1334   /* Check the parameters */
1335   assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
1336   assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
1337 
1338   /* Process locked */
1339   __HAL_LOCK(hadc);
1340 
1341   /* Enable the ADC peripheral */
1342   /* Check if ADC peripheral is disabled in order to enable it and wait during
1343   Tstab time the ADC's stabilization */
1344   if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON)
1345   {
1346     /* Enable the Peripheral */
1347     __HAL_ADC_ENABLE(hadc);
1348 
1349     /* Delay for ADC stabilization time */
1350     /* Compute number of CPU cycles to wait for */
1351     counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000U));
1352     while(counter != 0U)
1353     {
1354       counter--;
1355     }
1356   }
1357 
1358   /* Start conversion if ADC is effectively enabled */
1359   if(HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_ADON))
1360   {
1361     /* Set ADC state                                                          */
1362     /* - Clear state bitfield related to regular group conversion results     */
1363     /* - Set state bitfield related to regular group operation                */
1364     ADC_STATE_CLR_SET(hadc->State,
1365                       HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR,
1366                       HAL_ADC_STATE_REG_BUSY);
1367 
1368     /* If conversions on group regular are also triggering group injected,    */
1369     /* update ADC state.                                                      */
1370     if (READ_BIT(hadc->Instance->CR1, ADC_CR1_JAUTO) != RESET)
1371     {
1372       ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
1373     }
1374 
1375     /* State machine update: Check if an injected conversion is ongoing */
1376     if (HAL_IS_BIT_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY))
1377     {
1378       /* Reset ADC error code fields related to conversions on group regular */
1379       CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
1380     }
1381     else
1382     {
1383       /* Reset ADC all error code fields */
1384       ADC_CLEAR_ERRORCODE(hadc);
1385     }
1386 
1387     /* Process unlocked */
1388     /* Unlock before starting ADC conversions: in case of potential           */
1389     /* interruption, to let the process to ADC IRQ Handler.                   */
1390     __HAL_UNLOCK(hadc);
1391 
1392     /* Set the DMA transfer complete callback */
1393     hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt;
1394 
1395     /* Set the DMA half transfer complete callback */
1396     hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt;
1397 
1398     /* Set the DMA error callback */
1399     hadc->DMA_Handle->XferErrorCallback = ADC_DMAError;
1400 
1401 
1402     /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC     */
1403     /* start (in case of SW start):                                           */
1404 
1405     /* Clear regular group conversion flag and overrun flag */
1406     /* (To ensure of no unknown state from potential previous ADC operations) */
1407     __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOC | ADC_FLAG_OVR);
1408 
1409     /* Enable ADC overrun interrupt */
1410     __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
1411 
1412     /* Enable ADC DMA mode */
1413     hadc->Instance->CR2 |= ADC_CR2_DMA;
1414 
1415     /* Start the DMA channel */
1416     HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->DR, (uint32_t)pData, Length);
1417 
1418     /* Check if Multimode enabled */
1419     if(HAL_IS_BIT_CLR(ADC->CCR, ADC_CCR_MULTI))
1420     {
1421       /* if no external trigger present enable software conversion of regular channels */
1422       if((hadc->Instance->CR2 & ADC_CR2_EXTEN) == RESET)
1423       {
1424         /* Enable the selected ADC software conversion for regular group */
1425         hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
1426       }
1427     }
1428     else
1429     {
1430       /* if instance of handle correspond to ADC1 and  no external trigger present enable software conversion of regular channels */
1431       if((hadc->Instance == ADC1) && ((hadc->Instance->CR2 & ADC_CR2_EXTEN) == RESET))
1432       {
1433         /* Enable the selected ADC software conversion for regular group */
1434           hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
1435       }
1436     }
1437   }
1438   else
1439   {
1440     /* Update ADC state machine to error */
1441     SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
1442 
1443     /* Set ADC error code to ADC IP internal error */
1444     SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
1445   }
1446 
1447   /* Return function status */
1448   return HAL_OK;
1449 }
1450 
1451 /**
1452   * @brief  Disables ADC DMA (Single-ADC mode) and disables ADC peripheral
1453   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1454   *         the configuration information for the specified ADC.
1455   * @retval HAL status
1456   */
HAL_ADC_Stop_DMA(ADC_HandleTypeDef * hadc)1457 HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc)
1458 {
1459   HAL_StatusTypeDef tmp_hal_status = HAL_OK;
1460 
1461   /* Check the parameters */
1462   assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
1463 
1464   /* Process locked */
1465   __HAL_LOCK(hadc);
1466 
1467   /* Stop potential conversion on going, on regular and injected groups */
1468   /* Disable ADC peripheral */
1469   __HAL_ADC_DISABLE(hadc);
1470 
1471   /* Check if ADC is effectively disabled */
1472   if(HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_ADON))
1473   {
1474     /* Disable the selected ADC DMA mode */
1475     hadc->Instance->CR2 &= ~ADC_CR2_DMA;
1476 
1477     /* Disable the DMA channel (in case of DMA in circular mode or stop while */
1478     /* DMA transfer is on going)                                              */
1479     if (hadc->DMA_Handle->State == HAL_DMA_STATE_BUSY)
1480     {
1481       tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle);
1482 
1483       /* Disable ADC overrun interrupt */
1484       __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
1485 
1486       /* Set ADC state */
1487       ADC_STATE_CLR_SET(hadc->State,
1488                         HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
1489                         HAL_ADC_STATE_READY);
1490     }
1491   }
1492 
1493   /* Process unlocked */
1494   __HAL_UNLOCK(hadc);
1495 
1496   /* Return function status */
1497   return tmp_hal_status;
1498 }
1499 
1500 /**
1501   * @brief  Gets the converted value from data register of regular channel.
1502   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1503   *         the configuration information for the specified ADC.
1504   * @retval Converted value
1505   */
HAL_ADC_GetValue(ADC_HandleTypeDef * hadc)1506 uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef* hadc)
1507 {
1508   /* Return the selected ADC converted value */
1509   return hadc->Instance->DR;
1510 }
1511 
1512 /**
1513   * @brief  Regular conversion complete callback in non blocking mode
1514   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1515   *         the configuration information for the specified ADC.
1516   * @retval None
1517   */
HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef * hadc)1518 __weak void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
1519 {
1520   /* Prevent unused argument(s) compilation warning */
1521   UNUSED(hadc);
1522   /* NOTE : This function Should not be modified, when the callback is needed,
1523             the HAL_ADC_ConvCpltCallback could be implemented in the user file
1524    */
1525 }
1526 
1527 /**
1528   * @brief  Regular conversion half DMA transfer callback in non blocking mode
1529   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1530   *         the configuration information for the specified ADC.
1531   * @retval None
1532   */
HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef * hadc)1533 __weak void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc)
1534 {
1535   /* Prevent unused argument(s) compilation warning */
1536   UNUSED(hadc);
1537   /* NOTE : This function Should not be modified, when the callback is needed,
1538             the HAL_ADC_ConvHalfCpltCallback could be implemented in the user file
1539    */
1540 }
1541 
1542 /**
1543   * @brief  Analog watchdog callback in non blocking mode
1544   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1545   *         the configuration information for the specified ADC.
1546   * @retval None
1547   */
HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef * hadc)1548 __weak void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc)
1549 {
1550   /* Prevent unused argument(s) compilation warning */
1551   UNUSED(hadc);
1552   /* NOTE : This function Should not be modified, when the callback is needed,
1553             the HAL_ADC_LevelOoutOfWindowCallback could be implemented in the user file
1554    */
1555 }
1556 
1557 /**
1558   * @brief  Error ADC callback.
1559   * @note   In case of error due to overrun when using ADC with DMA transfer
1560   *         (HAL ADC handle parameter "ErrorCode" to state "HAL_ADC_ERROR_OVR"):
1561   *         - Reinitialize the DMA using function "HAL_ADC_Stop_DMA()".
1562   *         - If needed, restart a new ADC conversion using function
1563   *           "HAL_ADC_Start_DMA()"
1564   *           (this function is also clearing overrun flag)
1565   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1566   *         the configuration information for the specified ADC.
1567   * @retval None
1568   */
HAL_ADC_ErrorCallback(ADC_HandleTypeDef * hadc)1569 __weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc)
1570 {
1571   /* Prevent unused argument(s) compilation warning */
1572   UNUSED(hadc);
1573   /* NOTE : This function Should not be modified, when the callback is needed,
1574             the HAL_ADC_ErrorCallback could be implemented in the user file
1575    */
1576 }
1577 
1578 /**
1579   * @}
1580   */
1581 
1582 /** @defgroup ADC_Exported_Functions_Group3 Peripheral Control functions
1583  *  @brief   	Peripheral Control functions
1584  *
1585 @verbatim
1586  ===============================================================================
1587              ##### Peripheral Control functions #####
1588  ===============================================================================
1589     [..]  This section provides functions allowing to:
1590       (+) Configure regular channels.
1591       (+) Configure injected channels.
1592       (+) Configure multimode.
1593       (+) Configure the analog watch dog.
1594 
1595 @endverbatim
1596   * @{
1597   */
1598 
1599   /**
1600   * @brief  Configures for the selected ADC regular channel its corresponding
1601   *         rank in the sequencer and its sample time.
1602   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1603   *         the configuration information for the specified ADC.
1604   * @param  sConfig ADC configuration structure.
1605   * @retval HAL status
1606   */
HAL_ADC_ConfigChannel(ADC_HandleTypeDef * hadc,ADC_ChannelConfTypeDef * sConfig)1607 HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig)
1608 {
1609   __IO uint32_t counter = 0U;
1610 
1611   /* Check the parameters */
1612   assert_param(IS_ADC_CHANNEL(sConfig->Channel));
1613   assert_param(IS_ADC_REGULAR_RANK(sConfig->Rank));
1614   assert_param(IS_ADC_SAMPLE_TIME(sConfig->SamplingTime));
1615 
1616   /* Process locked */
1617   __HAL_LOCK(hadc);
1618 
1619   /* if ADC_Channel_10 ... ADC_Channel_18 is selected */
1620   if (sConfig->Channel > ADC_CHANNEL_9)
1621   {
1622     /* Clear the old sample time */
1623     hadc->Instance->SMPR1 &= ~ADC_SMPR1(ADC_SMPR1_SMP10, sConfig->Channel);
1624 
1625     /* Set the new sample time */
1626     hadc->Instance->SMPR1 |= ADC_SMPR1(sConfig->SamplingTime, sConfig->Channel);
1627   }
1628   else /* ADC_Channel include in ADC_Channel_[0..9] */
1629   {
1630     /* Clear the old sample time */
1631     hadc->Instance->SMPR2 &= ~ADC_SMPR2(ADC_SMPR2_SMP0, sConfig->Channel);
1632 
1633     /* Set the new sample time */
1634     hadc->Instance->SMPR2 |= ADC_SMPR2(sConfig->SamplingTime, sConfig->Channel);
1635   }
1636 
1637   /* For Rank 1 to 6 */
1638   if (sConfig->Rank < 7U)
1639   {
1640     /* Clear the old SQx bits for the selected rank */
1641     hadc->Instance->SQR3 &= ~ADC_SQR3_RK(ADC_SQR3_SQ1, sConfig->Rank);
1642 
1643     /* Set the SQx bits for the selected rank */
1644     hadc->Instance->SQR3 |= ADC_SQR3_RK(sConfig->Channel, sConfig->Rank);
1645   }
1646   /* For Rank 7 to 12 */
1647   else if (sConfig->Rank < 13U)
1648   {
1649     /* Clear the old SQx bits for the selected rank */
1650     hadc->Instance->SQR2 &= ~ADC_SQR2_RK(ADC_SQR2_SQ7, sConfig->Rank);
1651 
1652     /* Set the SQx bits for the selected rank */
1653     hadc->Instance->SQR2 |= ADC_SQR2_RK(sConfig->Channel, sConfig->Rank);
1654   }
1655   /* For Rank 13 to 16 */
1656   else
1657   {
1658     /* Clear the old SQx bits for the selected rank */
1659     hadc->Instance->SQR1 &= ~ADC_SQR1_RK(ADC_SQR1_SQ13, sConfig->Rank);
1660 
1661     /* Set the SQx bits for the selected rank */
1662     hadc->Instance->SQR1 |= ADC_SQR1_RK(sConfig->Channel, sConfig->Rank);
1663   }
1664 
1665   /* if ADC1 Channel_18 is selected enable VBAT Channel */
1666   if ((hadc->Instance == ADC1) && (sConfig->Channel == ADC_CHANNEL_VBAT))
1667   {
1668     /* Enable the VBAT channel*/
1669     ADC->CCR |= ADC_CCR_VBATE;
1670   }
1671 
1672   /* if ADC1 Channel_16 or Channel_17 is selected enable TSVREFE Channel(Temperature sensor and VREFINT) */
1673   if ((hadc->Instance == ADC1) && ((sConfig->Channel == ADC_CHANNEL_TEMPSENSOR) || (sConfig->Channel == ADC_CHANNEL_VREFINT)))
1674   {
1675     /* Enable the TSVREFE channel*/
1676     ADC->CCR |= ADC_CCR_TSVREFE;
1677 
1678     if(sConfig->Channel == ADC_CHANNEL_TEMPSENSOR)
1679     {
1680       /* Delay for temperature sensor stabilization time */
1681       /* Compute number of CPU cycles to wait for */
1682       counter = (ADC_TEMPSENSOR_DELAY_US * (SystemCoreClock / 1000000U));
1683       while(counter != 0U)
1684       {
1685         counter--;
1686       }
1687     }
1688   }
1689 
1690   /* Process unlocked */
1691   __HAL_UNLOCK(hadc);
1692 
1693   /* Return function status */
1694   return HAL_OK;
1695 }
1696 
1697 /**
1698   * @brief  Configures the analog watchdog.
1699   * @note Analog watchdog thresholds can be modified while ADC conversion
1700   * is on going.
1701   * In this case, some constraints must be taken into account:
1702   * The programmed threshold values are effective from the next
1703   * ADC EOC (end of unitary conversion).
1704   * Considering that registers write delay may happen due to
1705   * bus activity, this might cause an uncertainty on the
1706   * effective timing of the new programmed threshold values.
1707   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1708   *         the configuration information for the specified ADC.
1709   * @param  AnalogWDGConfig pointer to an ADC_AnalogWDGConfTypeDef structure
1710   *         that contains the configuration information of ADC analog watchdog.
1711   * @retval HAL status
1712   */
HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef * hadc,ADC_AnalogWDGConfTypeDef * AnalogWDGConfig)1713 HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig)
1714 {
1715 #ifdef USE_FULL_ASSERT
1716   uint32_t tmp = 0U;
1717 #endif /* USE_FULL_ASSERT  */
1718 
1719   /* Check the parameters */
1720   assert_param(IS_ADC_ANALOG_WATCHDOG(AnalogWDGConfig->WatchdogMode));
1721   assert_param(IS_ADC_CHANNEL(AnalogWDGConfig->Channel));
1722   assert_param(IS_FUNCTIONAL_STATE(AnalogWDGConfig->ITMode));
1723 
1724 #ifdef USE_FULL_ASSERT
1725   tmp = ADC_GET_RESOLUTION(hadc);
1726   assert_param(IS_ADC_RANGE(tmp, AnalogWDGConfig->HighThreshold));
1727   assert_param(IS_ADC_RANGE(tmp, AnalogWDGConfig->LowThreshold));
1728 #endif /* USE_FULL_ASSERT  */
1729 
1730   /* Process locked */
1731   __HAL_LOCK(hadc);
1732 
1733   if(AnalogWDGConfig->ITMode == ENABLE)
1734   {
1735     /* Enable the ADC Analog watchdog interrupt */
1736     __HAL_ADC_ENABLE_IT(hadc, ADC_IT_AWD);
1737   }
1738   else
1739   {
1740     /* Disable the ADC Analog watchdog interrupt */
1741     __HAL_ADC_DISABLE_IT(hadc, ADC_IT_AWD);
1742   }
1743 
1744   /* Clear AWDEN, JAWDEN and AWDSGL bits */
1745   hadc->Instance->CR1 &=  ~(ADC_CR1_AWDSGL | ADC_CR1_JAWDEN | ADC_CR1_AWDEN);
1746 
1747   /* Set the analog watchdog enable mode */
1748   hadc->Instance->CR1 |= AnalogWDGConfig->WatchdogMode;
1749 
1750   /* Set the high threshold */
1751   hadc->Instance->HTR = AnalogWDGConfig->HighThreshold;
1752 
1753   /* Set the low threshold */
1754   hadc->Instance->LTR = AnalogWDGConfig->LowThreshold;
1755 
1756   /* Clear the Analog watchdog channel select bits */
1757   hadc->Instance->CR1 &= ~ADC_CR1_AWDCH;
1758 
1759   /* Set the Analog watchdog channel */
1760   hadc->Instance->CR1 |= (uint32_t)((uint16_t)(AnalogWDGConfig->Channel));
1761 
1762   /* Process unlocked */
1763   __HAL_UNLOCK(hadc);
1764 
1765   /* Return function status */
1766   return HAL_OK;
1767 }
1768 
1769 /**
1770   * @}
1771   */
1772 
1773 /** @defgroup ADC_Exported_Functions_Group4 ADC Peripheral State functions
1774  *  @brief   ADC Peripheral State functions
1775  *
1776 @verbatim
1777  ===============================================================================
1778             ##### Peripheral State and errors functions #####
1779  ===============================================================================
1780     [..]
1781     This subsection provides functions allowing to
1782       (+) Check the ADC state
1783       (+) Check the ADC Error
1784 
1785 @endverbatim
1786   * @{
1787   */
1788 
1789 /**
1790   * @brief  return the ADC state
1791   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1792   *         the configuration information for the specified ADC.
1793   * @retval HAL state
1794   */
HAL_ADC_GetState(ADC_HandleTypeDef * hadc)1795 uint32_t HAL_ADC_GetState(ADC_HandleTypeDef* hadc)
1796 {
1797   /* Return ADC state */
1798   return hadc->State;
1799 }
1800 
1801 /**
1802   * @brief  Return the ADC error code
1803   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1804   *         the configuration information for the specified ADC.
1805   * @retval ADC Error Code
1806   */
HAL_ADC_GetError(ADC_HandleTypeDef * hadc)1807 uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc)
1808 {
1809   return hadc->ErrorCode;
1810 }
1811 
1812 /**
1813   * @}
1814   */
1815 
1816 /** @addtogroup ADC_Private_Functions
1817   * @{
1818   */
1819 
1820 /**
1821   * @brief  Initializes the ADCx peripheral according to the specified parameters
1822   *         in the ADC_InitStruct without initializing the ADC MSP.
1823   * @param  hadc pointer to a ADC_HandleTypeDef structure that contains
1824   *         the configuration information for the specified ADC.
1825   * @retval None
1826   */
ADC_Init(ADC_HandleTypeDef * hadc)1827 static void ADC_Init(ADC_HandleTypeDef* hadc)
1828 {
1829   /* Set ADC parameters */
1830   /* Set the ADC clock prescaler */
1831   ADC->CCR &= ~(ADC_CCR_ADCPRE);
1832   ADC->CCR |=  hadc->Init.ClockPrescaler;
1833 
1834   /* Set ADC scan mode */
1835   hadc->Instance->CR1 &= ~(ADC_CR1_SCAN);
1836   hadc->Instance->CR1 |=  ADC_CR1_SCANCONV(hadc->Init.ScanConvMode);
1837 
1838   /* Set ADC resolution */
1839   hadc->Instance->CR1 &= ~(ADC_CR1_RES);
1840   hadc->Instance->CR1 |=  hadc->Init.Resolution;
1841 
1842   /* Set ADC data alignment */
1843   hadc->Instance->CR2 &= ~(ADC_CR2_ALIGN);
1844   hadc->Instance->CR2 |= hadc->Init.DataAlign;
1845 
1846   /* Enable external trigger if trigger selection is different of software  */
1847   /* start.                                                                 */
1848   /* Note: This configuration keeps the hardware feature of parameter       */
1849   /*       ExternalTrigConvEdge "trigger edge none" equivalent to           */
1850   /*       software start.                                                  */
1851   if(hadc->Init.ExternalTrigConv != ADC_SOFTWARE_START)
1852   {
1853     /* Select external trigger to start conversion */
1854     hadc->Instance->CR2 &= ~(ADC_CR2_EXTSEL);
1855     hadc->Instance->CR2 |= hadc->Init.ExternalTrigConv;
1856 
1857     /* Select external trigger polarity */
1858     hadc->Instance->CR2 &= ~(ADC_CR2_EXTEN);
1859     hadc->Instance->CR2 |= hadc->Init.ExternalTrigConvEdge;
1860   }
1861   else
1862   {
1863     /* Reset the external trigger */
1864     hadc->Instance->CR2 &= ~(ADC_CR2_EXTSEL);
1865     hadc->Instance->CR2 &= ~(ADC_CR2_EXTEN);
1866   }
1867 
1868   /* Enable or disable ADC continuous conversion mode */
1869   hadc->Instance->CR2 &= ~(ADC_CR2_CONT);
1870   hadc->Instance->CR2 |= ADC_CR2_CONTINUOUS((uint32_t)hadc->Init.ContinuousConvMode);
1871 
1872   if(hadc->Init.DiscontinuousConvMode != DISABLE)
1873   {
1874     assert_param(IS_ADC_REGULAR_DISC_NUMBER(hadc->Init.NbrOfDiscConversion));
1875 
1876     /* Enable the selected ADC regular discontinuous mode */
1877     hadc->Instance->CR1 |= (uint32_t)ADC_CR1_DISCEN;
1878 
1879     /* Set the number of channels to be converted in discontinuous mode */
1880     hadc->Instance->CR1 &= ~(ADC_CR1_DISCNUM);
1881     hadc->Instance->CR1 |=  ADC_CR1_DISCONTINUOUS(hadc->Init.NbrOfDiscConversion);
1882   }
1883   else
1884   {
1885     /* Disable the selected ADC regular discontinuous mode */
1886     hadc->Instance->CR1 &= ~(ADC_CR1_DISCEN);
1887   }
1888 
1889   /* Set ADC number of conversion */
1890   hadc->Instance->SQR1 &= ~(ADC_SQR1_L);
1891   hadc->Instance->SQR1 |=  ADC_SQR1(hadc->Init.NbrOfConversion);
1892 
1893   /* Enable or disable ADC DMA continuous request */
1894   hadc->Instance->CR2 &= ~(ADC_CR2_DDS);
1895   hadc->Instance->CR2 |= ADC_CR2_DMAContReq((uint32_t)hadc->Init.DMAContinuousRequests);
1896 
1897   /* Enable or disable ADC end of conversion selection */
1898   hadc->Instance->CR2 &= ~(ADC_CR2_EOCS);
1899   hadc->Instance->CR2 |= ADC_CR2_EOCSelection(hadc->Init.EOCSelection);
1900 }
1901 
1902 /**
1903   * @brief  DMA transfer complete callback.
1904   * @param  hdma pointer to a DMA_HandleTypeDef structure that contains
1905   *                the configuration information for the specified DMA module.
1906   * @retval None
1907   */
ADC_DMAConvCplt(DMA_HandleTypeDef * hdma)1908 static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma)
1909 {
1910   /* Retrieve ADC handle corresponding to current DMA handle */
1911   ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
1912 
1913   /* Update state machine on conversion status if not in error state */
1914   if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL | HAL_ADC_STATE_ERROR_DMA))
1915   {
1916     /* Update ADC state machine */
1917     SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
1918 
1919     /* Determine whether any further conversion upcoming on group regular   */
1920     /* by external trigger, continuous mode or scan sequence on going.      */
1921     /* Note: On STM32F2, there is no independent flag of end of sequence.   */
1922     /*       The test of scan sequence on going is done either with scan    */
1923     /*       sequence disabled or with end of conversion flag set to        */
1924     /*       of end of sequence.                                            */
1925     if(ADC_IS_SOFTWARE_START_REGULAR(hadc)                   &&
1926        (hadc->Init.ContinuousConvMode == DISABLE)            &&
1927        (HAL_IS_BIT_CLR(hadc->Instance->SQR1, ADC_SQR1_L) ||
1928         HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_EOCS)  )   )
1929     {
1930       /* Disable ADC end of single conversion interrupt on group regular */
1931       /* Note: Overrun interrupt was enabled with EOC interrupt in          */
1932       /* HAL_ADC_Start_IT(), but is not disabled here because can be used   */
1933       /* by overrun IRQ process below.                                      */
1934       __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC);
1935 
1936       /* Set ADC state */
1937       CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
1938 
1939       if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_INJ_BUSY))
1940       {
1941         SET_BIT(hadc->State, HAL_ADC_STATE_READY);
1942       }
1943     }
1944 
1945     /* Conversion complete callback */
1946 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
1947     hadc->ConvCpltCallback(hadc);
1948 #else
1949     HAL_ADC_ConvCpltCallback(hadc);
1950 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1951   }
1952   else /* DMA and-or internal error occurred */
1953   {
1954     if ((hadc->State & HAL_ADC_STATE_ERROR_INTERNAL) != 0UL)
1955     {
1956       /* Call HAL ADC Error Callback function */
1957 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
1958       hadc->ErrorCallback(hadc);
1959 #else
1960       HAL_ADC_ErrorCallback(hadc);
1961 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1962     }
1963 	else
1964 	{
1965       /* Call DMA error callback */
1966       hadc->DMA_Handle->XferErrorCallback(hdma);
1967     }
1968   }
1969 }
1970 
1971 /**
1972   * @brief  DMA half transfer complete callback.
1973   * @param  hdma pointer to a DMA_HandleTypeDef structure that contains
1974   *                the configuration information for the specified DMA module.
1975   * @retval None
1976   */
ADC_DMAHalfConvCplt(DMA_HandleTypeDef * hdma)1977 static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma)
1978 {
1979   ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
1980 
1981   /* Half conversion callback */
1982 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
1983   hadc->ConvHalfCpltCallback(hadc);
1984 #else
1985   HAL_ADC_ConvHalfCpltCallback(hadc);
1986 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
1987 }
1988 
1989 /**
1990   * @brief  DMA error callback
1991   * @param  hdma pointer to a DMA_HandleTypeDef structure that contains
1992   *                the configuration information for the specified DMA module.
1993   * @retval None
1994   */
ADC_DMAError(DMA_HandleTypeDef * hdma)1995 static void ADC_DMAError(DMA_HandleTypeDef *hdma)
1996 {
1997   ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
1998   hadc->State= HAL_ADC_STATE_ERROR_DMA;
1999   /* Set ADC error code to DMA error */
2000   hadc->ErrorCode |= HAL_ADC_ERROR_DMA;
2001    /* Error callback */
2002 #if (USE_HAL_ADC_REGISTER_CALLBACKS == 1)
2003   hadc->ErrorCallback(hadc);
2004 #else
2005   HAL_ADC_ErrorCallback(hadc);
2006 #endif /* USE_HAL_ADC_REGISTER_CALLBACKS */
2007 }
2008 
2009 /**
2010   * @}
2011   */
2012 
2013 /**
2014   * @}
2015   */
2016 
2017 #endif /* HAL_ADC_MODULE_ENABLED */
2018 /**
2019   * @}
2020   */
2021 
2022 /**
2023   * @}
2024   */
2025 
2026