Documentation

https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/api-reference/storage/nvs_flash.html

Initialse NVS

Needs to be done before your program tries to access the NVS

#include "nvs_flash.h"

	//INITIALIZE NVS
	printf("Initialising NVS...\n");

	esp_err_t err = nvs_flash_init();
	//err = nvs_flash_init();
	if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND)
	{
		// NVS partition was truncated and needs to be erased
		// Retry nvs_flash_init
		printf("Initialise NVS erase needed\n");

		ESP_ERROR_CHECK(nvs_flash_erase());
		err = nvs_flash_init();
	}
	ESP_ERROR_CHECK (err);

Write value

#include "nvs_flash.h"

	//WRITE TO NV MEMORY
	uint8_t MyNvValue = 123;
	nvs_handle_t my_handle;

	printf("Writing NVS value...\n");
	esp_err_t err = nvs_open("storage", NVS_READWRITE, &my_handle);
	err = nvs_open("storage", NVS_READWRITE, &my_handle);
	if (err != ESP_OK)
	{
		printf("Error (%s) opening NVS handle!\n", esp_err_to_name(err));
	}
	else
	{
		//Write
		err = nvs_set_u8(my_handle, "MyNvValue", MyNvValue);		//<<< nvs_set_u8, nvs_set_i16, nvs_set_u16, nvs_set_i32, nvs_set_u32, nvs_set_i64, nvs_set_u64, nvs_set_str
		printf((err != ESP_OK) ? "Failed!\n" : "Done\n");

		//Commit written value (nvs_commit() must be called to ensure changes are written to flash storage)
		printf("Committing updates in NVS... ");
		err = nvs_commit(my_handle);
		printf((err != ESP_OK) ? "Failed!\n" : "Done\n");

		//Close
		nvs_close(my_handle);
	}

Read value

#include "nvs_flash.h"

	//READ FROM NV MEMORY
	printf("Reading NVS value...\n");
	nvs_handle_t my_handle;
	uint8_t MyNvValue = 0;

	esp_err_t err = nvs_open("storage", NVS_READWRITE, &my_handle);
	if (err != ESP_OK)
	{
		printf("Error (%s) opening NVS handle!\n", esp_err_to_name(err));
	}
	else
	{
		err = nvs_get_u8(my_handle, "MyNvValue", &MyNvValue);		//<<< nvs_get_u8, nvs_get_i16, nvs_get_u16, nvs_get_i32, nvs_get_u32, nvs_get_i64, nvs_get_u64, nvs_get_str
		switch (err)
		{
			case ESP_OK:
				printf("MyNvValue = %d\n", MyNvValue);
				break;
			case ESP_ERR_NVS_NOT_FOUND:
				printf("The MyNvValue value is not initialized yet!\n");
				//MyNvValue = 0;			//<Not necessary, the previous value will not have been overwritten if not found
				break;
			default :
				printf("Error (%s) reading!\n", esp_err_to_name(err));
		}

		// Close
		nvs_close(my_handle);
	}
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published. Required fields are marked *