#include "p33fxxxx.h"
#include "Master.h"
#include "Master_private.h"

/* Tx Variables */
#define Tx_BUFF_SIZE_Uart2             64

volatile uint8_T TxTab_Uart2[Tx_BUFF_SIZE_Uart2];
volatile uint8_T TxPtrHaut_Uart2 = 0;
volatile uint8_T TxPtrBas_Uart2 = 0;

/* Rx Variables */
#define Rx_BUFF_SIZE_Uart2             64

volatile uint8_T RxTab_Uart2[Rx_BUFF_SIZE_Uart2];
volatile uint8_T RxPtrHaut_Uart2 = 0;
volatile uint8_T RxPtrBas_Uart2 = 0;
void __attribute__((__interrupt__,__auto_psv__)) _U2TXInterrupt(void)
{
  _U2TXIF = 0;
  while ((U2STAbits.UTXBF == 0) && (TxPtrHaut_Uart2 != TxPtrBas_Uart2) ) {/* while UxTXREG buffer is not full */
    U2TXREG = TxTab_Uart2[TxPtrBas_Uart2];
    TxPtrBas_Uart2 = (TxPtrBas_Uart2 + 1) & (Tx_BUFF_SIZE_Uart2-1);
  }

  if (TxPtrHaut_Uart2 == TxPtrBas_Uart2)
    _U2TXIE = 0;                       /* remove interrupt  */
}

void __attribute__((__interrupt__,__auto_psv__)) _U2RXInterrupt(void)
{
  uint8_T Tmp;
  Tmp = ~(RxPtrHaut_Uart2 - RxPtrBas_Uart2);/* Tmp = 7 - (Haut - Bas) modulo buffersize	*/
  Tmp = Tmp & (Rx_BUFF_SIZE_Uart2-1);
  _U2RXIF = 0;
  while ((Tmp--) && (U2STAbits.URXDA == 1)) {
    RxTab_Uart2[RxPtrHaut_Uart2++] = (uint8_T) U2RXREG;
    RxPtrHaut_Uart2 &= (Rx_BUFF_SIZE_Uart2-1);
  }

  if (U2STAbits.OERR == 1)
    U2STAbits.OERR = 0;                /* Buffer Overflow cleared */
}
