/********************************************************************************
* @file    ADC_SingleConversion.c
* @author  SOC AE Team
* @version V1.1
* @date    2025-06-27
* @brief   获取内部四分之一VDD通道的ADC转换值与ADC采样通道为AIN0的值。
*
*******************************************************************************/
#include "sc32_conf.h"
#include "Function_Init.h"

static volatile FlagStatus ADC_Flag;

void ADC_SingleConversion_Function(void)
{
   static volatile uint16_t ADC_Value_VDD4 = 0, ADC_Value0 = 0;
	 GPIO_InitTypeDef GPIO_InitStruct; //定义GPIO初始化结构体变量
#if defined(SC32f10xx) 
  /* PC6设置为推挽输出 */
  GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6;
  GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_PU;
  GPIO_Init(GPIOC, &GPIO_InitStruct);
#elif defined(SC32f12xx) 
  /* PC6设置为推挽输出 */
  GPIO_InitStruct.GPIO_Pin = GPIO_Pin_2;
  GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_PU;
  GPIO_Init(GPIOB, &GPIO_InitStruct);	

#endif
  ADC_InitTypeDef ADC_InitStruct; //定义ADC初始化结构体变量

  RCC_APB2Cmd(ENABLE);  //ADC外设挂载在APB2时钟上

  ADC_StructInit(&ADC_InitStruct);
  
  ADC_InitStruct.ADC_ConvMode = ADC_ConvMode_Single;  //ADC单次转换模式
  ADC_InitStruct.ADC_Prescaler = ADC_Prescaler_3CLOCK;  //转换时间为3个周期
#if defined(SC32f10xx) || defined(SC32f12xx) 
  ADC_InitStruct.ADC_VREF = ADC_VREF_VDD; //参考电压为VDD
#endif
  ADC_InitStruct.ADC_EAIN = ADC_EAIN_0; //把ADC0设为ADC输入引脚
  
  ADC_Init(ADC, &ADC_InitStruct); //根据结构体标志位配置ADC
  ADC_SetChannel(ADC,ADC_Channel_0);
#if defined(SC32f10xx) || defined(SC32f12xx) 
  ADC_ITConfig(ADC, ADC_IT_ADCIF, ENABLE);	//使能ADC中断
#endif
  NVIC_EnableIRQ(ADC_IRQn);

  ADC_Cmd(ADC, ENABLE);	//使能ADC
  while(1)
	{
	  ADC_SetChannel(ADC, ADC_Channel_VDD_D4);//设置ADC采样通道为VDD/4
		ADC_Value_VDD4 = ADC_AverageValue();//获取平均采样值
	  printf("\r\n ADC VDD/4 Conversion Value is 0x%x \r\n", ADC_Value_VDD4);
		
		ADC_SetChannel(ADC, ADC_Channel_0);//设置ADC采样通道为AIN0
		ADC_Value0 = ADC_AverageValue();//获取平均采样值
	  printf("\r\n ADC AIN0 Conversion Value is 0x%x \r\n", ADC_Value0);
	}

}
//ADC采样10次求平均值（去除最大最小值）
uint16_t ADC_AverageValue(void)
{
    uint16_t i;
    uint16_t ADC_ValueMax = 0, ADC_ValueMin = 0X01 << 14, ADC_ValueMean = 0, ADC_ValueTad = 0;
    uint32_t ADC_ValueSum = 0;
	for(i=0;i<10;i++)
	{
        ADC_SoftwareStartConv(ADC);// 开启转换
		
        while(ADC_Flag == RESET);//等待ADC单次转换完成
        ADC_Flag = RESET;
		
		ADC_ValueTad = ADC_GetConversionValue(ADC);  //获取一次ADC转换值
		if(ADC_ValueTad>ADC_ValueMax)
		{
		   ADC_ValueMax = ADC_ValueTad;
		}
		if(ADC_ValueTad<ADC_ValueMin)
		{
		   ADC_ValueMin = ADC_ValueTad;
		}
		ADC_ValueSum += ADC_ValueTad;
	}
  ADC_ValueMean = (uint16_t)((ADC_ValueSum - ADC_ValueMax - ADC_ValueMin) / 8);
  return ADC_ValueMean;
}
void ADC_SingleConversion_ADCHandler(void)
{
  if(ADC_GetFlagStatus(ADC,ADC_Flag_ADCIF)) //判断ADC标志位
  {
    ADC_ClearFlag(ADC,ADC_Flag_ADCIF);  //清除ADC标志位
    ADC_Flag = SET;  //自定义标志置起
  }
}
