/********************************************************************/
/*filename: voltmeter.c                                             */
/* This program will create a simple voltmeter using the onboard    */
/* analog-to-digital converter in the 68HC12.  It will perform one  */
/* conversion and then the user will have to manually restart the   */ 
/* program to convert another voltage.                              */
/********************************************************************/
 
#include <912b32.h>
#include <stdio.h> 
 
#define DECIMAL 0x2E                   /*macro: decimal point in ASCII*/
#define V 0x56                         /*macro:  "V" in ASCII*/
 
/*function prototypes*/
void delay_100us(void);		
void ADC_convert(void);	

 
 
void main(void)
{
printf("HELLO\n");
ATDCTL2 = 0x80;                        /*power up ADC, disable interrupts*/
printf("ADC2\n");
delay_100us();                         /*wait for ADC to warm up*/
printf("warmed up\n");
ATDCTL3 = 0x00;                        /*select active background mode*/
ATDCTL4 = 0x01;                        /*sample time 2 ADC clk, prescale 4 */
printf("ready\n");
ADC_convert();                         /*perform conv, convert value*/
}
 
/********************************************************************/ 
/* void ADC_convert(void): function to perform a single conversion  */
/* and stores it for user access. The function then converts the    */
/* binary result to an analog (floating point) value and outputs    */
/* to the PC display.        					    */
/********************************************************************/
  	  
void ADC_convert(void)
{
unsigned int sumadr;
unsigned int avg_bin_voltage;
float	analog_voltage;

		
ATDCTL5 = 0x06;                        /*perform 4 conv, ch 6*/  
	
while((ATDSTAT & 0x8000) != 0x8000)	 
  {                     /*Wait for conversion to finish*/ 
  ;
  }

/*print results to PC screen for verification             */		
printf("%x %x %x %x\n", ADR0H, ADR1H, ADR2H, ADR3H);

/*average four results for noise reduction                */
sumadr = ADR0H + ADR1H + ADR2H + ADR3H;
avg_bin_voltage = 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 6 is %4.3f \n", voltage);
}

 
/********************************************************************/ 
/*100us delay based on an 8MHz clock                                */
/********************************************************************/

void delay_100us(void)
{
int i;

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


