#include "p33fxxxx.h"
#include "Vejlupek_CAR4_dsPIC33_ACU44_SlaveBoard_direct.h"
#include "Vejlupek_CAR4_dsPIC33_ACU44_SlaveBoard_direct_private.h"

/* Tx Variables */
#define Tx_BUFF_SIZE_Uart1             32

volatile uint8_T TxTab_Uart1[Tx_BUFF_SIZE_Uart1];
volatile uint8_T TxPtrHaut_Uart1 = 0;
volatile uint8_T TxPtrBas_Uart1 = 0;

/* Rx Variables */
#define Rx_BUFF_SIZE_Uart1             32

volatile uint8_T RxTab_Uart1[Rx_BUFF_SIZE_Uart1];
volatile uint8_T RxPtrHaut_Uart1 = 0;
volatile uint8_T RxPtrBas_Uart1 = 0;
void __attribute__((__interrupt__)) _U1TXInterrupt(void)
{
  _U1TXIF = 0;
  while ((U1STAbits.UTXBF == 0) && (TxPtrHaut_Uart1 != TxPtrBas_Uart1) ) {/* while UxTXREG buffer is not full */
    U1TXREG = TxTab_Uart1[TxPtrBas_Uart1];
    TxPtrBas_Uart1 = (TxPtrBas_Uart1 + 1) & (Tx_BUFF_SIZE_Uart1-1);
  }

  if (TxPtrHaut_Uart1 == TxPtrBas_Uart1)
    _U1TXIE = 0;                       /* remove interrupt  */
}

void __attribute__((__interrupt__)) _U1RXInterrupt(void)
{
  uint8_T Tmp;
  Tmp = ~(RxPtrHaut_Uart1 - RxPtrBas_Uart1);/* Tmp = 7 - (Haut - Bas) modulo buffersize	*/
  Tmp = Tmp & (Rx_BUFF_SIZE_Uart1-1);
  _U1RXIF = 0;
  while ((Tmp--) && (U1STAbits.URXDA == 1)) {
    RxTab_Uart1[RxPtrHaut_Uart1++] = (uint8_T) U1RXREG;
    RxPtrHaut_Uart1 &= (Rx_BUFF_SIZE_Uart1-1);
  }

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