1 /**
2   ******************************************************************************
3   * @file    stm32f7xx_hal_adc.c
4   * @author  MCD Application Team
5   * @version V1.0.1
6   * @date    25-June-2015
7   * @brief   This file provides firmware functions to manage the following
8   *          functionalities of the Analog to Digital Convertor (ADC) peripheral:
9   *           + Initialization and de-initialization functions
10   *           + IO operation functions
11   *           + State and errors functions
12   *
13   @verbatim
14   ==============================================================================
15                     ##### ADC Peripheral features #####
16   ==============================================================================
17   [..]
18   (#) 12-bit, 10-bit, 8-bit or 6-bit configurable resolution.
19   (#) Interrupt generation at the end of conversion, end of injected conversion,
20       and in case of analog watchdog or overrun events
21   (#) Single and continuous conversion modes.
22   (#) Scan mode for automatic conversion of channel 0 to channel x.
23   (#) Data alignment with in-built data coherency.
24   (#) Channel-wise programmable sampling time.
25   (#) External trigger option with configurable polarity for both regular and
26       injected conversion.
27   (#) Dual/Triple mode (on devices with 2 ADCs or more).
28   (#) Configurable DMA data storage in Dual/Triple ADC mode.
29   (#) Configurable delay between conversions in Dual/Triple interleaved mode.
30   (#) ADC conversion type (refer to the datasheets).
31   (#) ADC supply requirements: 2.4 V to 3.6 V at full speed and down to 1.8 V at
32       slower speed.
33   (#) ADC input range: VREF(minus) = VIN = VREF(plus).
34   (#) DMA request generation during regular channel conversion.
35 
36 
37                      ##### How to use this driver #####
38   ==============================================================================
39   [..]
40   (#)Initialize the ADC low level resources by implementing the HAL_ADC_MspInit():
41        (##) Enable the ADC interface clock using __HAL_RCC_ADC_CLK_ENABLE()
42        (##) ADC pins configuration
43              (+++) Enable the clock for the ADC GPIOs using the following function:
44                    __HAL_RCC_GPIOx_CLK_ENABLE()
45              (+++) Configure these ADC pins in analog mode using HAL_GPIO_Init()
46        (##) In case of using interrupts (e.g. HAL_ADC_Start_IT())
47              (+++) Configure the ADC interrupt priority using HAL_NVIC_SetPriority()
48              (+++) Enable the ADC IRQ handler using HAL_NVIC_EnableIRQ()
49              (+++) In ADC IRQ handler, call HAL_ADC_IRQHandler()
50        (##) In case of using DMA to control data transfer (e.g. HAL_ADC_Start_DMA())
51              (+++) Enable the DMAx interface clock using __HAL_RCC_DMAx_CLK_ENABLE()
52              (+++) Configure and enable two DMA streams stream for managing data
53                  transfer from peripheral to memory (output stream)
54              (+++) Associate the initialized DMA handle to the CRYP DMA handle
55                  using  __HAL_LINKDMA()
56              (+++) Configure the priority and enable the NVIC for the transfer complete
57                  interrupt on the two DMA Streams. The output stream should have higher
58                  priority than the input stream.
59 
60     *** Configuration of ADC, groups regular/injected, channels parameters ***
61   ==============================================================================
62   [..]
63   (#) Configure the ADC parameters (resolution, data alignment, ...)
64       and regular group parameters (conversion trigger, sequencer, ...)
65       using function HAL_ADC_Init().
66 
67   (#) Configure the channels for regular group parameters (channel number,
68       channel rank into sequencer, ..., into regular group)
69       using function HAL_ADC_ConfigChannel().
70 
71   (#) Optionally, configure the injected group parameters (conversion trigger,
72       sequencer, ..., of injected group)
73       and the channels for injected group parameters (channel number,
74       channel rank into sequencer, ..., into injected group)
75       using function HAL_ADCEx_InjectedConfigChannel().
76 
77   (#) Optionally, configure the analog watchdog parameters (channels
78       monitored, thresholds, ...) using function HAL_ADC_AnalogWDGConfig().
79 
80   (#) Optionally, for devices with several ADC instances: configure the
81       multimode parameters using function HAL_ADCEx_MultiModeConfigChannel().
82 
83                        *** Execution of ADC conversions ***
84   ==============================================================================
85   [..]
86   (#) ADC driver can be used among three modes: polling, interruption,
87       transfer by DMA.
88 
89      *** Polling mode IO operation ***
90      =================================
91      [..]
92        (+) Start the ADC peripheral using HAL_ADC_Start()
93        (+) Wait for end of conversion using HAL_ADC_PollForConversion(), at this stage
94            user can specify the value of timeout according to his end application
95        (+) To read the ADC converted values, use the HAL_ADC_GetValue() function.
96        (+) Stop the ADC peripheral using HAL_ADC_Stop()
97 
98      *** Interrupt mode IO operation ***
99      ===================================
100      [..]
101        (+) Start the ADC peripheral using HAL_ADC_Start_IT()
102        (+) Use HAL_ADC_IRQHandler() called under ADC_IRQHandler() Interrupt subroutine
103        (+) At ADC end of conversion HAL_ADC_ConvCpltCallback() function is executed and user can
104            add his own code by customization of function pointer HAL_ADC_ConvCpltCallback
105        (+) In case of ADC Error, HAL_ADC_ErrorCallback() function is executed and user can
106            add his own code by customization of function pointer HAL_ADC_ErrorCallback
107        (+) Stop the ADC peripheral using HAL_ADC_Stop_IT()
108 
109      *** DMA mode IO operation ***
110      ==============================
111      [..]
112        (+) Start the ADC peripheral using HAL_ADC_Start_DMA(), at this stage the user specify the length
113            of data to be transferred at each end of conversion
114        (+) At The end of data transfer by HAL_ADC_ConvCpltCallback() function is executed and user can
115            add his own code by customization of function pointer HAL_ADC_ConvCpltCallback
116        (+) In case of transfer Error, HAL_ADC_ErrorCallback() function is executed and user can
117            add his own code by customization of function pointer HAL_ADC_ErrorCallback
118        (+) Stop the ADC peripheral using HAL_ADC_Stop_DMA()
119 
120      *** ADC HAL driver macros list ***
121      =============================================
122      [..]
123        Below the list of most used macros in ADC HAL driver.
124 
125       (+) __HAL_ADC_ENABLE : Enable the ADC peripheral
126       (+) __HAL_ADC_DISABLE : Disable the ADC peripheral
127       (+) __HAL_ADC_ENABLE_IT: Enable the ADC end of conversion interrupt
128       (+) __HAL_ADC_DISABLE_IT: Disable the ADC end of conversion interrupt
129       (+) __HAL_ADC_GET_IT_SOURCE: Check if the specified ADC interrupt source is enabled or disabled
130       (+) __HAL_ADC_CLEAR_FLAG: Clear the ADC's pending flags
131       (+) __HAL_ADC_GET_FLAG: Get the selected ADC's flag status
132       (+) ADC_GET_RESOLUTION: Return resolution bits in CR1 register
133 
134      [..]
135        (@) You can refer to the ADC HAL driver header file for more useful macros
136 
137                       *** Deinitialization of ADC ***
138   ==============================================================================
139   [..]
140   (#) Disable the ADC interface
141      (++) ADC clock can be hard reset and disabled at RCC top level.
142      (++) Hard reset of ADC peripherals
143           using macro __HAL_RCC_ADC_FORCE_RESET(), __HAL_RCC_ADC_RELEASE_RESET().
144      (++) ADC clock disable using the equivalent macro/functions as configuration step.
145                (+++) Example:
146                    Into HAL_ADC_MspDeInit() (recommended code location) or with
147                    other device clock parameters configuration:
148                (+++) HAL_RCC_GetOscConfig(&RCC_OscInitStructure);
149                (+++) RCC_OscInitStructure.OscillatorType = RCC_OSCILLATORTYPE_HSI;
150                (+++) RCC_OscInitStructure.HSIState = RCC_HSI_OFF; (if not used for system clock)
151                (+++) HAL_RCC_OscConfig(&RCC_OscInitStructure);
152 
153   (#) ADC pins configuration
154      (++) Disable the clock for the ADC GPIOs using macro __HAL_RCC_GPIOx_CLK_DISABLE()
155 
156   (#) Optionally, in case of usage of ADC with interruptions:
157      (++) Disable the NVIC for ADC using function HAL_NVIC_DisableIRQ(ADCx_IRQn)
158 
159   (#) Optionally, in case of usage of DMA:
160         (++) Deinitialize the DMA using function HAL_DMA_DeInit().
161         (++) Disable the NVIC for DMA using function HAL_NVIC_DisableIRQ(DMAx_Channelx_IRQn)
162 
163     @endverbatim
164   ******************************************************************************
165   * @attention
166   *
167   * <h2><center>&copy; COPYRIGHT(c) 2015 STMicroelectronics</center></h2>
168   *
169   * Redistribution and use in source and binary forms, with or without modification,
170   * are permitted provided that the following conditions are met:
171   *   1. Redistributions of source code must retain the above copyright notice,
172   *      this list of conditions and the following disclaimer.
173   *   2. Redistributions in binary form must reproduce the above copyright notice,
174   *      this list of conditions and the following disclaimer in the documentation
175   *      and/or other materials provided with the distribution.
176   *   3. Neither the name of STMicroelectronics nor the names of its contributors
177   *      may be used to endorse or promote products derived from this software
178   *      without specific prior written permission.
179   *
180   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
181   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
182   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
183   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
184   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
185   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
186   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
187   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
188   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
189   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
190   *
191   ******************************************************************************
192   */
193 
194 /* Includes ------------------------------------------------------------------*/
195 #include "stm32f7xx_hal.h"
196 
197 /** @addtogroup STM32F7xx_HAL_Driver
198   * @{
199   */
200 
201 /** @defgroup ADC ADC
202   * @brief ADC driver modules
203   * @{
204   */
205 
206 #ifdef HAL_ADC_MODULE_ENABLED
207 
208 /* Private typedef -----------------------------------------------------------*/
209 /* Private define ------------------------------------------------------------*/
210 /* Private macro -------------------------------------------------------------*/
211 /* Private variables ---------------------------------------------------------*/
212 /** @addtogroup ADC_Private_Functions
213   * @{
214   */
215 /* Private function prototypes -----------------------------------------------*/
216 static void ADC_Init(ADC_HandleTypeDef* hadc);
217 static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma);
218 static void ADC_DMAError(DMA_HandleTypeDef *hdma);
219 static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma);
220 /**
221   * @}
222   */
223 
224 /* Exported functions --------------------------------------------------------*/
225 /** @defgroup ADC_Exported_Functions ADC Exported Functions
226   * @{
227   */
228 
229 /** @defgroup ADC_Exported_Functions_Group1 Initialization and de-initialization functions
230  *  @brief    Initialization and Configuration functions
231  *
232 @verbatim
233  ===============================================================================
234               ##### Initialization and de-initialization functions #####
235  ===============================================================================
236     [..]  This section provides functions allowing to:
237       (+) Initialize and configure the ADC.
238       (+) De-initialize the ADC.
239 
240 @endverbatim
241   * @{
242   */
243 
244 /**
245   * @brief  Initializes the ADCx peripheral according to the specified parameters
246   *         in the ADC_InitStruct and initializes the ADC MSP.
247   *
248   * @note   This function is used to configure the global features of the ADC (
249   *         ClockPrescaler, Resolution, Data Alignment and number of conversion), however,
250   *         the rest of the configuration parameters are specific to the regular
251   *         channels group (scan mode activation, continuous mode activation,
252   *         External trigger source and edge, DMA continuous request after the
253   *         last transfer and End of conversion selection).
254   *
255   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
256   *         the configuration information for the specified ADC.
257   * @retval HAL status
258   */
HAL_ADC_Init(ADC_HandleTypeDef * hadc)259 HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc)
260 {
261     /* Check ADC handle */
262     if (hadc == NULL) {
263         return HAL_ERROR;
264     }
265 
266     /* Check the parameters */
267     assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
268     assert_param(IS_ADC_CLOCKPRESCALER(hadc->Init.ClockPrescaler));
269     assert_param(IS_ADC_RESOLUTION(hadc->Init.Resolution));
270     assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ScanConvMode));
271     assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
272     assert_param(IS_ADC_EXT_TRIG(hadc->Init.ExternalTrigConv));
273     assert_param(IS_ADC_DATA_ALIGN(hadc->Init.DataAlign));
274     assert_param(IS_ADC_REGULAR_LENGTH(hadc->Init.NbrOfConversion));
275     assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests));
276     assert_param(IS_ADC_EOCSelection(hadc->Init.EOCSelection));
277     assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DiscontinuousConvMode));
278 
279     if (hadc->Init.ExternalTrigConv != ADC_SOFTWARE_START) {
280         assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
281     }
282 
283     if (hadc->State == HAL_ADC_STATE_RESET) {
284         /* Allocate lock resource and initialize it */
285         hadc->Lock = HAL_UNLOCKED;
286         /* Init the low level hardware */
287         HAL_ADC_MspInit(hadc);
288     }
289 
290     /* Initialize the ADC state */
291     hadc->State = HAL_ADC_STATE_BUSY;
292 
293     /* Set ADC parameters */
294     ADC_Init(hadc);
295 
296     /* Set ADC error code to none */
297     hadc->ErrorCode = HAL_ADC_ERROR_NONE;
298 
299     /* Initialize the ADC state */
300     hadc->State = HAL_ADC_STATE_READY;
301 
302     /* Release Lock */
303     __HAL_UNLOCK(hadc);
304 
305     /* Return function status */
306     return HAL_OK;
307 }
308 
309 /**
310   * @brief  Deinitializes the ADCx peripheral registers to their default reset values.
311   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
312   *         the configuration information for the specified ADC.
313   * @retval HAL status
314   */
HAL_ADC_DeInit(ADC_HandleTypeDef * hadc)315 HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef* hadc)
316 {
317     /* Check ADC handle */
318     if (hadc == NULL) {
319         return HAL_ERROR;
320     }
321 
322     /* Check the parameters */
323     assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
324 
325     /* Change ADC state */
326     hadc->State = HAL_ADC_STATE_BUSY;
327 
328     /* DeInit the low level hardware */
329     HAL_ADC_MspDeInit(hadc);
330 
331     /* Set ADC error code to none */
332     hadc->ErrorCode = HAL_ADC_ERROR_NONE;
333 
334     /* Change ADC state */
335     hadc->State = HAL_ADC_STATE_RESET;
336 
337     /* Return function status */
338     return HAL_OK;
339 }
340 
341 /**
342   * @brief  Initializes the ADC MSP.
343   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
344   *         the configuration information for the specified ADC.
345   * @retval None
346   */
HAL_ADC_MspInit(ADC_HandleTypeDef * hadc)347 __weak void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc)
348 {
349     /* NOTE : This function Should not be modified, when the callback is needed,
350               the HAL_ADC_MspInit could be implemented in the user file
351      */
352 }
353 
354 /**
355   * @brief  DeInitializes the ADC MSP.
356   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
357   *         the configuration information for the specified ADC.
358   * @retval None
359   */
HAL_ADC_MspDeInit(ADC_HandleTypeDef * hadc)360 __weak void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc)
361 {
362     /* NOTE : This function Should not be modified, when the callback is needed,
363               the HAL_ADC_MspDeInit could be implemented in the user file
364      */
365 }
366 
367 /**
368   * @}
369   */
370 
371 /** @defgroup ADC_Exported_Functions_Group2 IO operation functions
372  *  @brief    IO operation functions
373  *
374 @verbatim
375  ===============================================================================
376              ##### IO operation functions #####
377  ===============================================================================
378     [..]  This section provides functions allowing to:
379       (+) Start conversion of regular channel.
380       (+) Stop conversion of regular channel.
381       (+) Start conversion of regular channel and enable interrupt.
382       (+) Stop conversion of regular channel and disable interrupt.
383       (+) Start conversion of regular channel and enable DMA transfer.
384       (+) Stop conversion of regular channel and disable DMA transfer.
385       (+) Handle ADC interrupt request.
386 
387 @endverbatim
388   * @{
389   */
390 
391 /**
392   * @brief  Enables ADC and starts conversion of the regular channels.
393   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
394   *         the configuration information for the specified ADC.
395   * @retval HAL status
396   */
HAL_ADC_Start(ADC_HandleTypeDef * hadc)397 HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc)
398 {
399     __IO uint32_t counter = 0;
400 
401     /* Check the parameters */
402     assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
403     assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
404 
405     /* Process locked */
406     __HAL_LOCK(hadc);
407 
408     /* Check if an injected conversion is ongoing */
409     if (hadc->State == HAL_ADC_STATE_BUSY_INJ) {
410         /* Change ADC state */
411         hadc->State = HAL_ADC_STATE_BUSY_INJ_REG;
412     } else {
413         /* Change ADC state */
414         hadc->State = HAL_ADC_STATE_BUSY_REG;
415     }
416 
417     /* Check if ADC peripheral is disabled in order to enable it and wait during
418     Tstab time the ADC's stabilization */
419     if ((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON) {
420         /* Enable the Peripheral */
421         __HAL_ADC_ENABLE(hadc);
422 
423         /* Delay for ADC stabilization time */
424         /* Compute number of CPU cycles to wait for */
425         counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000));
426         while (counter != 0) {
427             counter--;
428         }
429     }
430 
431     /* Process unlocked */
432     __HAL_UNLOCK(hadc);
433 
434     /* Check if Multimode enabled */
435     if (HAL_IS_BIT_CLR(ADC->CCR, ADC_CCR_MULTI)) {
436         /* if no external trigger present enable software conversion of regular channels */
437         if ((hadc->Instance->CR2 & ADC_CR2_EXTEN) == RESET) {
438             /* Enable the selected ADC software conversion for regular group */
439             hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
440         }
441     } else {
442         /* if instance of handle correspond to ADC1 and  no external trigger present enable software conversion of regular channels */
443         if ((hadc->Instance == ADC1) && ((hadc->Instance->CR2 & ADC_CR2_EXTEN) == RESET)) {
444             /* Enable the selected ADC software conversion for regular group */
445             hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
446         }
447     }
448 
449     /* Return function status */
450     return HAL_OK;
451 }
452 
453 /**
454   * @brief  Disables ADC and stop conversion of regular channels.
455   *
456   * @note   Caution: This function will stop also injected channels.
457   *
458   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
459   *         the configuration information for the specified ADC.
460   *
461   * @retval HAL status.
462   */
HAL_ADC_Stop(ADC_HandleTypeDef * hadc)463 HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc)
464 {
465     /* Disable the Peripheral */
466     __HAL_ADC_DISABLE(hadc);
467 
468     /* Change ADC state */
469     hadc->State = HAL_ADC_STATE_READY;
470 
471     /* Return function status */
472     return HAL_OK;
473 }
474 
475 /**
476   * @brief  Poll for regular conversion complete
477   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
478   *         the configuration information for the specified ADC.
479   * @param  Timeout: Timeout value in millisecond.
480   * @retval HAL status
481   */
HAL_ADC_PollForConversion(ADC_HandleTypeDef * hadc,uint32_t Timeout)482 HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout)
483 {
484     uint32_t tickstart = 0;
485 
486     /* Verification that ADC configuration is compliant with polling for      */
487     /* each conversion:                                                       */
488     /* Particular case is ADC configured in DMA mode and ADC sequencer with   */
489     /* several ranks and polling for end of each conversion.                  */
490     /* For code simplicity sake, this particular case is generalized to       */
491     /* ADC configured in DMA mode and polling for end of each conversion.     */
492     if (HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_EOCS) &&
493             HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_DMA)    ) {
494         /* Update ADC state machine to error */
495         hadc->State = HAL_ADC_STATE_ERROR;
496 
497         /* Process unlocked */
498         __HAL_UNLOCK(hadc);
499 
500         return HAL_ERROR;
501     }
502 
503     /* Get tick */
504     tickstart = HAL_GetTick();
505 
506     /* Check End of conversion flag */
507     while (!(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC))) {
508         /* Check for the Timeout */
509         if (Timeout != HAL_MAX_DELAY) {
510             if ((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) {
511                 hadc->State= HAL_ADC_STATE_TIMEOUT;
512                 /* Process unlocked */
513                 __HAL_UNLOCK(hadc);
514                 return HAL_TIMEOUT;
515             }
516         }
517     }
518 
519     /* Check if an injected conversion is ready */
520     if (hadc->State == HAL_ADC_STATE_EOC_INJ) {
521         /* Change ADC state */
522         hadc->State = HAL_ADC_STATE_EOC_INJ_REG;
523     } else {
524         /* Change ADC state */
525         hadc->State = HAL_ADC_STATE_EOC_REG;
526     }
527 
528     /* Return ADC state */
529     return HAL_OK;
530 }
531 
532 /**
533   * @brief  Poll for conversion event
534   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
535   *         the configuration information for the specified ADC.
536   * @param  EventType: the ADC event type.
537   *          This parameter can be one of the following values:
538   *            @arg ADC_AWD_EVENT: ADC Analog watch Dog event.
539   *            @arg ADC_OVR_EVENT: ADC Overrun event.
540   * @param  Timeout: Timeout value in millisecond.
541   * @retval HAL status
542   */
HAL_ADC_PollForEvent(ADC_HandleTypeDef * hadc,uint32_t EventType,uint32_t Timeout)543 HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout)
544 {
545     uint32_t tickstart = 0;
546 
547     /* Check the parameters */
548     assert_param(IS_ADC_EVENT_TYPE(EventType));
549 
550     /* Get tick */
551     tickstart = HAL_GetTick();
552 
553     /* Check selected event flag */
554     while (!(__HAL_ADC_GET_FLAG(hadc,EventType))) {
555         /* Check for the Timeout */
556         if (Timeout != HAL_MAX_DELAY) {
557             if ((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) {
558                 hadc->State= HAL_ADC_STATE_TIMEOUT;
559                 /* Process unlocked */
560                 __HAL_UNLOCK(hadc);
561                 return HAL_TIMEOUT;
562             }
563         }
564     }
565 
566     /* Check analog watchdog flag */
567     if (EventType == ADC_AWD_EVENT) {
568         /* Change ADC state */
569         hadc->State = HAL_ADC_STATE_AWD;
570 
571         /* Clear the ADCx's analog watchdog flag */
572         __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD);
573     } else {
574         /* Change ADC state */
575         hadc->State = HAL_ADC_STATE_ERROR;
576 
577         /* Clear the ADCx's Overrun flag */
578         __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR);
579     }
580 
581     /* Return ADC state */
582     return HAL_OK;
583 }
584 
585 
586 /**
587   * @brief  Enables the interrupt and starts ADC conversion of regular channels.
588   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
589   *         the configuration information for the specified ADC.
590   * @retval HAL status.
591   */
HAL_ADC_Start_IT(ADC_HandleTypeDef * hadc)592 HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc)
593 {
594     __IO uint32_t counter = 0;
595 
596     /* Check the parameters */
597     assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
598     assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
599 
600     /* Process locked */
601     __HAL_LOCK(hadc);
602 
603     /* Check if an injected conversion is ongoing */
604     if (hadc->State == HAL_ADC_STATE_BUSY_INJ) {
605         /* Change ADC state */
606         hadc->State = HAL_ADC_STATE_BUSY_INJ_REG;
607     } else {
608         /* Change ADC state */
609         hadc->State = HAL_ADC_STATE_BUSY_REG;
610     }
611 
612     /* Set ADC error code to none */
613     hadc->ErrorCode = HAL_ADC_ERROR_NONE;
614 
615     /* Check if ADC peripheral is disabled in order to enable it and wait during
616        Tstab time the ADC's stabilization */
617     if ((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON) {
618         /* Enable the Peripheral */
619         __HAL_ADC_ENABLE(hadc);
620 
621         /* Delay for ADC stabilization time */
622         /* Compute number of CPU cycles to wait for */
623         counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000));
624         while (counter != 0) {
625             counter--;
626         }
627     }
628 
629     /* Enable the ADC overrun interrupt */
630     __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
631 
632     /* Enable the ADC end of conversion interrupt for regular group */
633     __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOC);
634 
635     /* Process unlocked */
636     __HAL_UNLOCK(hadc);
637 
638     /* Check if Multimode enabled */
639     if (HAL_IS_BIT_CLR(ADC->CCR, ADC_CCR_MULTI)) {
640         /* if no external trigger present enable software conversion of regular channels */
641         if ((hadc->Instance->CR2 & ADC_CR2_EXTEN) == RESET) {
642             /* Enable the selected ADC software conversion for regular group */
643             hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
644         }
645     } else {
646         /* if instance of handle correspond to ADC1 and  no external trigger present enable software conversion of regular channels */
647         if ((hadc->Instance == (ADC_TypeDef*)0x40012000) && ((hadc->Instance->CR2 & ADC_CR2_EXTEN) == RESET)) {
648             /* Enable the selected ADC software conversion for regular group */
649             hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;
650         }
651     }
652 
653     /* Return function status */
654     return HAL_OK;
655 }
656 
657 /**
658   * @brief  Disables the interrupt and stop ADC conversion of regular channels.
659   *
660   * @note   Caution: This function will stop also injected channels.
661   *
662   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
663   *         the configuration information for the specified ADC.
664   * @retval HAL status.
665   */
HAL_ADC_Stop_IT(ADC_HandleTypeDef * hadc)666 HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc)
667 {
668     /* Disable the ADC end of conversion interrupt for regular group */
669     __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC);
670 
671     /* Disable the ADC end of conversion interrupt for injected group */
672     __HAL_ADC_DISABLE_IT(hadc, ADC_CR1_JEOCIE);
673 
674     /* Enable the Peripheral */
675     __HAL_ADC_DISABLE(hadc);
676 
677     /* Change ADC state */
678     hadc->State = HAL_ADC_STATE_READY;
679 
680     /* Return function status */
681     return HAL_OK;
682 }
683 
684 /**
685   * @brief  Handles ADC interrupt request
686   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
687   *         the configuration information for the specified ADC.
688   * @retval None
689   */
HAL_ADC_IRQHandler(ADC_HandleTypeDef * hadc)690 void HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc)
691 {
692     uint32_t tmp1 = 0, tmp2 = 0;
693 
694     /* Check the parameters */
695     assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
696     assert_param(IS_ADC_REGULAR_LENGTH(hadc->Init.NbrOfConversion));
697     assert_param(IS_ADC_EOCSelection(hadc->Init.EOCSelection));
698 
699     tmp1 = __HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC);
700     tmp2 = __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_EOC);
701     /* Check End of conversion flag for regular channels */
702     if (tmp1 && tmp2) {
703         /* Check if an injected conversion is ready */
704         if (hadc->State == HAL_ADC_STATE_EOC_INJ) {
705             /* Change ADC state */
706             hadc->State = HAL_ADC_STATE_EOC_INJ_REG;
707         } else {
708             /* Change ADC state */
709             hadc->State = HAL_ADC_STATE_EOC_REG;
710         }
711 
712         if ((hadc->Init.ContinuousConvMode == DISABLE) && ((hadc->Instance->CR2 & ADC_CR2_EXTEN) == RESET)) {
713             if (hadc->Init.EOCSelection == ADC_EOC_SEQ_CONV) {
714                 /* DISABLE the ADC end of conversion interrupt for regular group */
715                 __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC);
716 
717                 /* DISABLE the ADC overrun interrupt */
718                 __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
719             } else {
720                 if (hadc->NbrOfCurrentConversionRank == 0) {
721                     hadc->NbrOfCurrentConversionRank = hadc->Init.NbrOfConversion;
722                 }
723 
724                 /* Decrement the number of conversion when an interrupt occurs */
725                 hadc->NbrOfCurrentConversionRank--;
726 
727                 /* Check if all conversions are finished */
728                 if (hadc->NbrOfCurrentConversionRank == 0) {
729                     /* DISABLE the ADC end of conversion interrupt for regular group */
730                     __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC);
731 
732                     /* DISABLE the ADC overrun interrupt */
733                     __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
734                 }
735             }
736         }
737 
738         /* Conversion complete callback */
739         HAL_ADC_ConvCpltCallback(hadc);
740 
741         /* Clear the ADCx flag for regular end of conversion */
742         __HAL_ADC_CLEAR_FLAG(hadc,ADC_FLAG_EOC);
743     }
744 
745     tmp1 = __HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOC);
746     tmp2 = __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_JEOC);
747     /* Check End of conversion flag for injected channels */
748     if (tmp1 && tmp2) {
749         /* Check if a regular conversion is ready */
750         if (hadc->State == HAL_ADC_STATE_EOC_REG) {
751             /* Change ADC state */
752             hadc->State = HAL_ADC_STATE_EOC_INJ_REG;
753         } else {
754             /* Change ADC state */
755             hadc->State = HAL_ADC_STATE_EOC_INJ;
756         }
757 
758         tmp1 = HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO);
759         tmp2 = HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_JEXTEN);
760         if (((hadc->Init.ContinuousConvMode == DISABLE) || tmp1) && tmp2) {
761             /* DISABLE the ADC end of conversion interrupt for injected group */
762             __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
763         }
764 
765         /* Conversion complete callback */
766         HAL_ADCEx_InjectedConvCpltCallback(hadc);
767 
768         /* Clear the ADCx flag for injected end of conversion */
769         __HAL_ADC_CLEAR_FLAG(hadc,ADC_FLAG_JEOC);
770     }
771 
772     tmp1 = __HAL_ADC_GET_FLAG(hadc, ADC_FLAG_AWD);
773     tmp2 = __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_AWD);
774     /* Check Analog watchdog flag */
775     if (tmp1 && tmp2) {
776         /* Change ADC state */
777         hadc->State = HAL_ADC_STATE_AWD;
778 
779         /* Clear the ADCx's Analog watchdog flag */
780         __HAL_ADC_CLEAR_FLAG(hadc,ADC_FLAG_AWD);
781 
782         /* Level out of window callback */
783         HAL_ADC_LevelOutOfWindowCallback(hadc);
784     }
785 
786     tmp1 = __HAL_ADC_GET_FLAG(hadc, ADC_FLAG_OVR);
787     tmp2 = __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_OVR);
788     /* Check Overrun flag */
789     if (tmp1 && tmp2) {
790         /* Change ADC state to overrun state */
791         hadc->State = HAL_ADC_STATE_ERROR;
792 
793         /* Set ADC error code to overrun */
794         hadc->ErrorCode |= HAL_ADC_ERROR_OVR;
795 
796         /* Clear the Overrun flag */
797         __HAL_ADC_CLEAR_FLAG(hadc,ADC_FLAG_OVR);
798 
799         /* Error callback */
800         HAL_ADC_ErrorCallback(hadc);
801     }
802 }
803 
804 /**
805   * @brief  Enables ADC DMA request after last transfer (Single-ADC mode) and enables ADC peripheral
806   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
807   *         the configuration information for the specified ADC.
808   * @param  pData: The destination Buffer address.
809   * @param  Length: The length of data to be transferred from ADC peripheral to memory.
810   * @retval HAL status
811   */
HAL_ADC_Start_DMA(ADC_HandleTypeDef * hadc,uint32_t * pData,uint32_t Length)812 HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length)
813 {
814     __IO uint32_t counter = 0;
815 
816     /* Check the parameters */
817     assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
818     assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge));
819 
820     /* Process locked */
821     __HAL_LOCK(hadc);
822 
823     /* Enable ADC overrun interrupt */
824     __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR);
825 
826     /* Enable ADC DMA mode */
827     hadc->Instance->CR2 |= ADC_CR2_DMA;
828 
829     /* Set the DMA transfer complete callback */
830     hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt;
831 
832     /* Set the DMA half transfer complete callback */
833     hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt;
834 
835     /* Set the DMA error callback */
836     hadc->DMA_Handle->XferErrorCallback = ADC_DMAError ;
837 
838     /* Enable the DMA Stream */
839     HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->DR, (uint32_t)pData, Length);
840 
841     /* Change ADC state */
842     hadc->State = HAL_ADC_STATE_BUSY_REG;
843 
844     /* Process unlocked */
845     __HAL_UNLOCK(hadc);
846 
847     /* Check if ADC peripheral is disabled in order to enable it and wait during
848        Tstab time the ADC's stabilization */
849     if ((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON) {
850         /* Enable the Peripheral */
851         __HAL_ADC_ENABLE(hadc);
852 
853         /* Delay for ADC stabilization time */
854         /* Compute number of CPU cycles to wait for */
855         counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000));
856         while (counter != 0) {
857             counter--;
858         }
859     }
860 
861     /* if no external trigger present enable software conversion of regular channels */
862     if ((hadc->Instance->CR2 & ADC_CR2_EXTEN) == RESET) {
863         /* Enable the selected ADC software conversion for regular group */
864         hadc->Instance->CR2 |= ADC_CR2_SWSTART;
865     }
866 
867     /* Return function status */
868     return HAL_OK;
869 }
870 
871 /**
872   * @brief  Disables ADC DMA (Single-ADC mode) and disables ADC peripheral
873   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
874   *         the configuration information for the specified ADC.
875   * @retval HAL status
876   */
HAL_ADC_Stop_DMA(ADC_HandleTypeDef * hadc)877 HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc)
878 {
879     /* Disable the Peripheral */
880     __HAL_ADC_DISABLE(hadc);
881 
882     /* Disable ADC overrun interrupt */
883     __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR);
884 
885     /* Disable the selected ADC DMA mode */
886     hadc->Instance->CR2 &= ~ADC_CR2_DMA;
887 
888     /* Disable the ADC DMA Stream */
889     HAL_DMA_Abort(hadc->DMA_Handle);
890 
891     /* Change ADC state */
892     hadc->State = HAL_ADC_STATE_READY;
893 
894     /* Return function status */
895     return HAL_OK;
896 }
897 
898 /**
899   * @brief  Gets the converted value from data register of regular channel.
900   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
901   *         the configuration information for the specified ADC.
902   * @retval Converted value
903   */
HAL_ADC_GetValue(ADC_HandleTypeDef * hadc)904 uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef* hadc)
905 {
906     /* Return the selected ADC converted value */
907     return hadc->Instance->DR;
908 }
909 
910 /**
911   * @brief  Regular conversion complete callback in non blocking mode
912   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
913   *         the configuration information for the specified ADC.
914   * @retval None
915   */
HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef * hadc)916 __weak void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
917 {
918     /* NOTE : This function Should not be modified, when the callback is needed,
919               the HAL_ADC_ConvCpltCallback could be implemented in the user file
920      */
921 }
922 
923 /**
924   * @brief  Regular conversion half DMA transfer callback in non blocking mode
925   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
926   *         the configuration information for the specified ADC.
927   * @retval None
928   */
HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef * hadc)929 __weak void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc)
930 {
931     /* NOTE : This function Should not be modified, when the callback is needed,
932               the HAL_ADC_ConvHalfCpltCallback could be implemented in the user file
933      */
934 }
935 
936 /**
937   * @brief  Analog watchdog callback in non blocking mode
938   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
939   *         the configuration information for the specified ADC.
940   * @retval None
941   */
HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef * hadc)942 __weak void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc)
943 {
944     /* NOTE : This function Should not be modified, when the callback is needed,
945               the HAL_ADC_LevelOoutOfWindowCallback could be implemented in the user file
946      */
947 }
948 
949 /**
950   * @brief  Error ADC callback.
951   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
952   *         the configuration information for the specified ADC.
953   * @retval None
954   */
HAL_ADC_ErrorCallback(ADC_HandleTypeDef * hadc)955 __weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc)
956 {
957     /* NOTE : This function Should not be modified, when the callback is needed,
958               the HAL_ADC_ErrorCallback could be implemented in the user file
959      */
960 }
961 
962 /**
963   * @}
964   */
965 
966 /** @defgroup ADC_Exported_Functions_Group3 Peripheral Control functions
967  *  @brief      Peripheral Control functions
968  *
969 @verbatim
970  ===============================================================================
971              ##### Peripheral Control functions #####
972  ===============================================================================
973     [..]  This section provides functions allowing to:
974       (+) Configure regular channels.
975       (+) Configure injected channels.
976       (+) Configure multimode.
977       (+) Configure the analog watch dog.
978 
979 @endverbatim
980   * @{
981   */
982 
983 /**
984 * @brief  Configures for the selected ADC regular channel its corresponding
985 *         rank in the sequencer and its sample time.
986 * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
987 *         the configuration information for the specified ADC.
988 * @param  sConfig: ADC configuration structure.
989 * @retval HAL status
990 */
HAL_ADC_ConfigChannel(ADC_HandleTypeDef * hadc,ADC_ChannelConfTypeDef * sConfig)991 HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig)
992 {
993     __IO uint32_t counter = 0;
994 
995     /* Check the parameters */
996     assert_param(IS_ADC_CHANNEL(sConfig->Channel));
997     assert_param(IS_ADC_REGULAR_RANK(sConfig->Rank));
998     assert_param(IS_ADC_SAMPLE_TIME(sConfig->SamplingTime));
999 
1000     /* Process locked */
1001     __HAL_LOCK(hadc);
1002 
1003     /* if ADC_Channel_10 ... ADC_Channel_18 is selected */
1004     if (sConfig->Channel > ADC_CHANNEL_9) {
1005         /* Clear the old sample time */
1006         hadc->Instance->SMPR1 &= ~ADC_SMPR1(ADC_SMPR1_SMP10, sConfig->Channel);
1007 
1008         /* Set the new sample time */
1009         hadc->Instance->SMPR1 |= ADC_SMPR1(sConfig->SamplingTime, sConfig->Channel);
1010     } else { /* ADC_Channel include in ADC_Channel_[0..9] */
1011         /* Clear the old sample time */
1012         hadc->Instance->SMPR2 &= ~ADC_SMPR2(ADC_SMPR2_SMP0, sConfig->Channel);
1013 
1014         /* Set the new sample time */
1015         hadc->Instance->SMPR2 |= ADC_SMPR2(sConfig->SamplingTime, sConfig->Channel);
1016     }
1017 
1018     /* For Rank 1 to 6 */
1019     if (sConfig->Rank < 7) {
1020         /* Clear the old SQx bits for the selected rank */
1021         hadc->Instance->SQR3 &= ~ADC_SQR3_RK(ADC_SQR3_SQ1, sConfig->Rank);
1022 
1023         /* Set the SQx bits for the selected rank */
1024         hadc->Instance->SQR3 |= ADC_SQR3_RK(sConfig->Channel, sConfig->Rank);
1025     }
1026     /* For Rank 7 to 12 */
1027     else if (sConfig->Rank < 13) {
1028         /* Clear the old SQx bits for the selected rank */
1029         hadc->Instance->SQR2 &= ~ADC_SQR2_RK(ADC_SQR2_SQ7, sConfig->Rank);
1030 
1031         /* Set the SQx bits for the selected rank */
1032         hadc->Instance->SQR2 |= ADC_SQR2_RK(sConfig->Channel, sConfig->Rank);
1033     }
1034     /* For Rank 13 to 16 */
1035     else {
1036         /* Clear the old SQx bits for the selected rank */
1037         hadc->Instance->SQR1 &= ~ADC_SQR1_RK(ADC_SQR1_SQ13, sConfig->Rank);
1038 
1039         /* Set the SQx bits for the selected rank */
1040         hadc->Instance->SQR1 |= ADC_SQR1_RK(sConfig->Channel, sConfig->Rank);
1041     }
1042 
1043     /* if ADC1 Channel_18 is selected enable VBAT Channel */
1044     if ((hadc->Instance == ADC1) && (sConfig->Channel == ADC_CHANNEL_VBAT)) {
1045         /* Enable the VBAT channel*/
1046         ADC->CCR |= ADC_CCR_VBATE;
1047     }
1048 
1049     /* if ADC1 Channel_16 or Channel_17 is selected enable TSVREFE Channel(Temperature sensor and VREFINT) */
1050     if ((hadc->Instance == ADC1) && ((sConfig->Channel == ADC_CHANNEL_TEMPSENSOR) || (sConfig->Channel == ADC_CHANNEL_VREFINT))) {
1051         /* Enable the TSVREFE channel*/
1052         ADC->CCR |= ADC_CCR_TSVREFE;
1053 
1054         if ((sConfig->Channel == ADC_CHANNEL_TEMPSENSOR)) {
1055             /* Delay for temperature sensor stabilization time */
1056             /* Compute number of CPU cycles to wait for */
1057             counter = (ADC_TEMPSENSOR_DELAY_US * (SystemCoreClock / 1000000));
1058             while (counter != 0) {
1059                 counter--;
1060             }
1061         }
1062     }
1063 
1064     /* Process unlocked */
1065     __HAL_UNLOCK(hadc);
1066 
1067     /* Return function status */
1068     return HAL_OK;
1069 }
1070 
1071 /**
1072   * @brief  Configures the analog watchdog.
1073   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
1074   *         the configuration information for the specified ADC.
1075   * @param  AnalogWDGConfig : pointer to an ADC_AnalogWDGConfTypeDef structure
1076   *         that contains the configuration information of ADC analog watchdog.
1077   * @retval HAL status
1078   */
HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef * hadc,ADC_AnalogWDGConfTypeDef * AnalogWDGConfig)1079 HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig)
1080 {
1081 #ifdef USE_FULL_ASSERT
1082     uint32_t tmp = 0;
1083 #endif /* USE_FULL_ASSERT  */
1084 
1085     /* Check the parameters */
1086     assert_param(IS_ADC_ANALOG_WATCHDOG(AnalogWDGConfig->WatchdogMode));
1087     assert_param(IS_ADC_CHANNEL(AnalogWDGConfig->Channel));
1088     assert_param(IS_FUNCTIONAL_STATE(AnalogWDGConfig->ITMode));
1089 
1090 #ifdef USE_FULL_ASSERT
1091     tmp = ADC_GET_RESOLUTION(hadc);
1092     assert_param(IS_ADC_RANGE(tmp, AnalogWDGConfig->HighThreshold));
1093     assert_param(IS_ADC_RANGE(tmp, AnalogWDGConfig->LowThreshold));
1094 #endif /* USE_FULL_ASSERT  */
1095 
1096     /* Process locked */
1097     __HAL_LOCK(hadc);
1098 
1099     if (AnalogWDGConfig->ITMode == ENABLE) {
1100         /* Enable the ADC Analog watchdog interrupt */
1101         __HAL_ADC_ENABLE_IT(hadc, ADC_IT_AWD);
1102     } else {
1103         /* Disable the ADC Analog watchdog interrupt */
1104         __HAL_ADC_DISABLE_IT(hadc, ADC_IT_AWD);
1105     }
1106 
1107     /* Clear AWDEN, JAWDEN and AWDSGL bits */
1108     hadc->Instance->CR1 &=  ~(ADC_CR1_AWDSGL | ADC_CR1_JAWDEN | ADC_CR1_AWDEN);
1109 
1110     /* Set the analog watchdog enable mode */
1111     hadc->Instance->CR1 |= AnalogWDGConfig->WatchdogMode;
1112 
1113     /* Set the high threshold */
1114     hadc->Instance->HTR = AnalogWDGConfig->HighThreshold;
1115 
1116     /* Set the low threshold */
1117     hadc->Instance->LTR = AnalogWDGConfig->LowThreshold;
1118 
1119     /* Clear the Analog watchdog channel select bits */
1120     hadc->Instance->CR1 &= ~ADC_CR1_AWDCH;
1121 
1122     /* Set the Analog watchdog channel */
1123     hadc->Instance->CR1 |= (uint32_t)((uint16_t)(AnalogWDGConfig->Channel));
1124 
1125     /* Process unlocked */
1126     __HAL_UNLOCK(hadc);
1127 
1128     /* Return function status */
1129     return HAL_OK;
1130 }
1131 
1132 /**
1133   * @}
1134   */
1135 
1136 /** @defgroup ADC_Exported_Functions_Group4 ADC Peripheral State functions
1137  *  @brief   ADC Peripheral State functions
1138  *
1139 @verbatim
1140  ===============================================================================
1141             ##### Peripheral State and errors functions #####
1142  ===============================================================================
1143     [..]
1144     This subsection provides functions allowing to
1145       (+) Check the ADC state
1146       (+) Check the ADC Error
1147 
1148 @endverbatim
1149   * @{
1150   */
1151 
1152 /**
1153   * @brief  return the ADC state
1154   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
1155   *         the configuration information for the specified ADC.
1156   * @retval HAL state
1157   */
HAL_ADC_GetState(ADC_HandleTypeDef * hadc)1158 HAL_ADC_StateTypeDef HAL_ADC_GetState(ADC_HandleTypeDef* hadc)
1159 {
1160     /* Return ADC state */
1161     return hadc->State;
1162 }
1163 
1164 /**
1165   * @brief  Return the ADC error code
1166   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
1167   *         the configuration information for the specified ADC.
1168   * @retval ADC Error Code
1169   */
HAL_ADC_GetError(ADC_HandleTypeDef * hadc)1170 uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc)
1171 {
1172     return hadc->ErrorCode;
1173 }
1174 
1175 /**
1176   * @}
1177   */
1178 
1179 /**
1180   * @}
1181   */
1182 
1183 /* Private functions ---------------------------------------------------------*/
1184 
1185 /** @defgroup ADC_Private_Functions ADC Private Functions
1186   * @{
1187   */
1188 
1189 /**
1190   * @brief  Initializes the ADCx peripheral according to the specified parameters
1191   *         in the ADC_InitStruct without initializing the ADC MSP.
1192   * @param  hadc: pointer to a ADC_HandleTypeDef structure that contains
1193   *         the configuration information for the specified ADC.
1194   * @retval None
1195   */
ADC_Init(ADC_HandleTypeDef * hadc)1196 static void ADC_Init(ADC_HandleTypeDef* hadc)
1197 {
1198     /* Set ADC parameters */
1199     /* Set the ADC clock prescaler */
1200     ADC->CCR &= ~(ADC_CCR_ADCPRE);
1201     ADC->CCR |=  hadc->Init.ClockPrescaler;
1202 
1203     /* Set ADC scan mode */
1204     hadc->Instance->CR1 &= ~(ADC_CR1_SCAN);
1205     hadc->Instance->CR1 |=  ADC_CR1_SCANCONV(hadc->Init.ScanConvMode);
1206 
1207     /* Set ADC resolution */
1208     hadc->Instance->CR1 &= ~(ADC_CR1_RES);
1209     hadc->Instance->CR1 |=  hadc->Init.Resolution;
1210 
1211     /* Set ADC data alignment */
1212     hadc->Instance->CR2 &= ~(ADC_CR2_ALIGN);
1213     hadc->Instance->CR2 |= hadc->Init.DataAlign;
1214 
1215     /* Enable external trigger if trigger selection is different of software  */
1216     /* start.                                                                 */
1217     /* Note: This configuration keeps the hardware feature of parameter       */
1218     /*       ExternalTrigConvEdge "trigger edge none" equivalent to           */
1219     /*       software start.                                                  */
1220     if (hadc->Init.ExternalTrigConv != ADC_SOFTWARE_START) {
1221         /* Select external trigger to start conversion */
1222         hadc->Instance->CR2 &= ~(ADC_CR2_EXTSEL);
1223         hadc->Instance->CR2 |= hadc->Init.ExternalTrigConv;
1224 
1225         /* Select external trigger polarity */
1226         hadc->Instance->CR2 &= ~(ADC_CR2_EXTEN);
1227         hadc->Instance->CR2 |= hadc->Init.ExternalTrigConvEdge;
1228     } else {
1229         /* Reset the external trigger */
1230         hadc->Instance->CR2 &= ~(ADC_CR2_EXTSEL);
1231         hadc->Instance->CR2 &= ~(ADC_CR2_EXTEN);
1232     }
1233 
1234     /* Enable or disable ADC continuous conversion mode */
1235     hadc->Instance->CR2 &= ~(ADC_CR2_CONT);
1236     hadc->Instance->CR2 |= ADC_CR2_CONTINUOUS(hadc->Init.ContinuousConvMode);
1237 
1238     if (hadc->Init.DiscontinuousConvMode != DISABLE) {
1239         assert_param(IS_ADC_REGULAR_DISC_NUMBER(hadc->Init.NbrOfDiscConversion));
1240 
1241         /* Enable the selected ADC regular discontinuous mode */
1242         hadc->Instance->CR1 |= (uint32_t)ADC_CR1_DISCEN;
1243 
1244         /* Set the number of channels to be converted in discontinuous mode */
1245         hadc->Instance->CR1 &= ~(ADC_CR1_DISCNUM);
1246         hadc->Instance->CR1 |=  ADC_CR1_DISCONTINUOUS(hadc->Init.NbrOfDiscConversion);
1247     } else {
1248         /* Disable the selected ADC regular discontinuous mode */
1249         hadc->Instance->CR1 &= ~(ADC_CR1_DISCEN);
1250     }
1251 
1252     /* Set ADC number of conversion */
1253     hadc->Instance->SQR1 &= ~(ADC_SQR1_L);
1254     hadc->Instance->SQR1 |=  ADC_SQR1(hadc->Init.NbrOfConversion);
1255 
1256     /* Enable or disable ADC DMA continuous request */
1257     hadc->Instance->CR2 &= ~(ADC_CR2_DDS);
1258     hadc->Instance->CR2 |= ADC_CR2_DMAContReq(hadc->Init.DMAContinuousRequests);
1259 
1260     /* Enable or disable ADC end of conversion selection */
1261     hadc->Instance->CR2 &= ~(ADC_CR2_EOCS);
1262     hadc->Instance->CR2 |= ADC_CR2_EOCSelection(hadc->Init.EOCSelection);
1263 }
1264 
1265 /**
1266   * @brief  DMA transfer complete callback.
1267   * @param  hdma: pointer to a DMA_HandleTypeDef structure that contains
1268   *                the configuration information for the specified DMA module.
1269   * @retval None
1270   */
ADC_DMAConvCplt(DMA_HandleTypeDef * hdma)1271 static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma)
1272 {
1273     ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
1274 
1275     /* Check if an injected conversion is ready */
1276     if (hadc->State == HAL_ADC_STATE_EOC_INJ) {
1277         /* Change ADC state */
1278         hadc->State = HAL_ADC_STATE_EOC_INJ_REG;
1279     } else {
1280         /* Change ADC state */
1281         hadc->State = HAL_ADC_STATE_EOC_REG;
1282     }
1283 
1284     HAL_ADC_ConvCpltCallback(hadc);
1285 }
1286 
1287 /**
1288   * @brief  DMA half transfer complete callback.
1289   * @param  hdma: pointer to a DMA_HandleTypeDef structure that contains
1290   *                the configuration information for the specified DMA module.
1291   * @retval None
1292   */
ADC_DMAHalfConvCplt(DMA_HandleTypeDef * hdma)1293 static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma)
1294 {
1295     ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
1296     /* Conversion complete callback */
1297     HAL_ADC_ConvHalfCpltCallback(hadc);
1298 }
1299 
1300 /**
1301   * @brief  DMA error callback
1302   * @param  hdma: pointer to a DMA_HandleTypeDef structure that contains
1303   *                the configuration information for the specified DMA module.
1304   * @retval None
1305   */
ADC_DMAError(DMA_HandleTypeDef * hdma)1306 static void ADC_DMAError(DMA_HandleTypeDef *hdma)
1307 {
1308     ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
1309     hadc->State= HAL_ADC_STATE_ERROR;
1310     /* Set ADC error code to DMA error */
1311     hadc->ErrorCode |= HAL_ADC_ERROR_DMA;
1312     HAL_ADC_ErrorCallback(hadc);
1313 }
1314 
1315 
1316 /**
1317   * @}
1318   */
1319 
1320 #endif /* HAL_ADC_MODULE_ENABLED */
1321 /**
1322   * @}
1323   */
1324 
1325 /**
1326   * @}
1327   */
1328 
1329 /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
1330