ESP32 Flash Memory: Read/Write, Partitions & Size (Arduino)

In this tutorial, you’ll learn how to use the ESP32 Flash Memory to save data permanently in Arduino IDE. You’ll learn how much flash your ESP32 really has, how it’s divided into partitions, how to create your own data partition with a custom partition table, and how to read and write any data type to it without killing the flash or your sketch.

We’ll also measure how long flash erase, write, and read operations take, and build a save-last-state example with wear leveling that erases a flash sector only once every 512 saves. If you only need to store a few settings, I’ll point you to the right library for that too. Without further ado, let’s get right into it!

ESP32 Flash Memory Read & Write Example

To write to the ESP32 flash memory, add a small data partition to your partition table, find it with esp_partition_find_first(), erase the 4kB sector you’re going to use with esp_partition_erase_range(), then write with esp_partition_write() and read with esp_partition_read(). Here is a complete boot counter that keeps its value in flash across resets and power loss:

Save the partitions.csv file below in the same folder as the sketch (the Arduino IDE picks it up automatically), upload, and press the EN (reset) button a few times. The boot count keeps going up. Note the 0xFFFFFFFF check: erased flash reads all ones, not zeros.

ESP32 flash memory read and write example serial monitor output: the boot count saved in flash increases after every reset

If you only need to save a few settings (WiFi credentials, a calibration value, the last state), the Preferences library is simpler, and it doesn’t need a custom partition table. The table below shows which method fits which job. The rest of this tutorial explains how the ESP32 flash memory works, the custom partition table, and the full examples.

Note: All examples in this tutorial are tested with: ESP32 DevKit V1 (ESP32-WROOM-32), Arduino-ESP32 core 3.3.12, Arduino IDE 2.x.


ESP32 Flash Memory Size & Memory Map

Most ESP32 boards have 4MB of external SPI flash memory, including the ESP32 DevKit V1 with the ESP32-WROOM-32 module. Modules with 8MB and 16MB are common too (the ESP32 chip can address up to 16MB of flash). The flash chip sits inside the module’s metal shield, next to the ESP32 chip, and it holds everything: the bootloader, your sketch, and your data.

A partition table at address 0x8000 divides the flash into partitions. This is the default partition table of the Arduino ESP32 core for a 4MB board (default.csv), next to the one we’ll use in this tutorial:

ESP32 4MB flash memory map: default Arduino partition table (nvs, otadata, app0, app1, spiffs, coredump) and a custom partitions.csv with a 64 kB storage data partition, plus a 4 kB flash sector made of 16 pages of 256 bytes

PartitionOffsetSizeWhat It Holds
Bootloader + partition table0x1000 / 0x800032kBSecond-stage bootloader and the partition table itself
nvs0x900020kBNon-Volatile Storage: Preferences, EEPROM library, WiFi and PHY calibration data
otadata0xE0008kBWhich app slot (app0 or app1) boots after an OTA update
app00x100001.25MBYour sketch (this is the “Maximum is 1310720 bytes” in the compile output)
app10x1500001.25MBThe second app slot for OTA (Over-The-Air) firmware updates
spiffs0x2900001.375MBFile system: LittleFS, SPIFFS, or FFat
coredump0x3F000064kBCrash dumps for debugging

So out of the 4MB, your sketch gets 1.25MB, files get 1.375MB, and NVS gets only 20kB. You can change all of these numbers with your own partition table, as you’ll see in a minute. To check the flash size and the partition table of your own board, run LAB 1.


How to Save Data to ESP32 Flash Memory

There are five ways to keep data on the ESP32 when it resets or loses power, and four of them use the flash memory. Use Preferences for settings, LittleFS for files and logs, and a raw data partition (this tutorial) when you need full control over a large block of flash.

MethodWhere It LivesBest ForSurvives Power Loss?
Preferences (NVS)nvs partitionSettings, WiFi credentials, counters (key-value pairs)Yes
EEPROM library (NVS)nvs partitionPorting old Arduino EEPROM code (deprecated, but works)Yes
LittleFS filesspiffs partitionFiles, logs, web pages, JSON or CSV dataYes
Raw flash partitionYour own data partitionLarge binary data, custom logs and ring buffers, full controlYes
RTC memory (RTC_DATA_ATTR)8kB RTC RAMValues that only need to survive deep sleepNo

