Serial Memory
Loading...
Searching...
No Matches
Serial Memory - External SPI Memory Interface Library for ModusToolbox™

Overview

Provides functions for interacting with an external memory connected through its Single SPI/Dual SPI/Quad SPI/Octal SPI interface. The read, write and erase operations are implemented as blocking functions. This library accepts the configuration generated using the QSPI Configurator tool.

The library is available for devices that define CY_IP_MXSMIF (devices with the MXSMIF peripheral); on other devices the API is not compiled. Read and write also work with HyperBus memories (through the PDL HyperBus functions), erase is supported only for SPI memories.

Features

  • Implements thread-safety for use with multi-threaded RTOS environment using the abstraction-rtos library. When MTB_SERIAL_MEMORY_THREAD_SAFE is defined, mtb_serial_memory_read(), mtb_serial_memory_write() and mtb_serial_memory_erase() are protected by a mutex of the mtb_serial_memory_t object. The other functions (for example mtb_serial_memory_set_active_chip(), mtb_serial_memory_enable_xip() and mtb_serial_memory_set_write_enable()) are not protected and must be serialized by the application. Thread-safety is not provided between different objects or between CPU cores
  • Accepts the configuration generated by the QSPI Configurator tool
  • Supports Execute-in-Place (XIP) mode of operation
  • Provides information about the external memory to the programming tool for it to be able to program the memory, for example, when user wants to place the code into the external memory for XIP operation
  • Allows for programming external memory if MTB_SERIAL_MEMORY_ENABLE_XIP_PROGRAM is defined when building the application

When to Use

Use this library when your application needs to interact with an external memory device connected via a Single/Dual/Quad/Octal SPI interface. Common scenarios include:

  • Storing and retrieving application data from external flash or PSRAM
  • Executing code from external memory (XIP mode)
  • Programming external memory with firmware or configuration data

How to use

Step 1. Add the library to the application using the Library Manager. The library needs a PDL that provides the SMIF MemNum API (Cy_SMIF_MemNum* functions and the cy_stc_smif_mem_context_t and cy_stc_smif_mem_info_t types) and a HAL that provides mtb_hal.h. Both are normally provided by the BSP of the target.

Step 2. Include the library header. The configurator-generated headers, including cycfg_qspi_memslot.h, are pulled in by cybsp.h:

#include <string.h> /* memset, memcmp and memcpy used in the snippets below */
#include "cybsp.h" /* Provides <alias>_hal_config and smifBlockConfig */
#include "mtb_serial_memory.h"

Step 3. Select the operating flow:

  • Bare metal: no additional setup is required.
  • RTOS (thread-safe): add the abstraction-rtos library and the RTOS asset used by the application, for example FreeRTOS, using the Library Manager. Enable the matching RTOS component and the thread-safety define in the application Makefile:
COMPONENTS+=FREERTOS
DEFINES+=MTB_SERIAL_MEMORY_THREAD_SAFE

Step 4. Declare the objects needed by the library and initialize the SMIF driver via PDL calls:

static mtb_serial_memory_t serial_memory_obj = {0};
static cy_stc_smif_mem_context_t mem_context;
static cy_stc_smif_mem_info_t mem_info;
/* Initialize SMIF with the configurator-generated config */
cy_en_smif_status_t smif_status = Cy_SMIF_Init(
MEMORYSPI0_hal_config.base,
MEMORYSPI0_hal_config.config,
10000u, /* Timeout in microseconds for the PDL blocking transfers, application choice */
&mem_context.smif_context);
CY_ASSERT(CY_SMIF_SUCCESS == smif_status);
/* Enable the SMIF block */
Cy_SMIF_Enable(MEMORYSPI0_hal_config.base, &mem_context.smif_context);
Serial memory object.
Definition mtb_serial_memory.h:194

Objects used above:

Object Source
MEMORYSPI0_hal_config Generated by the Device Configurator for the SMIF instance. Its name is <alias>_hal_config, where <alias> is the alias set on the SMIF personality (MEMORYSPI0 in this example). Available through cybsp.h.
smifBlockConfig Generated by the QSPI Configurator and declared in cycfg_qspi_memslot.h. The name depends on the configurator setup, for example smif0BlockConfig.
mem_context Declared by the application. mem_context.smif_context is initialized by Cy_SMIF_Init(), and the remaining fields are set by mtb_serial_memory_setup().
mem_info Declared by the application. It is an output filled in by mtb_serial_memory_setup() for the chip passed to it and refreshed by mtb_serial_memory_set_active_chip() for the selected chip, no initialization is needed.

