zephyr: cannot initiate nvs in NRF52840 dongle

iam new to nrf52840 DONGLE.i want to initiate nvs and read/write in it. but it kept on failed.my main.c

#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/storage/flash_map.h>
#include <zephyr/fs/nvs.h>
#include <cJSON.h>
#include <string.h>
#include <zephyr/drivers/flash.h>

static struct nvs_fs fs;

#define NVS_PARTITION          storage_partition
#define NVS_PARTITION_DEVICE   FIXED_PARTITION_DEVICE(NVS_PARTITION)
#define NVS_PARTITION_OFFSET   FIXED_PARTITION_OFFSET(NVS_PARTITION)

#define JSON_DATA_ID 10
#define SLEEP_TIME   2000  // 2 seconds

void store_json_data(struct nvs_fs *fs) {
    cJSON *root = cJSON_CreateObject();

    // Add actual numeric values
    cJSON_AddStringToObject(root, "name", "Bluetooth");

	char tx_power_str[16]; 
    sprintf(tx_power_str, "%d", -40);  // Example TX power value as string
    cJSON_AddStringToObject(root, "tx_power", tx_power_str);

    const char *json_string = cJSON_PrintUnformatted(root);
    printk("JSON data stored: %s\n", json_string);

    // Write to NVS
    int rc = nvs_write(fs, JSON_DATA_ID, json_string, strlen(json_string) + 1);
    if (rc < 0) {
        printk("Error: Failed to write JSON data to NVS, rc=%d\n", rc);
    } else {
        printk("JSON data successfully written to NVS\n");
    }

    cJSON_Delete(root);
}

#include <stdlib.h>  // For strtol

void read_json_data(struct nvs_fs *fs) {
    char json_buffer[256]; 
    
    int rc = nvs_read(fs, JSON_DATA_ID, json_buffer, sizeof(json_buffer));
    
    if (rc > 0) {
        json_buffer[rc] = '\0';  // Null-terminate the string
        printk("JSON data read: %s\n", json_buffer);

        cJSON *root = cJSON_Parse(json_buffer);
        if (root != NULL) {
            const cJSON *name = cJSON_GetObjectItem(root, "name");
            const cJSON *tx_power_str = cJSON_GetObjectItem(root, "tx_power");

            if (name && tx_power_str) {
                printk("Parsed JSON: name=%s, tx_power=%s\n",
                       name->valuestring,  
                       tx_power_str->valuestring 
                       );

                // Convert tx_power and battery_level to integers using strtol
                char *endptr;
                long tx_power = strtol(tx_power_str->valuestring, &endptr, 10);  // Convert to integer
              

                printk("Converted values: tx_power=%ld\n", tx_power);
            } else {
                printk("Error: JSON parsing error - missing fields\n");
            }

            cJSON_Delete(root);
        } else {
            printk("Error: Failed to parse JSON data\n");
        }
    } else if (rc == 0) {
        printk("Warning: No JSON data found in NVS\n");
    } else {
        printk("Error: Failed to read JSON data, rc=%d\n", rc);
    }
}

int main(void) {
    int rc;
    struct flash_pages_info info;

    // Initialize NVS file system
    fs.flash_device = NVS_PARTITION_DEVICE;
    if (!device_is_ready(fs.flash_device)) {
        printk("Error: Flash device not ready\n");
        return -1;
    }

    fs.offset = NVS_PARTITION_OFFSET;
    rc = flash_get_page_info_by_offs(fs.flash_device, fs.offset, &info);
    if (rc) {
        printk("Error: Failed to get page info, rc=%d\n", rc);
        return -1;
    }

    fs.sector_size = info.size;
    fs.sector_count = 3U;

    rc = nvs_mount(&fs);
    if (rc) {
        printk("Error: Failed to mount NVS, rc=%d\n", rc);
        return -1;
    }

    // Store and read JSON data
    store_json_data(&fs);
    read_json_data(&fs);

    while (1) {
        k_msleep(SLEEP_TIME);
    }

    return 0;
}

prj.conf

CONFIG_FLASH=y CONFIG_LOG=y CONFIG_UART_CONSOLE=y CONFIG_CONSOLE=y CONFIG_PM=y CONFIG_PM_LOG_LEVEL_DBG=y

CONFIG_NVS=y

CONFIG_LOG_MODE_IMMEDIATE=y CONFIG_NVS_LOG_LEVEL_DBG=y CONFIG_REBOOT=y CONFIG_MPU_ALLOW_FLASH_WRITE=y CONFIG_CLOCK_CONTROL_NRF_K32SRC_RC=y

