/** ###################################################################
**     THIS BEAN MODULE IS GENERATED BY THE TOOL. DO NOT MODIFY IT.
**     Filename  : BADGEI2C.C
**     Project   : DC17
**     Processor : MC56F8006_32_LQFP
**     Beantype  : InternalI2C
**     Version   : Bean 01.225, Driver 02.01, CPU db: 3.00.169
**     Compiler  : Metrowerks DSP C Compiler
**     Date/Time : 4/21/2009, 2:29 PM
**     Abstract  :
**          This bean encapsulates the internal I2C communication 
**          interface. The implementation of the interface is based 
**          on the Philips I2C-bus specification version 2.0. 
**          Interface features:
**          MASTER mode
**            - Multi master communication
**            - The combined format of communication possible 
**              (see "Automatic stop condition" property)
**            - 7-bit slave addressing (10-bit addressing can be made as well)
**            - Acknowledge polling provided
**            - No wait state initiated when a slave device holds the SCL line low
**            - Holding of the SCL line low by slave device recognized as 'not available bus'
**            - Invalid start/stop condition detection provided
**          SLAVE mode
**            - 7-bit slave addressing
**            - General call address detection provided
**     Settings  :
**         Serial channel              : I2C
**
**         Protocol
**             Mode                    : MASTER - SLAVE
**             Slave address           : 0
**             Empty character         : 0
**             Auto stop condition     : yes
**             SCL frequency           : 50 kHz
**
**         Initialization
**
**             Target slave address    : 0
**             Bean function           : Enabled
**             Events                  : Enabled
**
**         Registers
**             Input buffer            : I2C_DATA  [61732]
**             Output buffer           : I2C_DATA  [61732]
**             Control register        : I2C_CR1   [61730]
**             Status register         : I2C_SR    [61731]
**             Baud setting reg.       : I2C_FREQDIV [61729]
**             Address register        : I2C_ADDR  [61728]
**
**         Interrupt
**             Vector name             : INT_I2C
**             Priority                : 0
**
**         Used pins                   :
**       ----------------------------------------------------------
**            Function    | On package |    Name
**       ----------------------------------------------------------
**              SDA       |     19     |  GPIOB4_ANA0_ANB0_MISO_SDA_RXD_T0_CLKO_0
**              SCL       |     21     |  GPIOB0_ANB13_PWM3_SCLK_SCL_T1
**       ----------------------------------------------------------
**     Contents  :
**         Enable               - byte BADGEI2C_Enable(void);
**         Disable              - byte BADGEI2C_Disable(void);
**         SendBlock            - byte BADGEI2C_SendBlock(void* Ptr, word Siz, word *Snt);
**         RecvBlock            - byte BADGEI2C_RecvBlock(void* Ptr, word Siz, word *Rcv);
**         ClearRxBuf           - byte BADGEI2C_ClearRxBuf(void);
**         SelectSlave          - byte BADGEI2C_SelectSlave(byte Slv);
**         SelectSpecialCommand - byte BADGEI2C_SelectSpecialCommand(byte Cmd);
**         SetMode              - byte BADGEI2C_SetMode(bool MasterMode);
**
**     (c) Copyright UNIS, a.s. 1997-2008
**     UNIS, a.s.
**     Jundrovska 33
**     624 00 Brno
**     Czech Republic
**     http      : www.processorexpert.com
**     mail      : info@processorexpert.com
** ###################################################################*/


/* MODULE BADGEI2C. */


#include "Events.h"
#include "BADGEI2C.h"

#define OVERRUN_ERR      1             /* Overrun error flag bit   */
#define WAIT_RX_CHAR     2             /* Wait for received char. flag bit (Master)  */
#define CHAR_IN_TX       4             /* Char is in TX buffer (Master)    */
#define CHAR_IN_RX       8             /* Char is in RX buffer     */
#define FULL_TX          16            /* Full transmit buffer     */
#define IN_PROGRES       32            /* Communication is in progress (Master) */
#define FULL_RX          64            /* Full receive buffer      */
#define MSxSL            128           /* Master x Slave flag bit  */

