/**
  ******************************************************************************
  * @file    ys32f030_adc.c
  * @author  YSPRING Application Team
  * @version V1.0.1
  * @date    2023.6.25
  * @brief   This file provides firmware functions to manage the following 
  *          functionalities of the Analog to Digital Convertor (ADC) peripheral:
  *           + Initialization and Configuration
  *           + Analog Watchdog configuration
  *           + Temperature Sensor, Vrefint (Internal Reference Voltage) management 
  *           + ADC Channels Configuration
  *           + ADC Channels DMA Configuration
  *           + Interrupts and flags management
  *`
  *  @verbatim
 ===============================================================================
                      ##### How to use this driver #####
 ===============================================================================
    [..]
    (#) Enable the ADC interface clock using 
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC, ENABLE); 
    (#) ADC pins configuration
       (++) Enable the clock for the ADC GPIOs using the following function:
            RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOx, ENABLE);   
       (++) Configure these ADC pins in analog mode using GPIO_Init();  
    (#) Configure the ADC conversion resolution, data alignment, external
        trigger and edge, scan direction and Enable/Disable the continuous mode
        using the ADC_Init() function.
    (#) Activate the ADC peripheral using ADC_Cmd() function.

    *** ADC channels group configuration ***
    ============================================
    [..] 
    (+) To configure the ADC channels features, use ADC_Init() and 
        ADC_RegularChannelConfig() functions.
    (+) To activate the continuous mode, use the ADC_ContinuousModeCmd()
        function.
    (+) To activate the Discontinuous mode, use the ADC_DiscModeCmd() functions. 
    (+) To activate the overrun mode, use the ADC_OverrunModeCmd() functions.
    (+) To read the ADC converted values, use the ADC_GetConversionValue()
        function.

    *** DMA for ADC channels features configuration ***
    =============================================================
    [..] 
    (+) To enable the DMA mode for ADC channels group, use the ADC_DMACmd() function.

    @endverbatim
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "ys32f030_adc.h"
#include "ys32f030_rcc.h"

/** @addtogroup YS32F030_StdPeriph_Driver
  * @{
  */

/** @defgroup ADC 
  * @brief ADC driver modules
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/** @defgroup ADC_Private_Functions
  * @{
  */

/** @defgroup ADC_Group1 Initialization and Configuration functions
 *  @brief   Initialization and Configuration functions 
 *
@verbatim
 ===============================================================================
          ##### Initialization and Configuration functions #####
 ===============================================================================
    [..] This section provides functions allowing to:
        (+) Initialize and configure the ADC Prescaler
        (+) ADC Continuous Conversion Mode (Continuous or Single conversion)
        (+) External trigger Edge and source 
        (+) Converted data alignment (left or right)
        (+) The direction in which the channels will be scanned in the sequence
        (+) Enable or disable the ADC peripheral
   
@endverbatim
  * @{
  */

/**
  * @brief  Deinitializes ADC peripheral registers to their default reset values.
  * @param  ADCx: This parameter is ADC.
  * @retval None
  */
void ADC_DeInit(ADC_TypeDef* ADCx)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));

  if(ADCx == ADC)
  {
    /* Enable ADC reset state */
    RCC_APB2PeriphResetCmd(RCC_APB2Periph_ADC, ENABLE);

    /* Release ADC from reset state */
    RCC_APB2PeriphResetCmd(RCC_APB2Periph_ADC, DISABLE);
  }
}

/**
  * @brief  Initializes the ADC peripheral according to the specified parameters
  *         in the ADC_InitStruct.
  * @note   This function is used to configure the global features of the ADC ( 
  *         Resolution, Data Alignment, continuous mode activation, External 
  *         trigger source and edge, Sequence Scan Direction).   
  * @param  ADCx: This parameter is ADC.
  * @param  ADC_InitStruct: pointer to an ADC_InitTypeDef structure that contains 
  *         the configuration information for the specified ADC peripheral.
  * @retval None
  */
void ADC_Init(ADC_TypeDef* ADCx, ADC_InitTypeDef* ADC_InitStruct)
{
  uint32_t tmpreg1 = 0;
  uint32_t tmpreg2 = 0;

  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_CLOCKMODE(ADC_InitStruct->ClockMode));
  assert_param(IS_CONTINUOUS_CONV_MODE(ADC_InitStruct->ADC_ContinuousConvMode));
  assert_param(IS_ADC_EXT_TRIG_EDGE(ADC_InitStruct->ADC_ExternalTrigConvEdge));
  assert_param(IS_ADC_EXTERNAL_TRIG_CONV(ADC_InitStruct->ADC_ExternalTrigConv));
  assert_param(IS_ADC_EXT_TRIG_EDGE_JSQ(ADC_InitStruct->ADC_ExternalTrigInjectedConvEdge));
  assert_param(IS_ADC_EXTERNAL_TRIG_CONV_JSQ(ADC_InitStruct->ADC_ExternalTrigInjectedConv));
  assert_param(IS_ADC_DATA_ALIGN(ADC_InitStruct->ADC_DataAlign));
  assert_param(IS_ADC_SCAN_MODE(ADC_InitStruct->ADC_ScanMode)); 

  /* Get the ADCx CFGR value */
  tmpreg1 = ADCx->CR1;
  tmpreg2 = ADCx->CR2;

  /* Clear SCANMODE, CKMODE[3:0], ALIGN, EXTSEL[2:0], EXTTRIG and CONT bits */
  tmpreg1 &= (~ADC_CR1_SCAN); 
  tmpreg2 &= (~ADC_CR2_CKMODE) | (~ADC_CR2_ALIGN) | (~ADC_CR2_EXTSEL) | (~ADC_CR2_EXTTRIG) | (~ADC_CR2_CONT);

  tmpreg1 |= ADC_InitStruct->ADC_ScanMode;
  tmpreg2 |= (uint32_t)(ADC_InitStruct->ClockMode | ADC_InitStruct->ADC_DataAlign | ADC_InitStruct->ADC_ContinuousConvMode | \
             ADC_InitStruct->ADC_ExternalTrigConvEdge | ADC_InitStruct->ADC_ExternalTrigConv | \
             ADC_InitStruct->ADC_ExternalTrigInjectedConvEdge | ADC_InitStruct->ADC_ExternalTrigInjectedConv);

  /* Write to ADCx CFGR */
  ADCx->CR1 = tmpreg1;
  ADCx->CR2 = tmpreg2;
}

/**
  * @brief  Fills each ADC_InitStruct member with its default value.
  * @note   This function is used to initialize the global features of the ADC ( 
  *         Resolution, Data Alignment, continuous mode activation, External 
  *         trigger source and edge, Sequence Scan Direction).
  * @param  ADC_InitStruct: pointer to an ADC_InitTypeDef structure which will 
  *         be initialized.
  * @retval None
  */
