一、前言
本次使用STM8S003F芯片,编译环境为IAR,至于新建工程什么的教程很多,这里就不多叙述了。本次需要往内存存储数据,STM8S003F有128bytes EEPROM存储数据。
二、EEPROM解锁内存
因为只用到了EEPROM,因此只解锁了EEPROM,若要使用FLASH,可以将注释掉的代码使用。
void FLASH_Config(void)
{
/* Define flash programming Time*/
FLASH_SetProgrammingTime(FLASH_PROGRAMTIME_STANDARD);
// FLASH_Unlock(FLASH_MEMTYPE_PROG);
// /* Wait until Flash Program area unlocked flag is set*/
// while (FLASH_GetFlagStatus(FLASH_FLAG_PUL) == RESET)
// {}
/* Unlock flash data eeprom memory */
FLASH_Unlock(FLASH_MEMTYPE_DATA);
/* Wait until Data EEPROM area unlocked flag is set*/
while (FLASH_GetFlagStatus(FLASH_FLAG_DUL) == RESET)
{}
}
三、读写EEPROM函数
将EEPROM开头地址映射为0,封装后的函数便于调用,不用管写入内存到哪里了:
写数据函数:
uint8_t flash_date_write(uint32_t Addr, uint8_t *source, uint8_t nbyte)
{
uint8_t i = 0;
uint32_t FlashAddr = Addr+FLASH_DATA_START_PHYSICAL_ADDRESS;
if((FlashAddr<FLASH_DATA_START_PHYSICAL_ADDRESS) || (FlashAddr+nbyte>FLASH_DATA_END_PHYSICAL_ADDRESS))
{
return FALSE;
}
//按字节写入
for(i=0;i<nbyte;i++)
{
FLASH_ProgramByte(FlashAddr+i,source[i]);
FLASH_WaitForLastOperation(FLASH_MEMTYPE_DATA);
}
return TRUE;
}
读数据函数:
uint8_t flash_date_read(uint32_t Addr, uint8_t *source, uint8_t nbyte)
{
uint8_t i = 0;
uint32_t FlashAddr = Addr+FLASH_DATA_START_PHYSICAL_ADDRESS;
if((FlashAddr<FLASH_DATA_START_PHYSICAL_ADDRESS) || (FlashAddr+nbyte>FLASH_DATA_END_PHYSICAL_ADDRESS))
{
return FALSE;
}
//按字节写入
for(i=0;i<nbyte;i++)
{
source[i] = FLASH_ReadByte(FlashAddr+i);
FLASH_WaitForLastOperation(FLASH_MEMTYPE_DATA);
}
return TRUE;
}
读写数据例程:
uint8_t wBuf[]={0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80};
flash_date_write(0,wBuf,8);
uint8_t rBuf[8];
flash_date_read(0,rBuf,8);
RS485_SEND;
TxIndex=0;
while (TxIndex<8)
{
UART1_SendData8(rBuf[TxIndex]);
while (UART1_GetFlagStatus(UART1_FLAG_TXE) == RESET);
TxIndex++;
}
Delay(100);