/*SerFlag2 bits*/
#define ADDR_COMPLETE      1           /* 10-bit address transmission complete   */
#define REP_ADDR_COMPLETE  2           /* repeated address transmission complete */
#define GENERAL_CALL       4           /* General call flag */
#define ADDR_10            8           /* 10-bit addr flag */
#define ADDR_7             16          /* 7-bit addr flag */

static bool EnUser;                    /* Enable/Disable device */
static byte BADGEI2C_SlaveAddr;        /* Variable for Slave address */
static word InpLenM;                   /* Length of input bufer's content */
static byte *InpPtrM;                  /* Pointer to input buffer for Master mode */
static word OutLenM;                   /* Length of output bufer's content */
static byte *OutPtrM;                  /* Pointer to output buffer for Master mode */
static byte InpLenS;                   /* Length of input buffer's content */
static byte InpPtrRS;                  /* Index for reading from input buffer */
static byte InpPtrWS;                  /* Index for writing to input buffer */
static byte InpBufferS[6];             /* Input buffer I2C commmunication */
static byte OutLenS;                   /* Length of output bufer's content */
static byte OutPtrRS;                  /* Index for reading from output buffer */
static byte OutPtrWS;                  /* Index for writing to output buffer */
static byte OutBufferS[6];             /* Output buffer for I2C commmunication */
volatile byte BADGEI2C_SerFlag;        /* Flags for serial communication */
                                       /* Bits: 0 - OverRun error */
                                       /*       1 - Wait for received char. flag bit (Master) */
                                       /*       2 - Char is in TX buffer (Master) */
                                       /*       3 - Char in RX buffer */
                                       /*       4 - Full TX buffer */
                                       /*       5 - Running int from TX */
                                       /*       6 - Full RX buffer */
                                       /*       7 - Master x Slave */
static byte SerFlag2;                  /* more flags for serial communication */
                                       /* Bits: 0 - 10-bit address transmission complete   */
                                       /*       1 - repeated address transmission complete */
                                       /*       2 - 10-bit address reception */
                                       /*       3 - General Call flag */
                                       /*       4 - 10-bit addr flag */
                                       /*       5 - 7-bit addr flag */

