#include "oneWire.h"
#include <xc.h> //XC32 prekladac
#include "delay.h"

void delayNop(void) { //kratky delay
    _nop();_nop();_nop();_nop();_nop();
    _nop();_nop();_nop();_nop();_nop();
    _nop();_nop();_nop();_nop();_nop();
    _nop();_nop();_nop();_nop();_nop();
}

void initOneWire(void) {
    oneWire_ODC = 1; //open-drain
    oneWire = 1; //idle stav
    oneWire_TRIS = 0; //vystup
}

//void resetOneWire(void) { //resetovani sbernice
//    oneWire = 0;
//    delayUs(480); //reset pulz - cca 500 us
//    oneWire = 1;
//    delayUs(480);
//}

unsigned char resetOneWire(void) { //resetovani sbernice
    unsigned char initFlagOneWire;
    oneWire = 0;
    delayUs(480); //reset pulz - cca 500 us
    oneWire = 1;
    delayUs(48); //vzorkovani musi probehnout v case 60 - 75 us od nabezne hrany, upraveno s ohledem na nepresnost
    oneWire_TRIS = 1; //vstup
    initFlagOneWire = oneWire_PORT; //cteni presence pulzu
    oneWire_TRIS = 0; //vystup
    delayUs(430);
    
    return initFlagOneWire;
}

void writeOneWire(unsigned char level) {
    if(level) { //zapis 1
        oneWire = 0;
        delayNop();
        oneWire = 1;
        delayUs(60);
    }
    
    else { //zapis 0
        oneWire = 0;
        delayUs(60); //minimalni delka
        oneWire = 1;
        delayNop(); //pockat alespon 1 us
    }
}

unsigned char readOneWire(void) {
    unsigned char dataOneWire;
    
    oneWire = 0;
    delayNop();
    oneWire = 1;
    delayNop();
    delayNop();
    oneWire_TRIS = 1; //vstup
    dataOneWire = oneWire_PORT; //cteni datoveho bitu
    oneWire_TRIS = 0; //vystup
    delayUs(48);
    
    return dataOneWire;
}

//DS18B20 prikazy
void skipRomOneWire(void) { //0xCC = 0b11001100
    writeOneWire(0);
    writeOneWire(0);
    writeOneWire(1);
    writeOneWire(1);
    writeOneWire(0);
    writeOneWire(0);
    writeOneWire(1);
    writeOneWire(1);
}

void convertTOneWire(void) { //0x44 = 0b01000100
    writeOneWire(0);
    writeOneWire(0);
    writeOneWire(1);
    writeOneWire(0);
    writeOneWire(0);
    writeOneWire(0);
    writeOneWire(1);
    writeOneWire(0);
}

void readScratchpadOneWire(void) { //0xBE = 0b10111110
    writeOneWire(0);
    writeOneWire(1);
    writeOneWire(1);
    writeOneWire(1);
    writeOneWire(1);
    writeOneWire(1);
    writeOneWire(0);
    writeOneWire(1);
}