.equ DS1307_ADDRESS_W=0xD0	;   DS1307; 
.equ DS1307_ADDRESS_R=0xD1	;   DS1307; 

.equ START=0x08				;A START condition has been transmitted
.equ R_START=0x10			;A repeated START condition has been transmitted
.equ MT_SLA_ACK=0x18		;SLA+W has been transmitted; ACK has been received
.equ MT_SLA_NOTACK=0x20		;SLA+W has been transmitted; NOT ACK has been received
.equ MT_DATA_ACK=0x28		;Data byte has been transmitted; ACK has been received
.equ MT_DATA_NOTACK=0x30	;Data byte has been transmitted; NOT ACK has been received
.equ ARBITRATION_LOST =0x38	;Arbitration lost in SLA+W or data bytes

.equ MR_SLA_ACK=0x40		;SLA+R has been transmitted; ACK has been received
.equ MR_SLA_NOTACK=0x48		;SLA+R has been transmitted; NOT ACK has been received
.equ MR_DATA_ACK=0x50		;Data byte has been received; ACK has been returned
.equ MR_DATA_NOTACK=0x58	;Data byte has been received; NOT ACK has been returned

ldi temp,32
out TWBR,temp

main:
	rcall StartTWI
	rcall MasterReceiverMode
	ldi temp,0
m1:
	rcall ReceiveData
	inc temp
	cpi temp, 8			;  8 
	brne m1		
	rcall StopTWI

	rcall cycle

;-----------------------------------------------------------
StartTWI:
	push temp
	ldi temp,(1<<TWINT)|(1<<TWSTA)|(1<<TWEN)	;  
	out TWCR, temp

	wait1:										;   TWINT
	in temp,TWCR								;     
	sbrs temp,TWINT							
	rjmp wait1							

	in temp,TWSR								;   TWI.
	andi temp, 0xF8								;.  .      ,
	cpi temp, START								;   ERROR
	brne ERROR
	pop temp
	ret

;-----------------------------------------------------------
StopTWI:
	push temp
	ldi temp, (1<<TWINT)|(1<<TWEN)|(1<<TWSTO)	;  
	out TWCR, temp
	pop temp
	ret

;-----------------------------------------------------------  /
MasterReceiverMode:
	push temp
	ldi temp, DS1307_ADDRESS_R					; _ +    TWDR.
	out TWDR, temp								;  TWINT  TWCR    
	ldi temp, (1<<TWINT) | (1<<TWEN)
	out TWCR, temp

	wait2:										;   TWINT.
	in temp,TWCR								;    _ + 
	sbrs temp,TWINT								; /  (/ ).
	rjmp wait2

	in temp,TWSR								;   .
	andi temp, 0xF8								;  .     MR_SLA_ACK,
	cpi temp, MR_SLA_ACK						;   ERROR
	brne ERROR
	pop temp
	ret

;-----------------------------------------------------------
ReceiveData:
	push temp
	ldi temp, (1<<TWINT) | (1<<TWEN)			;  TWINT  TWCR    
	out TWCR, temp

	wait3:										;   TWINT.  ,
	in temp,TWCR								;     / 
	sbrs temp,TWINT								; (/ ).
	rjmp wait3

	in data, TWDR								;   TWDR.

	in temp,TWSR								;    TWI.
	andi temp, 0xF8								;  .
	cpi temp, MR_DATA_ACK						;    MR_DATA_ACK,    ERROR
	brne ERROR					;     ERROR
	pop temp
	ret
