stc15w系列单片机内部自带1~9k EEPROM,对于需要存储数据的项目,十分方便,而且读写也简单
以下是我整理的EEPROM接口函数,参照了stc官方例程
eeprom.h 头文件
#ifndef EEPROM_H_
#define EEPROM_H_
#include "mydatatype.h"
#define CMD_IDLE 0
#define CMD_READ 1
#define CMD_PROGRAM 2
#define CMD_ERASE 3
#define MileageAddr 64
#define BLaddr 1024
#define BYTE unsigned char
#define WORD unsigned int
BYTE IAPreadbyte(WORD addr);
void IAPprogrambyte(WORD addr,BYTE dat);
void IAPerasesector(WORD addr);
void IAPidle();
void writeDatas(WORD addr,BYTE *pdat,BYTE n); //写入一串数据
#endif
eeprom.c文件
#include "eeprom.h"
#include "intrins.h"#include "stc15.h"
#include "string.h"
void IAPidle()
{
IAP_CONTR = 0;
IAP_CMD = 0;
IAP_TRIG = 0;
IAP_ADDRH = 0X80; //将地址设置到非IAP区
IAP_ADDRL = 0;
}
BYTE IAPreadbyte(WORD addr) //从EEPROM指定位置读取一个字节
{
BYTE dat;
IAP_CONTR = 0X83;
IAP_CMD = CMD_READ;
IAP_ADDRL = addr;
IAP_ADDRH = addr>>8;
IAP_TRIG = 0X5A;
IAP_TRIG = 0XA5;
_nop_();
dat = IAP_DATA;
IAPidle();
return dat;
}
void IAPprogrambyte(WORD addr,BYTE dat) //写一个字节到指定位置EEPROM
{
IAP_CONTR = 0X83;
IAP_CMD = CMD_PROGRAM;
IAP_ADDRL = addr;
IAP_ADDRH = addr>>8;
IAP_DATA = dat;
IAP_TRIG = 0X5A;
IAP_TRIG = 0XA5;
_nop_();
IAPidle();
}
void IAPerasesector(WORD addr) //扇区擦除
{
IAP_CONTR = 0X83;
IAP_CMD = CMD_ERASE;
IAP_ADDRL = addr;
IAP_ADDRH = addr>>8;
IAP_TRIG = 0X5A;
IAP_TRIG = 0XA5;
_nop_();
IAPidle();
}
void writeDatas(WORD addr,BYTE *pdat,BYTE n)
{
BYTE i;
IAPerasesector(addr);
for(i=0;i<n;i++)
{
IAPprogrambyte(addr+i,pdat[i]);
}
}
我用的是stc15w408as,亲测好用