The EEPROM library and Preferences are covered in the ESP32 EEPROM Tutorial, including a measured size limit and a Preferences example. For deep sleep, check out ESP32 Sleep Modes. Here is a minimal LittleFS example that appends a line to a file in flash on every boot (it uses the spiffs partition, which is in both the default and our custom partition table):


How ESP32 Flash Memory Works (Erase, Write, Read)

ESP32 flash memory can only be written after it’s erased, and it erases in 4kB sectors. This one rule explains most flash bugs. The external flash is a NOR flash chip, and it has three basic operations:

  • Erase sets every bit of a whole 4kB sector to 1, so every byte reads 0xFF. You can’t erase less than a sector.
  • Write (program) can only change bits from 1 to 0, up to one 256-byte page per flash command (the driver splits larger writes for you).
  • Read works at any address, any size, as many times as you want.
ESP32 flash erase before write animation: an erased byte reads 0xFF, writing 0xF0 clears bits, writing 0x0F without erasing gives 0x00, and only a 4 kB sector erase sets the bits back to 1

So if you write 0x0F over a byte that holds 0xF0 without erasing it first, you get 0x00: the flash can clear bits but can’t set them back. And esp_partition_write() still returns ESP_OK (LAB 4 shows this on real hardware). The library won’t warn you, so it’s your job to erase before you write.

ESP32 Flash Memory Write Cycles

The SPI flash in ESP32 modules is typically rated for 100,000 erase cycles per 4kB sector, with 20 years of data retention (check the datasheet of your module’s flash chip). The wear comes from erasing, not from writing one byte, so what counts is how often each sector gets erased.

Here is what that means in practice. If you erase the same sector on every save (like the old wrapper functions did), 100,000 saves wear it out. Saving once a minute, that’s about 69 days. If you append each new value to a log that walks through all the sectors of the partition instead, each sector is erased only when the log comes back to it. In our 64kB partition with 8-byte records, that’s once every 8,192 saves per sector, so the same flash lasts about 8,000 times longer. That’s what LAB 3 does.

ESP32 flash wear leveling animation: erasing one sector on every save versus appending records to a log over 16 sectors, which erases each sector about 8,000 times less

Note: While the flash is being erased or written, the ESP32 turns off its flash cache, so the CPU can’t run code from flash. Interrupt handlers that aren’t marked IRAM_ATTR are delayed until the operation ends, which can be tens of milliseconds for a sector erase (see the measured times). Keep flash writes out of timing-critical code. This is also why EEPROM.commit() and Preferences writes can make you miss interrupts.


ESP32 Custom Partition Table in Arduino IDE

To create a custom partition table in Arduino IDE, save a file named partitions.csv in your sketch folder. The Arduino ESP32 core copies it into the build and flashes it with your sketch, instead of the table selected in Tools > Partition Scheme. For simple changes (a bigger app, no OTA), first check that menu: it has ready-made schemes like Huge APP, Minimal SPIFFS, and No OTA.

Here are the steps I used to make a 64kB raw data partition called storage:

  1. Step #1 Start from the default.csv of your flash size, so the app partitions stay where they are.
  2. Step #2 Take the space from the spiffs partition: it starts at 0x290000, so the new storage partition starts there with a size of 0x10000 (64kB).
  3. Step #3 Move the spiffs partition after it (0x2A0000) and reduce its size by the same 0x10000, so it still ends at 0x3F0000, where coredump starts.
  4. Step #4 Give the new partition type data and subtype undefined. It’s raw data that no ESP32 library should touch.
  5. Step #5 Save it as partitions.csv next to the .ino file and upload. The compile output now shows the new table in the build folder.

Follow these rules, or the build fails or the board won’t boot:

  • Each partition’s offset = the previous partition’s offset + its size. No gaps are needed and no overlaps are allowed.
  • Data partitions start on a 4kB boundary (0x1000). App partitions start on a 64kB boundary (0x10000), and app0 must start at 0x10000.
  • The last partition must end at or before the end of your flash (0x400000 for 4MB).
  • Keep the nvs partition (WiFi and Bluetooth need it) and keep its subtype nvs only for real NVS data. A raw data partition must not use subtype nvs.
  • Changing the table doesn’t erase what was stored with the old one, and a partition you move or shrink can contain stale data. Erase it in your code or use Tools > Erase All Flash Before Sketch Upload once.

The full format is in Espressif’s partition tables guide, and the Arduino side is in the Arduino ESP32 partition table tutorial.

Note: Never write to the app0 partition (or any absolute flash address you haven’t checked) from your sketch. You’d overwrite the code that’s running, and the ESP32 will crash and keep restarting until you upload again. The esp_partition_* functions below can only touch the partition you pass them, which is why I use them instead of absolute addresses.


ESP32 Flash Read/Write Functions

The ESP32 flash memory is read and written with the esp_partition functions of ESP-IDF, which are built into the Arduino ESP32 core (no library to install). Include esp_partition.h and you get these functions:

FunctionWhat It Does
esp_partition_find_first(type, subtype, label)Returns a pointer to the partition (or NULL if it’s not in the table). Use ESP_PARTITION_SUBTYPE_ANY and the label
esp_partition_erase_range(part, offset, size)Erases flash to 0xFF. offset and size must be multiples of 4096
esp_partition_write(part, offset, src, size)Writes size bytes at offset in the partition. The area must be erased first
esp_partition_read(part, offset, dst, size)Reads size bytes from offset into dst
esp_partition_find(type, subtype, label)Returns an iterator to walk through the partition table (LAB 1)
part->address, part->size, part->labelThe partition’s flash offset, size in bytes, and name

Every function returns an esp_err_t: ESP_OK on success, ESP_ERR_INVALID_SIZE if you go past the end of the partition, or ESP_ERR_INVALID_ARG for a misaligned erase. Check it when the data matters. The full reference is in Espressif’s partitions API docs.

Write Any Data Type to ESP32 Flash

These two wrapper functions write and read any variable or struct in the storage partition. The write erases every 4kB sector the data touches before writing (that fixes the old version, which erased only the first sector):

Keep in mind that erasing a sector clears everything in it. If you keep several variables in the same sector, put them in one struct and write the struct, as in LAB 2.

Note: Never write a String object to flash with FlashWrite<String>(). sizeof(String) is the size of the object (a pointer to the text, its length and capacity), not the text. Reading it back seems to work until the next reset, then you get garbage, because the pointer points to RAM that no longer holds your text. Copy the text into a char array ( strlcpy(buf, myString.c_str(), sizeof(buf))) and save the array.

ESP.h flash functions (ESP.flashWrite, ESP.partitionWrite)

The Arduino ESP32 core also has flash functions in ESP.h (no include needed). The ESP.flashRead/Write/EraseSector() versions use absolute flash addresses with no bounds check, which is how the first version of this tutorial did it. The ESP.partition*() versions are bounded to one partition, like esp_partition. Both take a uint32_t* data pointer:

Here is the float example from the first version of this tutorial, moved to the bounded functions and the storage partition. It prints 3.14159:


ESP32 Flash Memory Size Check (LAB 1)

In this first example, we’ll read the flash chip’s ID and size and print the partition table of the running firmware. It needs no wiring, only the ESP32 board and a USB cable, like all the examples in this tutorial.

LAB 1 Code Explanation

esp_flash_read_id() reads the flash chip’s JEDEC ID: the manufacturer in the first byte and the capacity code in the last one. esp_flash_get_physical_size() calculates the real size from that ID, while esp_flash_get_size() returns the size the firmware was built for (Tools > Flash Size). In core 3.x, ESP.getFlashChipSize() also reads the chip ID, so it reports the physical size.

Then esp_partition_find() returns an iterator over every partition, and esp_partition_next() walks through them. Each esp_partition_t gives us the label, type, subtype, flash offset, and size.

LAB 1 Result

This is the output on my ESP32 DevKit V1 with this tutorial’s partitions.csv:

ESP32 flash memory size check serial output: flash JEDEC ID, 4 MB physical and configured flash size, flash speed, and the partition table with the storage partition

My board’s flash chip ID is 0xD84016: 0x16 is the capacity code, so 222 = 4,194,304 bytes (4MB), the same as the size the firmware was built for. The partition table shows our 64kB storage partition at 0x290000 with subtype 0x06 (undefined), right before the smaller spiffs partition. If the physical size is larger than the configured size on your board, select the right Flash Size in the Tools menu to use all of it.


