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

void __ISR(_TIMER_4_VECTOR, IPL2AUTO) Timer4Handler(void) { //preruseni timer 4
    IR_TX ^= 1; //negace
    IFS0bits.T4IF = 0; //nulovat flag
}

void initIr(void) {
    IR_TX_TRIS = 0; //vystup
    IR_TX = 0; //vypnout
    
    IR_RX_TRIS = 1; //vstup
    
    //timer 4
    T4CONbits.ON = 0; //vypnout
    T4CONbits.TCKPS1 = 0; //prescaler /1 => 1 / 1MHz = 1us
    T4CONbits.TCKPS0 = 0;
    PR4 = 12; //cca 38,5 kHz
    IPC4bits.T4IP = 2; //priorita 2
    IFS0bits.T4IF = 0; //nulovat flag
    IEC0bits.T4IE = 1; //povolit preruseni
}

void outputIr(unsigned char level) { //nastavit vystup
    if(level) { //zapnout IR LED
        TMR4 = 0;
        T4CONbits.ON = 1;
    }
    
    else { //vypnout IR LED
        T4CONbits.ON = 0;
        IR_TX = 0;
    }
}

unsigned char inputIr(void) { //precist vstup
    return !IR_RX; //aktivni v log. 0
}