[PICO W] Writing and reading data from flash

December 4, 2024, 22:34

martynaskre

I've seen examples on github how to program Pico's flash but I have no success on my own implementation. I am running this on FreeRTOS, but I think it will be not related. When erased, the printed buffer shows ff which is correct. Also when data is written it shows different values than ff. But the get function always returns random values or empty chars. What could be the problem?
cpp
#define FLASH_TARGET_OFFSET (512  1024)

struct FlashData {
    int test;
    char ssid[33];
    char password[64];
};

class Flash {
    static void rangeErase(void parameter);
    static void rangeProgram(void parameter);
public:
    static std::optional<FlashData> get();
    static void set(FlashData data);
};

std::optional<FlashData> Flash::get() {
    FlashData data{};

    const auto flash_target_contents = (const uint8_t ) (XIP_BASE + FLASH_TARGET_OFFSET);
    memcpy(&data, flash_target_contents, sizeof(data));

    return data;
}

void Flash::rangeErase(void parameter) {
    int myDataSize = sizeof(FlashData);

    int writeSize = (myDataSize / FLASH_PAGE_SIZE) + 1;
    int sectorCount = ((writeSize  FLASH_PAGE_SIZE) / FLASH_SECTOR_SIZE) + 1;

    flash_range_erase(FLASH_TARGET_OFFSET, FLASH_SECTOR_SIZE  sectorCount);
}

void Flash::rangeProgram(void parameter) {
    auto wrappedData = static_cast<FlashData>(parameter);

    auto dataAsBytes = (uint8_t) &wrappedData;
    int writeSize = (sizeof(&wrappedData) / FLASH_PAGE_SIZE) + 1;

    flash_range_program(FLASH_TARGET_OFFSET, dataAsBytes, FLASH_PAGE_SIZE  writeSize);
}

void Flash::set(FlashData data) {
    int rc = flash_safe_execute(Flash::rangeErase, nullptr, UINT32_MAX);
    hard_assert(rc == PICO_OK);

    rc = flash_safe_execute(Flash::rangeProgram, &data, UINT32_MAX);
    hard_assert(rc == PICO_OK);
}