ESP32 Save Data to Flash: int, float, Text & struct (LAB 2)

In this example, we’ll save a group of settings of different types (an unsigned counter, a signed int, a float, and a text) to the flash memory as one struct, and read them back after every reset. A magic number tells a valid record from erased flash, and a CRC32 catches a record that was only half written when the power went off.

LAB 2 Code Explanation

All the data goes into one Settings struct, so it’s saved and loaded in one write and one read. The text is a char deviceName[24] array, never a String object. The last field is a CRC32 of everything before it, calculated with the ROM function esp_rom_crc32_le().

loadSettings() reads the struct from offset 0 of the storage partition and accepts it only if both the magic number and the CRC match. On the first run the flash is erased (all 0xFF), the check fails, and the sketch starts from default values. saveSettings() updates the magic and the CRC, erases the first sector, and writes the struct.

LAB 2 Result

On the very first run, the flash is erased, so the sketch prints that no valid data was found and saves the defaults. Here are three of the following resets: every boot reads the previous values back from flash, checks the CRC, and saves the updated ones:

ESP32 save data to flash serial output: int, float, and text values in a struct with CRC are read back from flash after every reset


ESP32 Flash Memory Wear Leveling Example: Save Last LED State (LAB 3)

In this example, we’ll toggle an LED with a push button and save its state to the flash memory, so the ESP32 restores the last LED state after a reset or a power loss. This time, instead of erasing a sector on every save, each new state is appended to a log of 8-byte records, and a sector is erased only when the log enters it.

To keep it wiring-free, it uses the DevKit’s on-board BOOT button (GPIO0) and the on-board blue LED (GPIO2). If you prefer an external LED and button, change LED_GPIO and BTN_GPIO (for a button to 3.3v with a pull-down resistor, check for HIGH instead of LOW). For the full pin map, see the ESP32 DevKit V1 Pinout.

LAB 3 Code Explanation

Each save is one 8-byte Record: a sequence number that goes up with every save, the LED state, and a check value (the state inverted). An empty slot reads seq = 0xFFFFFFFF, and the check value rejects a record that was cut short by a power loss.

At startup, findLastRecord() scans all 8,192 slots of the 64kB partition once and keeps the valid record with the highest sequence number. That’s the last saved state, and the slot after it is where the next record goes.

saveState() writes the next record into the next free slot. Only when that slot is the first one of a sector does it erase the sector first, which happens once every 512 saves. After the last slot, the log wraps around to slot 0, so all 16 sectors share the wear equally.

The button part is the standard debounce logic: the input has to stay in its new state for 50ms before the LED toggles and the new state is saved. Note that lastDebounceTime is an unsigned long, because millis() overflows a signed int after about 24.8 days.

LAB 3 Result

I toggled the LED 518 times with the BOOT button (the presses were automated through the USB-serial chip’s DTR line, so it’s the same as pressing BOOT), with resets in between. Every reset restored the last LED state. The first 512 records went into sector 0, record 513 moved the log into sector 1, and sector 0 was erased only once in all those saves. The startup scan of all 8,192 slots took 468 ms on every boot. That’s the price of this simple log. If your boot time matters, scan only the first record of each sector to find the newest sector, then scan that one sector.

ESP32 flash memory wear leveling example serial output: LED state restored after reset from the log, records moving from sector 0 to sector 1 after 512 saves


ESP32 Flash Speed Test: Erase, Write & Read Times (LAB 4)

In this example, we’ll measure how long the ESP32 flash memory takes to erase, write, and read data, and we’ll see what happens when you write without erasing. These numbers tell you how much a flash save costs your application.

LAB 4 Code Explanation

Each operation is timed with esp_timer_get_time(), which returns microseconds since boot. The sector erase is repeated on 8 different sectors and averaged, then the whole 64kB partition is erased at once. The write tests use a 4-byte value, one 256-byte page, and a full 4kB sector, and the read test reads that sector back.

The last part erases a sector, writes 0xF0 to its first byte, then writes 0x0F over it without erasing, and prints what the flash really holds after each step, together with the return value of esp_partition_write().

LAB 4 Result

