-->
Page 1 of 2

Saving some char and integer variables permanently in memory

PostPosted: Wed Apr 22, 2015 6:53 am
by sean_intez
Hey guys could anyone please help me achieve this?

I need to save probably one or two lines of strings and integers permanently and retrieve them in the next power cycle. so removing power from esp should not delete the data.

Thanks in advance

Re: Saving some char and integer variables permanently in me

PostPosted: Wed Apr 22, 2015 7:24 am
by Israel Lot
You can save data in flash. I use the bottom sectors of the chip so it does't get erased on a reprogram as well.
spi_flash_write and spi_flash_read does what you need.
The only concern is that reading and writing to flash has to be 4byte aligned.

Re: Saving some char and integer variables permanently in me

PostPosted: Wed Apr 22, 2015 8:30 am
by AcmeUK
Hi Israel

Care to share example code with us?

Re: Saving some char and integer variables permanently in me

PostPosted: Wed Apr 22, 2015 9:46 am
by Israel Lot
First choose a sector of the flash memory to write to.
Doing some tests I realized the last two sectors are used for storing wifi config, so get the Last - 4 for example.
The 515k flash has 0x80 sectors, so:
Code: Select all#define CONFIG_SECTOR 0x80-4


Define your struct:
Code: Select alltypedef struct {
   uint32_t A;
   char B[256];
} config;


In ESP you have to erase the whole sector, so:
Code: Select allspi_flash_erase_sector(CONFIG_SECTOR);


To write , you need the sector address.
Code: Select all #define CONFIG_ADDRESS = ( CONFIG_SECTOR * 4096 )

Note that the sector size in ESP' flash is usually 4096

To write, simply :
Code: Select allspi_flash_write(CONFIG_ADDRESS ,(uint32 *)(some_config_pointer),sizeof(config));


And to read :
Code: Select allspi_flash_read(CONFIG_ADDRESS ,(uint32 *)(some_config_pointer),sizeof(config));


Note the need to cast to uint32 pointer and always remember that size should be 4byte aligned.