/*********************************************************
*Copyright (C), 2017, Shanghai Eastsoft Microelectronics Co., Ltd.
 * @文件名:  adc.c
 * @作  者:  AE Team
 * @版  本:  V1.00
 * @日  期:  2022/07/25
 * @描  述:  ADC模块程序
 * @note
 *          Change Logs:
 *          Date            Author          Notes
 *          25 July 2022    AE Team         change license to Apache-2.0
 *
 * Copyright (C) Shanghai Eastsoft Microelectronics Co. Ltd. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the License); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 **********************************************************************************
 */


#include "adc.h"
#include "string.h"

/***************************************************************
 函数名：ADCInit
 描  述：ADC 初始化
 输入值：无
 输出值：无
 返回值：无
***************************************************************/
void ADCInit(void)
{
    ADC_InitStruType x;
    GPIO_InitSettingType y;
	memset(&x, 0, sizeof(x));
	memset(&y, 0, sizeof(y));

    y.Signal = GPIO_Pin_Signal_Analog;
    y.Dir = GPIO_Direction_Input;
    y.Func = GPIO_Reuse_Func0;
    GPIO_Init(GPIO_Pin_B9, &y);

    x.CLKS = ADC_CLKS_PCLK;
    x.CLKDIV = ADC_CLKDIV_1_32;
    x.VREF_SEL = ADC_VREF_SEL_0;
    x.VREFP = ADC_VREFP_VDD;        /* 选择芯片的工作电压VDD */
    x.VREFN = ADC_VREFN_VSS;
    x.CHS = ADC_CHS_AIN4;
    x.SMPS = ADC_SMPS_SOFT;
    x.BITSEL = ADC_BITSEL_8;        /* AD分辨率8位 */
    x.ST = 0;
    ADC_Init(&x);
}

/*********************************************************
函数名: ADCRead
描  述: ADC采样数据读取(16次采样平均值)(软件控制)
输入值: 无
输出值: 无
返回值: 平均值
**********************************************************/
uint32_t ADCRead(void)
{
    uint8_t i;
    uint32_t max, min, sum, ad_temp;

    max = 0x00;
    min = 0x0FFF;
    sum = 0x00;

    for (i = 0; i < 18; i++)
    {
        ADC_SoftStart();                                    /* 软件开启采样 */
        ADC_SoftStop();                                     /* 软件停止采样 */

        while (ADC_GetIFStatus(ADC_IF) == RESET);           /* 转换时间，等待采样结果 */

        ad_temp = ADC_GetConvValue();
        ADC_ClearIFStatus(ADC_IF);

        if (ad_temp > max)
        {
            max = ad_temp;
        }

        if (ad_temp < min)
        {
            min = ad_temp;
        }

        sum += ad_temp;
    }

    /* 去除采样中的最大值和最小值 */
    sum -= min;
    sum -= max;

    /* 返回平均值 */
    return sum >> 4;
}


/*************************END OF FILE**********************/
