;Sample 8051 routines for accessing I2C memory
;**** Start condition ********
i2c_start:
	SETB sda
	NOP
	SETB scl
	ACALL i2c_wait
	CLR sda        
	NOP
	CLR scl       
	RET
; ***** Stop condition *******
i2c_stop:
	SETB scl           
	NOP
	SETB sda          
	RET
;****** Send Acc to I2C line ******
i2c_send:
       MOV R7,#8
send_loop:
       RLC A
       MOV sda,C
       NOP
       SETB scl
       ACALL i2c_wait
       CLR scl
       DJNZ R7,send_sloop
       NOP
       SETB sda
       NOP
       SETB scl
       ACALL i2c_wait           
       MOV C,sda
       NOP
       CLR scl
       NOP
       CLR sda
       RET
;**** Receive in Acc I2C data ******
i2c_rec:
       MOV R7,#8
       CLR A
       SETB sda
rec_loop:
       ACALL i2c_wait
       SETB scl
       NOP
       MOV C,sda
       RLC A
       NOP
       CLR scl
       DJNZ R7,rec_loop
       NOP
       SETB	sda
       NOP
       SETB scl
       ACALL i2c_wait
       CLR scl
       NOP
       CLR sda
       RET
;****** Read in R5 one byte from EEPROM (addr. in R4)***
i2c_read:
;	CLR	ea		;disable interrupt
	ACALL	i2c_start
	MOV	A,#10100000b	;write mode
	ACALL	i2c_send
	NOP
	MOV	A,R4
	ACALL	i2c_send
	ACALL	i2c_start
	MOV	A,#10100001b	;read mode
	ACALL	i2c_send
	ACALL	i2c_wait
	ACALL	i2c_rec
	MOV	R5,A
	ACALL	i2c_stop
;	SETB	ea		;enable interrupt
	RET
;**** Write to EEPROM one byte in R5 to addr in R4 ****
i2c_write:
;	CLR	ea		;disable interrupt
	ACALL	i2c_start
	MOV	A,#10100000b	;write mode
	ACALL	i2c_send
	MOV	A,R4
	ACALL	i2c_send
	MOV	A,R5
	ACALL	i2c_send
	ACALL	i2c_stop
;	SETB	ea		;enable interrupt
	RET
;***** Wait 
i2c_wait:
	NOP
	NOP
	RET