/******************************************************************\

   IOE_AD.C
   
   BL11xx/Little Giant with IOE-A/D expansion board. 

   The following functions are used in this sample program:

   int exp_init(int ppia, int ppib, int ppicu, int ppicl);
   int ad20_mux (int chan);
   int ad20_cal (int mode);
   int ad20_rdy ();
   long ad20_rd ();

   Always run exp_init() first to initial ppicn,ppida,ppidb,ppidc,rdttl,pal.

   This sample program is designed for measuring the voltage difference 
   from a set value using the AD7703 20-bit ADC, LT1101 instrumentation 
   amplifier, and the Op07 op. amp.

   LT1101 has a fixed gain of 10, Op-07 has a gain of 1 with 
   R1=R2=R10=R11=2K. Total signal gain = 10.
   Due to the system error, n = 25 is used to average the A/D readings. 
       
   
\******************************************************************/

int i, j, k, m, n;
char par;
long sum [100];
long dat, dat1, dat2;
float volts;

main()
{
   exp_init (0, -1, -1, -1);
   ad20_mux (0); /* Unipolar, select multiplexer AN0, Zero input for cal. */
   
   for (j = 0;j < 30000; j++) hitwd();   /* delay for ? */
   for (j = 0;j < 30000; j++) hitwd();   /* delay for ? */

   par = inport(PPIA);

   while (1)
   {
   	hitwd();
      i = 0;
      wdac (i);
      ad20_cal (0);           /* Mode 0 self calibration   */
      printf ("CALIBRATION\n");

      for(j=0;j<30000;j++);   /* delay for ? */
      for(j=0;j<30000;j++);   /* delay for ? */
      
      n = 100;
      for (m = 0; m < n; m++)
      {
      	hitwd();
         for (j = 0; j < 2000; j++);   /* delay for ? */
         while (ad20_rdy ()) hitwd();          /* wait for A/D */
         sum[m] = ad20_rd ();
      }
      
      dat = 0;
      for (m = 0; m < n; m++) {
         dat += sum [m];
         hitwd();
      }

      dat1 = dat / n;
      dat1++;
   
      /* continue 200 times display input voltage in millivolts */
      for (k = 0; k < 200; k++)
      {
      	hitwd();
         i++;
         wdac (i);              /* If you have a DAC connect it to mux */

         n = 25;
         for (m = 0;m < n; m++)
            sum[m]=0;
         
         for (m = 0; m < n; m++)
         {
         	hitwd();
            for (j = 0; j < 2000; j++);   /* delay for ? */
            while (ad20_rdy ()) hitwd();
            sum[m] = ad20_rd ();
         }
      
         dat=0;
         for (m = 0; m < n; m++)
            dat += sum[m];

			hitwd();
         dat2 = dat / n;
         volts = (dat2 - dat1) * 0.0000002384186;    /* calculate volts */
         printf ("%10.6f mV %d\n", volts*1000, i);
      }
   }
}

/********************************************** End of IOE_AD.C ********/