void ADC_StructInit(ADC_InitTypeDef* ADC_InitStruct)
{
  /* Reset ADC init structure parameters values */
  /* Initialize the ADC_Resolution member */
  ADC_InitStruct->ClockMode = ADC_ClockMode_PCLK;

   /* Initialize the ADC_ContinuousConvMode member */
  ADC_InitStruct->ADC_ContinuousConvMode = ADC_ContinuousConvMode_OFF;

  /* Initialize the ADC_ExternalTrigConvEdge member */
  ADC_InitStruct->ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;

  /* Initialize the ADC_ExternalTrigConv member */
  ADC_InitStruct->ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_CC1;

  /* Initialize the ADC_ExternalTrigInjectedConvEdge member */
  ADC_InitStruct->ADC_ExternalTrigInjectedConvEdge = ADC_ExternalTrigInjectedConvEdge_None;

  /* Initialize the ADC_ExternalTrigInjectedConv member */
  ADC_InitStruct->ADC_ExternalTrigInjectedConv = ADC_ExternalTrigInjectedConv_T1_TRGO;

  /* Initialize the ADC_DataAlign member */
  ADC_InitStruct->ADC_DataAlign = ADC_DataAlign_Right;

  /* Initialize the ADC_ScanMode member */
  ADC_InitStruct->ADC_ScanMode = ADC_ScanMode_OFF;
}

/**
  * @brief  Enables or disables the specified ADC peripheral.
  * @param  ADCx: This parameter is ADC.
  * @param  NewState: new state of the ADC peripheral. 
  *          This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void ADC_Cmd(ADC_TypeDef* ADCx, FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  if (NewState != DISABLE)
  {
    /* Set the ADEN bit to Enable the ADC peripheral */
    ADCx->CR2 |= (uint32_t)ADC_CR2_ADON;
  }
  else
  {
    /* Set the ADDIS to Disable the ADC peripheral */
    ADCx->CR2 &= (uint32_t)~ADC_CR2_ADON;
  }
}

/**
  * @brief  Configure the ADC to either be clocked by the asynchronous clock
  * @note   This function can be called only when ADC is disabled.
  * @param  ADCx: This parameter is ADC.
  * @param  ADC_ClockMode: This parameter can be :
  *            @arg ADC_ClockMode_PCLK  :The ADC clock comes from PCLK
  *            @arg ADC_ClockMode_PCLK_Div2 :The ADC clock comes from PCLK/2
  *            @arg ADC_ClockMode_PCLK_Div4 :The ADC clock comes from PCLK/4
  *            @arg ADC_ClockMode_PCLK_Div6 :The ADC clock comes from PCLK/6
  *            @arg ADC_ClockMode_PCLK_Div8 :The ADC clock comes from PCLK/8
  *            @arg ADC_ClockMode_HSI       :The ADC clock comes from HSI 
  *            @arg ADC_ClockMode_HSI_Div2  :The ADC clock comes from HSI/2 
  *            @arg ADC_ClockMode_HSI_Div4  :The ADC clock comes from HSI/4 
  *            @arg ADC_ClockMode_HSI_Div6  :The ADC clock comes from HSI/6 
  *            @arg ADC_ClockMode_HSI_Div8  :The ADC clock comes from HSI/8 
  * @retval None
  */
void ADC_ClockModeConfig(ADC_TypeDef* ADCx, uint32_t ADC_ClockMode)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_CLOCKMODE(ADC_ClockMode));

  /* Configure the ADC Clock mode according to ADC_ClockMode */
  ADCx->CR2 &= ~(ADC_CR2_CKMODE);
  ADCx->CR2 |= (uint32_t)ADC_ClockMode;
}

/**
  * @brief  Set ADC Bias Current
  * @param  Current This parameter can be one of the following values:
  *         @arg @ref ADC_Current_16uA   
  *         @arg @ref ADC_Current_20uA   
  *         @arg @ref ADC_Current_24uA   
  *         @arg @ref ADC_Current_28uA
  * @retval None
  */
void ADC_BiasCurrentConfig(ADC_TypeDef* ADCx, uint32_t Current)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_CURRENT(Current));

  MODIFY_REG(ADC->CR2, ADC_CR2_CUR, Current);
}

/**
  * @}
  */

/** @defgroup ADC_Group2 Power saving functions
 *  @brief   Power saving functions 
 *
@verbatim
 ===============================================================================
          ##### Power saving functions #####
 ===============================================================================
    [..] This section provides functions allowing to reduce power consumption.
    [..] The two function must be combined to get the maximal benefits:
         When the ADC frequency is higher than the CPU one, it is recommended to 
         (#) Enable the Auto Delayed Conversion mode : 
             ==> using ADC_WaitModeCmd(ADC_TypeDef* ADCx, FunctionalState NewState);

@endverbatim
  * @{
  */

/**
  * @brief  Enables or disables the Wait conversion mode.
  * @note   When the CPU clock is not fast enough to manage the data rate, a 
  *         Hardware delay can be introduced between ADC conversions to reduce 
  *         this data rate. 
  * @note   The Hardware delay is inserted after each conversions and until the
  *         previous data is read from the ADC data register
  * @note   This is a way to automatically adapt the speed of the ADC to the speed 
  *         of the system which will read the data.
  * @note   Any hardware triggers wich occur while a conversion is on going or 
  *         while the automatic Delay is applied are ignored 
  * @param  ADCx: This parameter is ADC.
  * @param  NewState: new state of the ADC Auto-Delay.
  *          This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void ADC_WaitModeCmd(ADC_TypeDef* ADCx, FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_FUNCTIONAL_STATE(NewState));
  
  if (NewState != DISABLE)
  {
    /* Enable the ADC Automatic Delayed conversion */
    ADCx->CR1 |= ADC_CR1_WAIT;
  }
  else
  {
    /* Disable the ADC Automatic Delayed conversion */
    ADCx->CR1 &= (uint32_t)~ADC_CR1_WAIT;
  }
}
/**
  * @}
  */

/** @defgroup ADC_Group3 Analog Watchdog configuration functions
 *  @brief   Analog Watchdog configuration functions 
 *
@verbatim
 ===============================================================================
                   ##### Analog Watchdog configuration functions #####
 ===============================================================================  
    [..] This section provides functions allowing to configure the Analog Watchdog
         (AWD) feature in the ADC.
    [..] A typical configuration Analog Watchdog is done following these steps :
         (#) the ADC guarded channel(s) is (are) selected using the 
             ADC_AnalogWatchdogSingleChannelConfig() function.
         (#) The Analog watchdog lower and higher threshold are configured using the  
             ADC_AnalogWatchdogThresholdsConfig() function.
         (#) The Analog watchdog is enabled and configured to enable the check, on one
             or more channels, using the  ADC_AnalogWatchdogCmd() function.
         (#) Enable the analog watchdog on the selected channel using
             ADC_AnalogWatchdogSingleChannelCmd() function

@endverbatim
  * @{
  */

/**
  * @brief  Enables or disables the Regular analog watchdog 
  * @param  ADCx: This parameter is ADC.
  * @param  NewState: new state of the ADC Analog Watchdog.
  *          This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void ADC_AnalogWatchdogCmd(ADC_TypeDef* ADCx, FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_FUNCTIONAL_STATE(NewState));
  
  if (NewState != DISABLE)
  {
    /* Enable the ADC Analog Watchdog */
    ADCx->CR1 |= ADC_CR1_AWDEN;
  }
  else
  {
    /* Disable the ADC Analog Watchdog */
    ADCx->CR1 &= (uint32_t)~ADC_CR1_AWDEN;
  }
}

