/************************************************************************/
/* Program Name: ATOD3.C                                                */
/* Description: Program reads the analog inputs, converts to digital,   */
/*              and displays eight channels of readings on terminal.    */
/*              Program is written for NMIX/T-0020 + AD/DA (SPCL-0102). */
/* Date : Dec.30,1994.                                                  */
/************************************************************************/

/* FORTH version */

/* Define where the program should reside. */
#code   0x0800   /* RAM needs to be installed on U2 socket */
#data   0x0700

/* Link in the device driver for the 68HC11 */
#include <FORTH.k>
#include <FOR_out.c>
#include <FOR_in.c>
#include <68hc11.h>
#include <stdio.h>

/* Link in the libraries  */
#include <fopen.c>
#include <fputs.c>
#include <fputc.c>
#include <itoa.c>
#include <atoi.c>
#include <is.c>
#include <fprintf.c>
#include <itoab.c>
#include <reverse.c>
#include <strlen.c>
#include <delay.c>

/* define A/D registers */
#define AD_CONV 0xB5FA  /* A/D converter */
#define AD_MULT 0xB5F8  /* A/D multiplexer channel */

FILE stdout;

void title()
{
   fputs("\n Starting A/D conversion...\n\n",stdout);
   fputs("                     CHANNEL READINGS \n",stdout);
   fputs("   CH-0   CH-1   CH-2   CH-3   CH-4   CH-5   CH-6   CH-7\n",stdout);
   fputs("   ~~~~   ~~~~   ~~~~   ~~~~   ~~~~   ~~~~   ~~~~   ~~~~\n",stdout);
   return(0);
}

/* A/D input channel selection */
inp_chnl(j)
unsigned int j;
{
   unsigned int ch;
   switch(j)
   {
      case 0 : ch =  7; break;   /* channel #0 =  7 */
      case 1 : ch =  6; break;   /*   "     #1 =  6 */
      case 2 : ch =  5; break;   /*   "     #2 =  5 */
      case 3 : ch =  4; break;   /*   "     #3 =  4 */
      case 4 : ch = 11; break;   /*   "     #4 = 11 */
      case 5 : ch = 10; break;   /*   "     #5 = 10 */
      case 6 : ch =  9; break;   /*   "     #6 =  9 */                             
      case 7 : ch =  8; break;   /*   "     #7 =  8 */
   }
   return(ch);
}

/* Reads the inputs, and displays eight channel readings on terminal. 
   Values are in decimals, and the blanks after decimal points are 
   considered as zeros.  */
void scan_AD()       
{
  unsigned int i, channel, ch_array[8];
  for(i = 0; i <= 8; i++)
  {
    channel = inp_chnl(i);
    pokeb(AD_MULT,channel);
    pokeb(AD_CONV,0);
    delay(period1);
    ch_array[i]=((peek(AD_CONV) >> 4) & 0xFFF);
    fprintf(stdout,"%4d.%2d",ch_array[i]/409,((ch_array[i]%409)*100)/409);
  }
  return(0);
}

main()
{
   unsigned int period1, period2;
   period1 = 500;
   period2 = 1000; 
   stdout=fopen(FOR_out);
   title();
   while(1)
   {
     scan_AD();
     fprintf(stdout,"\n");
     delay(period2);              
   }
   return(0);
}

