Writing persistent data to Flash memory.

Components

  • 1x pushbutton

C Interface

Documentation

// Run a function safely while modifying flash.
int flash_safe_execute(void(*func)(void*), void* param, uint32_t enter_exit_timeout_ms);
 
// Erage a range of flash
void flash_range_erase(uint32_t flash_offs, size_t count);
 
// Program data to flash. Data size must be multiple of 256 bytes.
void flash_range_program(uint32)t flash_offs, const uint8_t* data, size_t count);

Instructions

Construct the button circuit again.

Look at and run flash.cpp. Connect to the serial console and you will see that a message is printed each time you press the button.

Unplug the power to the Pico, then connect it back and look at the serial port. The Pico will keep count even after it loses power.

Info

The regular variables that you use in C are stored in RAM, which gets erased when the Pico loses power. We can keep persistent data by storing it to the Pico’s built in flash memory.

Flash memory is how the Pico stores the code that it runs, which means we have to be careful when we modify it as the Pico is already reading from flash to execute our code. This is why we use the flash_safe_execute function.

You can just write your data to flash memory whenever you want. Before it can be programmed, the page you want to write to has to be erased. This is a property of flash memory.

Warning

Flash memory can wear out after 10^3 to 10^6 erase-write cycles. Be careful not to continuously erase and write the same page of flash as you will cause it to wear out quickly.