/*
  FILE: ADC.C
  AUTH: P.OH - Boondog Automation
  DATE: 08/30/00
  DESC: Loops continuously and collects data
	into a file.  Use arrays and then write to file.
*/

#include<stdio.h>
#include<dos.h>
#include<stdlib.h>
#include<conio.h>

#define IRQ3         0x0b      /* IRQ3 */
#define BASEADDRESS  608       /* Shorting block on row 4 of card */
#define TRUE         1         /* Boolean */
#define FALSE        0         /* Boolean */
#define MAXSIZE      5000      /* Total number of samples */

/* globals */
int   EOC;                     /* End of conversion boolean */
int   readData;                /* Byte acquired from ADC (in decimal) */
float i;                       /* Sample iteration number */
float data[MAXSIZE][2];        /* Array of acquired samples */
FILE* fp;                      /* File pointer to ASCII data file */
int   j;                       /* Dummy counter variable */

/* prototypes */
void interrupt (*oldIrq3)(void);  /* IRQ 3 original setting */
void interrupt eocTrue(void);     /* IRQ 3 new ISR */

int main(void)
{
  clrscr();
  fp = fopen("data.txt", "wt");   /* ASCII data file */

  /* initialize data array to 0.0 */
  for(j=0; j < MAXSIZE; j++) {
    data[j][0] = 0.0;
    data[j][1] = 0.0;
  };
  printf("data array initialized\n");

  i = 0.0;
  oldIrq3 = getvect(IRQ3);  /* Set up the ISR we call eocTrue */
  setvect(IRQ3, eocTrue);
  outportb(0x21, ( inportb(0x21) & 0xF7 ) );

  EOC = FALSE;

  do {
    readData = inportb(BASEADDRESS);  /* Do first read of Channel 0 */
    while(EOC == FALSE) { /* do nothing until EOC true */ };
    readData = inportb(BASEADDRESS);  /* Read Channel 0 again */
    EOC = FALSE; /* Reset to FALSE */
    data[i][0] = i;
    data[i][1] = (float)(readData * 5.0/255.0); /* Volts calculation */
    i++;
  } while(i < MAXSIZE);

  printf("Writing to file...\n");
  for(j=0; j < MAXSIZE; j++) {
    fprintf(fp, "%f\t%f\n", data[j][0], data[j][1]);
  };
  printf("done\n");

  fclose(fp);
  setvect(IRQ3, oldIrq3);
  outportb(0x21, (inportb(0x21) | 0x08) );

  printf("Bye!\n");
  return 0;

} /* end of main */

/* this ISR should execute each time IRQ3 is triggered i.e. IRQ3 = HIGH */
void interrupt eocTrue(void)
{
  #pragma asm pushf;
  #pragma asm cli;
  EOC = TRUE;
  outportb(0x20, 0x20);
  #pragma asm popf;
  return;
} /* end of eocTrue */