Here are the results on my ESP32 DevKit V1 (average of 3 runs). A 4kB sector erase takes about 30ms, while reading the same 4kB takes 0.39ms, about 80 times faster. Erasing the whole 64kB partition took only about 35ms, barely more than one sector, because the driver uses the flash chip’s 64kB block erase command. So when you need to erase a large aligned area, erase it in one call. Writing is in between: about 0.5ms per 256-byte page and 6.4ms for 4kB. The 4-byte write was slower than the 256-byte write in all three runs, so small writes don’t save time; collect your data and write it in bigger chunks. And the write-without-erase test confirms the rule: 0xF0 written over with 0x0F gives 0x00, and esp_partition_write() still returns ESP_OK.

ESP32 flash speed test serial output: 4 kB sector erase time, 64 kB erase time, page write time, 4 kB read speed, and writing 0x0F without erase giving 0x00

ESP32 flash memory erase, write and read time chart measured on an ESP32 DevKit V1 with Arduino core 3.3.12


Why Raw Data Written to the ESP32 NVS Partition Disappears

If you write raw data into the nvs partition, the ESP32 erases it at the next boot. In the first version of this tutorial, I found that data written to the NVS partition was wiped out after a hard reset “for no apparent reason”, which is why I moved it to a new partition. Here is the reason.

The nvs partition isn’t free space: it holds pages with headers, entry tables, and CRCs in the NVS format. At every boot, the Arduino core calls nvs_flash_init() (in initArduino(), before your setup() runs). Raw bytes written over those structures break them. Depending on what they hit, NVS throws the broken pages away, or nvs_flash_init() finds no usable free page and the core erases the whole nvs partition and starts it again empty. Your data, your Preferences, and your saved WiFi settings all go with it.

So keep raw data in its own partition, and put data you want in NVS through Preferences or the EEPROM library, which speak the NVS format.


ESP32 Flash Memory Troubleshooting

esp_partition_find_first() Returns NULL

The partition isn’t in the partition table on the board. Check that partitions.csv is in the sketch folder (not in a subfolder), that the label in the code matches the file exactly, and that the build log shows the custom table. Then upload again: the table is flashed with every upload.

ESP32 Flash Reads 0xFF or -1

That area is erased and has never been written. Erased flash reads 0xFF in every byte, so an int reads -1 and a uint32_t reads 4294967295. Use a magic number or a blank check (as in LAB 2 and the boot counter) and fall back to a default value.

Wrong Values After Writing to Flash

You wrote over data that wasn’t erased, so bits could only go from 1 to 0 (LAB 4 shows 0xF0 + 0x0F = 0x00). Erase the sector before writing. Also remember that erasing a sector clears every other variable in that 4kB.

String Prints Garbage After Reset

You saved the String object, which holds a pointer, not the text. Save the characters in a char array instead (LAB 2).

Flash Data Lost After a New Sketch Upload

A normal upload only writes the bootloader, the partition table, and the app. It keeps your data partitions. Your data is erased if Tools > Erase All Flash Before Sketch Upload is enabled, or if your new partitions.csv moved the partition to a different offset.

ESP32 Keeps Restarting After a Flash Write

You wrote to an address outside your data partition, probably over the running app with ESP.flashWrite() and an absolute address. Upload the sketch again to recover, and use the esp_partition_* functions, which can’t write outside the partition.

Interrupts Missed or Delayed During a Flash Write

The flash cache is disabled during erase and write operations, so ISRs that live in flash wait until the operation ends. Mark time-critical ISRs IRAM_ATTR, and avoid erasing flash in timing-critical moments (LAB 4 shows how long a sector erase takes).

ESP_ERR_INVALID_ARG From esp_partition_erase_range()

The offset or the size isn’t a multiple of 4096 (the 4kB sector size). Erase whole sectors only.


ESP32-S3, ESP32-C3 & ESP32-C6 Flash Memory

The code in this tutorial works the same on the ESP32-S3, ESP32-S2, ESP32-C3, and ESP32-C6. All of them use external SPI flash with 4kB sectors and the same esp_partition functions in Arduino core 3.3.12. What changes is the flash size of the module (the ESP32-S3 boards often have 8MB or 16MB, plus PSRAM) and the default partition table for that size, so select the right Flash Size in the Tools menu and start your partitions.csv from the matching default file. Run LAB 1 on your board to see what it has.


Parts List

All the examples in this tutorial run on the ESP32 board alone. Here is what you need to follow along:

