1 /*
2 * Copyright (c) 2023 Espressif Systems (Shanghai) Co., Ltd.
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/kernel.h>
8 #include <zephyr/sys/printk.h>
9 #include <zephyr/device.h>
10 #include <zephyr/drivers/flash.h>
11 #include <zephyr/storage/flash_map.h>
12
13 #include <spi_flash_mmap.h>
14 #include <soc.h>
15
16 #include <zephyr/logging/log.h>
17 LOG_MODULE_REGISTER(flash_memory_mapped, CONFIG_LOG_DEFAULT_LEVEL);
18
main(void)19 int main(void)
20 {
21 uint8_t buffer[32];
22 const struct device *flash_device;
23 const void *mem_ptr;
24 spi_flash_mmap_handle_t handle;
25 off_t address = FIXED_PARTITION_OFFSET(scratch_partition);
26 size_t size = FIXED_PARTITION_SIZE(scratch_partition);
27
28 flash_device = DEVICE_DT_GET(DT_CHOSEN(zephyr_flash_controller));
29 if (!device_is_ready(flash_device)) {
30 printk("%s: device not ready.\n", flash_device->name);
31 return 0;
32 }
33
34 /* map selected region */
35 spi_flash_mmap(address, size, SPI_FLASH_MMAP_DATA, &mem_ptr, &handle);
36 LOG_INF("memory-mapped pointer address: %p", mem_ptr);
37
38 /* erase and read flash */
39 flash_erase(flash_device, address, size);
40 LOG_HEXDUMP_INF(mem_ptr, 32, "flash read using memory-mapped pointer");
41
42 LOG_INF("writing 32-bytes data using flash API");
43 memset(buffer, 0, sizeof(buffer));
44 for (int k = 0; k < 32; k++) {
45 buffer[k] = k;
46 }
47 flash_write(flash_device, address, buffer, 32);
48
49 /* read using flash API */
50 memset(buffer, 0, sizeof(buffer));
51 flash_read(flash_device, address, buffer, 32);
52 LOG_HEXDUMP_INF(buffer, 32, "flash read using flash API");
53
54 LOG_HEXDUMP_INF(mem_ptr, 32, "flash read using memory-mapped pointer");
55
56 if (memcmp(buffer, mem_ptr, 32) == 0) {
57 LOG_INF("memory-mapped reading matches flash API read");
58 } else {
59 LOG_ERR("memory-mapped reading does not match flash API read");
60 }
61
62 /* unmap mapped region */
63 spi_flash_munmap(handle);
64
65 return 0;
66 }
67