/**
 * @file Drv_AFE_ADC.c
 * @author 陳挺 (tony@e-besthealth.com)
 * @brief ADC 調用接口
 * @version 0.1
 * @date 2020-03-17
 *
 * @copyright BEST HEALTH ELECTRONIC INC (c) 2019
 *
 * Compiler Ver. : V3.57
 * IDE3000  Ver. : V8.02
 * MCU/CFG  Ver. : BH67F2472/1.1
 */
#include "common.h"
#include "Project_Global.h"
#include "BH67F5362.h"
#include "Drv_AFE_ADC.h"
#include "Drv_GPIO.h"
#include "Drv_IIC.h"

volatile u8 lu8v_read_reg; 
volatile bit ADC_success=0;

ADC_define	SDK_ADC;
volatile int ADC_Value_S16;
void Drv_ADCInit()
{
		SET_PC7_INT3();			//設置DRDYB引腳，開啟中斷
		SET_INT3_PC7();
		SET_INT3_Enable();
		SET_PD0_GPIO();			//設置SDA,SCL引腳
		SET_PD1_GPIO();
		IIC_WriteData(HIRCC ,1);
		lu8v_read_reg = IIC_ReadData(HIRCC);
		do
		{
			lu8v_read_reg = IIC_ReadData(HIRCC);
			GCC_CLRWDT();
		} 
		while (lu8v_read_reg != 0x03);	//等待HIRC穩定
		IIC_WriteData(DACC,0xc0);		//DAC_POWER ON; DAC_REF = VCM;
		IIC_WriteData(PWRC,0xac);
		IIC_WriteData(PGAC0,0x00);		//VREFGN=1,ADGN=1,PGAGN=1;
		IIC_WriteData(PGAC1,0x00);		//INIS OFF; Input_Change = Normal; DCSET = +0V;	
		IIC_WriteData(ADCS,0x1f); 		// fMCLK=fADC
		IIC_WriteData(ADCR0,0x62);
		//ADC_RefBufN = Disable; ADC_RefBufP = Disable; FLMS =CHOP=2,fM/12;
	    IIC_WriteData(ADCR1,0x40);
	    IIC_WriteData(PGACS, 0x00);			//CHSP = AN0; CHSN = AN1;
	    IIC_WriteData(ADCTE,0xe7);
		//ADC Start
		lu8v_read_reg = IIC_ReadData(ADCR0);
		IIC_WriteData(ADCR0 ,lu8v_read_reg&0B10011111);		
		IIC_WriteData(ADCR0 ,(lu8v_read_reg&0B10011111)|0x80);   //ador[0:2]=111 -> OSR=128 
		IIC_WriteData(ADCR0 ,lu8v_read_reg&0B00011111);
}


/**
 * @brief開啟ADC通道
 *
 * @return gu8v_ad_data
 */
void Drv_GetADC()
{
		if(ADC_FLAG==1)                       //capture rising eage
		{
			ADC_FLAG=0;
			if(SDK_ADC.SampleCount < 3) 
			{
				SDK_ADC.SampleCount++;
				lu8v_read_reg = IIC_ReadData(ADCR1);
				IIC_WriteData(ADCR1,(lu8v_read_reg & 0xf8));   //adcdl = 0 eoc = 0	
			} 
			else
			{	
				SDK_ADC.SampleCount++;
				lu8v_read_reg = IIC_ReadData(ADCR1);
				if(lu8v_read_reg&&0x02 == 0x02)
				{
					IIC_WriteData(ADCR1 ,lu8v_read_reg|0x04);
					SDK_ADC.AdcData.u32 = 0;
					SDK_ADC.AdcData.byte.byte0	= IIC_ReadData(ADRL);
					SDK_ADC.AdcData.byte.byte1	= IIC_ReadData(ADRM);				
					SDK_ADC.AdcData.byte.byte2	= IIC_ReadData(ADRH);
					if(SDK_ADC.AdcData.bits.b23)
					{
						SDK_ADC.AdcData.byte.byte3 = 0xff;			//負數取補碼
					}
					
//					SDK_ADC.AdcData.s32 >>= 8;
//					ADC_Value_S16 = SDK_ADC.AdcData.s32;			//去掉後八位的數值
					gbv_adc_Success =1;	
					lu8v_read_reg = IIC_ReadData(ADCR1);
					IIC_WriteData(ADCR1,(lu8v_read_reg & 0xf8));   //adcdl = 0 eoc = 0
			    }
			}			
		
		}
}
