//  A to D test code
// NOTE -- You MUST mount the Aref jumper  

#include <Mega32.h>
#include <stdio.h> // sprintf 
#include <stdlib.h>

//I like these definitions
#define begin {
#define end   } 
#define Vref 4.95 

int Ain, AinLow ; 		//raw A to D number
float voltage ;		//scaled input voltage

void main(void)
begin 
   
   //init the A to D converter 
   //channel zero/ right adj /ext Aref
   //!!!CONNECT Aref jumper!!!!
   ADMUX = 0b00000000;   
   //enable ADC and set prescaler to 1/127*16MHz=125,000
   //and set int enable
   ADCSR = 0b10001111; 
   MCUCR = 0b10010000; //enable sleep and choose ADC mode 
   
   //init the UART
   UCSRB = 0x18;
   UBRRL = 103;
   printf("starting...\n\r");
                                
   #asm
   	sei
   #endasm
      
   // measure and display loop
   while (1)
   begin   
	    //get the sample  
	    //The sleep statment lowers digital noise   
	    //and starts the A/D conversion
	    #asm
 	   sleep
        #endasm  
        
        //program gets here when conversion is done
      	voltage = (float)Ain ;
      	voltage = (voltage/1024.0)*Vref ; //(fraction of full scale)*Vref
      	printf("%f\n\r", voltage) ;
      	printf("\n\r") ;
   end
end
     
interrupt [ADC_INT] void adc_done(void)
begin 
   //when reading 10-bit values 
   //you MUST read the low byte first 
   AinLow = (int)ADCL;
   Ain = (int)ADCH*256; 
   Ain = Ain + AinLow;
end