I created a new project based on the nvs sample template under nRF Connect v2.0.2 for an nRF DK (PCA10040) board. The source code looks like this:
#include <zephyr.h>
#include <sys/reboot.h>
#include <device.h>
#include <string.h>
#include <drivers/flash.h>
#include <storage/flash_map.h>
#include <fs/nvs.h>
#define STORAGE_NODE_LABEL storage
#include <zephyr/logging/log.h>
#define LOG_MODULE_NAME peripheral_uart
LOG_MODULE_REGISTER(LOG_MODULE_NAME);
static struct nvs_fs fs;
#define STORAGE_NODE_LABEL storage
#define BT_AD_ID 1
static K_SEM_DEFINE(sem_nvs_write, 0, 1);
static struct{
uint16_t id;
uint8_t* data;
uint32_t data_length;
}nvs_param;
#define NVS_THREAD_STACKSIZE 512
#define NVS_THREAD_PRIORITY 5
void nvs_write_thread(void)
{
while(1)
{
k_sem_take(&sem_nvs_write, K_FOREVER);
if (nvs_write(&fs, nvs_param.id, nvs_param.data, nvs_param.data_length) < 0)
LOG_ERR("Couldn't write data to NVS\n");
else
LOG_INF("data written to NVS");
}
}
K_THREAD_DEFINE(nvs_write_thread_id, NVS_THREAD_STACKSIZE, nvs_write_thread, NULL, NULL, NULL, NVS_THREAD_PRIORITY, 0, 0);
void main(void)
{
int rc = 0;
char buf[16];
struct flash_pages_info info;
fs.flash_device = FLASH_AREA_DEVICE(STORAGE_NODE_LABEL);
if (!device_is_ready(fs.flash_device)) {
printk("Flash device %s is not ready\n", fs.flash_device->name);
return;
}
fs.offset = FLASH_AREA_OFFSET(storage);
rc = flash_get_page_info_by_offs(fs.flash_device, fs.offset, &info);
if (rc) {
printk("Unable to get page info\n");
return;
}
fs.sector_size = info.size;
fs.sector_count = 3U;
rc = nvs_mount(&fs);
if (rc) {
printk("Flash Init failed\n");
return;
}
nvs_delete(&fs, BT_AD_ID);
while(1)
{
rc = nvs_read(&fs, BT_AD_ID, &buf, sizeof(buf));
if (rc > 0) { /* item was found, show it */
printk("Id: %d, BT Advertising string: %s\n", BT_AD_ID, buf);
break;
} else {/* item was not found, add it */
strcpy(buf, "nvsTest");
printk("No ad string found, adding %s at id %d\n", buf,
BT_AD_ID);
nvs_param.id = BT_AD_ID;
nvs_param.data = buf;
nvs_param.data_length = strlen(buf) + 1;
k_sem_give(&sem_nvs_write);
k_msleep(1000);
}
}
} If I set a breakpoint at LOG_INF("data written to NVS"); in nvs_write_thread, I find that hits the breakpoint when I run VSC in Debug mode, as it should.
else if (memcmp(data, "ad=", sizeof("ad=")-1) == 0)
{
snprintf(bt_ad_str, sizeof(bt_ad_str), "%s", &data[sizeof("ad=")-1]);
nvs_param.id = BT_AD_ID;
nvs_param.data = bt_ad_str;
nvs_param.data_length = strlen(bt_ad_str) + 1;
k_sem_give(&sem_nvs_write);
I would appreciate any advice you can give on this.
Alec
