天天看點

Zephyr Nordic 實作片内FLASH擦除和讀寫

裝置樹分區配置

&flash0 {

	partitions {
		compatible = "fixed-partitions";
		#address-cells = <1>;
		#size-cells = <1>;

		boot_partition: [email protected] {
			label = "mcuboot";
			reg = <0x000000000 0x0000C000>;
		};
		slot0_partition: [email protected] {
			label = "image-0";
			reg = <0x0000C000 0x00067000>;
		};
		slot1_partition: [email protected] {
			label = "image-1";
			reg = <0x00073000 0x00067000>;
		};
		scratch_partition: [email protected] {
			label = "image-scratch";
			reg = <0x000da000 0x0001e000>;
		};
		/*
		 * Storage partition will be used by FCB/LittleFS/NVS
		 * if enabled.
		 */
		storage_partition: [email protected] {
			label = "storage";
			reg = <0x000f8000 0x00008000>;
		};
		user_partition: [email protected] {
			label = "userstorage";
			reg = <0x000f8000 0x00100000>;
		};
	};
};
           

代碼執行個體

#include <zephyr.h>
#include <device.h>
#include <usb/usb_device.h>
#include <sys/printk.h>
#include <device.h>
#include <stdio.h>
#include <storage/flash_map.h>
#include <storage/stream_flash.h>

#define FLASH_NAME DT_LABEL(DT_NODELABEL(flash0))

//讀取裝置樹
#define FLASH_AREA_FOO(part)						\
	{.fa_id = DT_FIXED_PARTITION_ID(part),				\
	 .fa_off = DT_REG_ADDR(part),					\
	 .fa_dev_name = DT_LABEL(DT_MTD_FROM_FIXED_PARTITION(part)),	\
	 .fa_size = DT_REG_SIZE(part),},

//周遊所有分區
#define FOREACH_PARTITION(n) DT_FOREACH_CHILD(DT_DRV_INST(n), FLASH_AREA_FOO)


//生成flash map數組
const struct flash_area my_flash_map[] = {
	DT_INST_FOREACH_STATUS_OKAY(FOREACH_PARTITION)
};

//flash map中含有分區的總數
const int my_flash_map_entries = ARRAY_SIZE(my_flash_map);

//flash map的指針
const struct flash_area *pflash_map = my_flash_map;
static unsigned char buff[4096];
int flash_test(void)
{
    int ret = 0;
    int i = 0;

    const struct flash_area *partition;
    ret = flash_area_open(FLASH_AREA_ID(userstorage), &partition);
    if(ret < 0)
    {
        printk("flash_area_open error\r\n");
    }

    ret =  flash_area_erase(partition, 0x00000, 4096);
    if(ret < 0)
    {
        printk("flash_area_erase error\r\n");
    }

    ret =  flash_area_read(partition, 0x00000, buff,10);
    printk("erase -> ");
    for(i = 0; i < 10; i++)
    {
        printk("%x ",buff[i]);
    } 
    printk("\r\n");

    for(i = 0; i < 10; i++)
    {
        buff[i] = i;
    } 
    ret = flash_area_write(partition, 0x00000, buff,4096);
    if(ret < 0)
    {
        printk("flash_area_write error\r\n");
    }
   
    for(i = 0; i < 10; i++)
    {
        buff[i] = 0xff;
    } 
    ret =  flash_area_read(partition, 0x00000, buff,10);

    printk("read -> ");
    for(i = 0; i < 10; i++)
    {
        printk("%x ",buff[i]);
    } 
    printk("\r\n");

    flash_area_close(partition);

    return 0;
}
           

繼續閱讀