IRAM pre-caching


This is taken from the esp8266 arduino core. For details see:

See Flash memory for some background.

Code is always executed from IRAM, however it must be read in from flash memory on first use which can cause issues within timing-critical code.

This can be avoided by placing the code in IRAM. However, IRAM is a very limited resource and should generally be reserved for interrupt service routines.

An alternative solution is to arrange for critical code to be pre-loaded into IRAM before it starts execution.


This cannot be used for interrupt service routines.

By their nature, interrupts are essentially random events and therefore code must be available in IRAM at any time.


The steps required are:

  1. Mark the function containing code using IRAM_PRECACHE_ATTR()
  2. Place a call to IRAM_PRECACHE_START() before the first line of critical code
  3. Place a call to IRAM_PRECACHE_END() after the last line of critical code

You must always declare a tag to avoid the risk of section name conflicts.

You can find an example of how precaching is used here:

API Documentation

void iram_precache(void *addr, uint32_t bytes)

Pre-load flash data into the flash instruction cache.

All pages containing the requested region will be read to pull them into cache RAM.
  • addr: First location to cache, specify NULL to use current location.
  • bytes: Number of bytes to cache


Tools for pre-loading code into the flash cache.

  • It can be useful for code that accesses/uses SPI0 which is connected to the flash chip.
  • Non interrupt handler code that is infrequently called but might otherwise require being in valuable IRAM - such as bit-banging I/O code or some code run at bootup can avoid being permanently in IRAM. Mark functions containing critical code using this attribute


Place this macro before the first line of the critical code.

Do not omit the tag, and be careful with naming to avoid conflicts
  • tag: Used to create the precached section name, must be globally unique


Place this macro after the last line of critical code.