This library provides simple functions to serialize and deserialize settings or any other struct data to and from the ESP32's LittleFS (Little File System). It allows easy storage and retrieval of configuration parameters.
- Serialize any object of type
T
and save it as a file in LittleFS. - Deserialize the stored file back into an object.
- Supports arbitrary struct types.
- Error handling for file operations.
Ensure you have the following libraries installed in your Arduino IDE:
FS.h
(included with ESP32 support)LittleFS.h
(for ESP32 file system support) or any other file system
#include <Arduino.h>
#include <LittleFS.h>
typedef struct {
String ip;
int port;
String ssid;
String passwd;
bool autoConnect;
} Settings;
template <typename T> void save(const char *filename, const T *data) {
File file = LittleFS.open(filename, "w");
if (!file) {
throw std::runtime_error("Failed to open file for writing");
}
file.write(reinterpret_cast<const uint8_t *>(data), sizeof(T));
file.close();
}
template <typename T> void load(const char *filename, T *data) {
File file = LittleFS.open(filename, "r");
if (!file) {
throw std::runtime_error("Failed to open file for reading");
}
if (file.read(reinterpret_cast<uint8_t *>(data), sizeof(T)) != sizeof(T)) {
file.close();
throw std::runtime_error("Failed to read sufficient data");
}
file.close();
}
void setup() {
Serial.begin(115200);
LittleFS.begin();
// Initialize settings with example values
Settings settings = {
.ip = "localhost",
.port = 42,
.ssid = "Wifi password",
.passwd = "Strong & complicated password",
.autoConnect = true};
// Save data to flash FS
save("/settings", &settings);
// Load data from flash FS
Settings loadedSettings;
load("/settings", &loadedSettings);
}
void loop() {}
- If file operations fail, a
std::runtime_error
is thrown. - Ensure
LittleFS.begin()
is called before using serialization functions.
- Ensure the struct does not contain dynamic memory allocations (e.g., pointers). Using
String
is safe because it is managed internally by the Arduino framework. - The stored file size will be equal to
sizeof(T)
, so be mindful of memory usage when storing large structs.