#include "irrx.h"

//implementation
char IRstate=1; //idling high, ready to accept new bit
volatile char ir_t=0;
volatile char irbuf[256];
volatile char irbufptr=0;
//API
volatile char IRready=0;       //a packet is ready to be read
volatile char IRrpt=0;         //a repeat has been received
char IRadd=0;                  //address
char IRcode=0;                 //code
char rawIRpkt[4]={0,0,0,0};    //for receiving
char IRerror=1;                //validation
char bitMasks[256]={0,0,128,64,32,16,8,4,2,1,128,64,32,16,8,4,2,1,128,64,32,16,8,4,2,1,128,64,32,16,8,4,2,1};

void IRRXinit(void){
    //IR receiver with pullup
    anselbits.IRRX_PIN=0;
    trisbits.IRRX_PIN=1;
    wpubits.IRRX_PIN=1;
    iocxnbits.IRRX_PIN=1;   //enable negative IOC
    iocxpbits.IRRX_PIN=1;   //enable positive IOC
    iocxfbits.IRRX_PIN=0;   //clear flag
    PIE0bits.IOCIE=1;       //enable IOC
	INTCONbits.PEIE=1;      //peripheral interrupt enable
    //use TIMER1 for counting pulse lengths
    T1CONbits.TMR1ON=0;     //turn off
    //T1CONbits.RD16=1;       //allow 16-bit
    T1CONbits.RD16=0;       //8 bit (use TMR1H or TMR1L)
    TMR1=0;                 //reset
    T1CONbits.CKPS=0;       //0=1,1=2,2=4,3=8
    T1CONbits.nSYNC=1;      //do not synchronise
    T1GCONbits.GE=0;        //no gating
    T1CLK=1;                //1=FOSC/4, 2=FOSC
    PIR1bits.TMR1IF=0;      //clear flag
    //PIE1bits.TMR1IE=1;      //interrupt enabled
	//INTCONbits.PEIE=1;      //peripheral interrupt enable
    T1CONbits.TMR1ON=1;     //turn on    
    //set GIE in main if needed    
}

char getIRrpt(void){
    char r=IRrpt;    
    IRrpt=0;
    return r;
}