/**
  * @brief  Enables or disables the Injected analog watchdog 
  * @param  ADCx: This parameter is ADC.
  * @param  NewState: new state of the ADC Analog Watchdog.
  *          This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void ADC_InjectedAnalogWatchdogCmd(ADC_TypeDef* ADCx, FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_FUNCTIONAL_STATE(NewState));
  
  if (NewState != DISABLE)
  {
    /* Enable the ADC Analog Watchdog */
    ADCx->CR1 |= ADC_CR1_JAWDEN;
  }
  else
  {
    /* Disable the ADC Analog Watchdog */
    ADCx->CR1 &= (uint32_t)~ADC_CR1_JAWDEN;
  }
}

/**
  * @brief  Configures the high and low thresholds of the analog watchdog. 
  * @param  ADCx: This parameter is ADC.
  * @param  HighThreshold: the ADC analog watchdog High threshold value.
  *          This parameter must be a 12bit value.
  * @param  LowThreshold: the ADC analog watchdog Low threshold value.
  *          This parameter must be a 12bit value.
  * @retval None
  */
void ADC_AnalogWatchdogThresholdsConfig(ADC_TypeDef* ADCx, uint16_t HighThreshold,
                                        uint16_t LowThreshold)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_THRESHOLD(HighThreshold));
  assert_param(IS_ADC_THRESHOLD(LowThreshold));

  /* Set the ADCx high and low threshold */
  ADCx->HTR = (uint32_t)HighThreshold;
  ADCx->LTR = (uint32_t)LowThreshold;

}

/**
  * @brief  Configures the analog watchdog guarded single channel
  * @param  ADCx: This parameter is ADC.
  * @param  ADC_AnalogWatchdog_Channel: the ADC channel to configure for the analog watchdog.
  *          This parameter can be one of the following values:
  *            @arg ADC_AnalogWatchdog_Channel_None :reserved
  *            @arg ADC_AnalogWatchdog_Channel_1    :ADC analog channel 1
  *            @arg ADC_AnalogWatchdog_Channel_2    :ADC analog channel 2  
  *            @arg ADC_AnalogWatchdog_Channel_3    :ADC analog channel 3  
  *            @arg ADC_AnalogWatchdog_Channel_4    :ADC analog channel 4 
  *            @arg ADC_AnalogWatchdog_Channel_5    :ADC analog channel 5  
  *            @arg ADC_AnalogWatchdog_Channel_6    :ADC analog channel 6  
  *            @arg ADC_AnalogWatchdog_Channel_7    :ADC analog channel 7  
  *            @arg ADC_AnalogWatchdog_Channel_8    :ADC analog channel 8  
  *            @arg ADC_AnalogWatchdog_Channel_9    :ADC analog channel 9  
  *            @arg ADC_AnalogWatchdog_Channel_10   :ADC analog channel 10  
  *            @arg ADC_AnalogWatchdog_Channel_11   :ADC analog channel 11  
  *            @arg ADC_AnalogWatchdog_Channel_12   :ADC analog channel 12  
  *            @arg ADC_AnalogWatchdog_Channel_13   :ADC analog channel 13  
  *            @arg ADC_AnalogWatchdog_Channel_14   :ADC analog channel 14  
  *            @arg ADC_AnalogWatchdog_Channel_15   :ADC analog channel 15  
  *            @arg ADC_AnalogWatchdog_Channel_16   :ADC analog channel 16  
  *            @arg ADC_AnalogWatchdog_Channel_17   :ADC analog channel 17  
  *            @arg ADC_AnalogWatchdog_Channel_18   :ADC analog channel 18  
  *            @arg ADC_AnalogWatchdog_Channel_19   :ADC analog channel 19  
  *            @arg ADC_AnalogWatchdog_Channel_20   :ADC analog channel 20  
  * @note   The channel selected on the AWDCH must be also set into the CHSELR 
  *         register 
  * @retval None
  */
void ADC_AnalogWatchdogSingleChannelConfig(ADC_TypeDef* ADCx, uint32_t ADC_AnalogWatchdog_Channel)
{
  uint32_t tmpreg = 0;

  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_ANALOG_WATCHDOG_CHANNEL(ADC_AnalogWatchdog_Channel));

  /* Get the old register value */
  tmpreg = ADCx->CR1;

  /* Clear the Analog watchdog channel select bits */
  tmpreg &= ~ADC_CR1_AWDCH;

  /* Set the Analog watchdog channel */
  tmpreg |= ADC_AnalogWatchdog_Channel;

  /* Store the new register value */
  ADCx->CR1 = tmpreg;
}

/**
  * @brief  Enables or disables the ADC Analog Watchdog Single Channel.
  * @param  ADCx: This parameter is ADC.
  * @param  NewState: new state of the ADC ADC Analog Watchdog Single Channel.
  *          This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void ADC_AnalogWatchdogSingleChannelCmd(ADC_TypeDef* ADCx, FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  if (NewState != DISABLE)
  {
    /* Enable the ADC Analog Watchdog Single Channel */
    ADCx->CR1 |= ADC_CR1_AWDSGL;
  }
  else
  {
    /* Disable the ADC Analog Watchdog Single Channel */
    ADCx->CR1 &= (uint32_t)~ADC_CR1_AWDSGL;
  }
}

/**
  * @}
  */

/** @defgroup ADC_Group4 Temperature Sensor, Vrefint  and Vbat management functions
 *  @brief   Temperature Sensor, Vrefint  and Vbat management functions
 *
@verbatim
 ===============================================================================
 ##### Temperature Sensor function #####
 ===============================================================================
    [..] This section provides a function allowing to enable/disable the internal 
         connections between the ADC and the Temperature Sensor, the Vrefint and
         Vbat source.
     
    [..] A typical configuration to get the Temperature sensor, Vrefint and Vbat channels 
         voltages is done following these steps :
         (#) Enable the internal connection of Temperature sensor, Vrefint or Vbat sources 
             with the ADC channels using ADC_TempSensorCmd()
             functions. 
         (#) select the ADC_Channel_16(Temperature sensor) using ADC_RegularChannelConfig() function 
         (#) Get the voltage values, using ADC_GetConversionValue() function

@endverbatim
  * @{
  */

/**
  * @brief  Enables or disables the temperature sensor channel.
  * @param  NewState: new state of the temperature sensor input channel.
  *          This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void ADC_TempSensorCmd(FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  if (NewState != DISABLE)
  {
    /* Enable the temperature sensor channel*/
    ADC->CR2 |= (uint32_t)ADC_CR2_TSEN;
  }
  else
  {
    /* Disable the temperature sensor channel*/
    ADC->CR2 &= (uint32_t)(~ADC_CR2_TSEN);
  }
}

/**
  * @}
  */

/** @defgroup ADC_Group5 Channels Configuration functions
 *  @brief    Channels Configuration functions 
 *
@verbatim
 ===============================================================================
            ##### Channels Configuration functions #####
 ===============================================================================
    [..] This section provides functions allowing to manage the ADC channels,
         it is composed of 3 sub sections :
         (#) Configuration and management functions for ADC channels: This subsection 
             provides functions allowing to configure the ADC channels :    
             (++) Select the ADC channels
             (++) Activate ADC Calibration
             (++) Activate the Overrun Mode.
             (++) Activate the Discontinuous Mode 
             (++) Activate the Continuous Mode.
             (++) Configure the sampling time for each channel
             (++) Select the conversion Trigger and Edge for ADC channels
             (++) Select the scan direction.
             -@@- Please Note that the following features for ADC channels are configurated
                  using the ADC_Init() function : 
                  (+@@) Activate the Continuous Mode (can be also activated by ADC_OverrunModeCmd().
                  (+@@) Select the conversion Trigger and Edge for ADC channels
                  (+@@) Select the scan direction.
         (#) Control the ADC peripheral : This subsection permits to command the ADC:
             (++) Stop or discard an on-going conversion (ADSTP command)
             (++) Start the ADC conversion .
         (#) Get the conversion data: This subsection provides an important function in 
             the ADC peripheral since it returns the converted data of the current 
             ADC channel. When the Conversion value is read, the EOC Flag is 
             automatically cleared.

@endverbatim
  * @{
  */

