How to write string (const char*) to ESP32 NVS
Also see: How to read string (const char*) from ESP32 NVS
You can use this utility function to write a string (const char*) into the NVS:
nvs_write_cstring.cpp
bool _NVS_WriteString(nvs_handle_t nvs, const char* key, const char* value) {
esp_err_t err;
if((err = nvs_set_str(nvs, key, value)) != ESP_OK) {
Serial.printf("Failed to write 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.
usage_nvs_write_cstring.cpp
char mySerialNo[128] = {0};
_NVS_WriteString(myNVS, "SerialNo", "0000001");This will write the value 0000001 to the NVS with key SerialNo
Note that NVS strings are length-delimited (as in: The length is stored in the NVS) and not neccessarily NUL-terminated. This code does not store the NUL terminator in NVS.
Check out similar posts by category:
ESP8266/ESP32
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow