
;...KONFIGURACE I2C................
;V TRIS NASTAVIT VYSTUPY SBERNICE NA VSTUP

MASKA_IC		EQU	b'11001111'	;BITY SCL,SDA MUSI BYT V 0
PORT_IC		EQU	PORTC		;PORT SBERNICE
#define 	SCL		PORTC,4
#define 	SDA		PORTC,5		;DEFINICE VYSTUPU
#define 	F_ACK		FLAG,0		;ACK=0 NOACK=1




;.......................................................
;RUTINA PRO KOMUNIKACI I2C
;DEFINOVAT TMP_IC,CYKL PLATNE VE VSECH BANKACH!!!!!!!!

START_IC	MOVLW	MASKA_IC
	ANDWF	PORT_IC,F		;NASTAVENI LATCHU

	BANKSEL	TRISB
	BSF	SCL	
	BSF	SDA		;KLIDOVY STAV
	CALL	CEK5
	BCF	SDA
	CALL	CEK5
	BCF	SCL
	BANKSEL	0
	RETURN
;................

;DATA DO W, ACK DO F_ACK

WRITE_IC	MOVWF	TMP_IC
	MOVLW	8
	MOVWF	CYKL_IC		;8CYKLU-BITU

WRITE_IC1	RLF	TMP_IC,F
	BANKSEL	TRISB
	BCF	SDA
	BTFSC	STATUS,C		;C=0 ?		
	BSF	SDA		;NEE, PODLE C NASTAV SDA
	CALL	CEK5
	BSF	SCL
	CALL	CEK5
	BCF	SCL
	CALL	CEK5		;HODINOVY IMPULZ
	BANKSEL	0
	DECFSZ	CYKL_IC,F		;BYL POSLEDNI BIT??
	GOTO	WRITE_IC1		;NEE
	CALL	CEK5		;ANO, PRECIST ACK
	BANKSEL	TRISB
	BSF	SDA
	CALL	CEK5
	BSF	SCL
	CALL	CEK5
	BANKSEL	0
	BCF	F_ACK
	BTFSC	SDA
	BSF	F_ACK		;PODLE SDA/ACK/ F_ACK		
	BANKSEL	TRISB
	BCF	SCL
	BANKSEL	0
	RETURN
;................................
;VYSTUP V TMP_IC, W, FLAG-ACK

READ_IC	MOVLW	8
	MOVWF	CYKL_IC		;8CYKLU-BITU
	BANKSEL	TRISB
	BSF	SDA		;NASTAVIT TRETI STAV NA SDA
READ_IC1	CALL	CEK5
	BANKSEL	TRISB
	BSF	SCL		;NABEZNA HRANA HODIN
	CALL	CEK5
	BANKSEL	0
	BCF	STATUS,C
	BTFSC	SDA	
	BSF	STATUS,C		;PODLE SDA NASTAV C
	RLF	TMP_IC,F		;PROTOC C DO TMP_IC
	BANKSEL	TRISB	
	BCF	SCL		;KONEC HODIN
	CALL	CEK5
	BANKSEL	0
	DECFSZ	CYKL_IC,F		;JE POSLEDNI BIT??
	GOTO	READ_IC1		;NEE
	CALL	CEK5
	BANKSEL	TRISB
	BCF	SDA		;ACK
	BANKSEL	0
	BTFSS	F_ACK		;PODLE PRIZNAKU,NASTAV SDA
	GOTO	READ_IC2
	BANKSEL	TRISB
	BSF	SDA		;ACK-NOACK
READ_IC2	CALL	CEK5
	BANKSEL	TRISB
	BSF	SCL
	CALL	CEK5
	BCF	SCL		;HODINOVY IMPULZ
	BANKSEL	0
	MOVFW	TMP_IC		;ZKOPIROVAT DO W

	RETURN

;......................
STOP_IC	
	BANKSEL	TRISB
	BCF	SDA	
	CALL	CEK5
	BSF	SCL
	CALL	CEK5
	BSF	SDA		;UVEDENI DO KLIDOVEHO STAVU
	BANKSEL	0
	RETURN

;....................			
CEK5	NOP
	NOP
	NOP
	NOP
	RETURN
;..........................................................
