#define DQ		LATBbits.LATB0
#define DQ_R	PORTBbits.RB0
#define DQ_DIR	TRISBbits.TRISB0 

void Delay_Us(unsigned int us){	// 1/(64000000/4) == 0.00000000625 * 16 = 0.0000001 == 1us
	unsigned char i;
	while(us--){ 
		for(i=16; i==0; i--) Delay1TCY();
	}
}

char pd = 0;

void OW_HIZ(){
	DQ_DIR = 1;
}

void OW_LO(){
	DQ = 0;
	DQ_DIR = 0;
}

void OW_RESET(){
	OW_HIZ();
	while(DQ_R==0);
	pd = 0;
	OW_LO();
	Delay_Us(500);
	OW_HIZ();
	Delay_Us(70);
	if(DQ_R == 0)
		pd = 1;
	Delay_Us(430);
}

void DSTXBYTE(char byte){
	char count;
	for(count = 0; count < 8; count++){
		OW_LO();
		Delay_Us(3);
		DQ = (byte >> count) & 1;
		Delay_Us(60);
		OW_HIZ();
		Delay_Us(2);
	}
}

char DSRXBYTE(void){
	char count, byte=0, temp;
	for(count = 0; count < 8; count++){
		OW_LO();
		Delay_Us(6);
		OW_HIZ();
		Delay_Us(4);
		temp = DQ_R;
		Delay_Us(50);
		byte >>= 1;
		if(temp)
			byte |= 0x80;
	}
	return byte;
}
