//Tim Blythman
#include "io.h"

char reState,reStateOld;
volatile signed char reAccum=0;
const signed char reRes[]={0,1,-1,0,-1,0,0,1,1,0,0,-1,0,-1,1,0};
char buttonState, buttonPress;

void ioinit(void){
    ADCON0=0;            //reset
    //ADCON1= 0b11000000;  //1=right align, 100=1/4 FOSC, 00=NA, 00=V+REF=VDD
    ADCON1= 0b10110000;  //1=right align, 011=ADCRC, 00=NA, 00=V+REF=VDD    
    ADACT=0;             //no auto trigger    
    ADCON0bits.ADON=1;   //turn on    
}

void buttonInit(void){  //setup
    buttonPress=0;
    anselbits.SW1=0;
    trisbits.SW1=1;
    wpubits.SW1=1;      //pullup for safety    
    iocxpbits.SW1=1;       //enable IOC
    iocxnbits.SW1=1;
    iocxfbits.SW1=0;   //clear flags
    buttonState=portbits.SW1;
    IOCIE=1;
}

char buttonDown(void){ //report if press-down has happened
    char r;
    char intcon=INTCON; //get state
    GIE=0;             //interrupts off
    r=buttonPress;
    buttonPress=0;
    INTCON=intcon;      //restore interrupts    
    return r;
}

void reInit(void){  //rotary encoder
    anselbits.RE_A=0;
    anselbits.RE_B=0;
    trisbits.RE_A=1;
    trisbits.RE_B=1;
    wpubits.RE_A=1;      //pullup for safety    
    wpubits.RE_B=1;      //pullup for safety    
    iocxpbits.RE_A=1;       //enable IOC
    iocxpbits.RE_B=1;
    iocxnbits.RE_A=1;
    iocxnbits.RE_B=1;
    iocxfbits.RE_A=0;   //clear flags
    iocxfbits.RE_B=0;  
    reState=portbits.RE_A*2+portbits.RE_B; //capture initial state
    IOCIE=1;
}

signed char getRE(void){    //get accum
    signed char r;
    char intcon=INTCON; //get state
    GIE=0;             //interrupts off
    r=reAccum;
    reAccum=0;
    INTCON=intcon;      //restore interrupts    
    return r;
}

int getADC(unsigned char c){   //get result from preselected channel
    ADCON0bits.CHS=c;
    ADCON0bits.ADGO=1;              //start a dummy reading
    while(ADCON0bits.ADGO){}        //wait till done
    return (int)ADRES;        
}