Note: serial_memory_obj, mem_context and mem_info are referenced by the library after setup, so they must remain valid for as long as the library is used (declare them as global or static). serial_memory_obj must be zero-initialized before mtb_serial_memory_setup() is called, because the function updates its fields with read-modify-write operations; global and static objects are zero-initialized by default, and the explicit = {0} shows the requirement. Call mtb_serial_memory_setup() once per object, calling it again on the same object is not supported.

Step 5. Set up the serial memory library. The chip select is taken from the QSPI Configurator output, so the snippet does not depend on the slot the memory is placed in:

cy_rslt_t result = mtb_serial_memory_setup(
&serial_memory_obj,
(mtb_serial_memory_chip_select_t)smifBlockConfig.memConfig[0]->slaveSelect,
MEMORYSPI0_hal_config.base,
MEMORYSPI0_hal_config.clock,
&mem_context,
&mem_info,
&smifBlockConfig);
if (CY_RSLT_SUCCESS != result)
{
/* Stop here: do not call the other library functions after a failed setup */
handle_error(result); /* Application error handling */
}
mtb_serial_memory_chip_select_t
Serial Memory Chip Select Each chip select is represented by an enumeration that has the bit correspo...
Definition mtb_serial_memory.h:178
cy_rslt_t mtb_serial_memory_setup(mtb_serial_memory_t *obj, mtb_serial_memory_chip_select_t smif_active_chip, SMIF_Type *base, const mtb_hal_clock_t *clock, cy_stc_smif_mem_context_t *mem_context, cy_stc_smif_mem_info_t *mem_info, const cy_stc_smif_block_config_t *block_config)
Sets up the serial memory.
Definition mtb_serial_memory.c:427

memConfig[0] is the first memory configured in the QSPI Configurator. Use another index to select a different memory. The cy_en_smif_slave_select_t values match mtb_serial_memory_chip_select_t, so the cast is valid. The chip select can also be set explicitly using one of the following values:

Chip select Value
MTB_SERIAL_MEMORY_CHIP_SELECT_0 0x1 (SMIF slave select 0)
MTB_SERIAL_MEMORY_CHIP_SELECT_1 0x2 (SMIF slave select 1)
MTB_SERIAL_MEMORY_CHIP_SELECT_2 0x4 (SMIF slave select 2)
MTB_SERIAL_MEMORY_CHIP_SELECT_3 0x8 (SMIF slave select 3)

Note: The functions that need a successful setup (read, write, erase and the others except mtb_serial_memory_setup()) check this with CY_ASSERT. A build without assertions has no supported recovery path after a failed setup, so always check the setup result and stop the flow on failure.

Note: For memories that use Quad mode, mtb_serial_memory_setup() enables the Quad Enable (QE) bit if it is not already set. The enable command is sent once; the library then polls the memory until it is ready and reads the QE bit back, up to MTB_SERIAL_MEMORY_QUAD_ENABLE_MAX_ATTEMPTS times (default 3, must be at least 1). More attempts do not resend the command. Each poll uses the timeout MTB_SERIAL_MEMORY_QUAD_ENABLE_TIMEOUT_US (default 5000 us). The possible outcomes are:

  • The QE bit is already set: no command is sent and setup continues.
  • The QE bit is set after the command: setup continues.
  • The memory stays busy longer than the timeout (the QE bit is stored in a non-volatile register, so the write can keep the device busy for tens of milliseconds): setup returns CY_SMIF_EXCEED_TIMEOUT. Raise the timeout in the Makefile, for example DEFINES+=MTB_SERIAL_MEMORY_QUAD_ENABLE_TIMEOUT_US=1000000.
  • The readback succeeds but the QE bit is not set: setup returns MTB_RSLT_SERIAL_MEMORY_ERR_QUAD_ENABLE.
  • Another PDL SMIF error ends the sequence early and setup returns that status.

