This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

nrf51 pstrorage write zeros to flash memory

I'm trying to write some data to flash memory (32 bytes) every 1 minute. the data are not NULL but then I noticed that sometimes (not always) the pstroage module write zeros to flash memory. I can check that it's NULL data which are written by dumpting the flash content.

I'm using below function to write a block

I can check that err_code returns nrf_success

my question is

1 - it is mandatory to call pstorage_clear before calling pstorage_store when flash had already data on that location?

are my waiting functions correct for pstorage_clear and pstroage_store??

void save_to_flash(pstorage_handle_t * flash_handler, pstorage_size_t block_id, pstorage_handle_t * block_handle, uint8_t * data, pstorage_size_t size, pstorage_size_t offset)
{
    uint32_t err_code;
    uint32_t count;

    flash_busy = true;
    err_code = pstorage_block_identifier_get(flash_handler, block_id, block_handle);
    APP_ERROR_CHECK(err_code);

    err_code = pstorage_clear(block_handle, size);
    APP_ERROR_CHECK(err_code);

    pstorage_wait_handle = block_handle->block_id;  //Specify which pstorage handle to wait for
    while (pstorage_wait_flag) {
        manage_power();                             //Sleep until clear operation is finished.
    }
    err_code = pstorage_store(block_handle, data, size, offset);
    APP_ERROR_CHECK(err_code);

    count = 16;
    do {
        uint32_t ret = pstorage_access_status_get(&count);
    } while (count);
    flash_busy = false;
}

void flash_callback_handler(pstorage_handle_t * p_handle,
    uint8_t             op_code,
    uint32_t            result,
    uint8_t           * p_data,
    uint32_t            data_len)
{

    if (p_handle->block_id == pstorage_wait_handle) {
        pstorage_wait_flag = 0;         //If we are waiting for this callback, clear the wait flag.
    }

    switch (op_code) {
    case PSTORAGE_STORE_OP_CODE:
        if (result == NRF_SUCCESS) {
            ;                           // Nothing to do : Store operation successful.
        }
        else {
            APP_ERROR_CHECK(result);    // Store operation failed.
  • Hi

    You can only write once to a certain flash memory area. If you want to write to it again you must erase it first. Erase is performed on a whole page.

    The pstorage module queues the flash operations, e.g. pstorage_store and pstorage_clear, so you dont really need to wait for the pstorage_clear to finish before calling pstorage_store, pstorage module will take care of that. You do however need to wait for pstorage_store and pstorage_clear before reading the flash memory (with e.g. pstorage_load) because reads are read directly from flash and are not in queue in pstorage module. Otherwise you will read the flash contents before it is written/erased.

    There is pstorage example available here.

Related