text
stringlengths
1
3.82k
__index_level_0__
int64
0
366
Configure Other JTAG Interfaces {IDF_TARGET_JTAG_SEL_EFUSE:default="Not Updated!", esp32s3="STRAP_JTAG_SEL", esp32c6="JTAG_SEL_ENABLE", esp32h2="JTAG_SEL_ENABLE"} For guidance about which JTAG interface to select when using OpenOCD with {IDF_TARGET_NAME}, refer to the section :ref:`jtag-debugging-selecting-jtag-adapter`. Then follow the configuration steps below to get it working. .. only:: SOC_USB_SERIAL_JTAG_SUPPORTED Configure eFuses By default, {IDF_TARGET_NAME} JTAG interface is connected to the :doc:`built-in USB_SERIAL_JTAG peripheral `. To use an external JTAG adapter instead, you need to switch the JTAG interface to the GPIO pins. This can be done by burning eFuses using ``espefuse.py`` tool. .. only:: esp32c3 Burning ``DIS_USB_JTAG`` eFuse will permanently disable the connection between USB_SERIAL_JTAG and the JTAG port of the {IDF_TARGET_NAME}. JTAG interface can then be connected to |jtag-gpio-list|. Note that USB CDC functionality of USB_SERIAL_JTAG will still be usable, i.
316
e., flashing and monitoring over USB CDC will still work. .. only:: not esp32c3 - Burning ``DIS_USB_JTAG`` eFuse will permanently disable the connection between USB_SERIAL_JTAG and the JTAG port of the {IDF_TARGET_NAME}. JTAG interface can then be connected to |jtag-gpio-list|. Note that USB CDC functionality of USB_SERIAL_JTAG will still be usable, i.e., flashing and monitoring over USB CDC will still work. - Burning ``{IDF_TARGET_JTAG_SEL_EFUSE}`` eFuse will enable selection of JTAG interface by a strapping pin, |jtag-sel-gpio|. If the strapping pin is low when {IDF_TARGET_NAME} is reset, JTAG interface will use |jtag-gpio-list|. If the strapping pin is high, USB_SERIAL_JTAG will be used as the JTAG interface. .. warning:: Burning eFuses is an irreversible operation, so please consider the above option before starting the process. Configure Hardware .. include:: {IDF_TARGET_PATH_NAME}.inc :start-after: jtag-pins :end-before: --- Configure Drivers You may need to install driver software to make JTAG work with computer.
316
Refer to documentation of your JTAG adapter for related details. On Linux, adding OpenOCD udev rules is required and is done by copying the `udev rules file `_ into the ``/etc/udev/rules.d`` directory. Connect Connect JTAG interface to the computer. Power on {IDF_TARGET_NAME} and JTAG interface boards. Check if the JTAG interface is visible on the computer. To carry on with debugging environment setup, proceed to section :ref:`jtag-debugging-run-openocd`.
316
Building OpenOCD from Sources for Linux The following instructions are alternative to downloading binary OpenOCD from `Espressif GitHub `_. To quickly setup the binary OpenOCD, instead of compiling it yourself, backup and proceed to section :ref:`jtag-debugging-setup-openocd`. .. highlight:: bash Download Sources of OpenOCD The sources for the {IDF_TARGET_NAME}-enabled variant of OpenOCD are available from Espressif GitHub under https://github.com/espressif/openocd-esp32. To download the sources, use the following commands:: cd ~/esp git clone --recursive https://github.com/espressif/openocd-esp32.git The clone of sources should be now saved in ``~/esp/openocd-esp32`` directory. Install Dependencies Install packages that are required to compile OpenOCD. .. note:: Install the following packages one by one, check if installation was successful and then proceed to the next package. Resolve reported problems before moving to the next step. :: sudo apt-get install make sudo apt-get install libtool sudo apt-get install pkg-config sudo apt-get install autoconf sudo apt-get install automake sudo apt-get install texinfo sudo apt-get install libusb-1.
317
0 .. note:: Build OpenOCD Proceed with configuring and building OpenOCD:: cd ~/esp/openocd-esp32 ./bootstrap ./configure make Optionally you can add ``sudo make install`` step at the end. Skip it, if you have an existing OpenOCD (from e.g., another development platform), as it may get overwritten. .. note:: Once ``make`` process is successfully completed, the executable of OpenOCD will be saved in ``~/openocd-esp32/bin`` directory. Next Steps To carry on with debugging environment setup, proceed to section :ref:`jtag-debugging-configuring-target`.
317
.. include:: {IDF_TARGET_PATH_NAME}.inc :start-after: devkit-defs :end-before: --- Configure |devkit-name| JTAG Interface All versions of |devkit-name| boards have built-in JTAG functionality. Putting it to work requires setting jumpers or DIP switches to enable JTAG functionality, and configuring USB drivers. Please refer to step by step instructions below. Configure Hardware .. include:: {IDF_TARGET_PATH_NAME}.inc :start-after: devkit-hw-config :end-before: --- .. include:: {IDF_TARGET_PATH_NAME}.inc :start-after: jtag-pins :end-before: --- Configure USB Drivers Install and configure USB drivers, so OpenOCD is able to communicate with JTAG interface on |devkit-name| board as well as with UART interface used to upload application for flash. Follow steps below specific to your operating system. .. note:: |devkit-name| uses an FT2232 adapter. The following instructions can also be used for other FT2232 based JTAG adapters. Windows """"""" .
318
. figure:: ../../../_static/jtag-usb-configuration-zadig.jpg :align: center :alt: Configuration of JTAG USB driver in Zadig tool :figclass: align-center Configuration of JTAG USB driver in Zadig tool .. note:: Do not change the second device "Dual RS232-HS (Interface 1)". It is routed to {IDF_TARGET_NAME}'s serial port (UART) used for upload of application to {IDF_TARGET_NAME}'s flash. Now |devkit-name|'s JTAG interface should be available to the OpenOCD. To carry on with debugging environment setup, proceed to section :ref:`jtag-debugging-run-openocd`. Linux """"" .. highlight:: none :: user-name@computer-name:~/esp$ ls -l /dev/ttyUSB* crw-rw 1 root dialout 188, 0 Jul 10 19:04 /dev/ttyUSB0 crw-rw 1 root dialout 188, 1 Jul 10 19:04 /dev/ttyUSB1 :: user-name@computer-name:~/esp$ ls -l /dev/ttyUSB* crw-rw-r-- 1 root plugdev 188, 0 Jul 10 19:07 /dev/ttyUSB0 crw-rw-r-- 1 root plugdev 188, 1 Jul 10 19:07 /dev/ttyUSB1 If you see similar result and you are a member of ``plugdev`` group, then the set up is complete.
318
The ``/dev/ttyUSBn`` interface with lower number is used for JTAG communication. The other interface is routed to {IDF_TARGET_NAME}'s serial port (UART) used for upload of application to {IDF_TARGET_NAME}'s flash. Now |devkit-name|'s JTAG interface should be available to the OpenOCD. To carry on with debugging environment setup, proceed to section :ref:`jtag-debugging-run-openocd`. MacOS """"" On macOS, using FT2232 for JTAG and serial port at the same time needs some additional steps. When the OS loads FTDI serial port driver, it does so for both channels of FT2232 chip. However only one of these channels is used as a serial port, while the other is used as JTAG. If the OS has loaded FTDI serial port driver for the channel used for JTAG, OpenOCD will not be able to connect to the chip. There are two ways around this: Manually unloading the driver ............................. sudo kextunload -b com.FTDI.driver.FTDIUSBSerialDriver In some cases you may need to unload Apple's FTDI driver as well: CFBundleIdentifier com.
318
FTDI.driver.FTDIUSBSerialDriver IOClass FTDIUSBSerialDriver IOProviderClass IOUSBInterface bConfigurationValue 1 bInterfaceNumber 1 bcdDevice 1792 idProduct 24592 idVendor 1027 csrutil enable --without kext After these steps, serial port and JTAG can be used at the same time. To carry on with debugging environment setup, proceed to section :ref:`jtag-debugging-run-openocd`.
318
Minimizing Binary Size {IDF_TARGET_REDUCED_BY_IRAM: default="DRAM", esp32="IRAM and/or DRAM (depending on sizes)"} The ESP-IDF build system compiles all source files in the project and ESP-IDF, but only functions and variables that are actually referenced by the program are linked into the final binary. In some cases, it is necessary to reduce the total size of the firmware binary, e.g., in order to fit it into the available flash partition size. The first step to reducing the total firmware binary size is measuring what is causing the size to increase. .. _idf.py-size: Measuring Static Sizes To optimize both the firmware binary size and the memory usage, it is necessary to measure statically-allocated RAM (``data``, ``bss``), code (``text``), and read-only data (``rodata``) in your project. Using the :ref:`idf.py` sub-commands ``size``, ``size-components``, and ``size-files`` provides a summary of memory used by the project: .. note:: It is possible to add ``-DOUTPUT_FORMAT=csv`` or ``-DOUTPUT_FORMAT=json`` to get the output in CSV or JSON format.
319
Size Summary ``idf.py size`` .. only:: esp32 .. code-block:: bash $ idf.py size [...] Total sizes: Used static DRAM: 10608 bytes ( 170128 remain, 5.9% used) .data size: 8464 bytes .bss size: 2144 bytes Used static IRAM: 48834 bytes ( 82238 remain, 37.3% used) .text size: 47807 bytes .vectors size: 1027 bytes Used Flash size : 117391 bytes .text: 80103 bytes .rodata: 37032 bytes Total image size: 174689 bytes (.bin may be padded larger) .. only:: not esp32 .. code-block:: bash $ idf.py size [...] Total sizes: Used stat D/IRAM: 53743 bytes ( 122385 remain, 30.5% used) .data size: 6504 bytes .bss size: 1984 bytes .text size: 44228 bytes .vectors size: 1027 bytes Used Flash size : 118879 bytes .
319
text: 83467 bytes .rodata: 35156 bytes Total image size: 170638 bytes (.bin may be padded larger) This output breaks down the size of all static memory regions in the firmware binary: .. only:: esp32 .. code-block:: bash $ idf.py size [...] Total sizes: Used static DRAM: 10608 bytes ( 170128 remain, 5.9% used) .data size: 8464 bytes .bss size: 2144 bytes Used static IRAM: 48834 bytes ( 82238 remain, 37.3% used) .text size: 47807 bytes .vectors size: 1027 bytes Used Flash size : 117391 bytes .text: 80103 bytes .rodata: 37032 bytes Total image size: 174689 bytes (.bin may be padded larger) - ``Used static DRAM``: Total amount of DRAM allocated at compile time. ``remain`` indicates the amount of DRAM left to be used as heap memory at runtime. Note that due to meta data overhead, implementation constraints, and startup heap allocations, the actual size of the DRAM heap is smaller.
319
- ``.data size``: Amount of DRAM allocated at compile time for the ``.data`` (i.e., all statically allocated variables that are initialized to non-zero values). ``.data`` also consumes space in the binary image to store the non-zero initialization values. - ``.bss size``: Amount of DRAM allocated at compile time for ``.bss`` (i.e., all statically allocated variables that are initialized to zero). ``.bss`` does not consume extra space in flash. - ``Used static IRAM``: Total amount of IRAM allocated at compile time. ``remain`` indicates the amount of IRAM left to be used as heap memory at runtime. Note that due to meta data overhead, implementation constraints, and startup heap allocations, the actual size of the IRAM heap is smaller. - ``.text size``: Amount of IRAM used for ``.text`` (i.e., all code that is executed from :ref:`IRAM `). ``.text`` also consumes space in the binary image as the code is initially stored there and is then copied over to IRAM on startup.
319
- ``Used Flash size``: Total amount of flash used (excluding usage by DRAM and IRAM) - ``.text``: Amount of flash used for ``.text`` (i.e., all code that is executed via the flash cache, see :ref:`IROM `). - ``.rodata``: Amount of flash used for ``.rodata`` (i.e., read-only data that is loaded via the flash cache, see :ref:`DROM `). - ``Total image size`` is the estimated total size of the binary file. .. only:: not esp32 .. code-block:: bash $ idf.py size [...] Total sizes: Used stat D/IRAM: 53743 bytes ( 122385 remain, 30.5% used) .data size: 6504 bytes .bss size: 1984 bytes .text size: 44228 bytes .vectors size: 1027 bytes Used Flash size : 118879 bytes .text: 83467 bytes .rodata: 35156 bytes Total image size: 170638 bytes (.bin may be padded larger) - ``Used stat D/IRAM``: Total amount of D/IRAM used at compile time.
319
``remain`` indicates the amount of D/IRAM left to be used as heap memory at runtime. Note that due to meta data overhead, implementation constraints, and startup heap allocations, the actual size of the DRAM heap is smaller. - ``.data size``: Amount of D/IRAM allocated at compile time for the ``.data`` (i.e., all statically allocated variables that are initialized to non-zero values). ``.data`` also consumes space in the binary image to store the non-zero initialization values. - ``.bss size``: Amount of D/IRAM allocated at compile time for ``.bss`` (i.e., all statically allocated variables that are initialized to zero). ``.bss`` does not consume extra space in flash. - ``.text size``: Amount of D/IRAM used for ``.text`` (i.e., all code that is executed from internal RAM). ``.text`` also consumes space in the binary image as the code is initially stored there and is then copied over to D/IRAM on startup. - ``Used Flash size``: Total amount of flash used (excluding usage by D/IRAM) - ``.
319
text``: Amount of flash used for ``.text`` (i.e., all code that is executed via the flash cache, see :ref:`IROM `). - ``.rodata``: Amount of flash used for ``.rodata`` (i.e., read-only data that is loaded via the flash cache, see :ref:`DROM `). - ``Total image size`` is the estimated total size of the binary file. Component Usage Summary ``idf.py size-components`` The summary output provided by ``idf.py size`` does not give enough details to find the main contributor to excessive binary size. To analyze in detail, use ``idf.py size-components``. .. code-block:: bash $ idf.py size-components [...] Total sizes: DRAM .data size: 14956 bytes DRAM .bss size: 15808 bytes Used static DRAM: 30764 bytes ( 149972 available, 17.0% used) Used static IRAM: 83918 bytes ( 47154 available, 64.0% used) Flash code: 559943 bytes Flash rodata: 176736 bytes Total image size:~ 835553 bytes (.bin may be padded larger) Per-archive contributions to ELF file: Archive File DRAM .
319
data & .bss & other IRAM D/IRAM Flash code & rodata Total libnet80211.a 1267 6044 0 5490 0 107445 18484 138730 liblwip.a 21 3838 0 0 0 97465 16116 117440 libmbedtls.a 60 524 0 0 0 27655 69907 98146 libmbedcrypto.a 64 81 0 30 0 76645 11661 88481 libpp.a 2427 1292 0 20851 0 37208 4708 66486 libc.a 4 0 0 0 0 57056 6455 63515 libphy.a 1439 715 0 7798 0 33074 0 43026 libwpa_supplicant.a 12 848 0 0 0 35505 1446 37811 libfreertos.a 3104 740 0 15711 0 367 4228 24150 libnvs_flash.a 0 24 0 0 0 14347 2924 17295 libspi_flash.
319
a 1562 294 0 8851 0 1840 1913 14460 libesp_system.a 245 206 0 3078 0 5990 3817 13336 libesp-tls.a 0 4 0 0 0 5637 3524 9165 [... removed some lines here ...] libesp_rom.a 0 0 0 112 0 0 0 112 libcxx.a 0 0 0 0 0 47 0 47 (exe) 0 0 0 3 0 3 12 18 libesp_pm.a 0 0 0 0 0 8 0 8 libesp_eth.a 0 0 0 0 0 0 0 0 libmesh.a 0 0 0 0 0 0 0 0 The first lines of the output from ``idf.py size-components`` are the same as that from ``idf.py size``.
319
After this, a table is printed as ``Per-archive contributions to ELF file``. This means how much each static library archive has contributed to the final binary size. Generally, one static library archive is built per component, although some are binary libraries included by a particular component, for example, ``libnet80211.a`` is included by ``esp_wifi`` component. There are also toolchain libraries such as ``libc.a`` and ``libgcc.a`` listed here, these provide Standard C/C++ Library and toolchain built-in functionality. If your project is simple and only has a ``main`` component, then all of the project's code will be shown under ``libmain.a``. If your project includes its own components (see :doc:`/api-guides/build-system`), then they will each be shown on a separate line. The table is sorted in descending order of the total contribution of the static archive to the binary size. The columns are as follows: .. list:: - ``DRAM .data & .bss & other`` - ``.data`` and ``.bss`` are the same as for the totals shown above.
319
Both are static variables and reduce the total available RAM at runtime, but ``.bss`` does not contribute to the binary file size. ``other`` is a column for any custom section types that also contribute to RAM size. Usually, the value is 0. :esp32: - ``IRAM`` - is the same as for the totals shown above. It refers to code linked to execute from IRAM, which uses space in the binary file and also reduces IRAM that can be dynamically allocated at runtime using ``HEAP_CAP_32BIT``. :esp32: - ``D/IRAM`` - shows IRAM space which, due to occupying D/IRAM space, is also reducing available DRAM available as heap at runtime. :not esp32: - ``IRAM`` - is the same as for the totals shown above. It refers to code linked to execute from IRAM, which uses space in the binary file and also reduces DRAM available as heap at runtime. - ``Flash code & rodata`` - these are the same as the totals above, IROM and DROM space accessed from the flash cache that contribute to the binary size. Source File Usage Summary ``idf.
319
py size-files`` For even more details, run ``idf.py size-files`` to get a summary of the contribution each object file has made to the final binary size. Each object file corresponds to a single source file. .. code-block:: bash $ idf.py size-files [...] Total sizes: DRAM .data size: 14956 bytes DRAM .bss size: 15808 bytes Used static DRAM: 30764 bytes ( 149972 available, 17.0% used) Used static IRAM: 83918 bytes ( 47154 available, 64.0% used) Flash code: 559943 bytes Flash rodata: 176736 bytes Total image size:~ 835553 bytes (.bin may be padded larger) Per-file contributions to ELF file: Object File DRAM .data & .bss & other IRAM D/IRAM Flash code & rodata Total x509_crt_bundle.S.o 0 0 0 0 0 0 64212 64212 wl_cnx.o 2 3183 0 221 0 13119 3286 19811 phy_chip_v7.o 721 614 0 1642 0 16820 0 19797 ieee80211_ioctl.
319
o 740 96 0 437 0 15325 2627 19225 pp.o 1142 45 0 8871 0 5030 537 15625 ieee80211_output.o 2 20 0 2118 0 11617 914 14671 ieee80211_sta.o 1 41 0 1498 0 10858 2218 14616 lib_a-vfprintf.o 0 0 0 0 0 13829 752 14581 lib_a-svfprintf.o 0 0 0 0 0 13251 752 14003 ssl_tls.c.o 60 0 0 0 0 12769 463 13292 sockets.c.o 0 648 0 0 0 11096 1030 12774 nd6.c.o 8 932 0 0 0 11515 314 12769 phy_chip_v7_cal.o 477 53 0 3499 0 8561 0 12590 pm.o 32 364 0 2673 0 7788 782 11639 ieee80211_scan.
319
o 18 288 0 0 0 8889 1921 11116 lib_a-svfiprintf.o 0 0 0 0 0 9654 1206 10860 lib_a-vfiprintf.o 0 0 0 0 0 10069 734 10803 ieee80211_ht.o 0 4 0 1186 0 8628 898 10716 phy_chip_v7_ana.o 241 48 0 2657 0 7677 0 10623 bignum.c.o 0 4 0 0 0 9652 752 10408 tcp_in.c.o 0 52 0 0 0 8750 1282 10084 trc.o 664 88 0 1726 0 6245 1108 9831 tasks.c.o 8 704 0 7594 0 0 1475 9781 ecp_curves.c.o 28 0 0 0 0 7384 2325 9737 ecp.c.o 0 64 0 0 0 8864 286 9214 ieee80211_hostap.
319
o 1 41 0 0 0 8578 585 9205 wdev.o 121 125 0 4499 0 3684 580 9009 tcp_out.c.o 0 0 0 0 0 5686 2161 7847 tcp.c.o 2 26 0 0 0 6161 1617 7806 ieee80211_input.o 0 0 0 0 0 6797 973 7770 wpa.c.o 0 656 0 0 0 6828 55 7539 [... additional lines removed ...] After the summary of total sizes, a table of ``Per-file contributions to ELF file`` is printed. The columns are the same as shown above for ``idy.py size-components``, but this time the granularity is the contribution of each individual object file to the binary size. For example, we can see that the file ``x509_crt_bundle.S.o`` contributed 64,212 bytes to the total firmware size, all as ``.
319
rodata`` in flash. Therefore we can guess that this application is using the :doc:`/api-reference/protocols/esp_crt_bundle` feature and not using this feature would save at last this many bytes from the firmware size. Some of the object files are linked from binary libraries and therefore you will not find a corresponding source file. To locate which component a source file belongs to, it is generally possible to search in the ESP-IDF source tree or look in the :ref:`linker-map-file` for the full path. Comparing Two Binaries If making some changes that affect binary size, it is possible to use an ESP-IDF tool to break down the exact differences in size. This operation is not part of ``idf.py``, it is necessary to run the `esp_idf_size `_ Python tool directly. To do so, first, locate the linker map file with the name ``PROJECTNAME.map`` in the build directory. The ``esp_idf_size`` tool performs its analysis based on the output of the linker map file. To compare with another binary, you also need its corresponding ``.
319
map`` file saved from the build directory. For example, to compare two builds, one of which with the default :ref:`CONFIG_COMPILER_OPTIMIZATION` setting ``Debug (-Og)`` configuration while another with ``Optimize for size (-Os)``: .. code-block:: bash $ python -m esp_idf_size --diff build_Og/https_request.map build_Os/https_request.map MAP file: build_Os/https_request.map MAP file: build_Og/https_request.map Difference is counted as - , i.e. a positive number means that is larger. Total sizes of : Difference DRAM .data size: 14516 bytes 14956 -440 DRAM .bss size: 15792 bytes 15808 -16 Used static DRAM: 30308 bytes ( 150428 available, 16.8% used) 30764 -456 ( +456 available, +0 total) Used static IRAM: 78498 bytes ( 52574 available, 59.
319
9% used) 83918 -5420 ( +5420 available, +0 total) Flash code: 509183 bytes 559943 -50760 Flash rodata: 170592 bytes 176736 -6144 Total image size:~ 772789 bytes (.bin may be padded larger) 835553 -62764 We can see from the ``Difference`` column that changing this one setting caused the whole binary to be over 60 KB smaller and over 5 KB more RAM is available. It is also possible to use the ``diff`` mode to output a table of component-level (static library archive) differences: .. note:: To get the output in JSON or CSV format using ``esp_idf_size``, it is possible to use the ``--format`` option. .. code-block:: bash python -m esp_idf_size --archives --diff build_Og/https_request.map build_Oshttps_request.map Also at the individual source file level: .. code-block:: bash python -m esp_idf_size --files --diff build_Og/https_request.
319
map build_Oshttps_request.map Other options, like writing the output to a file, are available, pass ``--help`` to see the full list. .. _idf-size-linker-failed: Showing Size When Linker Fails If too much static memory is allocated, the linker will fail with an error such as ``DRAM segment data does not fit``, ``region `iram0_0_seg' overflowed by 44 bytes``, or similar. In these cases, ``idf.py size`` will not succeed either. However, it is possible to run ``esp_idf_size`` manually to view the **partial static memory usage**. The memory usage will miss the variables that could not be linked, so there still appears to be some free space. The map file argument is ``.map`` in the build directory. .. code-block:: bash python -m esp_idf_size build/project_name.map It is also possible to view the equivalent of ``size-components`` or ``size-files`` output: .. code-block:: bash python -m esp_idf_size --archives build/project_name.map python -m esp_idf_size --files build/project_name.
319
map .. _linker-map-file: Linker Map File .. note:: This is an advanced analysis method, but it can be very useful. Feel free to skip ahead to :ref:`reducing-overall-size` and possibly come back to this later. The ``idf.py size`` analysis tools all work by parsing the GNU binutils ``linker map file``, which is a summary of everything the linker did when it created (i.e., linked) the final firmware binary file. Linker map files themselves are plain text files, so it is possible to read them and find out exactly what the linker did. However, they are also very complex and long, often exceeding 100,000 lines. The map file itself is broken into parts and each part has a heading. The parts are: - ``Archive member included to satisfy reference by file (symbol)`` - This shows you: for each object file included in the link, what symbol (function or variable) was the linker searching for when it included that object file. - If you are wondering why some object file in particular was included in the binary, this part may give a clue.
319
This part can be used in conjunction with the ``Cross Reference Table`` at the end of the file. .. note:: Not every object file shown in this list ends up included in the final binary, some end up in the ``Discarded input sections`` list instead. - ``Allocating common symbols`` - This is a list of some global variables along with their sizes. Common symbols have a particular meaning in ELF binary files, but ESP-IDF does not make much use of them. - ``Discarded input sections`` - These sections were read by the linker as part of an object file to be linked into the final binary, but then nothing else referred to them, so they were discarded from the final binary. - For ESP-IDF, this list can be very long, as we compile each function and static variable to a unique section in order to minimize the final binary size. Specifically, ESP-IDF uses compiler options ``-ffunction-sections -fdata-sections`` and linker option ``--gc-sections``. - Items mentioned in this list **do not** contribute to the final binary.
319
- ``Memory Configuration``, ``Linker script and memory map`` - These two parts go together. Some of the output comes directly from the linker command line and the Linker Script, both provided by :doc:`/api-guides/build-system`. The linker script is partially generated from the ESP-IDF project using the :doc:`/api-guides/linker-script-generation` feature. - As the output of the ``Linker script and memory map`` part of the map unfolds, you can see each symbol (function or static variable) linked into the final binary along with its address (as a 16 digit hex number), its length (also in hex), and the library and object file it was linked from (which can be used to determine the component and the source file). - Following all of the output sections that take up space in the final ``.bin`` file, the ``memory map`` also includes some sections in the ELF file that are only used for debugging, e.g., ELF sections ``.debug_*``, etc. These do not contribute to the final binary size.
319
You can notice the address of these symbols is a very small number, starting from ``0x0000000000000000`` and counting up. - ``Cross Reference Table`` - This table shows the symbol (function or static variable) that the list of object file(s) refers to. If you are wondering why a particular thing is included in the binary, this will help determine what included it. .. note:: Unfortunately, the ``Cross Reference Table`` does not only include symbols that made it into the final binary. It also includes symbols in discarded sections. Therefore, just because something is shown here does not mean that it was included in the final binary - this needs to be checked separately. .. note:: Linker map files are generated by the GNU binutils linker ``ld``, not ESP-IDF. You can find additional information online about the linker map file format. This quick summary is written from the perspective of ESP-IDF build system in particular. .. _reducing-overall-size: Reducing Overall Size The following configuration options reduces the final binary size of almost any ESP-IDF project: .
319
. list:: - Set :ref:`CONFIG_COMPILER_OPTIMIZATION` to ``Optimize for size (-Os)``. In some cases, ``Optimize for performance (-O2)`` will also reduce the binary size compared to the default. Note that if your code contains C or C++ Undefined Behavior then increasing the compiler optimization level may expose bugs that otherwise do not happen. - Reduce the compiled-in log output by lowering the app :ref:`CONFIG_LOG_DEFAULT_LEVEL`. If the :ref:`CONFIG_LOG_MAXIMUM_LEVEL` is changed from the default then this setting controls the binary size instead. Reducing compiled-in logging reduces the number of strings in the binary, and also the code size of the calls to logging functions. - Set the :ref:`CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL` to ``Silent``. This avoids compiling in a dedicated assertion string and source file name for each assert that may fail. It is still possible to find the failed assert in the code by looking at the memory address where the assertion failed.
319
- Besides the :ref:`CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL`, you can disable or silent the assertion for the HAL component separately by setting :ref:`CONFIG_HAL_DEFAULT_ASSERTION_LEVEL`. It is to notice that ESP-IDF lowers the HAL assertion level in bootloader to be silent even if :ref:`CONFIG_HAL_DEFAULT_ASSERTION_LEVEL` is set to full-assertion level. This is to reduce the bootloader size. - Setting :ref:`CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT` removes specific error messages for particular internal ESP-IDF error check macros. This may make it harder to debug some error conditions by reading the log output. :esp32: - If the binary needs to run on only certain revision(s) of ESP32, increasing :ref:`CONFIG_ESP32_REV_MIN` to match can result in a reduced binary size. This will make a large difference if setting ESP32 minimum revision 3, and PSRAM is enabled. :esp32c3: - If the binary needs to run on only certain revision(s) of ESP32-C3, increasing :ref:`CONFIG_ESP32C3_REV_MIN` to match can result in a reduced binary size.
319
This is particularly true if setting ESP32-C3 minimum revision 3 and using Wi-Fi, as some functionality was moved to ROM code. - Do not enable :ref:`CONFIG_COMPILER_CXX_EXCEPTIONS`, :ref:`CONFIG_COMPILER_CXX_RTTI`, or set the :ref:`CONFIG_COMPILER_STACK_CHECK_MODE` to Overall. All of these options are already disabled by default, but they have a large impact on binary size. - Disabling :ref:`CONFIG_ESP_ERR_TO_NAME_LOOKUP` removes the lookup table to translate user-friendly names for error values (see :doc:`/api-guides/error-handling`) in error logs, etc. This saves some binary size, but error values will be printed as integers only. - Setting :ref:`CONFIG_ESP_SYSTEM_PANIC` to ``Silent reboot`` saves a small amount of binary size, however this is **only** recommended if no one will use UART output to debug the device. :CONFIG_IDF_TARGET_ARCH_RISCV: - Seting :ref:`CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS` reduces binary size by replacing inlined prologues/epilogues with library calls.
319
- If the application binary uses only one of the security versions of the protocomm component, then the support for others can be disabled to save some code size. The support can be disabled through :ref:`CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0`, :ref:`CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1` or :ref:`CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2` respectively. .. note:: In addition to the many configuration items shown here, there are a number of configuration options where changing the option from the default increases binary size. These are not noted here. Where the increase is significant is usually noted in the configuration item help text. .. _size-targeted-optimizations: Targeted Optimizations The following binary size optimizations apply to a particular component or a function: .. only:: SOC_WIFI_SUPPORTED Wi-Fi @@@@@ - Disabling :ref:`CONFIG_ESP_WIFI_ENABLE_WPA3_SAE` will save some Wi-Fi binary size if WPA3 support is not needed. Note that WPA3 is mandatory for new Wi-Fi device certifications.
319
- Disabling :ref:`CONFIG_ESP_WIFI_SOFTAP_SUPPORT` will save some Wi-Fi binary size if soft-AP support is not needed. - Disabling :ref:`CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT` will save some Wi-Fi binary size if enterprise support is not needed. .. only:: esp32 ADC @@@ - Disabling ADC calibration features :ref:`CONFIG_ADC_CAL_EFUSE_TP_ENABLE`, :ref:`CONFIG_ADC_CAL_EFUSE_VREF_ENABLE`, :ref:`CONFIG_ADC_CAL_LUT_ENABLE` will save a small amount of binary size if ADC driver is used, at expense of accuracy. .. only:: SOC_BT_SUPPORTED Bluetooth NimBLE @@@@@@@@@@@@@@@@ If using :doc:`/api-reference/bluetooth/nimble/index` then the following modifications can reduce binary size: .. list:: :esp32: - Set :ref:`CONFIG_BTDM_CTRL_BLE_MAX_CONN` to 1 if only one Bluetooth LE connection is needed. - Set :ref:`CONFIG_BT_NIMBLE_MAX_CONNECTIONS` to 1 if only one Bluetooth LE connection is needed. - Disable either :ref:`CONFIG_BT_NIMBLE_ROLE_CENTRAL` or :ref:`CONFIG_BT_NIMBLE_ROLE_OBSERVER` if these roles are not needed.
319
- Reducing :ref:`CONFIG_BT_NIMBLE_LOG_LEVEL` can reduce binary size. Note that if the overall log level has been reduced as described above in :ref:`reducing-overall-size` then this also reduces the NimBLE log level. lwIP IPv6 @@@@@@@@@ - Setting :ref:`CONFIG_LWIP_IPV6` to ``false`` will reduce the size of the lwIP TCP/IP stack, at the cost of only supporting IPv4. .. note:: IPv6 is required by some components such as :doc:`/api-reference/protocols/asio`. These components will not be available if IPV6 is disabled. lwIP IPv4 @@@@@@@@@ - If IPv4 connectivity is not required, setting :ref:`CONFIG_LWIP_IPV4` to ``false`` will reduce the size of the lwIP, supporting IPv6-only TCP/IP stack. .. note:: Before disabling IPv4 support, please note that IPv6 only network environments are not ubiquitous and must be supported in the local network, e.g., by your internet service provider or using constrained local network settings. .. _newlib-nano-formatting: Newlib Nano Formatting @@@@@@@@@@@@@@@@@@@@@@ By default, ESP-IDF uses Newlib "full" formatting for I/O functions (``printf()``, ``scanf()``, etc.
319
) .. only:: CONFIG_ESP_ROM_HAS_NEWLIB_NANO_FORMAT Enabling the config option :ref:`CONFIG_NEWLIB_NANO_FORMAT` will switch Newlib to the "Nano" formatting mode. This is smaller in code size, and a large part of the implementation is compiled into the {IDF_TARGET_NAME} ROM, so it does not need to be included in the binary at all. The exact difference in binary size depends on which features the firmware uses, but 25 KB ~ 50 KB is typical. .. only:: CONFIG_ESP_ROM_HAS_NEWLIB_NORMAL_FORMAT Disabling the config option :ref:`CONFIG_NEWLIB_NANO_FORMAT` will switch Newlib to the "full" formatting mode. This will reduce the binary size, as {IDF_TARGET_NAME} has the full formatting version of the functions in ROM, so it does not need to be included in the binary at all. Enabling "Nano" formatting reduces the stack usage of each function that calls ``printf()`` or another string formatting function, see :ref:`optimize-stack-sizes`. "Nano" formatting does not support 64-bit integers, or C99 formatting features.
319
For a full list of restrictions, search for ``--enable-newlib-nano-formatted-io`` in the `Newlib README file`_. .. only:: esp32c2 .. note:: :ref:`CONFIG_NEWLIB_NANO_FORMAT` is enabled by default on {IDF_TARGET_NAME}. .. _Newlib README file: https://sourceware.org/newlib/README .. _minimizing_binary_mbedtls: MbedTLS Features @@@@@@@@@@@@@@@@ Under **Component Config** > **mbedTLS**, there are multiple mbedTLS features enabled default, some of which can be disabled if not needed to save code size. These include: - :ref:`CONFIG_MBEDTLS_HAVE_TIME` - :ref:`CONFIG_MBEDTLS_ECDSA_DETERMINISTIC` - :ref:`CONFIG_MBEDTLS_SHA512_C` - :ref:`CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS` - :ref:`CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS` - :ref:`CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION` - :ref:`CONFIG_MBEDTLS_SSL_ALPN` - :ref:`CONFIG_MBEDTLS_SSL_RENEGOTIATION` - :ref:`CONFIG_MBEDTLS_CCM_C` - :ref:`CONFIG_MBEDTLS_GCM_C` - :ref:`CONFIG_MBEDTLS_ECP_C` (Alternatively: Leave this option enabled but disable some of the elliptic curves listed in the sub-menu.
319
) - :ref:`CONFIG_MBEDTLS_ECP_NIST_OPTIM` - :ref:`CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM` - Change :ref:`CONFIG_MBEDTLS_TLS_MODE` if both server & client functionalities are not needed - Consider disabling some cipher suites listed in the ``TLS Key Exchange Methods`` sub-menu (i.e., :ref:`CONFIG_MBEDTLS_KEY_EXCHANGE_RSA`) The help text for each option has some more information for reference. .. important:: It is **strongly not recommended to disable all these mbedTLS options**. Only disable options of which you understand the functionality and are certain that it is not needed in the application. In particular: - Ensure that any TLS server(s) the device connects to can still be used. If the server is controlled by a third party or a cloud service, it is recommended to ensure that the firmware supports at least two of the supported cipher suites in case one is disabled in a future update. - Ensure that any TLS client(s) that connect to the device can still connect with supported/recommended cipher suites.
319
Note that future versions of client operating systems may remove support for some features, so it is recommended to enable multiple supported cipher suites, or algorithms for redundancy. If depending on third party clients or servers, always pay attention to announcements about future changes to supported TLS features. If not, the {IDF_TARGET_NAME} device may become inaccessible if support changes. .. only:: CONFIG_ESP_ROM_HAS_MBEDTLS_CRYPTO_LIB Enabling the config option :ref:`CONFIG_MBEDTLS_USE_CRYPTO_ROM_IMPL` will use the crypto algorithms from mbedTLS library inside the chip ROM. Disabling the config option :ref:`CONFIG_MBEDTLS_USE_CRYPTO_ROM_IMPL` will use the crypto algorithms from the ESP-IDF mbedtls component library. This will increase the binary size (flash footprint). .. note:: Not every combination of mbedTLS compile-time config is tested in ESP-IDF. If you find a combination that fails to compile or function as expected, please report the details on `GitHub `_.
319
VFS @@@ :doc:`/api-reference/storage/vfs` feature in ESP-IDF allows multiple filesystem drivers and file-like peripheral drivers to be accessed using standard I/O functions (``open``, ``read``, ``write``, etc.) and C library functions (``fopen``, ``fread``, ``fwrite``, etc.). When filesystem or file-like peripheral driver functionality is not used in the application, this feature can be fully or partially disabled. VFS component provides the following configuration options: .. only:: CONFIG_ESP_ROM_HAS_HAL_SYSTIMER or CONFIG_ESP_ROM_HAS_HAL_WDT HAL @@@ .. list:: :CONFIG_ESP_ROM_HAS_HAL_SYSTIMER: * Enabling :ref:`CONFIG_HAL_SYSTIMER_USE_ROM_IMPL` can reduce the IRAM usage and binary size by linking in the systimer HAL driver of ROM implementation. :CONFIG_ESP_ROM_HAS_HAL_WDT: * Enabling :ref:`CONFIG_HAL_WDT_USE_ROM_IMPL` can reduce the IRAM usage and binary size by linking in the watchdog HAL driver of ROM implementation. Heap @@@@ .. list:: :CONFIG_ESP_ROM_HAS_HEAP_TLSF: * Enabling :ref:`CONFIG_HEAP_TLSF_USE_ROM_IMPL` can reduce the IRAM usage and binary size by linking in the TLSF library of ROM implementation.
319
Bootloader Size This document deals with the size of an ESP-IDF app binary only, and not the ESP-IDF :ref:`second-stage-bootloader`. For a discussion of ESP-IDF bootloader binary size, see :ref:`bootloader-size`. IRAM Binary Size If the IRAM section of a binary is too large, this issue can be resolved by reducing IRAM memory usage. See :ref:`optimize-iram-usage`.
319
Performance ESP-IDF ships with default settings that are designed for a trade-off between performance, resource usage, and available functionality. These guides describe how to optimize a firmware application for a particular aspect of performance. Usually this involves some trade-off in terms of limiting available functions, or swapping one aspect of performance (such as execution speed) for another (such as RAM usage). How to Optimize Performance Guides .. toctree:: :maxdepth: 2 speed size ram-usage
320
Speed Optimization {IDF_TARGET_CONTROLLER_CORE_CONFIG:default="CONFIG_BT_CTRL_PINNED_TO_CORE", esp32="CONFIG_BTDM_CTRL_PINNED_TO_CORE_CHOICE", esp32s3="CONFIG_BT_CTRL_PINNED_TO_CORE_CHOICE"} {IDF_TARGET_RF_TYPE:default="Wi-Fi/Bluetooth", esp32s2="Wi-Fi", esp32c6="Wi-Fi/Bluetooth/802.15.4", esp32h2="Bluetooth/802.15.4"} Overview Optimizing execution speed is a key element of software performance. Code that executes faster can also have other positive effects, e.g., reducing overall power consumption. However, improving execution speed may have trade-offs with other aspects of performance such as :doc:`size`. Choose What to Optimize If a function in the application firmware is executed once per week in the background, it may not matter if that function takes 10 ms or 100 ms to execute. If a function is executed constantly at 10 Hz, it matters greatly if it takes 10 ms or 100 ms to execute. Most kinds of application firmware only have a small set of functions that require optimal performance.
321
Perhaps those functions are executed very often, or have to meet some application requirements for latency or throughput. Optimization efforts should be targeted at these particular functions. Measuring Performance The first step to improving something is to measure it. Basic Performance Measurements You may be able to measure directly the performance relative to an external interaction with the world, e.g., see the examples :example:`wifi/iperf` and :example:`ethernet/iperf` for measuring general network performance. Or you can use an oscilloscope or logic analyzer to measure the timing of an interaction with a device peripheral. Otherwise, one way to measure performance is to augment the code to take timing measurements: .. code-block:: c #include "esp_timer.h" void measure_important_function(void) { const unsigned MEASUREMENTS = 5000; uint64_t start = esp_timer_get_time(); for (int retries = 0; retries ` is an excellent tool for visualizing task execution and looking for performance issues or improvements in the system as a whole.
321
Improving Overall Speed The following optimizations improve the execution of nearly all code, including boot times, throughput, latency, etc: .. list:: :esp32: - Set :ref:`CONFIG_ESPTOOLPY_FLASHFREQ` to 80 MHz. This is double the 40 MHz default value and doubles the speed at which code is loaded or executed from flash. You should verify that the board or module that connects the {IDF_TARGET_NAME} to the flash chip is rated for 80 MHz operation at the relevant temperature ranges before changing this setting. This information is contained in the hardware datasheet(s). - Set :ref:`CONFIG_ESPTOOLPY_FLASHMODE` to QIO or QOUT mode (Quad I/O). Both almost double the speed at which code is loaded or executed from flash compared to the default DIO mode. QIO is slightly faster than QOUT if both are supported. Note that both the flash chip model, and the electrical connections between the {IDF_TARGET_NAME} and the flash chip must support quad I/O modes or the SoC will not work correctly.
321
- Set :ref:`CONFIG_COMPILER_OPTIMIZATION` to ``Optimize for performance (-O2)`` . This may slightly increase binary size compared to the default setting, but almost certainly increases the performance of some code. Note that if your code contains C or C++ Undefined Behavior, then increasing the compiler optimization level may expose bugs that otherwise are not seen. :SOC_ASSIST_DEBUG_SUPPORTED: - Set :ref:`CONFIG_ESP_SYSTEM_HW_STACK_GUARD` to disabled. This may slightly increase the performance of some code, especially in cases where a lot of interrupts occur on the device. :esp32: - If the application uses PSRAM and is based on ESP32 rev. 3 (ECO3), setting :ref:`CONFIG_ESP32_REV_MIN` to ``3`` disables PSRAM bug workarounds, reducing the code size and improving overall performance. :SOC_CPU_HAS_FPU: - Avoid using floating point arithmetic ``float``. Even though {IDF_TARGET_NAME} has a single precision hardware floating point unit, floating point calculations are always slower than integer calculations.
321
If possible then use fixed point representations, a different method of integer representation, or convert part of the calculation to be integer only before switching to floating point. :not SOC_CPU_HAS_FPU: - Avoid using floating point arithmetic ``float``. On {IDF_TARGET_NAME} these calculations are emulated in software and are very slow. If possible, use fixed point representations, a different method of integer representation, or convert part of the calculation to be integer only before switching to floating point. - Avoid using double precision floating point arithmetic ``double``. These calculations are emulated in software and are very slow. If possible then use an integer-based representation, or single-precision floating point. Reduce Logging Overhead Although standard output is buffered, it is possible for an application to be limited by the rate at which it can print data to log output once buffers are full. This is particularly relevant for startup time if a lot of output is logged, but such problem can happen at other times as well.
321
There are multiple ways to solve this problem: .. list:: - Reduce the volume of log output by lowering the app :ref:`CONFIG_LOG_DEFAULT_LEVEL` (the equivalent bootloader setting is :ref:`CONFIG_BOOTLOADER_LOG_LEVEL`). This also reduces the binary size, and saves some CPU time spent on string formatting. :not SOC_USB_OTG_SUPPORTED: - Increase the speed of logging output by increasing the :ref:`CONFIG_ESP_CONSOLE_UART_BAUDRATE`. :SOC_USB_OTG_SUPPORTED: - Increase the speed of logging output by increasing the :ref:`CONFIG_ESP_CONSOLE_UART_BAUDRATE`. However, if you are using internal USB-CDC, the serial throughput is not dependent on the configured baud rate. Not Recommended The following options also increase execution speed, but are not recommended as they also reduce the debuggability of the firmware application and may increase the severity of any bugs. .. list:: - Set :ref:`CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL` to disabled. This also reduces firmware binary size by a small amount.
321
However, it may increase the severity of bugs in the firmware including security-related bugs. If it is necessary to do this to optimize a particular function, consider adding ``#define NDEBUG`` at the top of that single source file instead. .. _speed-targeted-optimizations: Targeted Optimizations The following changes increase the speed of a chosen part of the firmware application: .. list:: - Move frequently executed code to IRAM. By default, all code in the app is executed from flash cache. This means that it is possible for the CPU to have to wait on a "cache miss" while the next instructions are loaded from flash. Functions which are copied into IRAM are loaded once at boot time, and then always execute at full speed. IRAM is a limited resource, and using more IRAM may reduce available DRAM, so a strategic approach is needed when moving code to IRAM. See :ref:`iram` for more information. - Jump table optimizations can be re-enabled for individual source files that do not need to be placed in IRAM.
321
For hot paths in large ``switch cases``, this improves performance. For instructions on how to add the ``-fjump-tables`` and ``-ftree-switch-conversion`` options when compiling individual source files, see :ref:`component_build_control` Improving Startup Time In addition to the overall performance improvements shown above, the following options can be tweaked to specifically reduce startup time: .. list:: - Minimizing the :ref:`CONFIG_LOG_DEFAULT_LEVEL` and :ref:`CONFIG_BOOTLOADER_LOG_LEVEL` has a large impact on startup time. To enable more logging after the app starts up, set the :ref:`CONFIG_LOG_MAXIMUM_LEVEL` as well, and then call :cpp:func:`esp_log_level_set` to restore higher level logs. The :example:`system/startup_time` main function shows how to do this. :SOC_RTC_FAST_MEM_SUPPORTED: - If using Deep-sleep mode, setting :ref:`CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP` allows a faster wake from sleep. Note that if using Secure Boot, this represents a security compromise, as Secure Boot validation are not be performed on wake.
321
- Setting :ref:`CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON` skips verifying the binary on every boot from the power-on reset. How much time this saves depends on the binary size and the flash settings. Note that this setting carries some risk if the flash becomes corrupt unexpectedly. Read the help text of the :ref:`config item ` for an explanation and recommendations if using this option. - It is possible to save a small amount of time during boot by disabling RTC slow clock calibration. To do so, set :ref:`CONFIG_RTC_CLK_CAL_CYCLES` to 0. Any part of the firmware that uses RTC slow clock as a timing source will be less accurate as a result. The example project :example:`system/startup_time` is pre-configured to optimize startup time. The file :example_file:`system/startup_time/sdkconfig.defaults` contain all of these settings. You can append these to the end of your project's own ``sdkconfig`` file to merge the settings, but please read the documentation for each setting first.
321
Task Priorities As ESP-IDF FreeRTOS is a real-time operating system, it is necessary to ensure that high-throughput or low-slatency tasks are granted a high priority in order to run immediately. Priority is set when calling :cpp:func:`xTaskCreate` or :cpp:func:`xTaskCreatePinnedToCore` and can be changed at runtime by calling :cpp:func:`vTaskPrioritySet`. It is also necessary to ensure that tasks yield CPU (by calling :cpp:func:`vTaskDelay`, ``sleep()``, or by blocking on semaphores, queues, task notifications, etc) in order to not starve lower-priority tasks and cause problems for the overall system. The :ref:`task-watchdog-timer` provides a mechanism to automatically detect if task starvation happens. However, note that a TWDT timeout does not always indicate a problem, because sometimes the correct operation of the firmware requires some long-running computation. In these cases, tweaking the TWDT timeout or even disabling the TWDT may be necessary. .. _built-in-task-priorities: Built-in Task Priorities ESP-IDF starts a number of system tasks at fixed priority levels.
321
Some are automatically started during the boot process, while some are started only if the application firmware initializes a particular feature. To optimize performance, structure the task priorities of your application properly to ensure the tasks are not delayed by the system tasks, while also not starving system tasks and impacting other functions of the system. This may require splitting up a particular task. For example, perform a time-critical operation in a high-priority task or an interrupt handler and do the non-time-critical part in a lower-priority task. Header :idf_file:`components/esp_system/include/esp_task.h` contains macros for the priority levels used for built-in ESP-IDF tasks system. See :ref:`freertos_system_tasks` for more details about the system tasks. Common priorities are: .. Note: the following two lists should be kept the same, but the second list also shows CPU affinities .. only:: not SOC_HP_CPU_HAS_MULTIPLE_CORES .. list:: - :ref:`app-main-task` that executes app_main function has minimum priority (1).
321
- :doc:`/api-reference/system/esp_timer` system task to manage timer events and execute callbacks has high priority (22, ``ESP_TASK_TIMER_PRIO``) - FreeRTOS Timer Task to handle FreeRTOS timer callbacks is created when the scheduler initializes and has minimum task priority (1, :ref:`configurable `). - :doc:`/api-reference/system/esp_event` system task to manage the default system event loop and execute callbacks has high priority (20, ``ESP_TASK_EVENT_PRIO``). This configuration is only used if the application calls :cpp:func:`esp_event_loop_create_default`. It is possible to call :cpp:func:`esp_event_loop_create` with a custom task configuration instead. - :doc:`/api-guides/lwip` TCP/IP task has high priority (18, ``ESP_TASK_TCPIP_PRIO``). :SOC_WIFI_SUPPORTED: - :doc:`/api-guides/wifi` task has high priority (23). :SOC_WIFI_SUPPORTED: - Wi-Fi wpa_supplicant component may create dedicated tasks while the Wi-Fi Protected Setup (WPS), WPA2 EAP-TLS, Device Provisioning Protocol (DPP) or BSS Transition Management (BTM) features are in use.
321
These tasks all have low priority (2). :SOC_BT_SUPPORTED: - :doc:`/api-reference/bluetooth/controller_vhci` task has high priority (23, ``ESP_TASK_BT_CONTROLLER_PRIO``). The Bluetooth Controller needs to respond to requests with low latency, so it should always be among the highest priority task in the system. :SOC_BT_SUPPORTED: - :doc:`/api-reference/bluetooth/nimble/index` task has high priority (21). - The Ethernet driver creates a task for the MAC to receive Ethernet frames. If using the default config ``ETH_MAC_DEFAULT_CONFIG`` then the priority is medium-high (15). This setting can be changed by passing a custom :cpp:class:`eth_mac_config_t` struct when initializing the Ethernet MAC. - If using the :doc:`/api-reference/protocols/mqtt` component, it creates a task with default priority 5 (:ref:`configurable`), depending on :ref:`CONFIG_MQTT_USE_CUSTOM_CONFIG`, and also configurable at runtime by ``task_prio`` field in the :cpp:class:`esp_mqtt_client_config_t`) - To see what is the task priority for ``mDNS`` service, please check `Performance Optimization `__.
321
.. only:: SOC_HP_CPU_HAS_MULTIPLE_CORES .. list:: - :ref:`app-main-task` that executes app_main function has minimum priority (1). This task is pinned to Core 0 by default (:ref:`configurable`). - :doc:`/api-reference/system/esp_timer` system task to manage high precision timer events and execute callbacks has high priority (22, ``ESP_TASK_TIMER_PRIO``). This task is pinned to Core 0. - FreeRTOS Timer Task to handle FreeRTOS timer callbacks is created when the scheduler initializes and has minimum task priority (1, :ref:`configurable `). This task is pinned to Core 0. - :doc:`/api-reference/system/esp_event` system task to manage the default system event loop and execute callbacks has high priority (20, ``ESP_TASK_EVENT_PRIO``) and it is pinned to Core 0. This configuration is only used if the application calls :cpp:func:`esp_event_loop_create_default`, it is possible to call :cpp:func:`esp_event_loop_create` with a custom task configuration instead.
321
- :doc:`/api-guides/lwip` TCP/IP task has high priority (18, ``ESP_TASK_TCPIP_PRIO``) and is not pinned to any core (:ref:`configurable`). :SOC_WIFI_SUPPORTED: - :doc:`/api-guides/wifi` task has high priority (23) and is pinned to Core 0 by default (:ref:`configurable`). :SOC_WIFI_SUPPORTED: - Wi-Fi wpa_supplicant component may create dedicated tasks while the Wi-Fi Protected Setup (WPS), WPA2 EAP-TLS, Device Provisioning Protocol (DPP) or BSS Transition Management (BTM) features are in use. These tasks all have low priority (2) and are not pinned to any core. :SOC_BT_SUPPORTED: - :doc:`/api-reference/bluetooth/controller_vhci` task has high priority (23, ``ESP_TASK_BT_CONTROLLER_PRIO``) and is pinned to Core 0 by default (:ref:`configurable `). The Bluetooth Controller needs to respond to requests with low latency, so it should always be among the highest priority task assigned to a single CPU. :SOC_BT_SUPPORTED: - :doc:`/api-reference/bluetooth/nimble/index` task has high priority (21) and is pinned to Core 0 by default (:ref:`configurable `).
321
:esp32: - :doc:`/api-reference/bluetooth/index` creates multiple tasks when used: - Stack event callback task ("BTC") has high priority (19). - Stack BTU layer task has high priority (20). - Host HCI host task has high priority (22). All Bluedroid Tasks are pinned to the same core, which is Core 0 by default (:ref:`configurable `). - The Ethernet driver creates a task for the MAC to receive Ethernet frames. If using the default config ``ETH_MAC_DEFAULT_CONFIG`` then the priority is medium-high (15) and the task is not pinned to any core. These settings can be changed by passing a custom :cpp:class:`eth_mac_config_t` struct when initializing the Ethernet MAC. - If using the :doc:`/api-reference/protocols/mqtt` component, it creates a task with default priority 5 (:ref:`configurable `, depending on :ref:`CONFIG_MQTT_USE_CUSTOM_CONFIG`) and not pinned to any core (:ref:`configurable `). - To see what is the task priority for ``mDNS`` service, please check `Performance Optimization `__.
321
Choosing Task Priorities of the Application .. only:: not SOC_HP_CPU_HAS_MULTIPLE_CORES In general, it is not recommended to set task priorities higher than the built-in {IDF_TARGET_RF_TYPE} operations as starving them of CPU may make the system unstable. For very short timing-critical operations that do not use the network, use an ISR or a very restricted task (with very short bursts of runtime only) at the highest priority (24). Choosing priority 19 allows lower-layer {IDF_TARGET_RF_TYPE} functionality to run without delays, but still preempts the lwIP TCP/IP stack and other less time-critical internal functionality - this is the best option for time-critical tasks that do not perform network operations. Any task that does TCP/IP network operations should run at a lower priority than the lwIP TCP/IP task (18) to avoid priority-inversion issues. .. only:: SOC_HP_CPU_HAS_MULTIPLE_CORES With a few exceptions, most importantly the lwIP TCP/IP task, in the default configuration most built-in tasks are pinned to Core 0.
321
This makes it quite easy for the application to place high priority tasks on Core 1. Using priority 19 or higher guarantees that an application task can run on Core 1 without being preempted by any built-in task. To further isolate the tasks running on each CPU, configure the :ref:`lwIP task ` to only run on Core 0 instead of either core, which may reduce total TCP/IP throughput depending on what other tasks are running. In general, it is not recommended to set task priorities on Core 0 higher than the built-in {IDF_TARGET_RF_TYPE} operations as starving them of CPU may make the system unstable. Choosing priority 19 and Core 0 allows lower-layer {IDF_TARGET_RF_TYPE} functionality to run without delays, but still pre-empts the lwIP TCP/IP stack and other less time-critical internal functionality. This is an option for time-critical tasks that do not perform network operations. Any task that does TCP/IP network operations should run at lower priority than the lwIP TCP/IP task (18) to avoid priority-inversion issues.
321
.. note:: Setting a task to always run in preference to built-in ESP-IDF tasks does not require pinning the task to Core 1. Instead, the task can be left unpinned and assigned a priority of 17 or lower. This allows the task to optionally run on Core 0 if there are no higher-priority built-in tasks running on that core. Using unpinned tasks can improve the overall CPU utilization, however it makes reasoning about task scheduling more complex. .. note:: Task execution is always completely suspended when writing to the built-in SPI flash chip. Only :ref:`iram-safe-interrupt-handlers` continues executing. Improving Interrupt Performance ESP-IDF supports dynamic :doc:`/api-reference/system/intr_alloc` with interrupt preemption. Each interrupt in the system has a priority, and higher-priority interrupts preempts lower priority ones. Interrupt handlers execute in preference to any task, provided the task is not inside a critical section. For this reason, it is important to minimize the amount of time spent in executing an interrupt handler.
321
To obtain the best performance for a particular interrupt handler: .. list:: - Assign more important interrupts a higher priority using a flag such as ``ESP_INTR_FLAG_LEVEL2`` or ``ESP_INTR_FLAG_LEVEL3`` when calling :cpp:func:`esp_intr_alloc`. :SOC_HP_CPU_HAS_MULTIPLE_CORES: - Assign the interrupt on a CPU where built-in {IDF_TARGET_RF_TYPE} tasks are not configured to run, which means assigning the interrupt on Core 1 by default, see :ref:`built-in-task-priorities`. Interrupts are assigned on the same CPU where the :cpp:func:`esp_intr_alloc` function call is made. - If you are sure the entire interrupt handler can run from IRAM (see :ref:`iram-safe-interrupt-handlers`) then set the ``ESP_INTR_FLAG_IRAM`` flag when calling :cpp:func:`esp_intr_alloc` to assign the interrupt. This prevents it being temporarily disabled if the application firmware writes to the internal SPI flash. - Even if the interrupt handler is not IRAM-safe, if it is going to be executed frequently then consider moving the handler function to IRAM anyhow.
321
This minimizes the chance of a flash cache miss when the interrupt code is executed (see :ref:`speed-targeted-optimizations`). It is possible to do this without adding the ``ESP_INTR_FLAG_IRAM`` flag to mark the interrupt as IRAM-safe, if only part of the handler is guaranteed to be in IRAM. .. _improve-network-speed: Improving Network Speed .. list:: :SOC_WIFI_SUPPORTED: * For Wi-Fi, see :ref:`How-to-improve-Wi-Fi-performance` and :ref:`wifi-buffer-usage` :SOC_WIFI_SUPPORTED: * The :example:`wifi/iperf` example contains a configuration that is heavily optimized for Wi-Fi TCP/IP throughput, usually at the expense of higher RAM usage. Append the contents of the files :example_file:`wifi/iperf/sdkconfig.defaults`, :example_file:`wifi/iperf/sdkconfig.defaults.{IDF_TARGET_PATH_NAME}` and :example_file:`wifi/iperf/sdkconfig.ci.99` to the ``sdkconfig`` file in your project in order to add all of these options. Note that some of these options may have trade-offs in terms of reduced debuggability, increased firmware size, increased memory usage, or reduced performance of other features.
321
To get the best result, read the documentation pages linked above and use related information to determine exactly which options are best suited for your app. :SOC_EMAC_SUPPORTED: * The :example:`ethernet/iperf` example contains a configuration that is heavily optimized for Ethernet TCP/IP throughput, usually at the expense of higher RAM usage. Examine :example_file:`ethernet/iperf/sdkconfig.defaults` for more details. Note that some of these options may have trade-offs in terms of reduced debuggability, increased firmware size, increased memory usage, or reduced performance of other features. To get the best result, read the documentation pages linked above and use related information to determine exactly which options are best suited for your app. Improving I/O Performance Using standard C library functions like ``fread`` and ``fwrite`` instead of platform specific unbuffered syscalls such as ``read`` and ``write`` can be slow.These functions are designed to be portable, so they are not necessarily optimized for speed, have a certain overhead and are buffered.
321
:doc:`/api-reference/storage/fatfs` specific information and tips: .. list:: - Maximum size of the R/W request = FatFS cluster size (allocation unit size). - Use ``read`` and ``write`` instead of ``fread`` and ``fwrite``. - To increase speed of buffered reading functions like ``fread`` and ``fgets``, you can increase a size of the file buffer (Newlib's default is 128 bytes) to a higher number like 4096, 8192 or 16384. This can be done locally via the ``setvbuf`` function used on a certain file pointer or globally applied to all files via modifying :ref:`CONFIG_FATFS_VFS_FSTAT_BLKSIZE`. .. note:: Setting a bigger buffer size also increases the heap memory usage.
321
Minimizing RAM Usage {IDF_TARGET_STATIC_MEANS_HEAP:default="Wi-Fi library, Bluetooth controller", esp32s2="Wi-Fi library", esp32c6="Wi-Fi library, Bluetooth controller, IEEE 802.15.4 library", esp32h2="Bluetooth controller, IEEE 802.15.4 library"} In some cases, a firmware application's available RAM may run low or run out entirely. In these cases, it is necessary to tune the memory usage of the firmware application. In general, firmware should aim to leave some headroom of free internal RAM to deal with extraordinary situations or changes in RAM usage in future updates. Background Before optimizing ESP-IDF RAM usage, it is necessary to understand the basics of {IDF_TARGET_NAME} memory types, the difference between static and dynamic memory usage in C, and the way ESP-IDF uses stack and heap. This information can all be found in :doc:`/api-reference/system/mem_alloc`. Measuring Static Memory Usage The :ref:`idf.py` tool can be used to generate reports about the static memory usage of an application, see :ref:`idf.
322
py-size`. Measuring Dynamic Memory Usage ESP-IDF contains a range of heap APIs for measuring free heap at runtime, see :doc:`/api-reference/system/heap_debug`. .. note:: In embedded systems, heap fragmentation can be a significant issue alongside total RAM usage. The heap measurement APIs provide ways to measure the largest free block. Monitoring this value along with the total number of free bytes can give a quick indication of whether heap fragmentation is becoming an issue. Reducing Static Memory Usage - Reducing the static memory usage of the application increases the amount of RAM available for heap at runtime, and vice versa. - Generally speaking, minimizing static memory usage requires monitoring the ``.data`` and ``.bss`` sizes. For tools to do this, see :ref:`idf.py-size`. - Internal ESP-IDF functions do not make heavy use of static RAM in C. In many instances (such as {IDF_TARGET_STATIC_MEANS_HEAP}), static buffers are still allocated from the heap. However, the allocation is performed only once during feature initialization and will be freed if the feature is deinitialized.
322
This approach is adopted to optimize the availability of free memory at various stages of the application's life cycle. To minimize static memory use: .. list:: - Constant data can be stored in flash memory instead of RAM, thus it is recommended to declare structures, buffers, or other variables as ``const``. This approach may require modifying firmware functions to accept ``const *`` arguments instead of mutable pointer arguments. These changes can also help reduce the stack usage of certain functions. :SOC_BT_SUPPORTED: - If using Bluedroid, setting the option :ref:`CONFIG_BT_BLE_DYNAMIC_ENV_MEMORY` will cause Bluedroid to allocate memory on initialization and free it on deinitialization. This does not necessarily reduce the peak memory usage, but changes it from static memory usage to runtime memory usage. - If using OpenThread, enabling the option :ref:`CONFIG_OPENTHREAD_PLATFORM_MSGPOOL_MANAGEMENT` will cause OpenThread to allocate message pool buffers from PSRAM, which will reduce static memory use.
322
.. _optimize-stack-sizes: Reducing Stack Sizes In FreeRTOS, task stacks are usually allocated from the heap. The stack size for each task is fixed and passed as an argument to :cpp:func:`xTaskCreate`. Each task can use up to its allocated stack size, but using more than this will cause an otherwise valid program to crash, with a stack overflow or heap corruption. Therefore, determining the optimum sizes of each task stack, minimizing the required size of each task stack, and minimizing the number of task stacks as whole, can all substantially reduce RAM usage. To determine the optimum size for a particular task stack, users can consider the following methods: - At runtime, call the function :cpp:func:`uxTaskGetStackHighWaterMark` with the handle of any task where you think there is unused stack memory. This function returns the minimum lifetime free stack memory in bytes. - The easiest time to call :cpp:func:`uxTaskGetStackHighWaterMark` is from the task itself: call ``uxTaskGetStackHighWaterMark(NULL)`` to get the current task's high water mark after the time that the task has achieved its peak stack usage, i.
322
e., if there is a main loop, execute the main loop a number of times with all possible states, and then call :cpp:func:`uxTaskGetStackHighWaterMark`. - Often, it is possible to subtract almost the entire value returned here from the total stack size of a task, but allow some safety margin to account for unexpected small increases in stack usage at runtime. - Call :cpp:func:`uxTaskGetSystemState` at runtime to get a summary of all tasks in the system. This includes their individual stack high watermark values. - When debugger watchpoints are not being used, users can set the :ref:`CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK` option. This will cause one of the watchpoints to watch the last word of the task's stack. If that word is overwritten (such as in a stack overflow), a panic is triggered immediately. This is slightly more reliable than the default :ref:`CONFIG_FREERTOS_CHECK_STACKOVERFLOW` option of ``Check using canary bytes``, because the panic happens immediately, rather than on the next RTOS context switch.
322
Neither option is perfect. In some cases, it is possible that the stack pointer skips the watchpoint or canary bytes and corrupts another region of RAM instead. To reduce the required size of a particular task stack, users can consider the following methods: - Avoid stack heavy functions. String formatting functions (like ``printf()``) are particularly heavy users of the stack, so any task which does not ever call these can usually have its stack size reduced. - Enabling :ref:`newlib-nano-formatting` reduces the stack usage of any task that calls ``printf()`` or other C string formatting functions. - Avoid allocating large variables on the stack. In C, any large structures or arrays allocated as an automatic variable (i.e., default scope of a C declaration) uses space on the stack. To minimize the sizes of these, allocate them statically and/or see if you can save memory by dynamically allocating them from the heap only when they are needed. - Avoid deep recursive function calls.
322
Individual recursive function calls do not always add a lot of stack usage each time they are called, but if each function includes large stack-based variables then the overhead can get quite high. To reduce the total number of tasks, users can consider the following method: - Combine tasks. If a particular task is never created, the task's stack is never allocated, thus reducing RAM usage significantly. Unnecessary tasks can typically be removed if those tasks can be combined with another task. In an application, tasks can typically be combined or removed if: - The work done by the tasks can be structured into multiple functions that are called sequentially. - The work done by the tasks can be structured into smaller jobs that are serialized (via a FreeRTOS queue or similar) for execution by a worker task. Internal Task Stack Sizes ESP-IDF allocates a number of internal tasks for housekeeping purposes or operating system functions. Some are created during the startup process, and some are created at runtime when particular features are initialized.
322
The default stack sizes for these tasks are usually set conservatively high to allow all common usage patterns. Many of the stack sizes are configurable, and it may be possible to reduce them to match the real runtime stack usage of the task. .. important:: If internal task stack sizes are set too small, ESP-IDF will crash unpredictably. Even if the root cause is task stack overflow, this is not always clear when debugging. It is recommended that internal stack sizes are only reduced carefully (if at all), with close attention to high water mark free space under load. If reporting an issue that occurs when internal task stack sizes have been reduced, please always include the following information and the specific configuration that is being used. .. list:: - :ref:`app-main-task` has stack size :ref:`CONFIG_ESP_MAIN_TASK_STACK_SIZE`. - :doc:`/api-reference/system/esp_timer` system task which executes callbacks has stack size :ref:`CONFIG_ESP_TIMER_TASK_STACK_SIZE`. - FreeRTOS Timer Task to handle FreeRTOS timer callbacks has stack size :ref:`CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH`.
322
- :doc:`/api-reference/system/esp_event` system task to execute callbacks for the default system event loop has stack size :ref:`CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE`. - :doc:`/api-guides/lwip` TCP/IP task has stack size :ref:`CONFIG_LWIP_TCPIP_TASK_STACK_SIZE`. :SOC_BT_SUPPORTED: - :doc:`/api-reference/bluetooth/index` have task stack sizes :ref:`CONFIG_BT_BTC_TASK_STACK_SIZE`, :ref:`CONFIG_BT_BTU_TASK_STACK_SIZE`. :SOC_BT_SUPPORTED: - :doc:`/api-reference/bluetooth/nimble/index` has task stack size :ref:`CONFIG_BT_NIMBLE_HOST_TASK_STACK_SIZE`. - The Ethernet driver creates a task for the MAC to receive Ethernet frames. If using the default config ``ETH_MAC_DEFAULT_CONFIG`` then the task stack size is 4 KB. This setting can be changed by passing a custom :cpp:class:`eth_mac_config_t` struct when initializing the Ethernet MAC. - FreeRTOS idle task stack size is configured by :ref:`CONFIG_FREERTOS_IDLE_TASK_STACKSIZE`. - If using the :doc:`/api-reference/protocols/mqtt` component, it creates a task with stack size configured by :ref:`CONFIG_MQTT_TASK_STACK_SIZE`.
322
MQTT stack size can also be configured using ``task_stack`` field of :cpp:class:`esp_mqtt_client_config_t`. - To see how to optimize RAM usage when using ``mDNS``, please check `Minimizing RAM Usage `__. .. note:: Aside from built-in system features such as ESP-timer, if an ESP-IDF feature is not initialized by the firmware, then no associated task is created. In those cases, the stack usage is zero, and the stack-size configuration for the task is not relevant. Reducing Heap Usage For functions that assist in analyzing heap usage at runtime, see :doc:`/api-reference/system/heap_debug`. Normally, optimizing heap usage consists of analyzing the usage and removing calls to ``malloc()`` that are not being used, reducing the corresponding sizes, or freeing previously allocated buffers earlier. There are some ESP-IDF configuration options that can reduce heap usage at runtime: .. list:: - lwIP documentation has a section to configure :ref:`lwip-ram-usage`. :SOC_WIFI_SUPPORTED: - :ref:`wifi-buffer-usage` describes options to either reduce the number of static buffers or reduce the maximum number of dynamic buffers in use, so as to minimize memory usage at a possible cost of performance.
322
Note that static Wi-Fi buffers are still allocated from the heap when Wi-Fi is initialized, and will be freed if Wi-Fi is deinitialized. :esp32: - The Ethernet driver allocates DMA buffers for the internal Ethernet MAC when it is initialized - configuration options are :ref:`CONFIG_ETH_DMA_BUFFER_SIZE`, :ref:`CONFIG_ETH_DMA_RX_BUFFER_NUM`, :ref:`CONFIG_ETH_DMA_TX_BUFFER_NUM`. - Several Mbed TLS configuration options can be used to reduce heap memory usage. See the :ref:`reducing_ram_usage_mbedtls` docs for details. :esp32: - In single-core mode only, it is possible to use IRAM as byte-accessible memory added to the regular heap by enabling :ref:`CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY`. Note that this option carries a performance penalty, and the risk of security issues caused by executable data. If this option is enabled, then it is possible to set other options to prefer certain buffers allocated from this memory: :ref:`CONFIG_MBEDTLS_MEM_ALLOC_MODE`, :ref:`NimBLE `. :esp32: - Reduce :ref:`CONFIG_BTDM_CTRL_BLE_MAX_CONN` if using Bluetooth LE.
322
:esp32: - Reduce :ref:`CONFIG_BTDM_CTRL_BR_EDR_MAX_ACL_CONN` if using Bluetooth Classic. .. note:: There are other configuration options that increases heap usage at runtime if changed from the defaults. These options are not listed above, but the help text for the configuration item will mention if there is some memory impact. .. _optimize-iram-usage: Optimizing IRAM Usage .. only:: not esp32 The available DRAM at runtime for heap usage is also reduced by the static IRAM usage. Therefore, one way to increase available DRAM is to reduce IRAM usage. If the app allocates more static IRAM than available, then the app will fail to build, and linker errors such as ``section '.iram0.text' will not fit in region 'iram0_0_seg'``, ``IRAM0 segment data does not fit``, and ``region 'iram0_0_seg' overflowed by 84-bytes`` will be seen. If this happens, it is necessary to find ways to reduce static IRAM usage in order to link the application. To analyze the IRAM usage in the firmware binary, use :ref:`idf.
322
py-size`. If the firmware failed to link, steps to analyze are shown at :ref:`idf-size-linker-failed`. The following options will reduce IRAM usage of some ESP-IDF features: .. list:: - Enable :ref:`CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH`. Provided these functions are not incorrectly used from ISRs, this option is safe to enable in all configurations. - Enable :ref:`CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH`. Provided these functions are not incorrectly used from ISRs, this option is safe to enable in all configurations. - Enable :ref:`CONFIG_RINGBUF_PLACE_ISR_FUNCTIONS_INTO_FLASH`. This option is not safe to use if the ISR ringbuf functions are used from an IRAM interrupt context, e.g., if :ref:`CONFIG_UART_ISR_IN_IRAM` is enabled. For the ESP-IDF drivers where this is the case, you can get an error at run-time when installing the driver in question. :SOC_WIFI_SUPPORTED: - Disabling Wi-Fi options :ref:`CONFIG_ESP_WIFI_IRAM_OPT` and/or :ref:`CONFIG_ESP_WIFI_RX_IRAM_OPT` options frees available IRAM at the cost of Wi-Fi performance.
322
:CONFIG_ESP_ROM_HAS_SPI_FLASH: - Enabling :ref:`CONFIG_SPI_FLASH_ROM_IMPL` frees some IRAM but means that esp_flash bugfixes and new flash chip support are not available, see :doc:`/api-reference/peripherals/spi_flash/spi_flash_idf_vs_rom` for details. :esp32: - Disabling :ref:`CONFIG_SPI_FLASH_ROM_DRIVER_PATCH` frees some IRAM but is only available in some flash configurations, see the configuration item help text. :esp32: - If the application uses PSRAM and is based on ESP32 rev. 3 (ECO3), setting :ref:`CONFIG_ESP32_REV_MIN` to ``3`` disables PSRAM bug workarounds, saving 10 KB or more of IRAM. - Disabling :ref:`CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR` prevents posting ``esp_event`` events from :ref:`iram-safe-interrupt-handlers` but saves some IRAM. - Disabling :ref:`CONFIG_SPI_MASTER_ISR_IN_IRAM` prevents spi_master interrupts from being serviced while writing to flash, and may otherwise reduce spi_master performance, but saves some IRAM. - Disabling :ref:`CONFIG_SPI_SLAVE_ISR_IN_IRAM` prevents spi_slave interrupts from being serviced while writing to flash, which saves some IRAM.
322
- Setting :ref:`CONFIG_HAL_DEFAULT_ASSERTION_LEVEL` to disable assertion for HAL component saves some IRAM, especially for HAL code who calls ``HAL_ASSERT`` a lot and resides in IRAM. - Refer to the sdkconfig menu ``Auto-detect Flash chips``, and you can disable flash drivers which you do not need to save some IRAM. - Enable :ref:`CONFIG_HEAP_PLACE_FUNCTION_INTO_FLASH`. Provided that :ref:`CONFIG_SPI_MASTER_ISR_IN_IRAM` is not enabled and the heap functions are not incorrectly used from ISRs, this option is safe to enable in all configurations. :esp32c2: - Enable :ref:`CONFIG_BT_RELEASE_IRAM`. Release BT text section and merge BT data, bss & text into a large free heap region when ``esp_bt_mem_release`` is called. This makes Bluetooth unavailable until the next restart, but saving ~22 KB or more of IRAM. .. only:: esp32 Using SRAM1 for IRAM The SRAM1 memory area is normally used for DRAM, but it is possible to use parts of it for IRAM with :ref:`CONFIG_ESP_SYSTEM_ESP32_SRAM1_REGION_AS_IRAM`.
322
This memory would previously be reserved for DRAM data usage (e.g., ``.bss``) by the software bootloader and later added to the heap. After this option was introduced, the bootloader DRAM size was reduced to a value closer to what it normally actually needs. To use this option, ESP-IDF should be able to recognize that the new SRAM1 area is also a valid load address for an image segment. If the software bootloader was compiled before this option existed, then the bootloader will not be able to load the app that has code placed in this new extended IRAM area. This would typically happen if you are doing an OTA update, where only the app would be updated. If the IRAM section were to be placed in an invalid area, then this would be detected during the bootup process, and result in a failed boot: .. code-block:: text E (204) esp_image: Segment 5 0x400845f8-0x400a126c invalid: bad load address range .. warning:: Apps compiled with :ref:`CONFIG_ESP_SYSTEM_ESP32_SRAM1_REGION_AS_IRAM` may fail to boot, if used together with a software bootloader that was compiled before this config option was introduced.
322
If you are using an older bootloader and updating over OTA, please test carefully before pushing any updates. Any memory that ends up unused for static IRAM will be added to the heap. .. only:: esp32c3 Flash Suspend Feature When using SPI flash driver API and other APIs based on the former (NVS, Partition APIs, etc.), the Cache will be disabled. During this period, any code executed must reside in internal RAM, see :ref:`concurrency-constraints-flash`. Hence, interrupt handlers that are not in internal RAM will not be executed. To achieve this, ESP-IDF drivers usually have the following two options: - Place the driver's internal ISR handler in the internal RAM. - Place some control functions in the internal RAM. User ISR callbacks and involved variables have to be in internal RAM if they are also used in interrupt contexts. Placing additional code into IRAM will exacerbate IRAM usage. For this reason, there is :ref:`CONFIG_SPI_FLASH_AUTO_SUSPEND`, which can alleviate the aforementioned kinds of IRAM usage.
322
By enabling this feature, the Cache will not be disabled when SPI flash driver APIs and SPI flash driver-based APIs are used. Therefore, code and data in flash can be executed or accessed normally, but with some minor delay. See :ref:`auto-suspend` for more details about this feature. Regarding the flash suspend feature usage, and corresponding response time delay, please also see this example :example:`system/flash_suspend`. .. only:: esp32 Putting C Library in Flash When compiling for ESP32 revisions older than ECO3 (:ref:`CONFIG_ESP32_REV_MIN`), the PSRAM Cache bug workaround (:ref:`CONFIG_SPIRAM_CACHE_WORKAROUND`) option is enabled, and the C library functions normally located in ROM are recompiled with the workaround and placed into IRAM instead. For most applications, it is safe to move many of the C library functions into flash, reclaiming some IRAM. Corresponding options include: .. list:: - :ref:`CONFIG_SPIRAM_CACHE_LIBJMP_IN_IRAM`: affects the functions ``longjmp`` and ``setjump``.
322
- :ref:`CONFIG_SPIRAM_CACHE_LIBMATH_IN_IRAM`: affects the functions ``abs``, ``div``, ``labs``, ``ldiv``, ``quorem``, ``fpclassify`` and ``nan``. - :ref:`CONFIG_SPIRAM_CACHE_LIBNUMPARSER_IN_IRAM`: affects the functions ``utoa``, ``itoa``, ``atoi``, ``atol``, ``strtol``, and ``strtoul``. - :ref:`CONFIG_SPIRAM_CACHE_LIBIO_IN_IRAM`: affects the functions ``wcrtomb``, ``fvwrite``, ``wbuf``, ``wsetup``, ``fputwc``, ``wctomb_r``, ``ungetc``, ``makebuf``, ``fflush``, ``refill``, and ``sccl``. - :ref:`CONFIG_SPIRAM_CACHE_LIBTIME_IN_IRAM`: affects the functions ``asctime``, ``asctime_r``, ``ctime``, ``ctime_r``, ``lcltime``, ``lcltime_r``, ``gmtime``, ``gmtime_r``, ``strftime``, ``mktime``, ``tzset_r``, ``tzset``, ``time``, ``gettzinfo``, ``systimes``, ``month_lengths``, ``timelocal``, ``tzvars``, ``tzlock``, ``tzcalc_limits``, and ``strptime``. - :ref:`CONFIG_SPIRAM_CACHE_LIBCHAR_IN_IRAM`: affects the functions ``ctype_``, ``toupper``, ``tolower``, ``toascii``, ``strupr``, ``bzero``, ``isalnum``, ``isalpha``, ``isascii``, ``isblank``, ``iscntrl``, ``isdigit``, ``isgraph``, ``islower``, ``isprint``, ``ispunct``, ``isspace``, and ``isupper``.
322
- :ref:`CONFIG_SPIRAM_CACHE_LIBMEM_IN_IRAM`: affects the functions ``memccpy``, ``memchr``, ``memmove``, and ``memrchr``. - :ref:`CONFIG_SPIRAM_CACHE_LIBSTR_IN_IRAM`: affects the functions ``strcasecmp``, ``strcasestr``, ``strchr``, ``strcoll``, ``strcpy``, ``strcspn``, ``strdup``, ``strdup_r``, ``strlcat``, ``strlcpy``, ``strlen``, ``strlwr``, ``strncasecmp``, ``strncat``, ``strncmp``, ``strncpy``, ``strndup``, ``strndup_r``, ``strrchr``, ``strsep``, ``strspn``, ``strstr``, ``strtok_r, and ``strupr``. - :ref:`CONFIG_SPIRAM_CACHE_LIBRAND_IN_IRAM`: affects the functions ``srand``, ``rand``, and ``rand_r``. - :ref:`CONFIG_SPIRAM_CACHE_LIBENV_IN_IRAM`: affects the functions ``environ``, ``envlock``, and ``getenv_r``. - :ref:`CONFIG_SPIRAM_CACHE_LIBFILE_IN_IRAM`: affects the functions ``lock``, ``isatty``, ``fclose``, ``open``, ``close``, ``creat``, ``read``, ``rshift``, ``sbrk``, ``stdio``, ``syssbrk``, ``sysclose``, ``sysopen``, ``creat``, ``sysread``, ``syswrite``, ``impure``, ``fwalk``, and ``findfp``.
322
- :ref:`CONFIG_SPIRAM_CACHE_LIBMISC_IN_IRAM`: affects the functions ``raise`` and ``system``. The exact amount of IRAM saved will depend on how much C library code is actually used by the application. In addition, the following options may be used to move more of the C library code into flash, however note that this may result in reduced performance. Be careful not to use the C library function allocated with :c:macro:`ESP_INTR_FLAG_IRAM` flag from interrupts when cache is disabled, refer to :ref:`iram-safe-interrupt-handlers` for more details. For these reasons, the functions ``itoa``, ``memcmp``, ``memcpy``, ``memset``, ``strcat``, ``strcmp``, and ``strlen`` are always put in IRAM. .. note:: Moving frequently-called functions from IRAM to flash may increase their execution time. .. note:: Other configuration options exist that will increase IRAM usage by moving some functionality into IRAM, usually for performance, but the default option is not to do this. These are not listed here.
322
The IRAM size impact of enabling these options is usually noted in the configuration item help text.
322
Libraries and Frameworks .. toctree:: :maxdepth: 1 cloud-frameworks libs-frameworks
323
Espressif's Frameworks Here you will find a collection of the official Espressif libraries and frameworks. Espressif Audio Development Framework The ESP-ADF is a comprehensive framework for audio applications including: This framework is available on GitHub: `ESP-ADF `_. ESP-CSI ESP-CSI is an experimental implementation that uses the Wi-Fi Channel State Information to detect the presence of a human body. See the `ESP-CSI `_ project for more information. Espressif DSP Library The library provides algorithms optimized specifically for digital signal processing applications. This library supports: This library is available on Github: `ESP-DSP library `_. ESP-WIFI-MESH Development Framework This framework is based on the ESP-WIFI-MESH protocol with the following features: This framework is available on Github: `ESP-MDF `_. ESP-WHO The ESP-WHO is a face detection and recognition framework using the ESP32 and camera. This framework is available on Github: `ESP-WHO `_. ESP RainMaker `ESP RainMaker `_ is a complete solution for accelerated AIoT development.
324
Using ESP RainMaker, you can create AIoT devices from the firmware to the integration with voice-assistant, phone apps and cloud backend. This project is available on Github: `ESP RainMaker on GitHub `_. ESP-IoT-Solution `ESP-IoT-Solution `_ contains commonly used device drivers and code frameworks when developing IoT systems. The device drivers and code frameworks within the ESP-IoT-Solution are organized as separate components, allowing them to be easily integrated into an ESP-IDF project. ESP-IoT-Solution includes: This solution is available on Github: `ESP-IoT-Solution on GitHub `_. ESP-Protocols The `ESP-Protocols `_ repository contains a collection of protocol components for ESP-IDF. The code within ESP-Protocols is organized into separate components, allowing them to be easily integrated into an ESP-IDF project. Additionally, each component is available in `IDF Component Registry `_. ESP-Protocols components: ESP-BSP The `ESP-BSP `_ repository contains Board Support Packages (BSPs) for various Espressif's and third-party development boards.
324
BSPs help to quickly get started with a supported board. Usually they contain pinout definition and helper functions that will initialize peripherals for the specific board. Additionally, the BSPs contain drivers for external chips populated on the development board, such as sensors, displays, audio codecs, etc. ESP-IDF-CXX `ESP-IDF-CXX `_ contains C++ wrappers for part of ESP-IDF. The focuses are on ease of use, safety, automatic resource management. They also move error checking from runtime to compile time to prevent running failure. There are C++ classes for ESP-Timer, I2C, SPI, GPIO and other peripherals or features of ESP-IDF. ESP-IDF-CXX is `available as a component `_ from the component registry. Please check the project's `README.md `_ for more information.
324
Cloud Frameworks {IDF_TARGET_NAME} supports multiple cloud frameworks using agents built on top of ESP-IDF. Here are the pointers to various supported cloud frameworks' agents and examples: ESP RainMaker `ESP RainMaker `_ is a complete solution for accelerated AIoT development. `ESP RainMaker on GitHub `_. AWS IoT `https://github.com/espressif/esp-aws-iot `_ is an open source repository for {IDF_TARGET_NAME} based on Amazon Web Services' `aws-iot-device-sdk-embedded-C `_. Azure IoT `https://github.com/espressif/esp-azure `_ is an open source repository for {IDF_TARGET_NAME} based on Microsoft Azure's `azure-iot-sdk-c SDK `_. Google IoT Core `https://github.com/espressif/esp-google-iot `_ is an open source repository for {IDF_TARGET_NAME} based on Google's `iot-device-sdk-embedded-c SDK `_. Aliyun IoT `https://github.com/espressif/esp-aliyun `_ is an open source repository for {IDF_TARGET_NAME} based on Aliyun's `iotkit-embedded SDK `_. Joylink IoT `https://github.com/espressif/esp-joylink `_ is an open source repository for {IDF_TARGET_NAME} based on Joylink's `joylink_dev_sdk SDK `_.
325
Tencent IoT `https://github.com/espressif/esp-welink `_ is an open source repository for {IDF_TARGET_NAME} based on Tencent's `welink SDK `_. Tencentyun IoT `https://github.com/espressif/esp-qcloud `_ is an open source repository for {IDF_TARGET_NAME} based on Tencentyun's `qcloud-iot-sdk-embedded-c SDK `_. Baidu IoT `https://github.com/espressif/esp-baidu-iot `_ is an open source repository for {IDF_TARGET_NAME} based on Baidu's `iot-sdk-c SDK `_.
325
Get Started .. Please keep README.md in sync with these instructions. This document is intended to help you set up the software development environment for the hardware based on the {IDF_TARGET_NAME} chip by Espressif. After that, a simple example will show you how to use ESP-IDF (Espressif IoT Development Framework) for menu configuration, then for building and flashing firmware onto an {IDF_TARGET_NAME} board. .. include-build-file:: inc/version-note.inc Introduction {IDF_TARGET_NAME} is a system on a chip that integrates the following features: .. only:: esp32 .. only:: esp32s2 .. only:: esp32s3 .. only:: esp32c3 .. only:: esp32c2 .. only:: esp32c6 .. only:: esp32h2 Powered by 40 nm technology, {IDF_TARGET_NAME} provides a robust, highly integrated platform, which helps meet the continuous demands for efficient power usage, compact design, security, high performance, and reliability. Espressif provides basic hardware and software resources to help application developers realize their ideas using the {IDF_TARGET_NAME} series hardware.
326
The software development framework by Espressif is intended for development of Internet-of-Things (IoT) applications with Wi-Fi, Bluetooth, power management and several other system features. What You Need Hardware ~~~~~~~~ .. note:: Currently, some of the development boards are using USB Type C connectors. Be sure you have the correct cable to connect your board! If you have one of {IDF_TARGET_NAME} official development boards listed below, you can click on the link to learn more about the hardware. .. only:: esp32 .. toctree:: :maxdepth: 1 ESP32-DevKitC ESP-WROVER-KIT ESP32-PICO-KIT ESP32-Ethernet-Kit ESP32-DevKit-S(-R) ESP32-PICO-KIT-1 ESP32-PICO-DevKitM-2 ESP32-DevKitM-1 .. only:: esp32s2 .. toctree:: :maxdepth: 1 ESP32-S2-Saola-1 ESP32-S2-DevKitM-1 ESP32-S2-DevKitC-1 ESP32-S2-Kaluga-Kit .. only:: esp32c3 .. toctree:: :maxdepth: 1 ESP32-C3-DevKitM-1 ESP32-C3-DevKitC-02 .
326
. only:: esp32s3 .. toctree:: :maxdepth: 1 ESP32-S3-DevKitC-1 ESP32-S3-DevKitM-1 .. only:: esp32c2 .. toctree:: :maxdepth: 1 ESP8684-DevKitM-1 .. only:: esp32c6 .. toctree:: :maxdepth: 1 ESP32-C6-DevKitC-1 ESP32-C6-DevKitM-1 .. _get-started-get-prerequisites: Software ~~~~~~~~ To start using ESP-IDF on **{IDF_TARGET_NAME}**, install the following software: .. figure:: ../../_static/what-you-need.png :align: center :alt: Development of applications for {IDF_TARGET_NAME} :figclass: align-center .. _get-started-step-by-step: .. _get-started-how-to-get-esp-idf: Installation To install all the required software, we offer some different ways to facilitate this task. Choose from one of the available options. IDE ~~~ .. note:: We highly recommend installing the ESP-IDF through your favorite IDE. Manual Installation ~~~~~~~~~~~~~~~~~~~ For the manual procedure, please select according to your operating system.
326
.. toctree:: :maxdepth: 1 Windows Installer Linux and macOS Build Your First Project If you already have the ESP-IDF installed and are not using an IDE, you can build your first project from the command line following the :ref:`Start a Project on Windows ` or :ref:`Start a Project on Linux and macOS `. .. _Stable version: https://docs.espressif.com/projects/esp-idf/en/stable/ Uninstall ESP-IDF If you want to remove ESP-IDF, please follow :ref:`idf-tools-uninstall`.
326