#include "system.h"
#include "usart.h"
void USART_Init()
{
unsigned char c;
ANSELHbits.ANS11 = 0; // Make RB5 pin digital
#if defined(REMOTE)
UART_TRISRx=1; // RX
#elif defined(LOCAL)
UART_TRISTx=0; // TX
WPUB7=1;
#endif
BAUDCON = 0x08; // BRG16 = 1
SPBRG = 0x87;
SPBRGH = 0x13; // 0x1387 for 48MHz -> 2400 baud
c = RCREG; // read
#if defined(LOCAL)
TXSTA = 0x65; // TX enable BRGH=1
#elif defined(REMOTE)
RCSTA = 0xD0; // Single Character RX
PIR1bits.RCIF = 0;
PIE1bits.RCIE= 1;
INTCONbits.PEIE = 1;
INTCONbits.GIE = 1;
#endif
}//end USART_InitializeUSART
void USART_putc(unsigned char c)
{
while (!TXSTAbits.TRMT);
TXSTAbits.TX9D = CalcParity(c);
TXREG = c;
}
unsigned char USART_getc(void)
{
unsigned char tmp;
unsigned char c;
if (RCSTAbits.OERR) // in case of overrun error
{ // we should never see an overrun error, but if we do,
RCSTAbits.CREN = 0; // reset the port
tmp = RCREG;
if (CalcParity(tmp) == RCSTAbits.RX9D){c = tmp;}
else{c = 0;}
RCSTAbits.CREN = 1; // and keep going.
}
else
{
tmp = RCREG;
if (CalcParity(tmp) == RCSTAbits.RX9D){c = tmp;}
else{c = 0;}
}
// not necessary. EUSART auto clears the flag when RCREG is cleared
// PIR1bits.RCIF = 0; // clear Flag
return c;
}
unsigned char CalcParity(unsigned char scancode)
{
unsigned char parity = 0;
while (scancode > 0)
{
if (scancode & 0x01) // If LSB is 1, we have a parity bit
{
parity++;
}
scancode = scancode >> 1; // Next bit
}
return (parity & 0x01); // We do only need the low bit to determine odd or even
}