; *******************************************************
;
; Dallas 1-Wire Support for PIC16F628
;
; Processor has 4MHz clock and 1µs per instruction cycle.
;
; *******************************************************
; *******************************************************
; Dallas Semiconductor 1-Wire MACROS
; *******************************************************
OW_HIZ:MACRO
	BSF STATUS,RP0 ; Select Bank 1 of data memory
	BSF TRISB, DQ ; Make DQ pin High Z
	BCF STATUS,RP0 ; Select Bank 0 of data memory
	ENDM
; --------------------------------------------------------
OW_LO:MACRO
	BCF STATUS,RP0 ; Select Bank 0 of data memory
	BCF PORTB, DQ ; Clear the DQ bit
	BSF STATUS,RP0 ; Select Bank 1 of data memory
	BCF TRISB, DQ ; Make DQ pin an output
	BCF STATUS,RP0 ; Select Bank 0 of data memory
	ENDM
; --------------------------------------------------------
WAIT:MACRO TIME
;Delay for TIME µs.
;Variable time must be in multiples of 5µs.
	MOVLW (TIME/5)-1 ;1µs
	MOVWF TMP0 ;1µs
	CALL WAIT5U ;2µs
	ENDM
; *******************************************************
; Dallas Semiconductor 1-Wire ROUTINES
; *******************************************************
WAIT5U:
;This takes 5µS to complete
	NOP ;1µs
	NOP ;1µs
	DECFSZ TMP0,F ;1µs or 2µs
	GOTO WAIT5U ;2µs
	RETLW 0 ;2µs
; --------------------------------------------------------
OW_RESET:
	OW_HIZ ; Start with the line high
	CLRF PDBYTE ; Clear the PD byte
	OW_LO
	WAIT .500 ; Drive Low for 500µs
	OW_HIZ
	WAIT .70 ; Release line and wait 70µs for PD Pulse
	BTFSS PORTB,DQ ; Read for a PD Pulse
	INCF PDBYTE,F ; Set PDBYTE to 1 if get a PD Pulse
	WAIT .400 ; Wait 400µs after PD Pulse
	RETLW 0
; --------------------------------------------------------
DSRXBYTE: ; Byte read is stored in IOBYTE
	MOVLW .8
	MOVWF COUNT ; Set COUNT equal to 8 to count the bits
DSRXLP:
	OW_LO
	NOP
	NOP
	NOP
	NOP
	NOP
	NOP ; Bring DQ low for 6µs
	OW_HIZ
	NOP
	NOP
	NOP
	NOP ; Change to HiZ and Wait 4µs
	MOVF PORTB,W ; Read DQ
	ANDLW 1<<DQ ; Mask off the DQ bit
	ADDLW .255 ; C=1 if DQ=1: C=0 if DQ=0
	RRF IOBYTE,F ; Shift C into IOBYTE
	WAIT .50 ; Wait 50µs to end of time slot
	DECFSZ COUNT,F ; Decrement the bit counter
	GOTO DSRXLP
	RETLW 0
; --------------------------------------------------------
DSTXBYTE: ; Byte to send starts in W
	MOVWF IOBYTE ; We send it from IOBYTE
	MOVLW .8
	MOVWF COUNT ; Set COUNT equal to 8 to count the bits
DSTXLP:
	OW_LO
	NOP
	NOP
	NOP ; Drive the line low for 3µs
	RRF IOBYTE,F
	BSF STATUS,RP0 ; Select Bank 1 of data memory
	BTFSC STATUS,C ; Check the LSB of IOBYTE for 1 or 0
	BSF TRISB,DQ ; HiZ the line if LSB is 1
	BCF STATUS,RP0 ; Select Bank 0 of data memory
	WAIT .60 ; Continue driving line for 60µs
	OW_HIZ ; Release the line for pullup
	NOP
	NOP ; Recovery time of 2µs
	DECFSZ COUNT,F ; Decrement the bit counter
	GOTO DSTXLP
	RETLW 0
; --------------------------------------------------------