/*     ADC control program.
       This program shows how to access the MC145050 Via the Printer Port.
       Replace the main body of this program to do what you want.
       MFL'94
#Define constants for use latter
*/
 
#define power 0x70
#define clock 0x4
#define cs  0x2
#define eoc  0x40
#define addressbit  0x8
#define datamask  0x80
#define BIT0  1
#define BIT1  2
#define BIT2  4
#define BIT3  8
#define outputaddress  0x378    /* lpt1 */
#define inputaddress  0x379

#include <stdio.h>
#include <conio.h>
#include <dos.h>

float sample(int);

 main()
 {
 int    j;
 float  Value;

/* initialise port give power & cs hi. */
outportb(outputaddress, power | cs);

/* Your code goes here. E.G.             */

Value=sample(0);  /* Dummy Read to set address. */

for(j=1;j<15;j++)
	{
	Value=sample(j);
	printf("\t$f\n",Value);
	};

/* Power Down.  */
outportb(outputaddress, 0);

return (0);
};

/* Now read in a sample... This is the Function that does it all
   Order of events...
   Wait for EOC.       Make sure its ok to read the ADC.
   Chip Select low.
   Output the address MSB first onto the ADDR pin of the ADC
   Read in the result of the last conversion.
   and put it in the LSB of the Value read in.
   Clock the ADC.
   Move on to next bit of address. when past the end of the real 4bit address 
   all zero's are output.
   Repeat address, data and clock loop for all data bits (10)
   Chip select HIGH.   This with the clocked data transfer has started the 
   next conversion on the channel specified in the address sent.
   Convert Value into Volts.
   Note that BUSY is inverted so data bits have to be inverted before they 
   are used.
*/
float sample(int nexttosample)
{
int     Value = 0;
int     nextaddress = nexttosample & 0xF;


/* wait for EOC */
while (inportb(inputaddress) & eoc) == 0);

/* before clock data put the cs lo. */
outportb( outputaddress, power );

for(i=0;i<10;i++)
	{
	/* output the address  */
	outportb( outputaddress, power | (nextaddress & addressbit));

	/* read in data bits MSB first.   */
	Value = ((inportb(inputaddress) & datamask) / 128) | (Value * 2);

	/* rising edge of clock...  */
	outportb( outputaddress, clock | power | (nextaddress & addressbit));

	/* Move to next bit of address, if past the end zeros outputed.  */
	nextaddress *= 2;
	};

/* finished therefore cs to hi.  Therefore start next conversion. */
outportb(outputaddress, power | cs);

/* convert to volts and return */
Value = (Value ^ 0x3FF) & 0x3FF;

return (((float)Value))*(2.5/1024.0));

};