/*
** ===================================================================
**     Method      :  BADGEI2C_Interrupt (bean InternalI2C)
**
**     Description :
**         The method services the interrupt of the selected peripheral(s)
**         and eventually invokes the beans event(s).
**         This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
#define RXAK 1
#define SRW  4
#define IBAL 16
#define IAAS 64

#define ON_ARBIT_LOST 1
#define ON_FULL_RX    2
#define ON_RX_CHAR    4
#define ON_FREE_TX    8
#define ON_TX_CHAR    16
#define ON_OVERRUN    32
#define ON_TX_EMPTY   64

#pragma interrupt alignsp saveall
void BADGEI2C_Interrupt(void)
{
  register byte Flags = 0;             /* Temporary variable for flags */
  register word Status = getReg(I2C_SR); /* Safe status register */

  setRegBit(I2C_SR,IICIF);             /* Clear interrupt flag */
  if (getRegBit(I2C_CR1,MST)) {        /* Is device in master mode? */
    if (getRegBit(I2C_CR1,TX)) {       /* Is device in Tx mode? */
      if (Status & I2C_SR_RXAK_MASK) { /* NACK received? */
        clrRegBit(I2C_CR1,MST);        /* Switch device to slave mode (stop signal sent) */
        OutLenM = 0;                   /* No character for sending */
        InpLenM = 0;                   /* No character for reception */
        BADGEI2C_SerFlag &= ~(CHAR_IN_TX|WAIT_RX_CHAR|IN_PROGRES); /* No character for sending or reception */
        BADGEI2C_OnNACK();             /* Invoke OnNACK event */
      }
      else {
        if (OutLenM) {                 /* Is any char. for transmitting? */
          OutLenM--;                   /* Decrease number of chars for the transmit */
          setReg(I2C_DATA,*(OutPtrM)++); /* Send character */
        }
        else {
          if (InpLenM) {               /* Is any char. for reception? */
            if (InpLenM == 1) {        /* If only one char to receive */
              setRegBit(I2C_CR1,TXAK); /* then transmit ACK disable */
            } 
            else {
              clrRegBit(I2C_CR1,TXAK); /* else transmit ACK anable */
            }
            clrRegBit(I2C_CR1,TX);     /* Switch to Rx mode */
            getReg(I2C_DATA);          /* Dummy read character */
          }
          else {
            BADGEI2C_SerFlag &= ~IN_PROGRES; /* Clear flag "busy" */
            clrRegBit(I2C_CR1,MST);    /* Switch device to slave mode (stop signal sent) */
            clrRegBit(I2C_CR1,TX);     /* Switch to Rx mode */
          }
        }
      }
    }
    else {
      InpLenM--;                       /* Decrease number of chars for the receive */
      if (InpLenM) {                   /* Is any char. for reception? */
        if (InpLenM == 1)
          setRegBit(I2C_CR1,TXAK);     /* Transmit ACK disable */
      }
      else {
        clrRegBit(I2C_CR1,MST);        /* If no, switch device to slave mode (stop signal sent) */
        clrRegBit(I2C_CR1,TXAK);       /* Transmit ACK enable */
      }
      *(InpPtrM)++ = (byte)getReg(I2C_DATA); /* Receive character */
    }
  }
  else {
    if (Status & I2C_SR_IAAS_MASK) {   /* Addressed as a slave? */
      if(Status & I2C_SR_ARBL_MASK) {  /* Arbitration lost? */
        OutLenM = 0;                   /* No character for sending */
        InpLenM = 0;                   /* No character for reception */
        BADGEI2C_SerFlag &= ~(CHAR_IN_TX|WAIT_RX_CHAR|IN_PROGRES); /* No character for sending or reception */
        clrRegBit(I2C_CR1,TX);         /* Switch to Rx mode */
      }
      if (Status & I2C_SR_SRW_MASK) {  /* Read? */
        setRegBit(I2C_CR1,TX);         /* Switch to Tx mode */
        if (OutLenS) {                 /* Is number of bytes in the transmit buffer greater then 0? */
          OutLenS--;                   /* Decrease number of chars in the transmit buffer */
          setReg(I2C_DATA,OutBufferS[OutPtrRS++]); /* Store char to transmitter register */
          if (OutPtrRS >= 6)           /* Is the index out of the transmit buffer? */
            OutPtrRS = 0;              /* Set index on the first item into the transmit buffer */
        }
        else {
          setReg(I2C_DATA,BADGEI2C_EOF); /* Store the empty char to the transmit register */
        }
      }
      else {
        clrRegBit(I2C_CR1,TX);         /* Switch to Rx mode */
        getReg(I2C_DATA);              /* Dummy read character */
      }
    }
    else {
      if (Status & I2C_SR_ARBL_MASK) { /* Arbitration lost? */
        OutLenM = 0;                   /* Any character is not for sent */
        InpLenM = 0;                   /* Any character is not for reception */
        BADGEI2C_SerFlag &= ~(CHAR_IN_TX|WAIT_RX_CHAR|IN_PROGRES); /* Any character is not for sent or reception*/
        clrRegBit(I2C_CR1,TX);         /* Switch to Rx mode */
      }
      else {
        if (getRegBit(I2C_CR1,TX)) {   /* Transmit? */
          if (Status & I2C_SR_RXAK_MASK) { /* NACK from receiver */
            clrRegBit(I2C_CR1,TX);     /* Switch to Rx mode */
            getReg(I2C_DATA);          /* Dummy read character */
          }
          else {
            if (OutLenS) {             /* Is number of bytes in the transmit buffer greater then 0? */
              OutLenS--;               /* Decrease number of chars in the transmit buffer */
              setReg(I2C_DATA,OutBufferS[OutPtrRS++]); /* Store char to transmitter register */
              if (OutPtrRS >= 6) {     /* Is the index out of the transmit buffer? */
                OutPtrRS = 0;          /* Set index on the first item into the transmit buffer */
              }
            }
            else {
              setReg(I2C_DATA,BADGEI2C_EOF); /* Store the empty char to the transmit register */
            }
          }
        }
        else {
          if (InpLenS < 6) {           /* Is number of bytes in the receive buffer lower than size of buffer? */
            InpLenS++;                 /* Increse number of chars in the receive buffer */
            InpBufferS[InpPtrWS++] = (byte)getReg(I2C_DATA); /* Save received char to the receive buffer */
            if (InpPtrWS >= 6) {       /* Is the index out of the receive buffer? */
              InpPtrWS = 0;            /* Set index on the first item into the receive buffer */
            }
            if (InpLenS == 6) {        /* Is number of bytes in the receive buffer equal to the size of buffer? */
              Flags |= ON_FULL_RX;     /* Set OnFullRxBuf flag */
            }
          }
          else {
            getReg(I2C_DATA);          /* Dummy read data register */
            BADGEI2C_SerFlag |= FULL_RX; /* Set flag "full RX buffer" */
          }
        }
      }
    }
    if (Flags & ON_FULL_RX) {          /* Is OnFullRxBuf flag set? */
      BADGEI2C_OnFullRxBuf();          /* If yes then invoke user event */
    }
  }
}

