#include <REG51.H>                /* special function register declarations   */                                 /* for the intended 8051 derivative         */
#include <stdio.h>                /* prototype declarations for I/O functions */
#ifdef MONITOR51                         /* Debugging with Monitor-51 needs   */
char code reserve [3] _at_ 0x23;         /* space for serial interrupt if     */
#endif                                   /* Stop Exection with Serial Intr.   */                               /* is enabled                        */ 
sbit  ALE	=	P2^7  ;
sbit  OE	=	P2^4 ;
sbit  START =	P2^3 ;
sbit  EOC   =	P2^6 ;
sbit  SEL_A =	P2^2 ;
sbit  SEL_B =	P2^1 ;
 	
#define ADC_DATA P1
  

 unsigned char ADC_rezult();
 unsigned char ADC_rezult()
  
 {
    unsigned char adc_data;
  	EOC = 1; 
	ALE = OE = START = 0; 	
		/* Select channel 1 */
		SEL_A = 1; /* LSB */
		SEL_B = 0;
	//	SEL_C = 0; /* MSB */ 
		/* Latch channel select/address */
		ALE = 1;
		/* Start conversion */
		START = 1; 	    
		ALE = 0;
		START = 0;
		/* Wait for end of conversion */
		while (EOC == 1);
	    while (EOC == 0);
 		
		/* Assert Read signal */
		OE = 1;
		/* Read Data */
		 	
		adc_data = ADC_DATA;			
		OE = 0;
		return adc_data;
 } 

void main () {
 P3 = 0x22;
 ADC_DATA = 0xff; 
#ifndef MONITOR51

    SCON  = 0x50;		        /* SCON: mode 1, 8-bit UART, enable rcvr      */
	ET0 = 1;
    TMOD |= 0x20;               /* TMOD: timer 1, mode 2, 8-bit reload        */
    TH1   = 221;                /* TH1:  reload value for 1200 baud @ 16MHz   */
    TR1   = 1;                  /* TR1:  timer 1 run                          */
    TI    = 1;                  /* TI:   set TI to send first char of UART    */
//	EA = 1;
//	TR0 = 1;
#endif

  while (1)
   {  	
    	 
    	ADC_rezult();
	   	printf ("%u\n", ADC_rezult()); 
   }
}
