//basic IO setup and defines

#include "io.h"
//for SPI
#include "backpack.h"

const char chanMap[4]={3,1,0,2}; //physical to logical mapping

void ioinit(void){
    //IO for CS and SHDN_DP
    //none selected, all high
    latbits.CS_1=1;
    latbits.CS_2=1;
    latbits.CS_3=1;
    latbits.CS_4=1;
    latbits.CS_5=1;
    latbits.SHDN_DP=0;  //off for start
    //all digital
    anselbits.CS_1=0;
    anselbits.CS_2=0;
    anselbits.CS_3=0;
    anselbits.CS_4=0;
    anselbits.CS_5=0;
    anselbits.SHDN_DP=0;
    //all outputs
    trisbits.CS_1=0;
    trisbits.CS_2=0;
    trisbits.CS_3=0;
    trisbits.CS_4=0;
    trisbits.CS_5=0;
    trisbits.SHDN_DP=0;
}

void tmr2init(void){
    //TIMER2
    T2CON=0;    //reset
    T2CLKCON=5;             //500kHz MFINTOSC
    //T2CLKCON=1;             //FOSC/4
    T2CONbits.T2CKPS=7;     //128 3.9kHz
    T2CONbits.T2OUTPS=0;    //postscale is n+1
    T2HLT=0;                //free running
    TMR2=0;
    PR2=255;                //full period
    PIR2bits.TMR2IF=0;
    PIE2bits.TMR2IE=1;
    INTCONbits.PEIE=1;
    T2CONbits.TMR2ON=1;    
}

void sendDP(unsigned char chan, unsigned char val){
    char cmask=chanMap[chan&3];      //lower 2 bits
    char cs=(chan>>2)&7;    //cs select
    SPI_BRG=TOUCH_BRG;  //use slower
    if(cs==0){latbits.CS_1=0;}
    if(cs==1){latbits.CS_2=0;}
    if(cs==2){latbits.CS_3=0;}
    if(cs==3){latbits.CS_4=0;}
    if(cs==4){latbits.CS_5=0;}
    backpackdata(cmask);    //DP takes 2 address bits
    backpackdata(val);      //and 8 data bits
    latbits.CS_1=1;         //latch last 10 bits sent
    latbits.CS_2=1;
    latbits.CS_3=1;
    latbits.CS_4=1;
    latbits.CS_5=1;    
    SPI_BRG=LCD_BRG;
}