/*
** ===================================================================
**     Method      :  BADGEI2C_Enable (bean InternalI2C)
**
**     Description :
**         Enables I2C bean. Events may be generated
**         ("DisableEvent"/"EnableEvent").
**     Parameters  : None
**     Returns     :
**         ---             - Error code, possible codes:
**                           ERR_OK - OK
**                           ERR_SPEED - This device does not work in
**                           the active speed mode
** ===================================================================
*/
byte BADGEI2C_Enable(void)
{
  if (!EnUser) {                       /* Is the device disabled by user? */
    EnUser = TRUE;                     /* If yes then set the flag "device enabled" */
    BADGEI2C_SerFlag &= ~127;          /* Clear the status variable */
    setRegBit(I2C_CR1,IICEN);          /* Enable device */
    /* I2C_CR1: IICEN=1,IICIE=1,MST=0,TX=0,TXAK=0,RSTA=0,??=0,??=0 */
    setReg(I2C_CR1,192);               /* Control register settings */
  }
  return ERR_OK;                       /* OK */
}

/*
** ===================================================================
**     Method      :  BADGEI2C_Disable (bean InternalI2C)
**
**     Description :
**         Disables I2C bean. No events will be generated.
**     Parameters  : None
**     Returns     :
**         ---             - Error code, possible codes:
**                           ERR_OK - OK
**                           ERR_SPEED - This device does not work in
**                           the active speed mode
** ===================================================================
*/
byte BADGEI2C_Disable(void)
{
  if (EnUser) {                        /* Is the device enabled by user? */
    EnUser = FALSE;                    /* If yes then set the flag "device disabled" */
    /* I2C_CR1: IICEN=0,IICIE=0,MST=0,TX=0,TXAK=0,RSTA=0,??=0,??=0 */
    setReg(I2C_CR1,0);                 /* Disable device */
  }
  return ERR_OK;                       /* OK */
}