/**
  * @brief  Configures for the selected ADC.
  * @param  ADCx: This parameter is ADC.
  * @param  ADC_Channel: the ADC channel to configure. 
  *          This parameter can be any combination of the following values:
  *            @arg ADC_Channel_1: ADC Channel1 selected
  *            @arg ADC_Channel_2: ADC Channel2 selected
  *            @arg ADC_Channel_3: ADC Channel3 selected
  *            @arg ADC_Channel_4: ADC Channel4 selected
  *            @arg ADC_Channel_5: ADC Channel5 selected
  *            @arg ADC_Channel_6: ADC Channel6 selected
  *            @arg ADC_Channel_7: ADC Channel7 selected
  *            @arg ADC_Channel_8: ADC Channel8 selected
  *            @arg ADC_Channel_9: ADC Channel9 selected
  *            @arg ADC_Channel_10: ADC Channel10 selected
  *            @arg ADC_Channel_11: ADC Channel11 selected
  *            @arg ADC_Channel_12: ADC Channel12 selected
  *            @arg ADC_Channel_13: ADC Channel13 selected
  *            @arg ADC_Channel_14: ADC Channel14 selected
  *            @arg ADC_Channel_15: ADC Channel15 selected
  *            @arg ADC_Channel_16: ADC Channel16 selected
  *            @arg ADC_Channel_17: ADC Channel17 selected
  *            @arg ADC_Channel_TempSensor: ADC TempSensor selected
  *            @arg ADC_Channel_Vrefint: ADC Vrefint selected
  * @param  Rank: Sampling sequence 1~20. 
  * @param  ADC_SampleTime: The sample time value to be set. 
  *          This parameter can be one of the following values:
  *            @arg ADC_SampleTime_1_5Cycles :ADC Sample time 1.5Cycles
  *            @arg ADC_SampleTime_2_5Cycles :ADC Sample time 2.5Cycles  
  *            @arg ADC_SampleTime_3_5Cycles :ADC Sample time 3.5Cycles  
  *            @arg ADC_SampleTime_4_5Cycles :ADC Sample time 4.5Cycles  
  *            @arg ADC_SampleTime_5_5Cycles :ADC Sample time 5.5Cycles  
  *            @arg ADC_SampleTime_6_5Cycles :ADC Sample time 6.5Cycles  
  *            @arg ADC_SampleTime_7_5Cycles :ADC Sample time 7.5Cycles  
  *            @arg ADC_SampleTime_8_5Cycles :ADC Sample time 8.5Cycles  
  *            @arg ADC_SampleTime_9_5Cycles :ADC Sample time 9.5Cycles  
  *            @arg ADC_SampleTime_10_5Cycles:ADC Sample time 10.5Cycles  
  *            @arg ADC_SampleTime_11_5Cycles:ADC Sample time 11.5Cycles  
  *            @arg ADC_SampleTime_15_5Cycles:ADC Sample time 15.5Cycles  
  *            @arg ADC_SampleTime_31_5Cycles:ADC Sample time 31.5Cycles  
  *            @arg ADC_SampleTime_63_5Cycles:ADC Sample time 63.5Cycles  
  *            @arg ADC_SampleTime_127_5Cycles:ADC Sample time 127.5Cycles 
  *            @arg ADC_SampleTime_255_5Cycles:ADC Sample time 255.5Cycles 
  * @retval None
  */
void ADC_RegularChannelConfig(ADC_TypeDef* ADCx, uint32_t ADC_Channel, uint32_t Rank, uint32_t ADC_SampleTime)
{
  uint32_t id;
  volatile uint32_t * pReg;
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_CHANNEL(ADC_Channel));
  assert_param(IS_ADC_SAMPLE_TIME(ADC_SampleTime));

  if(Rank <= 6)
  {
    id = (Rank-1);
    pReg = &ADCx->SQR4;
  }
  else if(Rank <= (6*2))
  {
    id = (Rank-(6*1)-1);
    pReg = &ADCx->SQR3;
  }
  else if(Rank <= (6*3))
  {
    id = (Rank-(6*2)-1);
    pReg = &ADCx->SQR2;
  }
  else
  {
    id = (Rank-(6*3)-1);
    pReg = &ADCx->SQR1;
  }
	
  id *= 5; 
  *pReg &= ~(0x1F<<id);
  *pReg |= (ADC_Channel<<id);
  ADCx->SMPR = (uint32_t)ADC_SampleTime;
}

/**
  * @brief  Configures for the Regular Sequencer Length.
  * @param  ADCx: This parameter is ADC.
  * @param  Length: Sampling sequence 1~20. 
  * @retval None
  */
void ADC_RegularSequencerLengthConfig(ADC_TypeDef* ADCx, uint32_t Length)
{
  uint32_t regTmp;
  assert_param(IS_ADC_REGULAR_RANK(Length));

  regTmp = ADCx->SQR1 & (~ADC_SQR1_L);
  regTmp |= ((Length-1)<<ADC_SQR1_L_Pos);
  ADCx->SQR1 = regTmp;
}

