/*
 * ADC_interface.h
 *
 * Created: 15.11.2012 20:03:44
 *  Author: Kubrt
 */ 


#ifndef ADC_INTERFACE_H_
#define ADC_INTERFACE_H_

uint16_t ADC_read(unsigned char channel)
{
	uint16_t vystup = 0;
	#define SET_CS_PIN PORTA |= 0x08
	#define CLEAR_CS_PIN PORTA &= ~(0x08)
	#define SET_DCLK_PIN PORTA |= 0x10
	#define CLEAR_DCLK_PIN PORTA &= ~(0x10)	
	#define SET_DIN_PIN PORTA |= 0x04
	#define CLEAR_DIN_PIN PORTA &= ~(0x04)
	uint8_t data = 0b10000111;
	switch (channel)
	{
		case 0:
			data |= 0x10;
			break;
		case 1:
			data |= 0x50;
			break;
		case 2:
			data |= 0x20;
			break;
		case 3:
			data |= 0x60;
			break;
		default:
			return 1;
	}	
	CLEAR_CS_PIN;						//Control byte
	for (uint8_t i = 0; i < 8; i++)
	{
		if (data & (0x80>>i))
			SET_DIN_PIN;
		else
			CLEAR_DIN_PIN;
		
						//150 ns
		SET_DCLK_PIN;
						//150 ns
		CLEAR_DCLK_PIN;	
	}
	CLEAR_DIN_PIN;						//100 ns
	/*
	if (PINC & 0x04)		//kontrola BUSY
	{
		LCD_gotoXY(0,1);
		LCD_writeNumber(1);		
	}		
	else
	{
		LCD_gotoXY(0,1);
		LCD_writeNumber(0);	
	}	*/	
	_delay_ms(1);
	SET_DCLK_PIN;
		
	for (uint8_t i = 0; i < 16; i++)
	{
		CLEAR_DCLK_PIN;
		vystup <<=1;
		SET_DCLK_PIN;
		vystup |= (PINA & 0x01) ? 1 : 0;	

	}

	for (int i = 0; i < 8; i++)
	{
		CLEAR_DCLK_PIN;
		SET_DCLK_PIN;
	}
	CLEAR_DCLK_PIN;
	SET_CS_PIN;
	return vystup;
}


#endif /* ADC_INTERFACE_H_ */