/*
** ===================================================================
**     Method      :  BADGEI2C_SendBlock (bean InternalI2C)
**
**     Description :
**         When working as a MASTER, this method writes one (7-bit
**         addressing) or two (10-bit addressing) slave address
**         bytes inclusive of R/W bit = 0 to the I2C bus and then
**         writes the block of characters to the bus. The slave
**         address must be specified before, by the "SelectSlave" or
**         "SlaveSelect10" method or in bean initialization section,
**         "Target slave address init" property. If interrupt
**         service is enabled and the method returns ERR_OK, it
**         doesn't mean that transmission was successful. The state
**         of transmission is detectable by means of events
**         (OnTransmitData, OnError or OnArbitLost). Data to be send
**         is not copied to an internal buffer and remains in the
**         original location. Therefore the content of the buffer
**         should not be changed until the transmission is complete.
**         Event OnTransmitData can be used to detect the end of the
**         transmission.
**         When working as a SLAVE, this method writes a block of
**         characters to the internal output slave buffer and then,
**         after the master starts the communication, to the I2C bus.
**         If no character is ready for a transmission (internal
**         output slave buffer is empty), the "Empty character" will
**         be sent (see "Empty character" property). In SLAVE mode
**         the data are copied to an internal buffer, if specified
**         by "Output buffer size" property.
**     Parameters  :
**         NAME            - DESCRIPTION
**       * Ptr             - Pointer to the block of data to send.
**         Siz             - Size of the block.
**       * Snt             - Amount of data sent (moved to a buffer).
**                           In master mode, if interrupt support is
**                           enabled, the parameter always returns
**                           the same value as the parameter 'Siz' of
**                           this method.
**     Returns     :
**         ---             - Error code, possible codes:
**                           ERR_OK - OK
**                           ERR_SPEED - This device does not work in
**                           the active speed mode
**                           ERR_DISABLED -  Device is disabled
**                           ERR_BUSY - The slave device is busy, it
**                           does not respond by the acknowledge
**                           (only in master mode and when interrupt
**                           service is disabled)
**                           ERR_BUSOFF - Clock timeout elapsed or
**                           device cannot transmit data
**                           ERR_TXFULL - Transmitter is full. Some
**                           data has not been sent. (slave mode only)
**                           ERR_ARBITR - Arbitration lost (only when
**                           interrupt service is disabled and in
**                           master mode)
** ===================================================================
*/
byte BADGEI2C_SendBlock(void* Ptr,word Siz,word *Snt)
{
  register word count;                 /* Number of sent chars */

  if (!Siz) {                          /* Test variable Size on zero */
    *Snt = 0;
    return ERR_OK;                     /* If zero then OK */
  }
  if (BADGEI2C_SerFlag & MSxSL) {
    if (!EnUser) {                     /* Is the device disabled by user? */
      return ERR_DISABLED;             /* If yes then error */
    }
    if ((getRegBit(I2C_SR,BUSY))||(InpLenM)||(BADGEI2C_SerFlag&(CHAR_IN_TX|WAIT_RX_CHAR|IN_PROGRES))) { /* Is the bus busy */
      return ERR_BUSOFF;               /* If yes then error */
    }
    EnterCritical();                   /* Enter the critical section */
    BADGEI2C_SerFlag |= IN_PROGRES;    /* Set flag "busy" */
    OutLenM = Siz;                     /* Set lenght of data */
    OutPtrM = (byte *)Ptr;             /* Save pointer to data for transmitting */
    setRegBit(I2C_CR1,TX);             /* Set TX mode */
    if (getRegBit(I2C_CR1,MST)) {      /* Is device in master mode? */
      setRegBit(I2C_CR1,RSTA);         /* If yes then repeat start cycle generated */
    }
    else {
      setRegBit(I2C_CR1,MST);          /* If no then start signal generated */
    }
    if (SerFlag2 & GENERAL_CALL) {     /* Is general call command required ? */
      setReg(I2C_DATA,0);              /* Send general call address */
    }
    else {                             /* Is 7-bit addressing set ? */
      setReg(I2C_DATA,BADGEI2C_SlaveAddr); /* Send slave address */
    }
    ExitCritical();                    /* Exit the critical section */
    *Snt = Siz;                        /* Dummy number of really sent chars */
  }
  else {
    EnterCritical();                   /* Enter the critical section */
    *Snt = 0;                          /* Return number of sent chars */
    for (count=0; count < Siz; count++) {
      if (OutLenS < 6) {               /* Is number of bytes in the receive buffer lower than size of buffer? */
        OutLenS++;                     /* Increase number of bytes in the transmit buffer */
        OutBufferS[OutPtrWS++] = *((byte *)Ptr + count); /* Store char to buffer */
        if (OutPtrWS >= 6) {           /* Is the pointer out of the transmit buffer? */
          OutPtrWS = 0;                /* Set pointer to the first item in the transmit buffer */
        }
        (*Snt)++;                      /* Increment number of sent chars */
      }
      else {
        ExitCritical();                /* Exit the critical section */
        return ERR_TXFULL;             /* Return with error */
      }
    }
    ExitCritical();                    /* Exit the critical section */
  }
  return ERR_OK;                       /* OK */
}

