/*
  FILE: ADDA1_1.C - WORKS!
  AUTH: P.OH
  DATE: 07/10/00
  DESC: SAME AS 1.0 BUT GIVES AVERAGE SAMPLING TIME.  WITH 1000 SAMPLES
	ON 386 16MHZ, WE GET 833 USEC AVERAGE SAMPLING TIME.
*/

#include<stdio.h>
#include<stdlib.h>
#include<dos.h>
#include<conio.h>
#include "pchrt.h"
 
#define IRQ3       0x0b   /* IRQ 3 address */
#define TRUE       1      /* Boolean for ISR */
#define FALSE      0      /* Boolean for ISR */
#define VREF       5      /* Reference voltage [V] for DAC and ADC */

/* globals */
int     EOC;
long unsigned hits, elapsed;         /* Needed for TCHRT */

/* prototypes */
void interrupt (*oldIrq3)(void);     /* IRQ3 hardware interrupt */
void interrupt newIrq3(void);        /* IRQ3 ISR */

void main(void)
{
  int   baseAddress = 608;
  int   adcData, dacData;         /* Acquired data, output data */
  int   i;                        /* Dummy counter variable */
  float samplingTime;             /* Sampling time [usec] */
  int   totalIterations = 1000;   /* 1000 samples */

  /* setup IRQ3 hardware interrupt */
  oldIrq3 = getvect(IRQ3);
  setvect(IRQ3, newIrq3);
  outportb(0x21, (inportb(0x21) & 0xF7));

  EOC = FALSE;

  clrscr();
  window(5,5,50,75);

  i = 0;
  t_request(1);
  t_start();  /* initialize all TCHRT-related calls */
  t_entry(0);

  do
  {
     i++;
     adcData = inportb(baseAddress);
     while(EOC == FALSE) { /* do nothing */ };
     adcData = inportb(baseAddress);
     dacData = 128*adcData/255 + 128;
     outportb(baseAddress, dacData);
     if(i == totalIterations)
      {
	 t_exit(0);
	 t_ask_timer(0, &hits, &elapsed);
	 samplingTime = (float)(elapsed/totalIterations);  /* [usec] */
	 gotoxy(2,10);
	 cprintf("Sampling time averaged over %d iterations", totalIterations);
	 gotoxy(2,11);
	 cprintf("is %f sec\n", samplingTime/1000000.0);
	 gotoxy(2,15); cprintf("Hit a key to quit\n");

      }
   } while (!kbhit());


   /* Return things back to original */
  setvect(IRQ3, oldIrq3);
  outportb(0x21, (inportb(0x21) | 0x08));
  printf("Bye!\n");

} /* end of main */

void interrupt newIrq3(void)
{
  #pragma asm pushf;    /* preserve interrupt flag */
  #pragma asm cli;
  EOC = TRUE;           /* signal end-of-interrupt (EOI) */
  outportb(0x20, 0x20); /* signal end-of-interrupt (EOI) */
  #pragma asm popf;     /* restore interrupt flag */
  return;
} /* end of newIrq3 */