/**
  * @brief  Configures for the selected ADC.
  * @note   Please set the length before configuring the injection channel.
  *          ADC_InjectedSequencerLengthConfig(n);
  *          ADC_InjectedChannelConfig(1);
  *          ...
  *          ADC_InjectedChannelConfig(n);
  * 
  * @param  ADCx: This parameter is ADC.
  * @param  ADC_Channel: the ADC channel to configure. 
  *          This parameter can be any combination of the following values:
  *            @arg ADC_Channel_1: ADC Channel1 selected
  *            @arg ADC_Channel_2: ADC Channel2 selected
  *            @arg ADC_Channel_3: ADC Channel3 selected
  *            @arg ADC_Channel_4: ADC Channel4 selected
  *            @arg ADC_Channel_5: ADC Channel5 selected
  *            @arg ADC_Channel_6: ADC Channel6 selected
  *            @arg ADC_Channel_7: ADC Channel7 selected
  *            @arg ADC_Channel_8: ADC Channel8 selected
  *            @arg ADC_Channel_9: ADC Channel9 selected
  *            @arg ADC_Channel_10: ADC Channel10 selected
  *            @arg ADC_Channel_11: ADC Channel11 selected
  *            @arg ADC_Channel_12: ADC Channel12 selected
  *            @arg ADC_Channel_13: ADC Channel13 selected
  *            @arg ADC_Channel_14: ADC Channel14 selected
  *            @arg ADC_Channel_15: ADC Channel15 selected
  *            @arg ADC_Channel_16: ADC Channel16 selected
  *            @arg ADC_Channel_17: ADC Channel17 selected
	*            @arg ADC_Channel_18: ADC Channel18 selected
  *            @arg ADC_Channel_TempSensor: ADC TempSensor selected
  *            @arg ADC_Channel_Vrefint: ADC Vrefint selected
  * @param  Rank: Sampling sequence 1~5. 
  * @param  ADC_SampleTime: The sample time value to be set. 
  *          This parameter can be one of the following values:
  *            @arg ADC_SampleTime_1_5Cycles :ADC Sample time 1.5Cycles
  *            @arg ADC_SampleTime_2_5Cycles :ADC Sample time 2.5Cycles  
  *            @arg ADC_SampleTime_3_5Cycles :ADC Sample time 3.5Cycles  
  *            @arg ADC_SampleTime_4_5Cycles :ADC Sample time 4.5Cycles  
  *            @arg ADC_SampleTime_5_5Cycles :ADC Sample time 5.5Cycles  
  *            @arg ADC_SampleTime_6_5Cycles :ADC Sample time 6.5Cycles  
  *            @arg ADC_SampleTime_7_5Cycles :ADC Sample time 7.5Cycles  
  *            @arg ADC_SampleTime_8_5Cycles :ADC Sample time 8.5Cycles  
  *            @arg ADC_SampleTime_9_5Cycles :ADC Sample time 9.5Cycles  
  *            @arg ADC_SampleTime_10_5Cycles:ADC Sample time 10.5Cycles  
  *            @arg ADC_SampleTime_11_5Cycles:ADC Sample time 11.5Cycles  
  *            @arg ADC_SampleTime_15_5Cycles:ADC Sample time 15.5Cycles  
  *            @arg ADC_SampleTime_31_5Cycles:ADC Sample time 31.5Cycles  
  *            @arg ADC_SampleTime_63_5Cycles:ADC Sample time 63.5Cycles  
  *            @arg ADC_SampleTime_127_5Cycles:ADC Sample time 127.5Cycles 
  *            @arg ADC_SampleTime_255_5Cycles:ADC Sample time 255.5Cycles 
  * @retval None
  */
void ADC_InjectedChannelConfig(ADC_TypeDef* ADCx, uint32_t ADC_Channel, uint32_t Rank, uint32_t ADC_SampleTime)
{
  uint32_t ID, Len;
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_CHANNEL(ADC_Channel));
  assert_param(IS_ADC_INJECTED_RANK(Rank));
  assert_param(IS_ADC_SAMPLE_TIME(ADC_SampleTime));
  
  Len = ((ADCx->JSQR>>ADC_JSQR_JL_Pos) & 0x07)+1;
  ID = 5-Len+(Rank-1);
  if(ID < 5)
  {
    ADCx->JSQR &= ~(0x1F<<(ID*5));
    ADCx->JSQR |= (ADC_Channel<<(ID*5));
    ADCx->SMPR = (uint32_t)ADC_SampleTime;	
  }
}

/**
  * @brief  Configures for the Injected Sequencer Length.
  * @param  ADCx: This parameter is ADC.
  * @param  Length: Sampling sequence 1~5. 
  * @retval None
  */
void ADC_InjectedSequencerLengthConfig(ADC_TypeDef* ADCx, uint32_t Length)
{
  uint32_t regTmp;
  assert_param(IS_ADC_INJECTED_RANK(Length));

  regTmp = ADCx->JSQR & (~ADC_JSQR_JL);
  regTmp |= ((Length-1)<<ADC_JSQR_JL_Pos);
  ADCx->JSQR = regTmp;
}

/**
  * @brief  Configures ADC sampling time.
  * @param  ADCx: This parameter is ADC.
  * @param  ADC_SampleTime: The sample time value to be set. 
  *          This parameter can be one of the following values:
  *            @arg ADC_SampleTime_1_5Cycles :ADC Sample time 1.5Cycles
  *            @arg ADC_SampleTime_2_5Cycles :ADC Sample time 2.5Cycles  
  *            @arg ADC_SampleTime_3_5Cycles :ADC Sample time 3.5Cycles  
  *            @arg ADC_SampleTime_4_5Cycles :ADC Sample time 4.5Cycles  
  *            @arg ADC_SampleTime_5_5Cycles :ADC Sample time 5.5Cycles  
  *            @arg ADC_SampleTime_6_5Cycles :ADC Sample time 6.5Cycles  
  *            @arg ADC_SampleTime_7_5Cycles :ADC Sample time 7.5Cycles  
  *            @arg ADC_SampleTime_8_5Cycles :ADC Sample time 8.5Cycles  
  *            @arg ADC_SampleTime_9_5Cycles :ADC Sample time 9.5Cycles  
  *            @arg ADC_SampleTime_10_5Cycles:ADC Sample time 10.5Cycles  
  *            @arg ADC_SampleTime_11_5Cycles:ADC Sample time 11.5Cycles  
  *            @arg ADC_SampleTime_15_5Cycles:ADC Sample time 15.5Cycles  
  *            @arg ADC_SampleTime_31_5Cycles:ADC Sample time 31.5Cycles  
  *            @arg ADC_SampleTime_63_5Cycles:ADC Sample time 63.5Cycles  
  *            @arg ADC_SampleTime_127_5Cycles:ADC Sample time 127.5Cycles 
  *            @arg ADC_SampleTime_255_5Cycles:ADC Sample time 255.5Cycles  
  * @retval None
  */
void ADC_SampleTimeConfig(ADC_TypeDef* ADCx, uint32_t ADC_SampleTime)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_SAMPLE_TIME(ADC_SampleTime));

  /* Configure the ADC Sample time register */
  ADCx->SMPR = (uint32_t)ADC_SampleTime;
}

/**
  * @brief  Enable the Continuous mode for the selected ADCx channels.
  * @param  ADCx: This parameter is ADC.
  * @param  NewState: new state of the Continuous mode.
  *          This parameter can be: ENABLE or DISABLE.
  * @note   It is not possible to have both discontinuous mode and continuous mode
  *         enabled. In this case (If DISCEN and CONT are Set), the ADC behaves 
  *         as if continuous mode was disabled
  * @retval None
  */
void ADC_ContinuousModeCmd(ADC_TypeDef* ADCx, FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  if (NewState != DISABLE)
  {
    /* Enable the Continuous mode*/
    ADCx->CR2 |= (uint32_t)ADC_CR2_CONT;
  }
  else
  {
    /* Disable the Continuous mode */
    ADCx->CR2 &= (uint32_t)(~ADC_CR2_CONT);
  }
}


/**
  * @brief  Enable the discontinuous mode for the selected ADC channels.
  * @param  ADCx: This parameter is ADC.
  * @param  NewState: new state of the discontinuous mode.
  *          This parameter can be: ENABLE or DISABLE.
  * @note   It is not possible to have both discontinuous mode and continuous mode
  *         enabled. In this case (If DISCEN and CONT are Set), the ADC behaves 
  *         as if continuous mode was disabled
  * @retval None
  */
void ADC_DiscModeCmd(ADC_TypeDef* ADCx, FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  if (NewState != DISABLE)
  {
    /* Enable the Discontinuous mode */
    ADCx->CR1 |= (uint32_t)ADC_CR1_DISCEN;
  }
  else
  {
    /* Disable the Discontinuous mode */
    ADCx->CR1 &= (uint32_t)(~ADC_CR1_DISCEN);
  }
}

