December 4, 2024, 22:34
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); }