/*
** ===================================================================
**     Method      :  BADGEI2C_RecvBlock (bean InternalI2C)
**
**     Description :
**         When working as a MASTER, this method writes one (7-bit
**         addressing) or two (10-bit addressing) slave address
**         bytes inclusive of R/W bit = 1 to the I2C bus, then reads
**         the block of characters from the bus and then sends the
**         stop condition. The slave address must be specified
**         before, by the "SelectSlave" or "SelectSlave10" method or
**         in bean initialization section, "Target slave address
**         init" property. If interrupt service is enabled and the
**         method returns ERR_OK, it doesn't mean that transmission
**         was finished successfully. The state of transmission must
**         be tested by means of events (OnReceiveData, OnError or
**         OnArbitLost). In case of successful transmission,
**         received data is ready after OnReceiveData event is
**         called. 
**         When working as a SLAVE, this method reads a block of
**         characters from the input slave buffer.
**     Parameters  :
**         NAME            - DESCRIPTION
**       * Ptr             - A pointer to the block space for
**                           received data.
**         Siz             - The size of the block.
**       * Rcv             - Amount of received data. In master mode,
**                           if interrupt support is enabled, the
**                           parameter always returns the same value
**                           as the parameter 'Siz' of this method.
**     Returns     :
**         ---             - Error code, possible codes:
**                           ERR_OK - OK
**                           ERR_SPEED - This device does not work in
**                           the active speed mode
**                           ERR_DISABLED -  Device is disabled
**                           ERR_BUSY - The slave device is busy, it
**                           does not respond by an acknowledge (only
**                           in master mode and when interrupt
**                           service is disabled)
**                           ERR_BUSOFF - Clock timeout elapsed or
**                           device cannot receive data
**                           ERR_RXEMPTY - The receive buffer didn't
**                           contain the requested number of data.
**                           Only available data (or no data) has
**                           been returned  (slave mode only).
**                           ERR_OVERRUN - Overrun error was detected
**                           from last character or block receiving
**                           (slave mode only)
**                           ERR_ARBITR - Arbitration lost (only when
**                           interrupt service is disabled and in
**                           master mode)
** ===================================================================
*/
byte BADGEI2C_RecvBlock(void* Ptr,word Siz,word *Rcv)
{
  register word count;                 /* Number of sent chars */
  register byte errrc = ERR_OK;        /* Most serious error */

  if (!Siz) {                          /* Test variable Size on zero */
    *Rcv = 0;
    return ERR_OK;                     /* If zero then OK */
  }
  if (BADGEI2C_SerFlag & MSxSL) {
    if (!EnUser) {                     /* Is the device disabled by user? */
      return ERR_DISABLED;             /* If yes then error */
    }
    if(SerFlag2 & GENERAL_CALL) {      /* Is the general call flag set (SelectSpecialCommand - general call was called) ? */
      return ERR_NOTAVAIL;             /* It is not possible to receive data - Call SelectSlave or SelectSlave10 method */
    }
    if ((getRegBit(I2C_SR,BUSY))||(InpLenM)||(BADGEI2C_SerFlag&(CHAR_IN_TX|WAIT_RX_CHAR|IN_PROGRES))) { /* Is the bus busy */
      return ERR_BUSOFF;               /* If yes then error */
    }
    EnterCritical();                   /* Enter the critical section */
    InpLenM = Siz;                     /* Set lenght of data */
    InpPtrM = (byte *)Ptr;             /* Save pointer to data for reception */
    setRegBit(I2C_CR1,TX);             /* Set TX mode */
    if (getRegBit(I2C_CR1,MST)) {      /* Is device in master mode? */
      setRegBit(I2C_CR1,RSTA);         /* If yes then repeat start cycle generated */
    }
    else {
      setRegBit(I2C_CR1,MST);          /* If no then start signal generated */
    }
    setReg(I2C_DATA,(byte)(BADGEI2C_SlaveAddr+1)); /* Send slave address */
    ExitCritical();                    /* Exit the critical section */
    *Rcv = Siz;                        /* Dummy number of really received chars */
  }
  else {
    EnterCritical();                   /* Enter the critical section */
    if ((BADGEI2C_SerFlag & (OVERRUN_ERR | FULL_RX)) != 0) { /* Has the overrun occured? */
      errrc = ERR_OVERRUN;             /* If yes then return OVERRUN error */
    }
    BADGEI2C_SerFlag &= ~(OVERRUN_ERR | CHAR_IN_RX | FULL_RX); /* Clear flag "char in RX buffer" */
    *Rcv = 0;                          /* Clear number of received chars */
    for (count=0; count < Siz; count++) {
      if (InpLenS) {                   /* Is number of bytes in the receive buffer lower than size of buffer? */
        InpLenS--;                     /* Decrease number of received chars */
        *((byte *)Ptr + count) = InpBufferS[InpPtrRS++]; /* Read the char */
        if (InpPtrRS >= 6) {           /* Is the index out of the receive buffer? */
          InpPtrRS = 0;                /* Set index to the first item into the receive buffer */
        }
        (*Rcv)++;                      /* Increment number of sent chars */
      }
      else {
        ExitCritical();                /* Exit the critical section */
        if (errrc==ERR_OVERRUN) {
          return ERR_OVERRUN;          /* Return with error */
        }
        else {
          return ERR_RXEMPTY;          /* Return with error */
        }
      }
    }
    ExitCritical();                    /* Exit the critical section */
    return errrc;                      /* Return error code */
  }
  return ERR_OK;                       /* OK */
}

