#include "ps.h"
#include <xc.h> //XC32 prekladac

void initPs(void) {
    PS_RX_ANSEL = 1; //analog. vstup
    
    PS_PWR_TRIS = 0; //vystup
    PS_PWR = 1; //vypnout
    
    PS_TX_TRIS = 0; //vystup
    PS_RX_TRIS = 1; //vstup
    
    //ADC init    
    AD1CON1bits.SSRC2 = 1; //auto-convert
    AD1CON1bits.SSRC1 = 1;
    AD1CON1bits.SSRC0 = 1;
    
    AD1CON3bits.SAMC4 = 0; //sample time 8 TAD = 80 us
    AD1CON3bits.SAMC3 = 0;
    AD1CON3bits.SAMC2 = 1;
    AD1CON3bits.SAMC1 = 1;
    AD1CON3bits.SAMC0 = 1;
    
    AD1CON3bits.ADCS7 = 0; //TAD = (4 + 1) * 2 * TPB = 10 * TPB
    AD1CON3bits.ADCS6 = 0;
    AD1CON3bits.ADCS5 = 0;
    AD1CON3bits.ADCS4 = 0;
    AD1CON3bits.ADCS3 = 0;
    AD1CON3bits.ADCS2 = 0;
    AD1CON3bits.ADCS1 = 1;
    AD1CON3bits.ADCS0 = 1;
    
    AD1CHSbits.CH0SA4 = 0; //vstup AN14
    AD1CHSbits.CH0SA3 = 1;
    AD1CHSbits.CH0SA2 = 1;
    AD1CHSbits.CH0SA1 = 1;
    AD1CHSbits.CH0SA0 = 0;
    
    AD1CON1bits.ON = 1; //zapnout ADC
}

void outputPs(unsigned char level) { //nastavit vystup
    if(level == 0) { //vypnout
       PS_PWR = 1;
    }
    
    else {
        if(level == 1) { //4mA
            PS_TX = 1;
        }
        
        else { //20mA
            PS_TX = 0;
        }
        
        PS_PWR = 0; //(zapnout)
    }
}

unsigned int inputPs(void) { //precist vstup
    AD1CON1bits.SAMP = 1;
    while(!AD1CON1bits.DONE);
    
    return ADC1BUF0;
}