I’ve been enjoying using the Arduino Nano Sense BLE 33 board as an all-round microcontroller for my machine learning work, but I had trouble figuring out how to programmatically write to flash memory from a sketch. I need to do this because I want to be able to download ML models over Bluetooth and then have them persist even if the user unplugs the board or resets it. After some research and experimentation I finally have a solution I’m happy with, so I’ve put an example sketch and documentation up at github.com/petewarden/arduino_nano_ble_write_flash.
The main hurdle I had to overcome was how to initialize an area of memory that would be loaded into flash when the program was first uploaded, but not touched on subsequent resets. Since modifying linker scripts isn’t recommended in the Arduino IDE, I had to come up with a home-brewed solution using const arrays and C++’s alignas() command. Thankfully it seems to work in my testing.
There’s a lot more documentation in the README and inline in the sketch, but I would warn anyone interested in this that flash has a limited number of erase/write cycles it can handle reliably, so don’t go too crazy with high-frequency changes!