CONFIG_FLASH_MAP=y CONFIG_USB_DEVICE_STACK=y

CONFIG_CJSON_LIB=y

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 19 (6 by maintainers)

Most upvoted comments

The problem is the address of the storage partition. It does not take into account that all addresses on the dongle are 0x1000 shifted because of MBR. I had the same problem and solved it by fixing zephyr/boards/nordic/nrf52840dongle/fstab-stock.dtsi

               slot1_partition: partition@76000 {
			label = "image-1";
			reg = <0x00076000 0x00066000>;
		};
		storage_partition: partition@db000 {
			label = "storage";
			reg = <0x000db000 0x00004000>;
		};

namely the size of slot1_partition was reduced and the start of the storage changed to 0xdb000

Thanks a lot, @otzy . With your help I could finally make it work. For reference, I have attached a project nvs.zip which compiles and runs on the nrf52840 dongle, including when using sysbuild. To build this, open in VS code, add a build configuration for the nrf52840dongle using sysbuild, compile it and flash via e.g. the nRF Connect Desktop Programmer.

As many people have mentioned, the problem is if the flash area is trying to write into the boot loader. I was a bit confused at first, becuase the MBR is located at 0x0000 to 0x1000. However, there’s the MCUBoot loader located at 0xe00000 in the memory, as pointed out here. Maybe it helps others to better understand what is going on.

Moreover, when using non-sysbuild, and the fstab-stock.dtsi modifications as mentioned by otzy are applied, the STORAGE_OFFSET is at 0xdb000 (897024 decimal). Compiling and running with this offset makes the example work.

Then, when setting the offset manually (and not from the compile time constant FIXED_PARTITION_OFFSET(storage_partition), it will also works when using sysbuild. In sysbuild, the partion manager siliently ignores that there is the mcu bootloader living at the high end of the flash space. This can be overcome, by artificially increasing the storage partition size to grow below the bootloader start via

CONFIG_PM_PARTITION_SIZE_NVS_STORAGE=0x25000

Moreover, I have found out that the entire program only works, if

ENABLE_BT=y

is contained in the project configuration. Otherwise, the device still hangs upon calling nvs_mount. I don’t know why this is and I leave this for others to figure out.

As mentioned by otzy, I changed the fstab-stock.dtsi file to (I think this is not needed when using sysbuild and the partition manager)

&flash0 {
  10   │     partitions {
  11   │         compatible = "fixed-partitions";
  12   │         #address-cells = <1>;
  13   │         #size-cells = <1>;
  14   │ 
  15   │         /* MCUboot placed after Nordic MBR (this is set with the FLASH_LOAD_OFFSET
  16   │          * Kconfig value when BOARD_HAS_NRF5_BOOTLOADER is enabled), otherwise MCUboot
  17   │          * will be placed at 0x0. The size of this partition ensures that MCUBoot can
  18   │          * be built with CDC ACM support and w/o optimizations.
  19   │          */
  20   │         boot_partition: partition@0 {
  21   │             label = "mcuboot";
  22   │             reg = <0x00000000 0x00010000>;
  23   │         };
  24   │ 
  25   │         slot0_partition: partition@10000 {
  26   │             label = "image-0";
  27   │             reg = <0x00010000 0x00066000>;
  28   │         };
  29   │         slot1_partition: partition@76000 {
  30   │             label = "image-1";
  31 ~ │             reg = <0x00076000 0x00065000>;
  32   │         };
  33 ~ │         storage_partition: partition@db000 {
  34   │             label = "storage";
  35 ~ │             reg = <0x000db000 0x00004000>;
  36   │         };
  37   │ 
  38   │         /* Nordic nRF5 bootloader <0xe0000 0x1c000>
  39   │          *
  40   │          * In addition, the last and second last flash pages
  41   │          * are used by the nRF5 bootloader and MBR to store settings.
  42   │          */
  43   │     };
  44   │ };

I hope others having the same problem can also benefit from these findings. I don’t know what are the further implications that the storage area and the boot loader area are overlapping, but at least for now and for a simple NVS examples, this is sufficient.

@Saranya-karan would you be able to bisect this to figure out when your code stopped working? Thanks!

I don’t think it ever worked, the author is referring to a different device. The nrf52480 dongle is a bit of an annoying device as most users will want to use the usb to debug. This takes some time to get up and as the authors code is direct returning on error there might never be anything visible.

I think the problem is related to a storage partition that already contains data. Doing a partial erase on these devices might also be a problem.