
//2016.4.4
//发现了一个BUG, 小于4分频, 会导致AD转换出现问题

//2016.4.9
//发现加上DIDR0寄存器设置定后干扰了按键端口, 不知道为何, 于是去掉了.

unit ADbasic
{
	public link unit PX {}
	const uint8 channelX = PX.AD_INDEX;
	public link unit PY {}
	const uint8 channelY = PY.AD_INDEX;
	public link unit PZ {}
	const uint8 channelZ = PZ.AD_INDEX;
	
	public const int32 MinValue = 0;
	public const int32 MaxValue = 1000;
	
	const int32 MAX = 675;
	
	//---------------------------------------------------
	//[i] function_void OS_init;
	public void OS_init()
	{
		PX.D0_DIR = 0;
		PX.D0_OUT = 0;
		PY.D0_DIR = 0;
		PY.D0_OUT = 0;
		PZ.D0_DIR = 0;
		PZ.D0_OUT = 0;
		
		#.MEGA2560.ADCSRA = 0b1000_0011;  //8分频
		#.MEGA2560.ADMUX = 0b0100_0000;
		
		//uint8 BIT = 0x01;
		//#.MEGA2560.DIDR0 = #.MEGA328.DIDR0 | (BIT << 1);
	}
	//---------------------------------------------------
	//[i] function_int32 get_dataX;
	public int32 get_dataX()
	{
		return get_data( channelX );
	}
	//---------------------------------------------------
	//[i] function_int32 get_dataY;
	public int32 get_dataY()
	{
		return get_data( channelY );
	}
	//---------------------------------------------------
	//[i] function_int32 get_dataZ;
	public int32 get_dataZ()
	{
		return get_data( channelZ );
	}



	int32 get_data( uint8 c )
	{
		uint8 cn = c & 0x07;
		if( c > 7 ) {
			#.MEGA2560.ADCSRB.3(bit) = 1;
		}
		else {
			#.MEGA2560.ADCSRB.3(bit) = 0;
		}
		
		#.MEGA2560.ADMUX = 0b0100_0000 + cn;
		#.MEGA2560.ADCSRA.6(bit) = 1;
		while( #.MEGA2560.ADCSRA.6(bit) == 1 ) {}
		
		uint16 data;
		data.0(uint8) = #.MEGA2560.ADCL;
		data.8(uint8) = #.MEGA2560.ADCH;
		
		//丢弃此结果
		//uint32 d = data;
		//return MinValue + (int)d * (MaxValue - MinValue) / MAX;
		
		#.MEGA2560.ADMUX = 0b0100_0000 + cn;
		#.MEGA2560.ADCSRA.6(bit) = 1;
		while( #.MEGA2560.ADCSRA.6(bit) == 1 ) {}
		
		data.0(uint8) = #.MEGA2560.ADCL;
		data.8(uint8) = #.MEGA2560.ADCH;
		
		uint32 d = data;
		return MinValue + (int)d * (MaxValue - MinValue) / MAX;
	}
}





