/*
 Author: Obrtac Tomas  
 Mail: obrtac.tomas@gmail.com
 2017
 */


#include <xc.h>

#define UART_RX TRISA0
#define UART_TX TRISA5
#define UART_RX_N 2
#define UART_TX_N RPOR0


void UART_PutChar(char c)
{
    // Wait for previous transmission
    while(!TRMT);   
    // Put char
    TXREG = c;
}

void UART_PutStr(char * str)
{
    int i = 0;
    while(1){
        if(str[i] == 0) break;
        UART_PutChar(str[i++]);
    }
}

void UART_PutChar2(char c)
{
    // Wait for previous transmission
    while(!TXSTA2bits.TRMT2);
    // Put char
    TXREG2 = c;
}

void UART_PutStr2(char * str)
{
    int i = 0;
    while(1){
        if(str[i] == 0) break;
        UART_PutChar2(str[i++]);
    }
}

int UART_GetChar2(void)
{
 
    if(RCSTA2bits.OERR == 1){
    RCSTA2bits.OERR= 0;
    RCSTA2bits.CREN = 0;      // Disable RX
    RCSTA2bits.CREN = 1;      // Enable RX
    return -1;  // Return -1 if overrun occurred
    }
    if(!PIR3bits.RC2IF){
       return -1;  // No char available
    }
    // return char
    return RCREG2;
}

char UART_CharAvailable2(void)
{
    return PIR3bits.RC2IF;
}

void Remap_UART_2(void)
{   
    DSCONHbits.DSULPEN = 0;
    DSCONLbits.ULPWDIS = 1;
    CM1CONbits.CON = 0;
    T3CONbits.T3CKPS = 0b11;    // TMR3 prescaler
    T3CONbits.TMR3ON = 1;       // TMR3 on
    TRISB5 = 0;
    UART_TX = 1;
    UART_RX = 0;
    RPINR16 = UART_RX_N; // Assign RX
    //RPOR8 = 5;
    UART_TX_N = 5; // Assign TX
    RPOR13 = 5;
    RCSTA2bits.SPEN = 1;      // Enable UART peripheral
    RCSTA2bits.CREN = 1;      // Enable RX
    TXSTA2bits.TXEN = 1;  // Enable TX
    TXSTA2bits.BRGH = 1; // For Baudrate settings
    BAUDCON2bits.BRG16 = 1; // For baudrate settings
    SPBRG2 = 34; // Baud rate http://www.nicksoft.info/el/calc/?ac=spbrg&submitted=1&mcu=PIC18F45J10&Fosc=8.000&FoscMul=1000000&FoscAutoSelector=0&MaxBaudRateError=1
}

void Uart_Init()
{
    TRISCbits.TRISC6 = 0;  
    SPBRG = 12;
    RCSTAbits.SPEN = 1;      // Enable UART peripheral
    TXSTAbits.TXEN = 1;      // Enable TX
}