Note: Octal memories (MXSMIF version 4 and later) must already be in Octal mode (SDR or DDR, as configured) when mtb_serial_memory_setup() is called. The library sets the SMIF RX capture mode first and sends the Octal enable command only if the mode still differs, so for a memory with an explicit part number the command is not sent. This avoids a hang that can occur when SMIF is disabled and re-enabled while the code executes from the same memory (XIP). If the memory is still in single SPI mode, setup returns CY_RSLT_SUCCESS and the following operations fail, typically with CY_SMIF_EXCEED_TIMEOUT (0x00B20002). The PDL requires Cy_SMIF_MemOctalEnable() to be executed before octal commands are sent, so a memory that powers up in single SPI mode needs it from the application before setup: Cy_SMIF_MemNumInit(), Cy_SMIF_Enable(), Cy_SMIF_Reset_Memory(), Cy_SMIF_MemOctalEnable(), then set the RX capture mode required by the configuration. Nothing is needed for memories that power up in Octal mode or for Single, Dual and Quad SPI memories.

Step 6. Use the library to erase, write, and read external memory. All of these functions are blocking:

#define DATA_SIZE 64u
uint8_t write_buf[DATA_SIZE];
uint8_t read_buf[DATA_SIZE];
uint32_t address = 0x00000000;
/* Get the erase sector size for the target address */
uint32_t erase_size = mtb_serial_memory_get_erase_size(&serial_memory_obj, address);
/* Erase the sector before writing */
result = mtb_serial_memory_erase(&serial_memory_obj, address, erase_size);
CY_ASSERT(CY_RSLT_SUCCESS == result); /* Replace with application error handling */
/* Fill buffer with data and write to memory */
memset(write_buf, 0xA5, DATA_SIZE);
result = mtb_serial_memory_write(&serial_memory_obj, address, DATA_SIZE, write_buf);
CY_ASSERT(CY_RSLT_SUCCESS == result);
/* Read back and verify */
result = mtb_serial_memory_read(&serial_memory_obj, address, DATA_SIZE, read_buf);
CY_ASSERT(CY_RSLT_SUCCESS == result);
CY_ASSERT(0 == memcmp(write_buf, read_buf, DATA_SIZE));
cy_rslt_t mtb_serial_memory_erase(mtb_serial_memory_t *obj, uint32_t addr, size_t length)
Erases the serial memory, uses chip erase command when addr = 0 and length = flash_size otherwise use...
Definition mtb_serial_memory.c:870
size_t mtb_serial_memory_get_erase_size(mtb_serial_memory_t *obj, uint32_t addr)
Returns the size of the erase sector to which the given address belongs.
Definition mtb_serial_memory.c:690
cy_rslt_t mtb_serial_memory_write(mtb_serial_memory_t *obj, uint32_t addr, size_t length, const uint8_t *buf)
Writes the data to the serial memory.
Definition mtb_serial_memory.c:792
cy_rslt_t mtb_serial_memory_read(mtb_serial_memory_t *obj, uint32_t addr, size_t length, uint8_t *buf)
Reads data from the serial memory.
Definition mtb_serial_memory.c:730

Note: The CY_ASSERT calls keep the snippet short. Production code must check the result of every call and handle the error without relying on assertions.

Memory operations in detail

  • Erase: mtb_serial_memory_erase() uses the chip erase command when addr is 0 and length equals the memory size (mtb_serial_memory_get_size()), otherwise the sector erase command. addr and addr + length must be aligned to the erase sector size (mtb_serial_memory_get_erase_size()); for memories with hybrid sectors, use the sector size of the region each address is in. An unaligned range is rejected with MTB_RSLT_SERIAL_MEMORY_ERR_BAD_PARAM and nothing is erased, because the PDL function Cy_SMIF_MemNumEraseSector() would round addr down and addr + length up to sector boundaries and erase data outside the requested range. A range that exceeds the memory size is rejected by the PDL. Erase is supported only for SPI memories.
  • Zero length: read and write with length 0 return an error.
  • Byte emulation: some Octal DDR memories require an even address and an even length. To allow one-byte reads and writes at any address, add the following line to the application Makefile:
DEFINES+=_MTB_SERIAL_MEMORY_EMULATE_BYTE_ADDRESSABLE

