#include "rs485.h"
#include <xc.h> //XC32 prekladac
#include <sys/attribs.h> //obsahuje makra pro obsluhu preruseni

unsigned char rxFlagRs485;
unsigned char rxRs485;

void __ISR(_UART_2_VECTOR, IPL2AUTO) U2RXHandler(void) { //obsluha preruseni - prijem dat
    rxRs485 = U2RXREG; //prijata data
    rxFlagRs485 = 1; //nastavit flag
    IFS1bits.U2RXIF = 0; //nulovat flag
}

void initRs485(void) {
    RS485_RW_ANSEL = 0; //digitalni pin
    RS485_RX_ANSEL = 0; //digitalni pin
    
    RS485_RW = 0; //nastavit jako prijimac
    
    RS485_RW_TRIS = 0; //vystup
    RS485_RX_TRIS = 1; //vstup
    
    U2RXR = 0; //UART 2 RX na RPD2
    RPD3R = 1; //UART 2 TX na RPD3
    
    //start 1 bit, data 8 bit, no parity 0 bit, stop 1 bit, idle log. 1...
    U2STAbits.URXEN = 0; //receiver is disabled
    U2STAbits.UTXEN = 0; //transmitter is disabled
    
    U2BRG = 12; //4800 baud @1 MHz
    
    IPC9bits.U2IP = 2; //priorita
    IFS1bits.U2RXIF = 0; //nulovat flag
    rxFlagRs485 = 0; //nulovat flag
    IEC1bits.U2RXIE = 1; //povolit preruseni
}

void putCharRs485(unsigned char txRs485) { //odeslat znak
    while(U2STAbits.UTXBF); //pockat na uvolneni mista v bufferu
    
    U2TXREG = txRs485; //zapis znaku do bufferu
}

void transmiterRs485(void) { //nastavit jako vysilac
    U2MODEbits.ON = 0; //vypnout
    
    U2STAbits.URXEN = 0; //receiver is disabled
    U2STAbits.UTXEN = 1; //transmitter is enabled
    
    U2MODEbits.ON = 1; //zapnout
    
    RS485_RW = 1; //nastavit jako vysilac
}

void receiverRs485(void) { //nastavit jako prijimac
    RS485_RW = 0; //nastavit jako prijimac
    
    U2MODEbits.ON = 0; //vypnout
    
    U2STAbits.URXEN = 1; //receiver is enabled
    U2STAbits.UTXEN = 0; //transmitter is disabled
    
    U2MODEbits.ON = 1; //zapnout
}