#include "REG_MG84FL54.H"
#include "Define.H"
#include "Extern.H"
#include "TWSI.H"


BYTE OutLen = 0;
XBYTE OutBuffer[TWSI_MAX] _at_ (0x200-TWSI_MAX); // XRAM total 576(0~575) bytes ( 512~575
                                                 // for InBuffer , 448~511 for OutBuffer )

TWSI Twsi;


void TWSI_Send_Data_To_PC( void )
  { if ( OutLen )
      { USB_Send_Data_To_PC( OutLen , OutBuffer );
        OutLen = 0;
        AUXIE |= ETWSI;                          // Enable TWSI int
      }
  }


void TWSI_Send_Data_To_Device( void )
  { Twsi.InIndex = 0;                            // Into Master Transimitter 
    Twsi.Dev = TWSI_DEVICE_ADDRESS << 1;
    Twsi.Dev += TWSI_DEVICE_WRITE;
    
    Twsi.Stage = TWSI_IDLE;
    STA = SET;                                   // Generate a START
    
    while ( 1 )
      { TWSI_Send_Data_To_PC();
      	if (( Twsi.Stage == TWSI_ERROR )||( Twsi.Stage == TWSI_STOP ))
          break;
      }
    
    if ( Twsi.Stage == TWSI_ERROR )
      InLen = 0;
    else                                         // Into Master Receiver 
      { Twsi.InIndex = 0;
        Twsi.Dev = TWSI_DEVICE_ADDRESS << 1;
        Twsi.Dev += TWSI_DEVICE_READ;
        
        Twsi.Stage = TWSI_IDLE;
        STA = SET;                               // Generate a START
        
        while ( 1 )
          { TWSI_Send_Data_To_PC();
            if (( Twsi.Stage == TWSI_ERROR )||( Twsi.Stage == TWSI_STOP ))
              break;
          }
        
        if ( Twsi.Stage == TWSI_ERROR )
          InLen = 0;
      }
  }

void Initial_TWSI( void )
  { P2M0 = 0x03;                                 // Set P2.0 , P2.1 Open_Drain Output
    P2M1 = 0x03;                                 // Set P2.0 , P2.1 Open_Drain Output
    ENSI = SET;                                  // Enable TWSI
    CR1 = SET;                                   // CLK = 200K
    CR0 = SET;
    
    SIADR = TWSI_SLAVE_ADDRESS << 1;             // bit.0 -> GC , disable
    AA = SET;                                    // Assert ACK for SLAVE mode
    
    AUXIE |= ETWSI;                              // Enable TWSI int
//    AUXIP |= PTWSI;                              // TWSI int HIGH priority
  }