QTY.Component NameAmazon.comAliExpress
1ESP32 DevKit V1 (DOIT) BoardAmazonAliExpress
1Micro USB CableAmazonAliExpress

Wrap Up

To conclude this tutorial, the ESP32 keeps everything in an external SPI flash memory (4MB on most boards), divided by a partition table that you can change with a partitions.csv file in your sketch folder. For raw data, make your own data partition and use the esp_partition functions: erase whole 4kB sectors before writing, save text as char arrays, validate what you read back, and spread the erases over the partition to make the flash last.

For settings and small values, the ESP32 EEPROM and Preferences libraries do this work for you. If you’ve got any questions or suggestions, drop me a comment below and I’ll be glad to help! And check out the ESP32 Programming Tutorials series for more ESP32 tutorials.


Download ESP32 Flash Memory Project Files

Download all attachment files for this Article/Tutorial (project files, schematics, code, etc.) using the link below. Everything is tested and verified to work on real hardware, as you’ve seen in the demo videos & screenshots. Please consider supporting my work if it helped you.


ESP32 Flash Memory FAQ

How much flash memory does the ESP32 have?

Most ESP32 boards, like the ESP32 DevKit V1 with the ESP32-WROOM-32 module, have 4 MB of external SPI flash. Modules with 8 MB and 16 MB are also common. With the default Arduino partition table, your sketch can use up to 1.25 MB (1,310,720 bytes) and the file system gets about 1.4 MB.

How many times can you write to the ESP32 flash memory?

The SPI flash in ESP32 modules is typically rated for about 100,000 erase cycles per 4 KB sector. The wear comes from erasing, so spreading your saves over many sectors (a log, as Preferences and LittleFS do internally) makes the flash last thousands of times longer than erasing one sector on every save.

How many times can the ESP32 be flashed (programmed)?

Uploading a sketch erases and rewrites the app partition once, so the same 100,000-cycle rating applies: tens of thousands of uploads at the very least. You won’t wear out the flash by uploading sketches during development.

Can I use the whole 4 MB flash to store data?

Not all of it, because the bootloader, the partition table, NVS and your sketch need their space. But you can make a data partition of up to about 2.6 MB on a 4 MB board by removing the OTA app slot and the file system in a custom partitions.csv, and read and write it with the esp_partition functions.

Does the ESP32 have EEPROM?

No. The ESP32 has no internal EEPROM. The Arduino EEPROM library emulates one in the NVS partition of the flash memory. For new projects, Espressif recommends the Preferences library, and for large data you can use a file system or a raw flash partition.

Where are const arrays stored on the ESP32?

In flash. On the ESP32, a const global array (for example a lookup table or an image) is placed in the flash memory automatically and read through the cache, so it doesn’t use RAM. You don’t need PROGMEM, although it’s accepted for compatibility with AVR code.

Share This Page With Your Network!
Join Our +25,000 Newsletter Subscribers!

Stay Updated With All New Content Releases. You Also Get Occasional FREE Coupon Codes For Courses & Other Stuff!

Photo of author
Author
Embedded systems engineer with several years of experience in embedded software and hardware design. I work as an embedded SW engineer in the Automotive & e-Mobility industry. However, I still do Hardware design and SW development for DSP, Control Systems, Robotics, AI/ML, and other fields I'm passionate about.
I love reading, writing, creating projects, and teaching. A reader by day and a writer by night, it's my lifestyle. I believe that the combination of brilliant minds, bold ideas, and a complete disregard for what is possible, can and will change the world! I will be there when it happens, will you?

2 thoughts on “ESP32 Flash Memory: Read/Write, Partitions & Size (Arduino)”

  1. Hi,
    first of all great article, ended a nerve wracking coding-session.
    Im not quite an expert just a hobbyist, but wouldnt you have to enumerate the ESP.flashEraseSector over the whole partition (or at least that bit that is used) ?
    Because in your example it just erases the first sector so if you would store data bigger then 4KB this could become an issue, or am I missing something?

    Kind Regards

    Reply
    • Hi Simon, you’re right. The old example erased only the first 4kB sector, so data larger than 4kB would be written over sectors that were not erased. The tutorial is now updated: the FlashWrite() function erases every sector the data occupies, and LAB 3 shows how to spread the writes over the whole partition. Thank you for pointing it out!

      Reply

Leave a Comment