#include "saradc_key.h"

#define ADCCH_KEY       ADCCH_WKO
#define Sample          21			//Number of samples

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

    clock_gate0_cmd(CLOCK_GATE0_SARADC, ENABLE);

    //saradc key gpio init
    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(GPIOB_REG, &gpio_init_structure);

    adc_ch |= BIT(ADCCH_KEY);
    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, ADCCH_KEY);     //channel number 4
}

u16 ADC_GetValue(void)
{
    u16 key_val;
    u16 adc_ch = 0;
    adc_ch |= BIT(ADCCH_KEY);
    key_val = (u16)(sadc_get_data(ADCCH_KEY)*3300/1024);
    sadc_kick_start(adc_ch, ADCCH_KEY);
    return key_val;
}

u16 Adc_average() // Arithmetic average filter
{
    u16 count1;
	u32 sum = 0;
	for(count1 = 0;count1 < Sample;count1++)
	{
		sum += ADC_GetValue();
	}
	return (u16)(sum / Sample);
}

void Adc_run(void)
{
    u16 key_val;

    key_val = Adc_average();
    printf("/********************************/\n");
    printf("PB5_key_val:%d mv\n", key_val);
}

