/*
  sci.c 
*/

#include "XTWR-MCF51JE.h"
#include "sci.h"

void SCI_set_baudrate(UINT8 port, UINT16  br)   	
   	
{
   register UINT16 var_temporal;
      
   var_temporal = (UINT16)((BUS_CLOCK)/(br * 16));
    
    switch(port)
    {
      case 1: SCI1BD = var_temporal; 
        
        break;
        
      case 2: SCI2BD = var_temporal;
     
        break;
        
      default:
        for(;;)
        ; /*error*/
        break;
    }
    
}


void vfnSCI_init(UINT8 port, UINT16 br)
{

    /*ENABLE_MUX_CONTROL;*/

    switch(port)
    {
      /*SCI function*/
      case 1:
      {
        /*starting SCI clock*/
        SCGC1_SCI1 = 1;

        SCI_set_baudrate(port, br);
        SCI1C1 = 0x00;            /* start + 8 data bits (LSB first) + stop */
        SCI1C2_TE = 1;            /* enable transmitter */
        SCI1C2_RE = 1;            /* enable transmitter */
      }break;
        
      case 2:
      {
        /*starting SCI clock*/
        SCGC1_SCI2 = 1;

        SCI_set_baudrate(port, br);
        SCI2C1 = 0x00;            /* start + 8 data bits (LSB first) + stop */       
        SCI2C2_TE = 1;            /* enable transmitter */
        SCI2C2_RE = 1;            /* enable transmitter */     
      }break;
        
      default:
        for(;;)
        ; /*error*/
        break;
    }
    
    /*DISABLE_MUX_CONTROL;  */
}                        

UINT8 u8SCI_SendChr(UINT8 port, INT8 _char)
{
    UINT16 timeout = TIMEOUT_VALUE;
    UINT8 delay;
    
    for(delay=0; delay<100; delay++){};
    
    switch(port)
    {
      /* CI functions */
      case 1:
        while(!SCI1S1_TDRE) 
        {
           if(!(--timeout))
           {
               return -1;
           }
        };/*wait until  we have space*/
        SCI1D = (byte)_char;      /* 2nd part of the cleaning procedure for TRDE */
        break;
        
      case 2:
        while(!SCI2S1_TDRE)        
        {
           if(!(--timeout))
           {
               return -1;
           }
        };/*wait until  we have space*/
        SCI2D = (byte)_char;    /* 2nd part of the cleaning procedure for TRDE*/
        break;
        
      default:
        for(;;)
        ; /*error*/
        break;
    }
}

void vfnSCI_SendMsg(UINT8 port, INT8 *str)
{
    while(*str) u8SCI_SendChr(port,*str++);        
}


UINT8 u8SCI_Receivechar(UINT8 port, UINT8 *p_rx)
{
    switch(port)
    {
      /*SCI functions*/
      case 1:
         if (SCI1S1_RDRF) 
         {
           *p_rx = SCI1D;
           return 0;
         }   
         else
           return 1;  /*NO data received*/
        break;
        
      case 2:
         if (SCI2S1_RDRF) 
         {
           *p_rx = SCI2D;
           return 0;
         }   
         else
           return 1;  /*NO data received*/     
        break;
        
      default:
        for(;;)
        ; /*error*/
        break;
    }
}    


