#include "flash.h"
#define READword(addr) ((u16)(*(volatile u16 *__near)(addr))) //16位
#define DFLASH_LOWEST_START_PAGE 0x00 //dflash的起始页 0~ 31
#define DFLASH_START 0x00100000 //dflash的起始地址
#define DFLASH_PAGE_SIZE 0x0400 //dflash的大小为1K.
#define DFLASH_PAGE_WINDOW_START 0x0800 //dflash页面窗口的起始地址 0x0800~0x0bff 1K 窗口段 做映射
u16 Buffer[] = {0x0000,0x1111,0x2222,0x3333,0x4444,0x5555,0x0066,0x0077,0x8888,0x9999,0xaaaa};
u16 data_Address = 0x0000;
u16 date_read[11];
void DFlash_Init(void)
{
while(FSTAT_CCIF==0); //等待指令完成,FLASH操作完成
FCLKDIV = 0x0F; //OSC16M 20M/0X13
FCNFG = 0x00; //禁止中断
while(FCLKDIV_FDIVLD==0); //设置时钟成功被写入
}
void DFlash_Write(word ADDR16)
{
while(FSTAT_CCIF==0);
/*
if(FSTAT_ACCERR) //判断并清除标志位;
FSTAT_ACCERR=1;
if(FSTAT_FPVIOL) //判断并清除标志位;
FSTAT_FPVIOL=1;
*/
if(FSTAT & 0x30)
FSTAT |= 0x30;
FCCOBIX_CCOBIX=0x00;
FCCOB=0x1110; //命令和高位地址
FCCOBIX_CCOBIX=0x01; //地址后16位
FCCOB=ADDR16; //低16位地址
FCCOBIX_CCOBIX=0x02; //第一个数据
FCCOB=Buffer[0];
FCCOBIX_CCOBIX=0x03; //第二个数据
FCCOB=Buffer[1];
FCCOBIX_CCOBIX=0x04; //第三个数据
FCCOB=Buffer[2];
FCCOBIX_CCOBIX=0x05; //第四个数据
FCCOB=Buffer[3];
/*
FCCOBIX_CCOBIX=0x06;
FCCOB=Buffer[4];
FCCOBIX_CCOBIX=0x07;
FCCOB=Buffer[5];
FCCOBIX_CCOBIX=0x08;
FCCOB=Buffer[6];
FCCOBIX_CCOBIX=0x09;
FCCOB=Buffer[7];
FCCOBIX_CCOBIX=0x0a;
FCCOB=Buffer[8];
FCCOBIX_CCOBIX=0x0b;
FCCOB=Buffer[9];
FCCOBIX_CCOBIX=0x0c;
FCCOB=Buffer[10];
*/
FSTAT_CCIF=1; //执行命令
while(FSTAT_CCIF==0); //等待执行完毕
}
word DFlash_Read (word addr)
{
u8 lastepage; //zuihouEPAGE的值
u8 nowepage; //现在EPAGE的值
u16 data; //读取出的数据
lastepage = EPAGE; ///*** EPAGE - Data FLASH Page Index Register; 0x00000017 ***/
nowepage = (u8)((DFLASH_LOWEST_START_PAGE)+(addr >> 10)); //计算EPAGE addr/1024 求出第几页
EPAGE = nowepage; //给EPAGE赋值
data = READword((addr & (DFLASH_PAGE_SIZE - 1)) + DFLASH_PAGE_WINDOW_START); //读取页面窗口中的数据 == addr%1024
EPAGE = lastepage; //恢复EPAGE的值
return(data);
}
void DFlash_Erase(word ADDR16)
{
while(FSTAT_CCIF==0);
/*
if(FSTAT_ACCERR) //判断清除标志位;
FSTAT_ACCERR = 1;
if(FSTAT_FPVIOL) //一样,防止写入失败
FSTAT_FPVIOL = 1;
*/
if(FSTAT & 0x30)
FSTAT |= 0x30;
FCCOBIX_CCOBIX = 0x00; //高8命令,低八高地址
FCCOB = 0x1210; //写入擦除命令和高位地址 0x12擦除
FCCOBIX_CCOBIX = 0x01; //启动执行命令
FCCOB = ADDR16; //写入低16位的地址
FSTAT_CCIF = 1; //启动执行命令
while(FSTAT_CCIF==0);
}
/*
void main(void)
{
DFlash_Init();
DFlash_Erase(data_Address);
DFlash_Write(data_Address);
date_read[0] = DFlash_Read(data_Address);
date_read[1] = DFlash_Read(data_Address+2);
date_read[2] = DFlash_Read(data_Address+4);
date_read[3] = DFlash_Read(data_Address+6);
}
*/