#include "saradc_sampling.h"

adc_cb_t adc_cb;

#define ADC_GPIO                ADCCH_PE5   //ADC input pin
#define ADC_filters_number      12          //Number of samples

void Adc_sampling_init(void)
{
    u16 adc_ch = 0;
    sadc_init_typedef sadc_init_struct;

    clock_gate0_cmd(CLOCK_GATE0_SARADC, ENABLE);

    gpio_init_typedef gpio_init_structure;
    gpio_init_structure.gpio_pin = GPIO_PIN_5;
    gpio_init_structure.gpio_dir = GPIO_DIR_INPUT;
    gpio_init_structure.gpio_fen = GPIO_FEN_PER;
    gpio_init_structure.gpio_mode = GPIO_MODE_ANALOG;
    gpio_init_structure.gpio_pupd = GPIO_IN_FLOATING;
    gpio_init(GPIOE_REG, &gpio_init_structure);

    adc_ch |= BIT(ADC_GPIO);
    sadc_init_struct.clk = SADC_CLK_6M;
    sadc_init_struct.baud = SADC_ST_8_CLK;
    sadc_init(&sadc_init_struct);
    sadc_kick_start(adc_ch, ADC_GPIO);
}

u16 ADC_soft_filtering(u8 ch)   // Software filter
{
    u8 i;
    u32 sum;
    adc_cb.shock_wave_each_val[adc_cb.adc_i] = sadc_get_data(ch);

    for(i=0,sum=0;i<ADC_filters_number;i++)
    {
        sum += adc_cb.shock_wave_each_val[i];
    }
    adc_cb.adc_i = (adc_cb.adc_i+1)%ADC_filters_number;

    return (sum/ADC_filters_number);
}


void Adc_sampling_run(void)
{
    u16 adc_ch = BIT(ADC_GPIO);
    u32 adc_val,adc_val2;
    u32 adc_vbg;
    u32 voltage,voltage2;
    static u32 delay_cnt;

    if (!sadc_get_flag(SADC_FLAG_PENDING) || !tick_check_expire(delay_cnt, 500)) {
        return;
    }

    adc_val = sadc_get_data(ADC_GPIO);      // Collected ADC value
    adc_val2 = ADC_soft_filtering(ADC_GPIO);//ADC average

    voltage = (u32)adc_val *3300/1024;
    voltage2 = (u32)adc_val2 *3300/1024;

    printf("PE5_Adc_Val:\n");
    printf("voltage = %4dmV  filtingV = %4dmV \n", voltage,voltage2);
    printf("/********************************/\r\n");

    sadc_kick_start(adc_ch, ADC_GPIO);
    delay_cnt = tick_get();
}
