


#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ADuC845.h>    //To use this with an ADuC847 or ADuC848, simply change the
					    //header file to <ADuC847.h> or <ADuC848>

#define MAX 20
 
sbit LED = 0x0B4;


unsigned short int adcSamples[MAX];
int indexSample = 0;
volatile int flag = 0;

void delay(int count);

void ADC_Interrupt () interrupt 6
{
  unsigned short int adcH = ADC0H;

  if(indexSample < MAX)
  {
    adcSamples[indexSample++] = adcH;
    RDY0 = 0;
    //printf("indexSample: %d n", indexSample);
    //printf("Dec Value: %d n", adcH);
    LED ^= 1;
    //delay(1);

  }
  else
  {
    //printf("Exceeded Index Samplen");
    flag = 1;  //Cause main loop failure
    RDY0 = 1;           //Ensure primary ADC cannot be triggered
    ADCMODE &= 0x00;    //Disable primary ADC device 
    EADC = 0;           //Disable ADC Interrupt
    LED ^= 1;
  }

  return;
}

void main (void)
{
  int i = 0;
  int sum = 0;
  float average = 0;

  //Configure UART
  T3CON = 0x83;	//9600 Baud rate
  T3FD = 0x12;
  SCON = 0x52;

	//CONFIGURE ADC AND START CONVERTING....
  SF = 0x45;
  ADC0CON1 = 0x27;	  //Full Buffer, Unipolar, 0 - 650 mV range.
  ADC0CON2 = 0x01;	  //Refin+/-, Ain2
  EADC = 1;           //Enable ADC Interrupt
  EA = 1;             //Enable Global Interrupts
  ADCMODE = 0x03;	    //Continuous conversion on primary ADC device
  ADCMODE |= 0x20;    //Primary ADC Enable

  delay(5);
	while(flag == 0); 	//WAIT FOR INTERRUPTS....
  
  printf("Flag after interrupt loop %d n", flag);


  //printf("Escaped Interrupt Loopn");
  for(i = 0; i < MAX; ++i)
  { 
    sum += adcSamples[i];
    printf("adc Sample %d: %dn", i, adcSamples[i]); 
  }

  average = ceil(sum/20);
  printf("Average: %.2fn", average);
  
  delay(5);
  RDY0 = 1;           //Ensure primary ADC cannot be triggered
  ADCMODE^5 = 0;    //Disable primary ADC device 
  EADC = 0;           //Disable ADC Interrupt
  //PCON = 0x02; //Power Down to stop interrupt
  return;
}


void delay(int count)
{
  int i;
  int j;
  int max = 32766;
  
  for(i = 0; i < count; ++i)
  {
    for(j = 0; j < max; ++j);
  }
}
