Writing to internal FLASH

HI there,

SO If you’re using an nRF52840 Arduino core that supports LittleFS (e.g., the Adafruit nRF52 core or a similar fork), you can store files in flash without manually erasing pages:

Try this one:

#include <Adafruit_LittleFS.h>
#include <InternalFileSystem.h>

void setup() {
  Serial.begin(115200);
  if (!InternalFS.begin()) {
    Serial.println("Failed to mount InternalFS!");
    while (1) { delay(10); }
  }
  Serial.println("InternalFS mounted.");

const char data[] = "Hello Flash!";
  writeData("/hello.txt", (uint8_t*)data, strlen(data));
  readData("/hello.txt");
}

void writeData(const char* filename, const uint8_t* data, size_t length) {
  using namespace Adafruit_LittleFS_Namespace; 
  File myFile(InternalFS);

  myFile.open(filename, FILE_O_WRITE);
  if (!myFile) {
    Serial.println("Failed to open file for writing.");
    return;
  }
  myFile.write(data, length);
  myFile.close();
  Serial.println("Data written to flash.");
}

void readData(const char* filename) {
  using namespace Adafruit_LittleFS_Namespace;
  File myFile(InternalFS);

  myFile.open(filename, FILE_O_READ);
  if (!myFile) {
    Serial.println("Failed to open file for reading.");
    return;
  }
  while (myFile.available()) {
    Serial.write(myFile.read());
  }
  myFile.close();
  Serial.println("\nData read complete.");
}

Pros:

  • Very easy to use: files instead of raw flash addresses.
  • Automatically handles wear leveling, erases, etc.

Cons:

  • Requires your nRF52840 core to support Adafruit_LittleFS or a similar internal FS library.
  • Slight overhead in flash usage (for file system metadata).

Conclusion: On the Xiao nRF52840, you can write data to internal flash either via a file system approach (LittleFS) or direct NVMC calls. YMMV, for ease and safety, a file system is recommended if it’s supported by your Arduino core. Otherwise, carefully pick a free flash page and use the Nordic NVMC methods to erase and write data.

HTH
GL :slight_smile: PJ :v: