/* ************************ SCI0.C *****************************
 * Jonathan W. Valvano   March 27, 2000
 * Simple I/O routines to SCI0 serial port 
 * ************************************************************ */

#define RDRF 0x20   // Receive Data Register Full Bit
#define TDRE 0x80   // Transmit Data Register Empty Bit

//-------------------------Start of InitSCI------------------------
// Initialize Serial port SC0
void SCI0Init(void){
    SC0BDH=0;  // 38400 BR=13 (MCLK=8MHz) clock 
    SC0BDL=13; // BR=MCLK/(16*BaudRate)
    SC0CR1=0;
/* bit value meaning
    7   0    LOOPS, no looping, normal
    6   0    WOMS, normal high/low outputs
    5   0    RSRC, not appliable with LOOPS=0
    4   0    M, 1 start, 8 data, 1 stop
    3   0    WAKE, wake by idle (not applicable)
    2   0    ILT, short idle time (not applicable)
    1   0    PE, no parity
    0   0    PT, parity type (not applicable with PE=0) */ 
    SC0CR2=0x0C; 
/* bit value meaning
    7   0    TIE, no transmit interrupts on TDRE
    6   0    TCIE, no transmit interrupts on TC
    5   0    RIE, no receive interrupts on RDRF
    4   0    ILIE, no interrupts on idle
    3   1    TE, enable transmitter
    2   1    RE, enable receiver
    1   0    RWU, no receiver wakeup
    0   0    SBK, no send break */ 
    }
    
//-------------------------Start of SCI0InKey------------------------
// Wait for new serial port input, return ASCII code for key typed
char SCI0In(void){
   while ((SC0SR1 & RDRF) == 0){};
   return(SC0DRL);}
        
//-------------------------Start of SCI0Out------------------------
// Wait for buffer to be empty, output ASCII to serial port
void SCI0Out(char data){
   while ((SC0SR1 & TDRE) == 0){};
   SC0DRL = data;
   if(data==CR){   /* if CR add LF */
        while((SC0SR1 & TDRE) == 0){};
        SC0DRL = LF;}
   else if(data==LF){ /* if LF add CR */
        while((SC0SR1 & TDRE) == 0);
        SC0DRL = CR;}
}

//-------------------------Start of SCI0OutString------------------------
// Output String (NULL termination)
void SCI0OutString(char *pt){ char letter;
   while (letter=*pt++)
       SCI0Out(letter);}
    
//-------------------------Start of SCI0InStatus--------------------------
// Checks if new input is ready, TRUE if new input is ready
// Returns TRUE if a call to SCI0In will return right away
int SCI0InStatus(void){
   return(SC0SR1 & RDRF);}

//-----------------------Start of SCI0OutStatus----------------------------
// Checks if output data buffer is empty, TRUE if empty
// Returns TRUE if a call to SCI0Out will return right away
int SCI0OutStatus(void){
   return(SC0SR1 & TDRE);}