/**
  * @brief  Enable the Overrun mode for the selected ADC channels.
  * @param  ADCx: This parameter is ADC.
  * @param  NewState: new state of the Overrun mode.
  *          This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void ADC_OverrunModeCmd(ADC_TypeDef* ADCx, FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  if (NewState != DISABLE)
  {
    /* Enable the Overrun mode */
    ADCx->CR1 |= (uint32_t)ADC_CR1_OVRMODE;
  }
  else
  {
    /* Disable the Overrun mode */
    ADCx->CR1 &= (uint32_t)(~ADC_CR1_OVRMODE);
  }
}

/**
  * @brief  Stop the on going conversions Regular for the selected ADC.
  * @note   When ADSTP is set, any on going conversion is aborted, and the ADC 
  *         data register is not updated with current conversion. 
  * @param  ADCx: This parameter is ADC.
  * @retval None
  */
void ADC_StopOfConversion(ADC_TypeDef* ADCx)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  
  ADCx->CR2 &= (uint32_t)(~ADC_CR2_SWSTART);
}

/**
  * @brief  Start Conversion Regular for the selected ADC channels.
  * @note   In continuous mode, ADSTART is not cleared by hardware with the 
  *         assertion of EOSEQ because the sequence is automatic relaunched
  * @param  ADCx: This parameter is ADC.
  * @retval None
  */
void ADC_SoftwareStartConvCmd(ADC_TypeDef* ADCx)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  
  ADCx->CR2 |= (uint32_t)ADC_CR2_SWSTART;
}

/**
  * @brief  Stop the on going conversions Injected for the selected ADC.
  * @note   When ADSTP is set, any on going conversion is aborted, and the ADC 
  *         data register is not updated with current conversion. 
  * @param  ADCx: This parameter is ADC.
  * @retval None
  */
void ADC_StopOfInjectedConversion(ADC_TypeDef* ADCx)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  
  ADCx->CR2 &= (uint32_t)(~ADC_CR2_JSWSTART);
}

/**
  * @brief  Start Conversion Injected for the selected ADC channels.
  * @note   In continuous mode, ADSTART is not cleared by hardware with the 
  *         assertion of EOSEQ because the sequence is automatic relaunched
  * @param  ADCx: This parameter is ADC.
  * @retval None
  */
void ADC_SoftwareStartInjectedConvCmd(ADC_TypeDef* ADCx)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  
  ADCx->CR2 |= (uint32_t)ADC_CR2_JSWSTART;
}

/**
  * @brief  Returns the last ADCx conversion result data for ADC channel.  
  * @param  ADCx: This parameter is ADC.
  * @retval The Data conversion value.
  */
uint16_t ADC_GetConversionValue(ADC_TypeDef* ADCx)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));

  /* Return the selected ADC conversion value */
  return (uint16_t) ADCx->DR;
}

/**
  * @}
  */
  
/**
  * @brief  Returns the last ADCx Injected conversion result data for ADC channel.  
  * @note   When the data offset register is greater than the ADC converted data, 
  *         the return result is negative.
  * @param  ADCx: This parameter is ADC.
  * @param  Rank: Sampling sequence 1~5. 
  * @retval The Data conversion value.
  */
int16_t ADC_GetInjectedConversionValue(ADC_TypeDef* ADCx, uint32_t Rank)
{
	int32_t value;
	
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_INJECTED_RANK(Rank));
	
  value = *(int32_t *)((int32_t)(&ADCx->JDR5) - (Rank-1)*0x04);

  return (int16_t)value;
}

/**
  * @brief  Set Data offset for injected channel x
  * @param  ADCx: This parameter is ADC.
  * @param  Rank: Sampling sequence 1~5.  
  * @param  Value This parameter can be 0x00~0x7FF
  * @retval None
  */
void ADC_InjectedOffsetConfig(ADC_TypeDef* ADCx, uint32_t Rank, uint32_t Value)
{
    /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_INJECTED_RANK(Rank));

  MODIFY_REG(*(volatile uint32_t *)(&ADCx->JOFR5-(Rank-1)), ADC_JOFR1_JOFFSET1, Value);
}

/**
  * @}
  */

/** @defgroup ADC_Group6 DMA Configuration functions
 *  @brief   Regular Channels DMA Configuration functions 
 *
@verbatim
 ===============================================================================
          ##### DMA Configuration functions #####
 ===============================================================================
    [..] This section provides functions allowing to configure the DMA for ADC hannels.
         Since converted channel values are stored into a unique data register, 
         it is useful to use DMA for conversion of more than one channel. This 
         avoids the loss of the data already stored in the ADC Data register. 
         When the DMA mode is enabled (using the ADC_DMACmd() function), after each
         conversion of a channel, a DMA request is generated.

@endverbatim
  * @{
  */

/**
  * @brief  Enables or disables the specified ADC DMA request.
  * @param  ADCx: This parameter is ADC.
  * @param  NewState: new state of the selected ADC DMA transfer.
  *          This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void ADC_DMACmd(ADC_TypeDef* ADCx, FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  if (NewState != DISABLE)
  {
    /* Enable the selected ADC DMA request */
    ADCx->CR2 |= (uint32_t)ADC_CR2_DMA;
  }
  else
  {
    /* Disable the selected ADC DMA request */
    ADCx->CR2 &= (uint32_t)(~ADC_CR2_DMA);
  }
}


/** @defgroup ADC_Group7 Interrupts and flags management functions
 *  @brief   Interrupts and flags management functions.
 *
@verbatim   
 ===============================================================================
            ##### Interrupts and flags management functions #####
 ===============================================================================
    [..] This section provides functions allowing to configure the ADC Interrupts 
         and get the status and clear flags and Interrupts pending bits.
  
    [..] The ADC provide 6 Interrupts sources and 11 Flags which can be divided into 
         3 groups:

  *** Flags for ADC status ***
  ======================================================
    [..]
        (+)Flags :
           (##) ADC_FLAG_ADRDY : This flag is set after the ADC has been enabled (bit ADEN=1)
               and when the ADC reaches a state where it is ready to accept conversion requests
           (##) ADC_FLAG_ADEN : This flag is set by software to enable the ADC.
                The ADC will be effectively ready to operate once the ADRDY flag has been set.
           (##) ADC_FLAG_ADDIS : This flag is cleared once the ADC is effectively
                disabled.
           (##) ADC_FLAG_ADSTART : This flag is cleared after the execution of
                ADC_StopOfConversion() function, at the same time as the ADSTP bit is
                cleared by hardware
           (##) ADC_FLAG_ADSTP : This flag is cleared by hardware when the conversion
                is effectively discarded and the ADC is ready to accept a new start conversion
           (##) ADC_FLAG_ADCAL : This flag is set once the calibration is complete.

        (+)Interrupts 
           (##) ADC_IT_ADRDY : specifies the interrupt source for ADC ready event.

  *** Flags and Interrupts for ADC channel conversion ***
  =====================================================
    [..]
        (+)Flags :
        (+)Interrupts :

  *** Flags and Interrupts for the Analog Watchdog ***
  ================================================
    [..]
        (+)Flags :
           (##) ADC_FLAG_AWD: This flag is set by hardware when the converted
                voltage crosses the values programmed thrsholds

        (+)Interrupts :
           (##) ADC_IT_AWD : specifies the interrupt source for Analog watchdog 
                event.
  
    [..] The user should identify which mode will be used in his application to 
         manage the ADC controller events: Polling mode or Interrupt mode.
  
    [..] In the Polling Mode it is advised to use the following functions:
         (+) ADC_GetFlagStatus() : to check if flags events occur.
         (+) ADC_ClearFlag()     : to clear the flags events.
  
    [..] In the Interrupt Mode it is advised to use the following functions:
         (+) ADC_ITConfig()       : to enable or disable the interrupt source.
         (+) ADC_GetITStatus()    : to check if Interrupt occurs.
         (+) ADC_ClearITPendingBit() : to clear the Interrupt pending Bit 
             (corresponding Flag).

@endverbatim
  * @{
  */

