我贴一个QY4的:
//eeprom.c
#include
#include "utils.h"
#include "hidef.h"
#include "globdefs.h"
#define FLASH_CONTROL_LOCATION 0x88
#define CPU_BUS_CLOCK 5
#define CPU_SPEED_CONST (4*CPU_BUS_CLOCK)
#define ERASE_ROUTINE_ADDRESS 0x2806
#define PROGR_ROUTINE_ADDRESS 0x2809
#define DELAY_CYCLES_OK 2000
#define INIT_CMD 0xFF
void delay(word cycles);
static struct
{
byte CTRLBYT;
byte CPUSPD;
word LADDR;
byte DATA;
}
flash_control @FLASH_CONTROL_LOCATION;
bool WriteByteInFlash(word address, byte data)
{
byte low_adr = SB(address, 1);
byte high_adr = SB(address, 0);
DisableInterrupts;
flash_control.CTRLBYT = 0;
flash_control.CPUSPD = CPU_SPEED_CONST;
flash_control.LADDR = address;
flash_control.DATA = data;
asm
{
lda low_adr
psha
lda high_adr
psha
pulh
pulx
jsr PROGR_ROUTINE_ADDRESS
}
EnableInterrupts;
return (*((byte*)(address)) == data);
}
bool EraseSegmentInFlash(word address)
{
byte low_adr = SB(address, 1);
byte high_adr = SB(address, 0);
DisableInterrupts;
flash_control.CTRLBYT = 0;
flash_control.CPUSPD = CPU_SPEED_CONST;
flash_control.LADDR = address;
flash_control.DATA = 0;
asm
{
lda low_adr
psha
lda high_adr
psha
pulh
pulx
jsr ERASE_ROUTINE_ADDRESS
}
EnableInterrupts;
return 1;
}
void Node_Process_Config_Data(word data)
{
byte cmd, res = 0;
static byte prev_cmd = INIT_CMD;
if (
#if (USE_BUTTON)
BUTTON_BIT &&
#endif
(FLASH_CONFIG_CHECK == (SB(data, HIGH_BYTE) & FLASH_CONFIG_CHECK_MASK)))
{
cmd = (SB(data, HIGH_BYTE) & FLASH_ADDRESS_MASK);
switch (cmd)
{
case FLASH_RESET_CMD:
if (prev_cmd != INIT_CMD)
{
prev_cmd = INIT_CMD;
res = 1;
}
break;
case FLASH_PAGE_ERASE_CMD:
if (prev_cmd != cmd) res = EraseSegmentInFlash(FLASH_CONFIG_START_ADDRESS | cmd);
prev_cmd = cmd;
break;
default:
if (prev_cmd != cmd) res = WriteByteInFlash(FLASH_CONFIG_START_ADDRESS | cmd, SB(data, LOW_BYTE));
prev_cmd = cmd;
break;
}
if (res)
{
ERROR_LED_BIT = 1;
delay(DELAY_CYCLES_OK);
ERROR_LED_BIT = 0;
}
}
}
//eeprom.h
bool WriteByteInFlash(word address, byte data);
bool EraseSegmentInFlash(word address);
void Node_Process_Config_Data(word data); |