/********************************************************* * 
@file		:adc_convert_test.c 
@brief  	:adc convert function test
@author 	:zhongfeng
@version	:v1.0 
@date 		:19/10/28
Copyright (C) 2019 Panchip Technology Corp. All rights reserved. 
***********************************************************/

#include "pan271x.h"
#include "adc_common.h"

volatile bool isr_flag = false;
static uint16_t output_buf[ADC_CONV_CODE_TOTAL_CNT], buf_offset;

void ADC_IRQHandler(void)
{
	if (ADC_IsIntOccurred(ADC, ADC_STATUS_FIFO_OV_FALG_Msk, ADC_CTL_OV_INT_EN_Msk)) {
		SYS_TEST("Overflow\n");
	}
	if (ADC_IsIntOccurred(ADC, ADC_STATUS_FIFO_FULL_FALG_Msk, ADC_CTL_FULL_INT_EN_Msk)) {
		SYS_TEST("Full\n");
		ADC_ReadFifo(ADC, output_buf+buf_offset);
		buf_offset += 8;
	}
	if (ADC_IsIntOccurred(ADC, ADC_STATUS_FIFO_HALF_FALG_Msk, ADC_CTL_HALF_INT_EN_Msk)) {
		SYS_TEST("Half\n");
		ADC_ReadFifo(ADC, output_buf+buf_offset);
		buf_offset += 4;
	}
	if (ADC_IsIntOccurred(ADC, ADC_STATUS_FIFO_EMPTY_FALG_Msk, ADC_CTL_EMPTY_INT_EN_Msk)) {
		SYS_TEST("Empty\n");
	}
	if (ADC_IsIntOccurred(ADC, ADC_STATUS_ADC_FLAG_Msk, ADC_CTL_ADCIEN_Msk)) {
		SYS_TEST("Adc flag\n");
		ADC_ClearStatusFlag(ADC, ADC_STATUS_ADC_FLAG_Msk);
	}
}

/*
  * @brief	   :iic register default value check
  * @retval    :0/1
*/
uint32_t ADC_InterruptTest(void)
{
	NVIC_EnableIRQ(ADC_IRQn);

	//ADC_CTL_EMPTY_INT_EN_Msk/ADC_CTL_OV_INT_EN_Msk/ADC_CTL_HALF_INT_EN_Msk/ADC_CTL_FULL_INT_EN_Msk
	ADC_IntEnable(ADC, ADC_CTL_HALF_INT_EN_Msk, ENABLE);
	ADC_HwTrigEnable(ADC, DISABLE);
	ADC_VrefVoltageSelect(ADC, ADC_VREF_VOL_SEL_VBAT);
	ADC_EnableFifo(ADC, ENABLE);
	ADC_LoadWeightCfg();
	ADC_SetWeightRatio(ADC, weight_dif);
	ADC_SetSampleCount(ADC, 4);
	ADC_SetDiscardCount(ADC, 0x1);
	ADC_EnableAverage(ADC, ENABLE);

    // Power on ADC
    ADC_PowerOn(ADC);
	buf_offset = 0;

	uint32_t cnt = 100;
	while(cnt--){
		while(ADC_IsBusy(ADC)){}
		ADC_StartConvert(ADC);
	}

	for(cnt = 0;cnt < 100;cnt++){
		SYS_TEST("%d ",output_buf[cnt]);
		if(cnt % 10 == 9)
			SYS_TEST("\r\n");
	}

    // Power down ADC
    ADC_PowerDown(ADC);
    return 0;
}

