How to read string (const char*) from ESP32 NVS
Also see: How to write string (const char*) to ESP32 NVS
You can use this utility function to read a string:
bool _NVS_ReadString(nvs_handle_t nvs, const char* key, char* value, size_t maxSize) {
esp_err_t err;
if((err = nvs_get_str(nvs, key, value, &maxSize)) != ESP_OK) {
Serial.printf("Failed to read NVS key %s: %s\r\n", key, esp_err_to_name(err));
return false;
}
return true;
}
Usage example
This example is based on How to initialize NVS on ESP32. Most importantly, it assumes you have already initialized the NVS and myNVS
exists and is valid.
char mySerialNo[128] = {0};
_NVS_ReadString(myNVS, "SerialNo", mySerialNo, 128-1);
This will read the NVS entry with key SerialNo
into the buffer mySerialNo
. Note that we are using 128-1
as size, even though the buffer has a size of 128
. This is to ensure that there is ALWAYS a terminating NUL character at the last value of the buffer.
Note that NVS strings are length-delimited (as in: The length is stored in the NVS) and not neccessarily NUL-terminated. I recommend to not store the NUL terminator in the NVS.
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow