/*Copyright (C), 2024-2030
*文件名:	Nvr_Flash.c
*版  本:	Ver1.00
*日  期:	2025/04/30
*描  述:	Nvr_Flash配置
*备  注:     
**********************************************************/
#include "Nvr_Flash.h"
#include "BL51F003T.h"	
#include "stdio.h"
xdata INT8U buf[256] = {0};
/**
	* @brief  NVR扇区擦除 
  * @param  SectorAddr: 扇区起始地址
  * @retval None
	*/
void erase_nvr(unsigned int SectorAddr)
{
	FSFLG = NVR_UNLOCK;								//NVR解锁
	FSPTSL = (SectorAddr&0xff);				//地址位置
	FSPTSH = ((SectorAddr>>8)&0xff);
	FSCMD = NVR_ERASE;								//擦除NVR一个扇区
	FSFLG = NVR_LOCK;									//锁定NVR
}

/**
	* @brief  NVR扇区写
  * @param  buf：待写入数据的数组指针
						SectorAddr: 起始地址
						len: 数据长度
  * @retval None
	*/
void write_nvr(unsigned char *buf, unsigned int SectorAddr, unsigned int len)
{
	unsigned int i=0;

	FSFLG = NVR_UNLOCK;								//NVR解锁
	FSCMD = NVR_WRITE;								//写NVR DATA区	
	
	for(i=0; i<len; ++i)
	{
		FSPTSL =(SectorAddr&0xff);			//地址位置
		FSPTSH =((SectorAddr>>8)&0xff);
		SectorAddr++;
		FSDAT=buf[i];										//BUF赋值到FLASH数据寄存器
	}
	FSFLG = NVR_LOCK;									//锁定NVR
}

/**
	* @brief  NVR扇区读
  * @param  buf：待读入数据的数组指针
						SectorAddr: 起始地址
						len: 数据长度
  * @retval None
	*/
void read_nvr(unsigned char *buf,unsigned int SectorAddr,unsigned int len)
{
	unsigned int i=0;

	FSCMD=NVR_READ;										//读NVR DATA区
	for(i=0; i<len; ++i)
	{
		FSPTSL =(SectorAddr&0xff);			//地址位置
		FSPTSH =((SectorAddr>>8)&0xff);
		++SectorAddr;
		buf[i] = FSDAT;									//将FLASH数据寄存到BUF
	}
}
/**
	* @brief  NVR测试，擦除一个扇区，并写入一个扇区的数据。
  * @param  None
  * @retval None
	*/
void NVR_INIT()
{
	xdata INT8S buff[32];
	INT16S i;
	
	for(i=0; i<23; i++)
	{
		buff[i] = i;
	}
	erase_nvr(NVR1_START_ADDR);						//擦除NVR1扇区
	write_nvr(buff, NVR1_START_ADDR, 32);//写NVR扇区32个字节	
	for(i=0; i<32; i++)
	{
		buff[i] = 0xFF;
	}
	read_nvr(buff, NVR1_START_ADDR, 32);	//读NVR1扇区32个字节
}

