Analog to Digital


Analog to Digital conversion on TB-1 board

Toolkit:AVR Development System

Location:/bipom/devtools/WinAVR/minimaxavrc/Examples/Labs/Lab04

Code Example


#define ADCCS           2        //PB2

#define ADCCLK          0        //PD0

#define ADCDIN          7        //PD7



#define ADCCS_CLR() 	(PORTB	&=~ 0x04)
#define ADCCLK_CLR()  	(PORTD	&=~ 0x01)
#define ADCDIN_CLR()  	(PORTD	&=~ 0x80)

#define ADCCS_SET()     (PORTB	|= 0x04)
#define ADCCLK_SET()   	(PORTD	|= 0x01)
#define ADCDIN_SET()   	(PORTD	|= 0x80)


unsigned char Convert(unsigned char channel);
void Clock();

//======================== MAIN ======================

int main(void)
{
unsigned char channel,value;

	//Initialize port pins

 	/* Define pull-ups and set outputs */
	/* Define directions for port pins */
	PORTB |= (1<<ADCCS);
	DDRB  |= (1<<ADCCS);
	PORTD |= (1<<ADCDIN)|(1<<ADCCLK);
	DDRD  |= (1<<ADCDIN)|(1<<ADCCLK);

	/* Initialize the UART */
	uart0Init(19200);	
	channel=0;

	while(1)// loop forever

	{
		value=Convert(channel);
		uart0Printf("\n\rChannel %d Value:%d",channel,value);
		_delay_ms(1000);
		channel++;
		if(channel>3)channel=0;
	}
}


/****************************************************************
*
* Function : Convert 
*
* Discription : A/D conversion with ADC0834  (8bits)
*
* Input  : channel 0..3
*
* Output : analog value
*
*
*****************************************************************/
unsigned char Convert(unsigned char channel)
{
unsigned char value,i;
	
	/* Reset the A/D converter */	
	ADCCS_SET();
	ADCCLK_CLR() ;
	ADCDIN_SET();
	
	/**** Start Conversion ****/
	
	ADCCS_CLR();
	_delay_ms(1);
	
	/* Start bit */
	ADCDIN_SET();
	Clock();
	
	/* SGL/DIF */
	ADCDIN_SET();
	Clock();

	if( channel & 0x01 )
	{
		ADCDIN_SET();
	}
	else
	{
		ADCDIN_CLR();
	}
	Clock();

	/* SELECT */
	
	if( channel & 0x02 )
	{
		ADCDIN_SET();
	}
	else
	{
		ADCDIN_CLR();
	}
	Clock();
	
	/* 1 millisecond _delay_ms for the Multiplexer to settle */
	_delay_ms(1);
	Clock();
	
	value = 0;
	ADCDIN_SET();

	/*Pin ADCDIN configure is input*/
	DDRD &= ~(1<<ADCDIN);
	PORTD |= (1<<ADCDIN);
	/* Clock out the 8-bit data from A/D converter */
	for( i=0; i<8; i++ )
	{
		if( PIND & 0x80 )value |= 1;		
		Clock();
		if( i < 7 )value = value << 1;		
	}

	/*Pin ADCDIN configure is output*/
	DDRD  |= (1<<ADCDIN);
	PORTD |= (1<<ADCDIN);
	for( i=0; i<8; i++ )
	{
		Clock();
	}
	return value;
}




/****************************************************************
*
* Function : Clock 
*
* Discription : Genarate clock for A/D converter ADC0834  
*
* Input  : none
*
* Output : none
*
*
*****************************************************************/
void Clock()
{
	ADCCLK_SET();
	ADCCLK_SET();		/* A little _delay_ms */
	_delay_ms(1);
	ADCCLK_CLR() ;
	_delay_ms(1);
}