Hi,
I've been working on Thingy:91 under ncs tag 1.2.0, trying to develop simple application using NVS just to see how it works. Based on the zephyr sample I wrote the following app:
#include <zephyr.h> #include <power/reboot.h> #include <device.h> #include <string.h> #include <drivers/flash.h> #include <fs/nvs.h> static struct nvs_fs fs; #define ADDRESS_ID 1 #define STRING_ID 2 int rc = 0, cnt = 0, i=0; char buf[16]; char buf_2[16]; char data[16]; char data_2[16]; struct flash_pages_info info; void main(void) { printk("Application started \n"); fs.offset = DT_FLASH_AREA_STORAGE_OFFSET; rc = flash_get_page_info_by_offs(device_get_binding(DT_FLASH_DEV_NAME), fs.offset, &info); if (rc) { printk("Unable to get page info"); } fs.sector_size = info.size; fs.sector_count = 3U; printk("Initiating \n"); rc = nvs_init(&fs, DT_FLASH_DEV_NAME); if (rc) { printk("Flash Init failed\n"); } printk("Flash initiated \n"); while (1) { cnt++; sprintf(buf, "L: %d " , cnt); nvs_write(&fs, ADDRESS_ID, &buf, strlen(buf)+1); sprintf(buf_2, "R: %d ", cnt); nvs_write(&fs, STRING_ID, &buf_2, strlen(buf_2)+1); for (i=0; i<=cnt-1; i++){ rc = nvs_read_hist(&fs, ADDRESS_ID, &data, sizeof(data), i); if (rc < 0) { printk("Something went wrong \n"); break; } printk("%s ... ", data); } printk("\n"); for (i=0; i<=cnt-1; i++){ rc = nvs_read_hist(&fs, STRING_ID, &data_2, sizeof(data_2), i); if (rc < 0) { printk("Something went wrong \n"); break; } printk("%s ... ", data_2); } k_sleep(K_SECONDS(1)); } }
The app worked well few times (meaning multiple uploads with different data written into memory, as well as multiple power off/ons), but at some point it just stopped working - the application went all the way to nvs_init function call and got stuck there forever (I was waiting for one hour and then I gave up). I tried to reupload it many times, reboot the device and none of that helped. Finally I changed the fs.sector_count from 3U to 2U and it started working again. Surprisingly after changing it back to 3U it also worked again with no problem.
I'm trying to understand that behaviour and I am not sure - why did that happen? I know that the flash memory on Thingy has a supposed lifetime of 10 000 erase cycles, but I'm pretty sure I did not exceed it (I guess if I reached the lifetime limit it would not work now - and it does). I read somewhere on the forum that memory erase may take a lot of time - but could it be one hour or more?
Why did the sectors number change made it work again?
I guess it's mostly about understanding the work of flash memory, and I don't have that knowledge here, so I will appreciate the explanation from someone who does. It all comes down to reliability - I don't want the app to hang in the future for the same reason that I do not know.
Regards
Maciek