/*  Filename     Z82G516COM2.C
    Description  82G516A COM2 Example Program
    Hardware     82G516A + RS232 com1,com2 
    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>

sfr      S2CON     = 0xaa;   // 82g516a sfr (com2)
sfr      S2BUF     = 0x9a;
sfr      S2BRT     = 0xba;
sfr      AUXR2     = 0xa6;

/********** I/O PORT **********/

sbit     LED       = P1^0;   // led 

/********** 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--;
    }
}

void sbytep (unsigned char x) {             // send one byte (polling)
    while (!TI);
    TI = 0;
    SBUF = x;
}

unsigned char rbytep (void) {               // receive one byte (polling) 
    while (!RI);
    RI = 0;
    return (SBUF);
}

void sbytep2 (unsigned char x) {            // send one byte com2 (polling)
    while ((S2CON & 0x02)==0);              // check S2TI 
    S2CON &= 0xfd;
    S2BUF = x;
}

unsigned char rbytep2 (void) {              // receive one byte com2 (polling) 
    while ((S2CON & 0x01)==0);              // check S2RI  
    S2CON &= 0xfe;
    return (S2BUF);
}

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

void start (void) {              
    SCON = 0x52;             	  // set com1 (8 bit uart)
    TMOD = 0x20;
    TH1 = 0xfd;                   // 19200 
    PCON |= 0x80;  
    TR1 = 1;

    S2CON = 0x52;                 // set com2 (8 bit uart)
    S2BRT = 0xfd;                 // 19200 (9600)
    AUXR2 = 0x18;                 // enable,double up
    dmsec (500);
}

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

void main (void) {
    unsigned char x;
    start ();
    printf ("82G516A COM2 Example Program ...\r\n");
    printf ("Connect COM1-RX to COM2-TX and COM2-RX to COM1-TX\r\n");
    while (1) {
        if (RI) {                      // com1-rx to com2-tx (change data +1)
            x = rbytep ();
            LED = 0;  
            sbytep2 (x + 1);
            LED = 1;   
        }
        if ((S2CON & 0x01)==0x01) {    // com2-rx to com1-tx (change data -1)
            x = rbytep2 ();
            LED = 0; 
            sbytep (x - 1);
            LED = 1; 
        }
    }
}












