Just for the sake of testing - the first thing I do in the app_main(), is to initialize the NVS and then I'm trying to read a string value which certainly shouldn't exist as this is the very first time I'm accessing the NVS. If the nvs_get_str() fails (as it should), I call nvs_set_str() to set(for the first time) the value "Value1" for the "Tag1" key.
Sounds simple. However, the first time I call Get - it somehow reads correct value??? Before "Set" was ever called.
Here are the few lines from the log.
...
NVS partition found.
NVS partition namespace NVS_Test opened.
Get str returns 0.
NVS key Tag1 found. Value = Value1, size = 7
...
Note: there is no "NVS commit OK" line in the log at all.
I would really appreciate if you can shed some light on this issue.
Thanks a lot.
Here is the code:
Code: Select all
void app_main()
{
esp_err_t ret;
// Initialize NVS
ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
{
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK( ret );
if (ret == ESP_OK)
{
const esp_partition_t* nvs_partition =
esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_NVS, NULL);
if(!nvs_partition)
printf("FATAL ERROR: No NVS partition found\n");
else
{
printf("NVS partition found.\n");
// open the partition in RW mode
if (nvs_open("NVS_Test", NVS_READWRITE, &my_handle) == ESP_OK)
{
size_t required_size = 0;
printf("NVS partition namespace NVS_Test opened.\n");
ret = nvs_get_str(my_handle, "Tag1", NULL, &required_size);
printf("Get str returns %d.\n", ret);
if (ret == ESP_OK)
{
char* valueStr = malloc(required_size);
if (nvs_get_str(my_handle, "Tag1", valueStr, &required_size) == ESP_OK)
printf("NVS key Tag1 found. Value = %s, size = %d\n", valueStr, required_size);
else
printf("Error getting NVS key with size %d.\n", required_size);
free(valueStr);
}
else if (ret == ESP_ERR_NVS_NOT_FOUND)
{
const char tagValue[] = "Value1";
printf("NVS Tag1 key not found.\n");
// This key was not found in the "NVS_Test" namespace.
// Could be the first time we are using it, so create the key-value pair:
if (nvs_set_str(my_handle, "Tag1", tagValue) == ESP_OK)
{
printf("NVS key Tag1 created.\n");
if (nvs_commit(my_handle) == ESP_OK)
printf("NVS commit OK.\n");
else
printf("NVS commit failed.\n");
}
else
printf("NVS set key failed.\n");
}
nvs_close(my_handle);
}
}
}