; ************************************
; * EEPROM Access  by PEK '2000
; *
; ************************************


.include "8515def.inc"


; ************************************
; * Register and Variable Definitions             
; ************************************
.def	temp	=R16
.def	eedata	=R17			; EEPROM data


; ************************************
; * EEPROM Allocations
; ************************************
.eseg
data:	.DB 	0			; Declare one byte in EEPROM


; ************************************
; * Start of Code                    
; ************************************
.cseg
.org 0
	rjmp	Start

Start:	ldi	temp,low(RAMEND)
	out	SPL,temp		; Set stack pointer to last internal RAM location
	ldi	temp,high(RAMEND)
	out	SPH,temp

	ldi	ZH,high(data)		; Z points to EEPROM (data)
	ldi	ZL,low(data)

	rcall	Read_EEPROM

	ldi	eedata,0xEE		; Byte to write
	rcall	Write_EEPROM

Loop:
	rjmp	Loop


; ************************************
; * READ from EEPROM                 *
; * Z - points to location           *
; * eedata - data byte               *
; ************************************
Read_EEPROM:
	out	EEARH,ZH		; Set EEPROM Address Register
	out	EEARL,ZL

	ldi	temp,0x00		; Reset EEPROM Control Register
	out	EECR,temp

	sbi	EECR,EERE		; Set EEPROM Read Enable

EEPROM_Read_Loop:
	sbic	EECR,EERE		; Wait for EERE to get low
	rjmp	EEPROM_Read_Loop

	in	eedata,EEDR		; Save data from EEPROM Data Register
	ret


; ************************************
; * WRITE to EEPROM                  *
; * Z - points to location           *
; * eedata - byte to write           *
; ************************************
Write_EEPROM:
	out	EEARH,ZH		; Set EEPROM Address Register
	out	EEARL,ZL

	out	EEDR,eedata		; Byte to write

	sbi	EECR,EEMWE		; Set EEPROM Master Write Enable
	sbi	EECR,EEWE		; Set EEPROM Write Enable

EEPROM_Write_Loop:
	sbic	EECR,EEWE		; Wait for EEWE to get low
	rjmp	EEPROM_Write_Loop

	ret	