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

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

   The following functions are used in this sample program:

   int exp_init_n (int node, int ppia, int ppib, int ppicu, int ppicl, int def);
   int ad20_mux_n (int node, int chan, int def);
   int ad20_cal_n (int node, int mode, int def);
   int ad20_rdy_n (int node);
   long ad20_rd_n (int node, int def);

   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;
long sum [100];
long dat, dat1, dat2;
float volts;

main()
{
   exp_init_n (3, 0, -1, -1, -1, 1);
   ad20_mux_n (-1, 0, 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 ? */

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

      for(j=0;j<30000;j++) hitwd();   /* delay for ? */
      for(j=0;j<30000;j++) hitwd();   /* delay for ? */
      
      n = 100;
      for (m = 0; m < n; m++)
      {
      	hitwd();
         for (j = 0; j < 2000; j++);   /* delay for ? */
         while (ad20_rdy_n (-1)) hitwd(); /* wait for A/D, cannot set def */
         sum[m] = ad20_rd_n (-1, 0);
      }
      
      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;
            hitwd();
         }
         
         for (m = 0; m < n; m++)
         {
            for (j = 0; j < 2000; j++);   /* delay for ? */
            while (ad20_rdy_n (-1)) hitwd();
            sum[m] = ad20_rd_n (-1, 0);
         }
      
         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_N.C ********/
