#include "battery_voltage.h"
#include "AI8051U.h"
#include "intrins.h"
#include "global.h"


void Delay1ms(void)	//@40MHz
{
	unsigned long edata i;

	_nop_();
	_nop_();
	_nop_();
	i = 9998UL;
	while (i) i--;
}

void bat_voltage_init()
{
	/* 选择ADC输入的IO必须配置为高阻输入模式	*/
    P0M0 &= ~0x01; 
	P0M1 |= 0x01; 

    ADCCFG = 0x20+BAT_ADC_DIV;/* 设置ADC时钟分频，默认为8(18分频，计算为(n+1)*2分频)，转换结果右对齐 */
    ADCTIM = 0x3f;/* 设置最长的采样时间，保证ADC采样窗口足够大，保证ADC采样保持电容的充电 */
	ADC_CONTR = 0x80 + 0;    //ADC on + channel
	
	Delay1ms();
}


float get_bat_voltage()
{
	uint16_t val = 0;
	val = ADC_convert(ADC_CH8);
	return (float)(val * 0.008862f);	/* 转换成实际电压 */
}	
	