/*
** ===================================================================
**     Method      :  BADGEI2C_ClearRxBuf (bean InternalI2C)
**
**     Description :
**         This method clears all characters in internal slave input
**         buffer. This method is not available for the MASTER mode.
**     Parameters  : None
**     Returns     :
**         ---             - Error code, possible codes:
**                           ERR_OK - OK
**                           ERR_SPEED - This device does not work in
**                           the active speed mode
** ===================================================================
*/
byte BADGEI2C_ClearRxBuf(void)
{
  EnterCritical();                     /* Enter the critical section */
  InpLenS = 0;                         /* Set number of chars in the transmit buffer to 0 */
  InpPtrRS = InpPtrWS = 0;             /* Set indexes on the first item in the transmit buffer */
  BADGEI2C_SerFlag &= ~(OVERRUN_ERR | CHAR_IN_RX | FULL_RX);
  ExitCritical();                      /* Exit the critical section */
  return ERR_OK;                       /* OK */
}

/*
** ===================================================================
**     Method      :  BADGEI2C_SelectSlave (bean InternalI2C)
**
**     Description :
**         This method selects a new slave for communication by its
**         7-bit slave address value. Any send or receive method
**         directs to or from selected device, until a new slave
**         device is selected by this method. This method is not
**         available for the SLAVE mode.
**     Parameters  :
**         NAME            - DESCRIPTION
**         Slv             - 7-bit slave address value.
**     Returns     :
**         ---             - Error code, possible codes:
**                           ERR_OK - OK
**                           ERR_BUSY - The device is busy, wait
**                           until the current operation is finished.
**                           ERR_SPEED - This device does not work in
**                           the active speed mode
**                           ERR_DISABLED -  The device is disabled
** ===================================================================
*/
byte BADGEI2C_SelectSlave(byte Slv)
{
  if (!EnUser) {                       /* Is the device disabled by user? */
    return ERR_DISABLED;               /* If yes then error */
  }
  if (getRegBit(I2C_CR1,MST)) {        /* Is the device in the active state? */
    return ERR_BUSY;                   /* If yes then error */
  }
  SerFlag2 &= (byte)((SerFlag2 & ~(GENERAL_CALL|ADDR_10)) | ADDR_7); /* Clear the general call flag and 10-bit address mode flag and set 7-bit address mode flag */
  BADGEI2C_SlaveAddr = (byte)(Slv << 1); /* Set slave address */
  return ERR_OK;                       /* OK */
}