/**
  * @brief  Enables or disables the specified ADC interrupts.
  * @param  ADCx: This parameter is ADC.
  * @param  ADC_IT: specifies the ADC interrupt sources to be enabled or disabled.
  *          This parameter can be one of the following values:
  *            @arg ADC_IT_EOC   :EOC interrupt flag
  *            @arg ADC_IT_AWD   :AWD interrupt flag
  *            @arg ADC_IT_JEOC  :JEOC interrupt flag
  *            @arg ADC_IT_EOSEQ :EOSEQ interrupt flag
  *            @arg ADC_IT_JEOSEQ:JEOSEQ interrupt flag
  *            @arg ADC_IT_EOS   :EOS interrupt flag
  * @param  NewState: new state of the specified ADC interrupts.
  *          This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void ADC_ITConfig(ADC_TypeDef* ADCx, uint32_t ADC_IT, FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_FUNCTIONAL_STATE(NewState));
  assert_param(IS_ADC_CONFIG_IT(ADC_IT)); 

  if (NewState != DISABLE)
  {
    /* Enable the selected ADC interrupts */
    ADCx->CR1 |= ADC_IT;
  }
  else
  {
    /* Disable the selected ADC interrupts */
    ADCx->CR1 &= (~(uint32_t)ADC_IT);
  }
}

/**
  * @brief  Checks whether the specified ADC flag is set or not.
  * @param  ADCx: This parameter is ADC.
  * @param  ADC_FLAG: specifies the flag to check. 
  *          This parameter can be one of the following values:
  *            @arg ADC_FLAG_AWD: Analog watchdog flag
  *            @arg ADC_FLAG_ADRDY: ADC Ready flag
  *            @arg ADC_FLAG_EOSMP: End of sampling flag
  *            @arg ADC_FLAG_EOC: End of conversion flag
  *            @arg ADC_FLAG_JEOC: End of conversion JSQ flag
  *            @arg ADC_FLAG_EOSEQ: End of Sequence flag
  *            @arg ADC_FLAG_JEOSEQ: End of Sequence flag
  *            @arg ADC_FLAG_EOS: End of ALL conversion flag
  *            @arg ADC_FLAG_OVR: Overrun flag 
  *            @arg ADC_FLAG_STRT: STRT flag 
  *            @arg ADC_FLAG_JSTRT: JSTRT flag 
  * @retval The new state of ADC_FLAG (SET or RESET).
  */
FlagStatus ADC_GetFlagStatus(ADC_TypeDef* ADCx, uint32_t ADC_FLAG)
{
  FlagStatus bitstatus = RESET;
    
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_GET_FLAG(ADC_FLAG));
  
  bitstatus = (FlagStatus)(ADCx->SR & ADC_FLAG)?SET : RESET;

  return bitstatus;
}

/**
  * @brief  Clears the ADCx's pending flags.
  * @param  ADCx: This parameter is ADC.
  * @param  ADC_FLAG: specifies the flag to clear. 
  *          This parameter can be any combination of the following values:
  *            @arg ADC_FLAG_AWD: Analog watchdog flag
  *            @arg ADC_FLAG_ADRDY: ADC Ready flag
  *            @arg ADC_FLAG_EOSMP: End of sampling flag
  *            @arg ADC_FLAG_EOC: End of conversion flag
  *            @arg ADC_FLAG_JEOC: End of conversion JSQ flag
  *            @arg ADC_FLAG_EOSEQ: End of Sequence flag
  *            @arg ADC_FLAG_JEOSEQ: End of Sequence flag
  *            @arg ADC_FLAG_EOS: End of ALL conversion flag
  *            @arg ADC_FLAG_OVR: Overrun flag 
  *            @arg ADC_FLAG_STRT: STRT flag 
  *            @arg ADC_FLAG_JSTRT: JSTRT flag 
  * @retval None
  */
void ADC_ClearFlag(ADC_TypeDef* ADCx, uint32_t ADC_FLAG)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_GET_FLAG(ADC_FLAG));
  
  ADCx->SR &= (~ADC_FLAG);
}

/**
  * @brief  Checks whether the specified ADC interrupt has occurred or not.
  * @param  ADCx: This parameter is ADC
  * @param  ADC_IT: specifies the ADC interrupt source to check.
  *          This parameter can be one of the following values:
  *            @arg ADC_IT_EOC   :EOC interrupt flag status
  *            @arg ADC_IT_AWD   :AWD interrupt flag status
  *            @arg ADC_IT_JEOC  :JEOC interrupt flag status
  *            @arg ADC_IT_EOSEQ :EOSEQ interrupt flag status
  *            @arg ADC_IT_JEOSEQ:JEOSEQ interrupt flag status
  *            @arg ADC_IT_EOS   :EOS interrupt flag status
  * @retval The new state of ADC_IT (SET or RESET).
  */
ITStatus ADC_GetITStatus(ADC_TypeDef* ADCx, uint32_t ADC_IT)
{
  ITStatus bitstatus = RESET;
  uint32_t enablestatus = 0;
    
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_CONFIG_IT(ADC_IT));

  if(ADC_IT == ADC_IT_AWD)
  {
    bitstatus = (ITStatus)(ADCx->SR & ADC_SR_AWD);
  }
  else if(ADC_IT == ADC_IT_EOC)
  {
    bitstatus = (ITStatus)(ADCx->SR & ADC_SR_EOC);
  }
  else
  {
    bitstatus = (ITStatus)(ADCx->SR & (ADC_IT>>3));
  }

  enablestatus = ADCx->CR1 & ADC_IT;
  if((bitstatus != 0) && (enablestatus != 0))
    bitstatus = SET;
  else
    bitstatus = RESET;

  return bitstatus;
}

/**
  * @brief  Clears the ADCx's interrupt pending bits.
  * @param  ADCx: This parameter is ADC.
  * @param  ADC_IT: specifies the ADC interrupt pending bit to clear.
  *          This parameter can be one of the following values:
  *            @arg ADC_IT_EOC   :EOC interrupt flag status
  *            @arg ADC_IT_AWD   :AWD interrupt flag status
  *            @arg ADC_IT_JEOC  :JEOC interrupt flag status
  *            @arg ADC_IT_EOSEQ :EOSEQ interrupt flag status
  *            @arg ADC_IT_JEOSEQ:JEOSEQ interrupt flag status
  *            @arg ADC_IT_EOS   :EOS interrupt flag status
  * @retval None
  */
void ADC_ClearITPendingBit(ADC_TypeDef* ADCx, uint32_t ADC_IT)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_CONFIG_IT(ADC_IT));
  
  if(ADC_IT == ADC_IT_AWD)
  {
    ADCx->SR &= (~ADC_SR_AWD);
  }
  else if(ADC_IT == ADC_IT_EOC)
  {
    ADCx->SR &= (~ADC_SR_EOC);
  }
  else
  {
    ADCx->SR &= (~(ADC_IT>>3));
  }
}

