Page 1 of 1

How to permanently store a bit value in my custom bootloader

Posted: Wed Mar 19, 2025 10:10 am
by t23319222
Hi,

I need to write a value (0 or 1) to flash storage in order to save it permanently. I need to do this in my custom bootloader (the bootloader_main.c code).

The way I do it now is I have a seperate partition to which i write the value with the function

Code: Select all

void write_boot_index(esp_partition_pos_t *pos, int boot_index)
{
    bootloader_flash_erase_range(pos->offset, 4096);
    esp_err_t write_ret = bootloader_flash_write(pos->offset, &boot_index, 4, false);
    if (write_ret != ESP_OK) {
        ESP_LOGE("CUSTOM", "Failed to write to flash");
    }
}
But I know that this is not a optimal solution at all, because I (for some reason) need to erase a whole sector for it to work properly and on the other hand I think a partition like this one is a waste of space. I did some research and unfortunately I don't think one can write to NVS in the bootloader environment, so my question is:

Is there a better way to do this?

Also: The data needs to be saved even if the ESP loses power.

Re: How to permanently store a bit value in my custom bootloader

Posted: Wed Mar 19, 2025 3:02 pm
by MicroController
Yes, you'll have to set aside (at least) one 4k block of flash for this in any case, because that's the size of an erase block.

Instead of erasing the block every time, you can also make use of the whole block for performance and/or wear-levelling, e.g. by appending one byte of 0x00 each time your bit/flag changes its value; then the latest written value can be read back by counting the number of 0 bytes: bit = (number of consecutive 0-bytes) % 2.