The define applies to all SPI memories, not only Octal DDR, and it restricts the access sizes that are accepted. See the description in mtb_serial_memory.h before enabling it.

Multiple memories, TrustZone and write enable

  • Multiple memories: the memories configured in the QSPI Configurator are selected by chip select. mtb_serial_memory_set_active_chip() selects the memory that read, write and erase operate on, mtb_serial_memory_get_active_chip() returns the active chip select and mtb_serial_memory_get_chip_count() returns the number of memories in the SMIF block configuration. The memory information (mem_info, and so the values returned by mtb_serial_memory_get_size(), mtb_serial_memory_get_erase_size() and mtb_serial_memory_get_prog_size()) is populated by mtb_serial_memory_setup() for the chip passed to it and read again by mtb_serial_memory_set_active_chip() for the selected chip, so it always describes the active memory and the memories can have different geometry. If the information cannot be read, mtb_serial_memory_set_active_chip() returns the PDL status and the previous chip stays active.
  • TrustZone: when the peripheral is secure, call mtb_serial_memory_setup() in the secure partition and then mtb_serial_memory_setup_nonsecure() in the non-secure partition. The non-secure function is not available when COMPONENT_SECURE_DEVICE is defined.
  • Write enable: mtb_serial_memory_set_write_enable() sends the Write Enable or Write Disable command to the memory that is currently active.

Return values

All library functions that return a result code return CY_RSLT_SUCCESS (defined in cy_result.h) on success. Any other value is an error. The library error codes are defined and documented in mtb_serial_memory.h.

mtb_serial_memory_setup() can also return a PDL SMIF status code, such as CY_SMIF_EXCEED_TIMEOUT.

Execute-in-Place (XIP)

After a successful mtb_serial_memory_setup(), call mtb_serial_memory_enable_xip() to map the external memory into the MCU address space:

/* Enable memory mapped (XIP) mode */
result = mtb_serial_memory_enable_xip(&serial_memory_obj, true);
CY_ASSERT(CY_RSLT_SUCCESS == result);
/* The memory is mapped at the base address set in the QSPI Configurator */
const uint8_t* xip_memory = (const uint8_t*)smifBlockConfig.memConfig[0]->baseAddress;
/* Read the data with a regular memory access, no library call is needed */
memcpy(read_buf, xip_memory, DATA_SIZE);
/* Return to normal mode before using erase, write or read */
result = mtb_serial_memory_enable_xip(&serial_memory_obj, false);
CY_ASSERT(CY_RSLT_SUCCESS == result);
cy_rslt_t mtb_serial_memory_enable_xip(mtb_serial_memory_t *obj, bool enable)
Enables Execute-in-Place (memory mapped) mode on the MCU.
Definition mtb_serial_memory.c:923

mtb_serial_memory_enable_xip() configures only the MCU and does not send any command to the memory. The erase, write and read functions must be called with XIP mode disabled.

Code placed in the mapped address range by the linker script can be executed directly. Code that executes from the external memory cannot run while XIP mode is disabled, so the calls to erase, write and read must be made from code located in internal memory.

Programming external memory

To let a programming tool (for example Cypress Programmer, OpenOCD or pyOCD) program the external memory together with the internal memory, for example when the application code is placed into the external memory for XIP, add the following line to the application Makefile:

DEFINES+=MTB_SERIAL_MEMORY_ENABLE_XIP_PROGRAM

With this define, the library places the information about the memory in the .cy_sflash_user_data and .cy_toc_part2 sections. These sections must be provided by the application linker script. The .cy_toc_part2 data ends with a CRC16 checksum that must be recomputed whenever its content changes, which can be done by running cymcuelftool -S on the built ELF file. The section placement options and the data layout are described in the comments of mtb_serial_memory_prog.c.

After the application is built, the programming tool reads these sections to detect the attached memory and to learn how to program it. No API calls are needed at run time.

Release Notes and Changelog

  • RELEASE.md - Detailed release notes for all versions

License

This library is licensed under the Apache License, Version 2.0.

  • LICENSE - Primary license terms (Apache License)
  • EULA - End User License Agreement

Copyright

(c) (2018-2026), Infineon Technologies AG, or an affiliate of Infineon Technologies AG. All rights reserved.