/*
** ===================================================================
**     Method      :  BADGEI2C_SelectSpecialCommand (bean InternalI2C)
**
**     Description :
**         This method selects a special command. Any send or receive
**         method directs to or from selected device, until a new slave
**         device is selected by this method. This method is not
**         available for the SLAVE mode. Certain commands may not be
**         supported on a specific derivative, if IIC module does not
**         have the capability.
**     Parameters  :
**         NAME            - DESCRIPTION
**         Cmd             - Special command. Possible values:
**                           0 - General call address
**                           1 - Start byte
**     Returns     :
**         ---             - Error code, possible codes:
**                           ERR_OK - OK
**                           ERR_BUSY - The device is busy, wait until
**                           the current operation is finished.
**                           ERR_SPEED - This device does not work in
**                           the active speed mode
**                           ERR_DISABLED -  The device is disabled
**                           ERR_RANGE -  Requested command is not
**                           supported.
** ===================================================================
*/
byte BADGEI2C_SelectSpecialCommand(byte Cmd)
{
  if (!EnUser) {                       /* Is the device disabled by user? */
    return ERR_DISABLED;               /* If yes then error */
  }
  if (Cmd != 0) {                      /* Is the value out of range? */
    return ERR_RANGE;                  /* If yes then error */
  }
  if (getRegBit(I2C_CR1,MST)) {        /* Is the device in the active state? */
    return ERR_BUSY;                   /* If yes then error */
  }
  SerFlag2 = (byte)((SerFlag2 & ~(ADDR_10|ADDR_7)) | GENERAL_CALL); /* Clear the general call flag and 7-bit address mode flag and set the general call flag */
  return ERR_OK;                       /* OK */
}

/*
** ===================================================================
**     Method      :  BADGEI2C_SetMode (bean InternalI2C)
**
**     Description :
**         This method sets actual operating mode of this bean. This
**         method is available only for the MASTER - SLAVE mode.
**         Note: If MASTER mode is selected as an operating mode,
**         the device can still be selected as a slave and
**         receive/transmit data. However, it's necessary to select
**         slave operating mode using SetMode( FALSE ) to access
**         this data.
**     Parameters  :
**         NAME            - DESCRIPTION
**         MasterMode      - Operating mode value:
**                           TRUE - Master
**                           FALSE - Slave
**     Returns     :
**         ---             - Error code, possible codes:
**                           ERR_OK - OK
**                           ERR_SPEED - This device does not work in
**                           the active speed mode
** ===================================================================
*/
byte BADGEI2C_SetMode(bool MasterMode)
{
  BADGEI2C_SerFlag = (byte)((BADGEI2C_SerFlag & ~(byte)MSxSL) | ((MasterMode)?(byte)MSxSL:(byte)0)); /* Set mode */
  return ERR_OK;                       /* OK */
}

/*
** ===================================================================
**     Method      :  BADGEI2C_Init (bean InternalI2C)
**
**     Description :
**         Initializes the associated peripheral(s) and the beans 
**         internal variables. The method is called automatically as a 
**         part of the application initialization code.
**         This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
void BADGEI2C_Init(void)
{
  /* I2C_CR1: IICEN=0,IICIE=0,MST=0,TX=0,TXAK=0,RSTA=0,??=0,??=0 */
  setReg(I2C_CR1,0);                   /* Clear control register */
  BADGEI2C_SerFlag = 128;              /* Reset all flags */
  SerFlag2 = ADDR_7;                   /* Reset all flags start with 7-bit address mode */
  EnUser = TRUE;                       /* Enable device */
  BADGEI2C_SlaveAddr = 0;              /* Set variable for slave address */
  InpLenS = 0;                         /* No char in the receive buffer */
  InpPtrWS = InpPtrRS = 0;             /* Set indexes on the first item in the receive buffer */
  OutLenS = 0;                         /* No char in the transmit buffer */
  OutPtrWS = OutPtrRS = 0;             /* Set indexes on the first item in the transmit buffer */
  /* I2C_ADDR: AD=0,??=0 */
  setReg(I2C_ADDR,0);                  /* Define slave address */
  /* I2C_CR2: GCAEN=1,ADEXT=0,??=0,??=0,??=0,AD10=0,AD9=0,AD8=0 */
  setReg(I2C_CR2,128);
  /* I2C_FREQDIV: MULT=2,ICR=0 */
  setReg(I2C_FREQDIV,128);             /* Set prescaler bits */
  setRegBit(I2C_CR1,IICEN);            /* Enable device */
  /* I2C_CR1: IICEN=1,IICIE=1,MST=0,TX=0,TXAK=0,RSTA=0,??=0,??=0 */
  setReg(I2C_CR1,192);                 /* Control register settings */
}


/* END BADGEI2C. */

/*
** ###################################################################
**
**     This file was created by UNIS Processor Expert 2.99 [04.17]
**     for the Freescale 56800 series of microcontrollers.
**
** ###################################################################
*/
