/*  Filename     Z82E54AD.C
    Description  82E54AE2 A/D Example Program
    Hardware     PRO-MISP with VR
    Clock        11.0592 Mhz
    Compiler     Keil PK51 v7.10
    Engineer     Kriangsak B. 
    Company      Sila Research Co.,Ltd. 
*/

#include <reg52.h>
#include <absacc.h>
#include <assert.h>
#include <ctype.h>
#include <intrins.h>
#include <math.h>
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

                             // 82E54A 
sfr      P1M0      = 0x91;   // port-1 configuration
sfr      P1M1      = 0x92;
sfr      ADCTL     = 0xC5;   // ADC control
sfr      ADCV      = 0xc6;   // ADC value
sfr      ADCVL     = 0xbe;

/********** BASIC FUNCTION **********/

void dmsec (unsigned int count) {           // mSec Delay
    unsigned int i;                         // for Keil PK51 (Speed x 12) 82E54AE2
    while (count) {
        i = 850; while (i>0) i--;
        count--;
    }
}

char putchar (unsigned char x) {            // change putchar for printf  
    while (!TI);
    TI = 0;
    return (SBUF = x);
}

/********** START FUNCTION **********/

void start (void) {               // speed x 1
    SCON = 0x52;             	  // set RS232 parameter
    TMOD = 0x20;
    TH1 = 0xfd; PCON |= 0x80;     // 19200
    TR1  = 1;

    P1M0 |= 0x01;                 // set P1.0 = input only (high-impedance)
	P1M1 |= 0x00;
	dmsec (100);
    ADCTL = 0x98;                 // ADC on,speed=1080,start,P1.0
	dmsec (100);
}

/********** MAIN **********/

unsigned int read_ad (void) {
    unsigned int x;
    while ((ADCTL & 0x10)==0);    // check convert flag
	x = ADCV;                     // 10 bit data
	x = (x << 2) | ADCVL;
	ADCTL &= 0xef;                // clear interrupt flag
	                              // set for next read  
    ADCTL = 0x98;                 // ADC on,speed=1080,start,P1.0
	return (x);
}

void main (void) {
    unsigned int x;
	float v;
    start ();
    printf ("Test 82E54AE2 A/D ...\r");
    while (1) {
	    x = read_ad ();
		v = x;
        v = (v * 5) / 1023;
        printf ("AIN0=%04X (Volt=%01.2f)\r",x,v);
        dmsec (250);
    }
}