/**
  * @brief  Enables or disables injected group discontinuous mode.
  * @param  ADCx: This parameter is ADC.
  * @param  NewState: new state of the ADC peripheral. 
  *          This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void ADC_InjectedDiscModeCmd(ADC_TypeDef* ADCx, FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  if (NewState != DISABLE)
  {
    /* Set the ADEN bit to Enable the ADC peripheral */
    ADCx->CR1 |= (uint32_t)ADC_CR1_JDISCEN;
  }
  else
  {
    /* Set the ADDIS to Disable the ADC peripheral */
    ADCx->CR1 &= (uint32_t)~ADC_CR1_JDISCEN;
  }
}

/**
  * @brief  ADC regular group discontinuous mode number.
  * @param  ADCx: This parameter is ADC.
  * @param  Number: 0~8
  * @retval None
  */
void ADC_DiscModeChannelCountConfig(ADC_TypeDef* ADCx, uint32_t Number)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_REGULAR_DISCONT_NUMBER(Number));

  if(Number <= 8)
  {
    /* Set the ADEN bit to Enable the ADC peripheral */
    ADCx->CR1 &= (uint32_t)~ADC_CR1_DISCNUM_Msk;
    ADCx->CR1 |= (uint32_t)(Number << ADC_CR1_DISCNUM_Pos);
  }
  else 
  {
    /* Set the ADDIS to Disable the ADC peripheral */
    ADCx->CR1 &= (uint32_t)~ADC_CR1_DISCNUM_Msk;
  }
}

/**
  * @brief  ADC injected group discontinuous mode number.
  * @param  ADCx: This parameter is ADC.
  * @param  NewState: new state of the ADC peripheral. 
  *         This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void ADC_AutoInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState)
{
 /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  if (NewState != DISABLE)
  {
    /* Set the ADEN bit to Enable the ADC peripheral */
    ADCx->CR1 |= (uint32_t)ADC_CR1_JAUTO;
  }
  else
  {
    /* Set the ADDIS to Disable the ADC peripheral */
    ADCx->CR1 &= (uint32_t)~ADC_CR1_JAUTO;
  }
}

/**
  * @brief  Set the injected channels conversion value offset
  * @param  ADCx: This parameter is ADC.
  * @param  ADC_InjectedChannel: the ADC injected channel to set its offset. 
  *          This parameter can be one of the following values:
  *            @arg ADC_InjectedChannel_1: Injected Channel1 selected
  *            @arg ADC_InjectedChannel_2: Injected Channel2 selected
  *            @arg ADC_InjectedChannel_3: Injected Channel3 selected
  *            @arg ADC_InjectedChannel_4: Injected Channel4 selected
  *            @arg ADC_InjectedChannel_5: Injected Channel4 selected
  * @param  Offset: the offset value for the selected ADC injected channel
  *          This parameter must be a 12bit value.
  * @retval None
  */
void ADC_SetInjectedOffset(ADC_TypeDef* ADCx, uint32_t ADC_InjectedChannel, uint32_t Offset)
{
	 __IO uint32_t tmp = 0;
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_INJECTED_CHANNEL(ADC_InjectedChannel));
  assert_param(IS_ADC_OFFSET(Offset));
  
  tmp = (uint32_t)ADCx;
  tmp += ADC_InjectedChannel;
  
  /* Set the selected injected channel data offset */
 *(__IO uint32_t *) tmp = (uint32_t)Offset;

}	

/**
  * @brief  Enables or disables injected group discontinuous mode.
  * @param  ADCx: This parameter is ADC.
  * @param  NewState: new state of the ADC peripheral. 
  *          This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void ADC_ExternalTrigInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  if (NewState != DISABLE)
  {
    ADCx->CR2 |= (uint32_t)ADC_CR2_JEXTTRIG;  
  }
  else
  {
    ADCx->CR2 &= (uint32_t)~ADC_CR2_JEXTTRIG;
  }
}

 /**
  * @brief  Configures the ADC external trigger for regular channels conversion.
  * @param  ADCx: ADC.
  * @param  ADC_ExternalTrigregularConv: specifies the ADC trigger to start injected conversion.
  *          This parameter can be one of the following values:                    
  *            @arg ADC_ExternalTrigConv_T1_CC1
  *            @arg ADC_ExternalTrigConv_T1_CC2
  *            @arg ADC_ExternalTrigConv_T1_CC3
  *            @arg ADC_ExternalTrigConv_T3_CC2
  *            @arg ADC_ExternalTrigConv_T15_CC2
  *            @arg ADC_ExternalTrigConv_T15_TRGO
  *            @arg ADC_ExternalTrigConv_EXTI4   
  *            @arg ADC_ExternalTrigConv_SWSTART
  * @retval None
  */
void ADC_ExternalTrigConvConfig(ADC_TypeDef* ADCx, uint32_t ADC_ExternalTrigregularConv)
{
	 uint32_t tmpreg = 0;
	
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_EXTERNAL_TRIG_CONV(ADC_ExternalTrigregularConv));

  /* Get the old register value */
  tmpreg = ADCx->CR2;
  
  /* Clear the old external event selection for injected group */
  tmpreg &= (uint32_t)~ADC_CR2_EXTSEL_Msk;
  
  /* Set the external event selection for injected group */
  tmpreg |= ADC_ExternalTrigregularConv;
  
  /* Store the new register value */
  ADCx->CR2 = tmpreg;
}

 /**
  * @brief  Configures the ADCx external trigger for injected channels conversion.
  * @param  ADCx: ADC.
  * @param  ADC_ExternalTrigInjecConv: specifies the ADC trigger to start injected conversion.
  *          This parameter can be one of the following values:                    
  *            @arg ADC_ExternalTrigInjectedConv_T1_TRGO
  *            @arg ADC_ExternalTrigInjectedConv_T1_CC4
  *            @arg ADC_ExternalTrigInjectedConv_T1_CC3
  *            @arg ADC_ExternalTrigInjectedConv_T3_CC1
  *            @arg ADC_ExternalTrigInjectedConv_T3_TRGO
  *            @arg ADC_ExternalTrigInjectedConv_T15_CC1
  *            @arg ADC_ExternalTrigInjectedConv_EXTI9   
  *            @arg ADC_ExternalTrigInjectedConv_SWSTART 
  * @retval None
  */
void ADC_ExternalTrigInjectedConvConfig(ADC_TypeDef* ADCx, uint32_t ADC_ExternalTrigInjecConv)
{
	 uint32_t tmpreg = 0;
	
  /* Check the parameters */
  assert_param(IS_ADC_ALL_PERIPH(ADCx));
  assert_param(IS_ADC_EXTERNAL_TRIG_CONV_JSQ(ADC_ExternalTrigInjecConv));

  /* Get the old register value */
  tmpreg = ADCx->CR2;
  
  /* Clear the old external event selection for injected group */
  tmpreg &= (uint32_t)~ADC_CR2_JEXTSEL_Msk;
  
  /* Set the external event selection for injected group */
  tmpreg |= ADC_ExternalTrigInjecConv;
  
  /* Store the new register value */
  ADCx->CR2 = tmpreg;
}

/**
  * @}
  */

/**
  * @}
  */ 

/**
  * @}
  */ 

/**
  * @}
  */ 
