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

unsigned char rxFlagUart;
unsigned char rxUart;

void __ISR(_UART_1_VECTOR, IPL2AUTO) U1RXHandler(void) { //obsluha preruseni - prijem dat
    rxUart = U1RXREG; //prijata data
    rxFlagUart = 1; //nastavit flag
    IFS1bits.U1RXIF = 0; //nulovat flag
}

void initUart(void) {
    UART_RX_ANSEL = 0; //digitalni pin
    UART_RX_TRIS = 1; //vstup
    
    U1RXR = 1; //UART 1 RX na RPG8
    RPG7R = 3; //UART 1 TX na RPG7
    
    //start 1 bit, data 8 bit, no parity 0 bit, stop 1 bit, idle log. 1...
    U1STAbits.URXEN = 1; //receiver is enabled
    U1STAbits.UTXEN = 1; //transmitter is enabled
    
    U1BRG = 12; //4800 baud @1 MHz
    
    IPC7bits.U1IP = 2; //priorita
    IFS1bits.U1RXIF = 0; //nulovat flag
    rxFlagUart = 0; //nulovat flag
    IEC1bits.U1RXIE = 1; //povolit preruseni
    
    U1MODEbits.ON = 1; //zapnout
}

void putCharUart(unsigned char txUart) { //odeslat znak
    while(U1STAbits.UTXBF); //pockat na uvolneni mista v bufferu
    
    U1TXREG = txUart; //zapis znaku do bufferu
}