#include "eeprom.h"


uint8_t code emenu1[]="Please input command:\r\n";
uint8_t code emenu2[]="command:0xa5(write),0xaa(read)\r\n";
uint8_t code emenu3[]="format(hex)：command,address,data\r\n";


void EEPROM_Wirte(uint8_t addr,uint8_t wdat)
{
	FSHADRH = 0xF0; //EEPROM 起始地址为0xF000
	FSHADRL = addr;
	FSHDATL = wdat;
	EA = 0;
	FSHCON = 0xA5;  //启动FLASH编程操作
	while(FSHCON & 0x01);
	while(FSHCON & 0x02);
	EA = 1;
}
uint8_t EEPROM_Read(uint8_t addr)
{
	uint8_t temp;
	uint8_t code *temp1;
	temp1 = 0xF000 + addr; //EEPROM 起始地址为0xF000
	temp = *temp1;
	return temp;
}

void receive1(uint8_t *rc,uint8_t count)
{
	while(count--)
	{
		while(~SCON & 0x01);
		SCON ^= 0x01;
		*rc = SBUF;
		rc++;
	}
}

/*
串口以(命令，地址，数据)格式发送3个字节；如果收到写命令(0xA5)，
会在相应的地址写入数据；如果收到读命令(0xAA)，会通过串口发出
相应地址的数据
通信数据使用hex格式
eg:串口收到 0xa5 0x10 0x47，表示在0x10地址写0x47
eg:串口收到 0xaa 0x10 0xxx，表示读取0x10地址的数据
*/

void EEPROM_Test(void)
{
	uint8_t rc[3];
	uint8_t temp;
	
	/***********add flash clk div**************/
	temp = SYSCON & 0xC0;
	switch(temp)
	{
		case 0x80: //2Mhz
			FSDIV = 0x04;   // FLASH 编程时钟分频到 200KHz,分频比fsys/(2*(FSDIV+1))
			break;
		case 0x40: //1Mhz
			FSDIV = 0x02;   // FLASH 编程时钟分频到 200KHz,分频比fsys/(2*(FSDIV+1))
			break;
		case 0xC0: //4Mhz
			FSDIV = 0x09;   // FLASH 编程时钟分频到 200KHz,分频比fsys/(2*(FSDIV+1))
			break;
		default:
			break;				
	}
	/***********************/
	Uart_Init();
	sendString(emenu1);
	sendString(emenu2);
	sendString(emenu3);

	while(1)
	{
		receive1(rc,3);
		if(rc[0] == 0xA5 && rc[1] < 0x80)
		{
			EEPROM_Wirte(rc[1],rc[2]);
		}
		if(rc[0] == 0xAA && rc[1] < 0x80)
		{
			sendChar(EEPROM_Read(rc[1]));
		}
		
	}
}