//Daniel Kohn
//ELEN 621
//Lab#: 8 - ATD 
//Date: 11/17/06
//****************** INCLUDE FILES ************************

#include <mc9s12dp256.h>      //DP256 header file
#include <stdio.h>		//Standard I/O C header


//****************** ISR Setup ***************************

#define CLI asm("CLI")

void ATD_Interrupt();

#pragma interrupt_handler ATD_Interrupt()
#pragma abs_address: 0x3FD2
void (*IRQ_vector[])()={ATD_Interrupt};
#pragma end_abs_address

//******************** function Prototypes ****************

void atd_init(void);
void delay_100us(void);	

// ******************* Initialize ATD *******************
void atd_init()
{
   ATD0CTL2 = 0xC2;
   ATD0CTL3 = 0x20;
   ATD0CTL4 = 0xE7;

   CLI;
}

/********************************************************************/ 
/*100us delay based on an 8MHz clock (Textbook 7.3.5)               */
/********************************************************************/

void delay_100us(void)
{
int i;

for (i=0; i<50; i++)
  {
  asm("nop");
  }
}

/************************ main ***************************************/ 

void main(void)
{
   atd_init();
   delay_100us();
   ATD0CTL5 = 0xA0;
   while(1);  	   		  // loop indifinitly (wait for interrupt)
}

/********************************************************************/
/* This code is primarily taken from example 7.3.5 in the text      */
/* and then converted to act as an ISR                              */
/********************************************************************/
  	  
void ATD_Interrupt(void)
{
unsigned int sumadr;
float avg_bin_voltage;
float analog_voltage;

/*print results to PC screen for testing             */		
// printf("%x %x %x %x\n", ATD0DR0L, ATD0DR1L, ATD0DR2L, ATD0DR3L);

/*average four results for noise reduction                */
sumadr = ATD0DR0L + ATD0DR1L + ATD0DR2L + ATD0DR3L;
avg_bin_voltage = (float) sumadr/4;

/*convert binary result to analog voltage between 0.00 (Vrl) and 5.00 (Vrh)         */
analog_voltage = (float) (avg_bin_voltage/255)*5;

/* print result to PC screen 						*/
printf("The voltage on Channel 0 is %4.3f \r", analog_voltage);
}
