
#ifndef __RAMFUNCTION_C
#define __RAMFUNCTION_C

#define	EEPROM_KEY	0x8AAA5551
#define ADDRESS		0x00002000

#include "opora.h"

void EraseEepromPage(uint32_t);
void WriteEeprom32bitWord(uint32_t,uint32_t);
void Pause(uint32_t);

void RAMFunction(uint32_t val)
{
	uint32_t temp_Counter,temp;

	temp_Counter=val;			//read last value of variable
	if(temp_Counter==0xFFFFFFFF) temp_Counter++;
	
	EEPROM->KEY=EEPROM_KEY;		//key for eeprom 
		
	temp=EEPROM->CMD;			//EEPROM programming mode
	temp|=1;
	EEPROM->CMD=temp;

	EraseEepromPage(ADDRESS);
	temp_Counter++;
	WriteEeprom32bitWord(ADDRESS,temp_Counter);

	temp=EEPROM->CMD;	//EEPROM normal mode
	temp&=0xFFFE;
	EEPROM->CMD=temp;

	EEPROM->KEY=0;
}

//	EraseEepromPage() - function for erase one page of EEPROM
//	Parameters:	uint32_t address - number of EEPROM page
void EraseEepromPage(uint32_t address)
{
	uint32_t temp;

	temp=EEPROM->CMD;				
	temp&=0xFDFF;
	EEPROM->CMD=temp;				//IFREN=0

	EEPROM->ADR=address;

	temp=EEPROM->CMD;				
	temp|=(1<<6)|(1<<10);
	EEPROM->CMD=temp;				//XE=1, ERASE=1

	Pause(40);						//Pause ~ 12us
	
	temp=EEPROM->CMD;				
	temp|=1<<13;
	EEPROM->CMD=temp;				//NVSTR=1

	Pause(320000);					//Pause ~ 40ms
	
	temp=EEPROM->CMD;				
	temp&=0xFBFF;
	EEPROM->CMD=temp;				//ERASE=0
	
	Pause(40);						//Pause ~ 12us

	temp=EEPROM->CMD;				
	temp&=0xDFBF;
	EEPROM->CMD=temp;				//XE=0, NVSTR=0

	Pause(10);						//Pause ~ 7us
}	

//	WriteEeprom32bitWord() - function for write 32-bits word in EEPROM
//	Parameters:	uint32_t address - address of word to write in EEPROM
//				uint32_t value - value for write in EEPROM
//	(EEPROM page with this word must be erase before write word)
void WriteEeprom32bitWord(uint32_t address, uint32_t value)
{
	uint32_t temp;

	temp=EEPROM->CMD;				
	temp&=0xFDFF;
	EEPROM->CMD=temp;				//IFREN=0

	EEPROM->ADR=address;
	EEPROM->DI=value;

	temp=EEPROM->CMD;				
	temp|=(1<<12)|(1<<6);
	EEPROM->CMD=temp;				//XE=1, PROG=1

	Pause(10);						//Pause ~ 7us

	temp=EEPROM->CMD;				
	temp|=1<<13;
	EEPROM->CMD=temp;				//NVSTR=1

	Pause(40);	  					//Pause ~ 12us

	temp=EEPROM->CMD;				
	temp|=1<<7;
	EEPROM->CMD=temp;				//YE=1

	Pause(320000);

	temp=EEPROM->CMD;				
	temp&=0xFF7F;
	EEPROM->CMD=temp;				//YE=0

	temp=EEPROM->CMD;				
	temp&=0xEFFF;
	EEPROM->CMD=temp;				//PROG=0

	Pause(40);						//Pause ~ 12us

	temp=EEPROM->CMD;				
	temp&=0xDFBF;
	EEPROM->CMD=temp;				//XE=0, NVSTR=0

	Pause(10);						//Pause ~ 7us
}

//	Pause() - function for set pause in system clock ticks
//	Parameters:	uint32_t Hclk_ticks - value of system_clock/2 ticks for pause
void Pause(uint32_t Hclk_ticks)
{
	TIMER1->ARR=Hclk_ticks;
	TIMER1->CNTRL|=1;
	while((TIMER1->STATUS&0x2)==0);
	TIMER1->CNTRL&=0xFFFE;
	TIMER1->STATUS=0;	
}

#endif	//__RAMFUNCTION_C

