Xesp Idf en v5.0 Dev 4037 G9b8c558e63 Esp32
Xesp Idf en v5.0 Dev 4037 G9b8c558e63 Esp32
Release v5.0-dev-4037-g9b8c558e63
Espressif Systems
Jul 08, 2022
Table of contents
Table of contents i
1 Get Started 3
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 What You Need . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.1 Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.2 Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
1.3 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
1.3.1 IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
1.3.2 Manual Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
1.4 Build Your First Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
i
2.5.5 IP Network Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 949
2.5.6 Application Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952
2.6 Peripherals API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952
2.6.1 Analog to Digital Converter (ADC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952
2.6.2 Clock Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 976
2.6.3 Digital To Analog Converter (DAC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 982
2.6.4 GPIO & RTC GPIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 986
2.6.5 General Purpose Timer (GPTimer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1005
2.6.6 Inter-Integrated Circuit (I2C) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1017
2.6.7 Inter-IC Sound (I2S) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1034
2.6.8 LCD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1067
2.6.9 LED Control (LEDC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1078
2.6.10 Motor Control Pulse Width Modulator (MCPWM) . . . . . . . . . . . . . . . . . . . . . 1096
2.6.11 Pulse Counter (PCNT) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1124
2.6.12 Remote Control Transceiver (RMT) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1138
2.6.13 SD Pull-up Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1162
2.6.14 SDMMC Host Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1166
2.6.15 SD SPI Host Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1171
2.6.16 SDIO Card Slave Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1176
2.6.17 Sigma-delta Modulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1186
2.6.18 SPI Master Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1189
2.6.19 SPI Slave Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1214
2.6.20 ESP32-WROOM-32SE (Secure Element) . . . . . . . . . . . . . . . . . . . . . . . . . 1221
2.6.21 Touch Sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1222
2.6.22 Two-Wire Automotive Interface (TWAI) . . . . . . . . . . . . . . . . . . . . . . . . . . 1239
2.6.23 Universal Asynchronous Receiver/Transmitter (UART) . . . . . . . . . . . . . . . . . . 1257
2.7 Project Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1282
2.7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1282
2.7.2 Project Configuration Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1282
2.7.3 Using sdkconfig.defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1282
2.7.4 Kconfig Formatting Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1282
2.7.5 Backward Compatibility of Kconfig Options . . . . . . . . . . . . . . . . . . . . . . . . 1283
2.7.6 Configuration Options Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1283
2.8 Provisioning API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1544
2.8.1 Protocol Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1544
2.8.2 Unified Provisioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1559
2.8.3 Wi-Fi Provisioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1563
2.9 Storage API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1583
2.9.1 FAT Filesystem Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1583
2.9.2 Manufacturing Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1590
2.9.3 Non-volatile storage library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1594
2.9.4 NVS Partition Generator Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1616
2.9.5 SD/SDIO/MMC Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1623
2.9.6 SPI Flash API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1636
2.9.7 SPIFFS Filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1672
2.9.8 Virtual filesystem component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1676
2.9.9 Wear Levelling API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1691
2.10 System API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1696
2.10.1 App Image Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1696
2.10.2 Application Level Tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1702
2.10.3 Call function with external stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1707
2.10.4 Console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1708
2.10.5 eFuse Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1717
2.10.6 Error Codes and Helper Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1737
2.10.7 ESP HTTPS OTA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1740
2.10.8 Event Loop Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1745
2.10.9 FreeRTOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1758
2.10.10 FreeRTOS Supplemental Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1868
ii
2.10.11 Heap Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1887
2.10.12 Heap Memory Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1900
2.10.13 High Resolution Timer (ESP Timer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1911
2.10.14 Internal and Unstable APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1917
2.10.15 Inter-Processor Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1919
2.10.16 Interrupt allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1923
2.10.17 Logging library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1930
2.10.18 Miscellaneous System APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1937
2.10.19 Over The Air Updates (OTA) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1950
2.10.20 Performance Monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1961
2.10.21 Power Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1965
2.10.22 POSIX Threads Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1971
2.10.23 Random Number Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1975
2.10.24 Sleep Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1977
2.10.25 SoC Capabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1989
2.10.26 System Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1998
2.10.27 The himem allocation API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2002
2.10.28 ULP Coprocessor programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2005
2.10.29 Watchdogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2037
iii
4.5.7 Preprocessor Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2079
4.5.8 Component Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2079
4.5.9 Overriding Parts of the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2083
4.5.10 Configuration-Only Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2084
4.5.11 Debugging CMake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2084
4.5.12 Example Component CMakeLists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2084
4.5.13 Custom sdkconfig defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2088
4.5.14 Flash arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2089
4.5.15 Building the Bootloader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2089
4.5.16 Writing Pure CMake Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2090
4.5.17 Using Third-Party CMake Projects with Components . . . . . . . . . . . . . . . . . . . 2090
4.5.18 Using Prebuilt Libraries with Components . . . . . . . . . . . . . . . . . . . . . . . . . 2091
4.5.19 Using ESP-IDF in Custom CMake Projects . . . . . . . . . . . . . . . . . . . . . . . . . 2091
4.5.20 ESP-IDF CMake Build System API . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2092
4.5.21 File Globbing & Incremental Builds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2096
4.5.22 Build System Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2097
4.5.23 Build System Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2097
4.5.24 Migrating from ESP-IDF GNU Make System . . . . . . . . . . . . . . . . . . . . . . . 2099
4.6 Core Dump . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2100
4.6.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2100
4.6.2 Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2100
4.6.3 Save core dump to flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2101
4.6.4 Print core dump to UART . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2102
4.6.5 ROM Functions in Backtraces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2102
4.6.6 Dumping variables on demand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2102
4.6.7 Running espcoredump.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2103
4.7 Deep Sleep Wake Stubs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2105
4.7.1 Rules for Wake Stubs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2105
4.7.2 Implementing A Stub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2106
4.7.3 Loading Code Into RTC Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2106
4.7.4 Loading Data Into RTC Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2106
4.7.5 CRC Check For Wake Stubs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2107
4.8 Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2107
4.8.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2107
4.8.2 Error codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2107
4.8.3 Converting error codes to error messages . . . . . . . . . . . . . . . . . . . . . . . . . . 2108
4.8.4 ESP_ERROR_CHECK macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2108
4.8.5 ESP_ERROR_CHECK_WITHOUT_ABORT macro . . . . . . . . . . . . . . . . . . . . . 2108
4.8.6 ESP_RETURN_ON_ERROR macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2109
4.8.7 ESP_GOTO_ON_ERROR macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2109
4.8.8 ESP_RETURN_ON_FALSE macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2109
4.8.9 ESP_GOTO_ON_FALSE macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2109
4.8.10 CHECK MACROS Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2109
4.8.11 Error handling patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2110
4.8.12 C++ Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2110
4.9 ESP-BLE-MESH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2111
4.9.1 Getting Started with ESP-BLE-MESH . . . . . . . . . . . . . . . . . . . . . . . . . . . 2111
4.9.2 ESP-BLE-MESH Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2118
4.9.3 ESP-BLE-MESH Demo Videos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2118
4.9.4 ESP-BLE-MESH FAQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2119
4.9.5 Related Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2119
4.10 ESP-IDF FreeRTOS (SMP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2148
4.10.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2148
4.10.2 Symmetric Multiprocessing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2149
4.10.3 Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2149
4.10.4 SMP Scheduler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2151
4.10.5 Critical Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2154
4.10.6 Misc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2155
iv
4.11 ESP-WIFI-MESH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2156
4.11.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2156
4.11.2 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2157
4.11.3 ESP-WIFI-MESH Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2157
4.11.4 Building a Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2163
4.11.5 Managing a Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2168
4.11.6 Data Transmission . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2171
4.11.7 Channel Switching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2173
4.11.8 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2176
4.11.9 Further Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2177
4.12 Event Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2177
4.12.1 Wi-Fi, Ethernet, and IP Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2177
4.12.2 Mesh Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2178
4.12.3 Bluetooth Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2179
4.13 Fatal Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2179
4.13.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2179
4.13.2 Panic Handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2179
4.13.3 Register Dump and Backtrace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2180
4.13.4 GDB Stub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2182
4.13.5 RTC Watchdog Timeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2183
4.13.6 Guru Meditation Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2183
4.13.7 Other Fatal Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2185
4.14 Flash Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2187
4.14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2187
4.14.2 Relevant eFuses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2188
4.14.3 Flash Encryption Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2188
4.14.4 Flash Encryption Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2189
4.14.5 Possible Failures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2195
4.14.6 ESP32 Flash Encryption Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2196
4.14.7 Reading and Writing Data in Encrypted Flash . . . . . . . . . . . . . . . . . . . . . . . 2197
4.14.8 Updating Encrypted Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2198
4.14.9 Disabling Flash Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2198
4.14.10 Key Points About Flash Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2198
4.14.11 Limitations of Flash Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2199
4.14.12 Flash Encryption and Secure Boot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2199
4.14.13 Advanced Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2199
4.14.14 Technical Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2201
4.15 Hardware Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2202
4.15.1 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2202
4.15.2 LL (Low Level) Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2203
4.15.3 HAL (Hardware Abstraction Layer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2204
4.16 High-Level Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2205
4.16.1 Interrupt Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2205
4.16.2 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2206
4.17 JTAG Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2206
4.17.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2207
4.17.2 How it Works? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2207
4.17.3 Selecting JTAG Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2208
4.17.4 Setup of OpenOCD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2208
4.17.5 Configuring ESP32 Target . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2209
4.17.6 Launching Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2214
4.17.7 Debugging Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2214
4.17.8 Building OpenOCD from Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2214
4.17.9 Tips and Quirks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2219
4.17.10 Related Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2224
4.18 Linker Script Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2249
4.18.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2249
4.18.2 Quick Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2249
v
4.18.3 Linker Script Generation Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2252
4.19 lwIP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2258
4.19.1 Supported APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2259
4.19.2 BSD Sockets API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2259
4.19.3 Netconn API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2263
4.19.4 lwIP FreeRTOS Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2263
4.19.5 IPv6 Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2263
4.19.6 esp-lwip custom modifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2264
4.19.7 Performance Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2265
4.20 Memory Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2266
4.20.1 DRAM (Data RAM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2266
4.20.2 IRAM (Instruction RAM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2267
4.20.3 IROM (code executed from flash) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2268
4.20.4 RTC FAST memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2268
4.20.5 DROM (data stored in flash) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2268
4.20.6 RTC Slow memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2269
4.20.7 DMA Capable Requirement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2269
4.20.8 DMA Buffer in the stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2269
4.21 OpenThread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2270
4.21.1 Mode of the OpenThread stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2270
4.21.2 How To Write an OpenThread Application . . . . . . . . . . . . . . . . . . . . . . . . . 2270
4.21.3 The OpenThread border router . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2272
4.22 Partition Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2272
4.22.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2272
4.22.2 Built-in Partition Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2272
4.22.3 Creating Custom Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2273
4.22.4 Generating Binary Partition Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2275
4.22.5 Partition Size Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2275
4.22.6 Flashing the partition table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2276
4.22.7 Partition Tool (parttool.py) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2276
4.23 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2277
4.23.1 How to Optimize Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2277
4.23.2 Guides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2278
4.24 RF calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2295
4.24.1 Partial calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2295
4.24.2 Full calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2295
4.24.3 No calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2295
4.24.4 PHY initialization data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2296
4.24.5 API Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2296
4.25 Secure Boot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2299
4.25.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2299
4.25.2 Secure Boot Process Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2299
4.25.3 Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2300
4.25.4 Bootloader Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2300
4.25.5 How To Enable Secure Boot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2300
4.25.6 Re-Flashable Software Bootloader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2301
4.25.7 Generating Secure Boot Signing Key . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2302
4.25.8 Remote Signing of Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2302
4.25.9 Secure Boot Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2302
4.25.10 Technical Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2303
4.25.11 Secure Boot & Flash Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2304
4.25.12 Signed App Verification Without Hardware Secure Boot . . . . . . . . . . . . . . . . . . 2304
4.25.13 Advanced Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2305
4.26 Secure Boot V2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2305
4.26.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2305
4.26.2 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2305
4.26.3 Secure Boot V2 Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2305
4.26.4 Signature Block Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2306
vi
4.26.5 Verifying a Signature Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2307
4.26.6 Verifying an Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2307
4.26.7 Bootloader Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2307
4.26.8 eFuse usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2307
4.26.9 How To Enable Secure Boot V2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2307
4.26.10 Restrictions after Secure Boot is enabled . . . . . . . . . . . . . . . . . . . . . . . . . . 2308
4.26.11 Generating Secure Boot Signing Key . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2308
4.26.12 Remote Signing of Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2309
4.26.13 Secure Boot Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2309
4.26.14 Technical Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2309
4.26.15 Secure Boot & Flash Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2309
4.26.16 Signed App Verification Without Hardware Secure Boot . . . . . . . . . . . . . . . . . . 2310
4.26.17 Advanced Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2310
4.27 Support for External RAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2310
4.27.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2311
4.27.2 Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2311
4.27.3 Configuring External RAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2311
4.27.4 Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2313
4.27.5 Failure to initialize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2313
4.27.6 Chip revisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2313
4.28 Thread Local Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2314
4.28.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2314
4.28.2 FreeRTOS Native API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2314
4.28.3 Pthread API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2314
4.28.4 C11 Standard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2315
4.29 Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2315
4.29.1 IDF Frontend - idf.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2315
4.29.2 IDF Docker Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2318
4.29.3 IDF Windows Installer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2320
4.29.4 IDF Component Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2321
4.29.5 IDF Clang Tidy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2322
4.29.6 Downloadable Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2323
4.30 Unit Testing in ESP32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2336
4.30.1 Normal Test Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2336
4.30.2 Multi-device Test Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2337
4.30.3 Multi-stage Test Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2338
4.30.4 Tests For Different Targets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2338
4.30.5 Building Unit Test App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2339
4.30.6 Running Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2340
4.30.7 Timing Code with Cache Compensated Timer . . . . . . . . . . . . . . . . . . . . . . . 2341
4.30.8 Mocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2342
4.31 Unit Testing on Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2343
4.31.1 Embedded Software Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2344
4.31.2 IDF Unit Tests on Linux Host . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2344
4.32 Wi-Fi Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2345
4.32.1 ESP32 Wi-Fi Feature List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2345
4.32.2 How To Write a Wi-Fi Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2345
4.32.3 ESP32 Wi-Fi API Error Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2346
4.32.4 ESP32 Wi-Fi API Parameter Initialization . . . . . . . . . . . . . . . . . . . . . . . . . 2346
4.32.5 ESP32 Wi-Fi Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2346
4.32.6 ESP32 Wi-Fi Event Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2347
4.32.7 ESP32 Wi-Fi Station General Scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . 2350
4.32.8 ESP32 Wi-Fi AP General Scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2353
4.32.9 ESP32 Wi-Fi Scan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2353
4.32.10 ESP32 Wi-Fi Station Connecting Scenario . . . . . . . . . . . . . . . . . . . . . . . . . 2360
4.32.11 ESP32 Wi-Fi Station Connecting When Multiple APs Are Found . . . . . . . . . . . . . 2364
4.32.12 Wi-Fi Reconnect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2364
4.32.13 Wi-Fi Beacon Timeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2364
vii
4.32.14 ESP32 Wi-Fi Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2364
4.32.15 Wi-Fi Easy Connect™ (DPP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2370
4.32.16 Wireless Network Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2370
4.32.17 Radio Resource Measurement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2370
4.32.18 ESP32 Wi-Fi Power-saving Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2371
4.32.19 ESP32 Wi-Fi Throughput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2371
4.32.20 Wi-Fi 80211 Packet Send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2372
4.32.21 Wi-Fi Sniffer Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2373
4.32.22 Wi-Fi Multiple Antennas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2374
4.32.23 Wi-Fi Channel State Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2375
4.32.24 Wi-Fi Channel State Information Configure . . . . . . . . . . . . . . . . . . . . . . . . . 2377
4.32.25 Wi-Fi HT20/40 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2377
4.32.26 Wi-Fi QoS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2377
4.32.27 Wi-Fi AMSDU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2378
4.32.28 Wi-Fi Fragment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2378
4.32.29 WPS Enrollee . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2378
4.32.30 Wi-Fi Buffer Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2378
4.32.31 How to Improve Wi-Fi Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2379
4.32.32 Wi-Fi Menuconfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2382
4.32.33 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2385
4.33 Wi-Fi Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2388
4.33.1 ESP32 Wi-Fi Security Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2388
4.33.2 Protected Management Frames (PMF) . . . . . . . . . . . . . . . . . . . . . . . . . . . 2391
4.33.3 WPA3-Personal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2392
4.34 RF Coexistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2393
4.34.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2393
4.34.2 Supported Coexistence Scenario for ESP32 . . . . . . . . . . . . . . . . . . . . . . . . . 2393
4.34.3 Coexistence Mechanism and Policy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2393
4.34.4 How to Use the Coexistence Feature . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2394
4.35 Reproducible Builds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2396
4.35.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2396
4.35.2 Reasons for non-reproducible builds . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2396
4.35.3 Enabling reproducible builds in ESP-IDF . . . . . . . . . . . . . . . . . . . . . . . . . . 2396
4.35.4 How reproducible builds are achieved . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2396
4.35.5 Reproducible builds and debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2397
4.35.6 Factors which still affect reproducible builds . . . . . . . . . . . . . . . . . . . . . . . . 2397
viii
5.5.3 FreeRTOS Asserts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2403
5.5.4 Port Macro APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2403
5.6 Migrate Peripherals to ESP-IDF 5.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2403
5.6.1 Peripheral Clock Gating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2403
5.6.2 RTC Subsystem Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2403
5.6.3 SPI Flash Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2403
5.6.4 ADC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2404
5.6.5 GPIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2404
5.6.6 Timer Group Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2405
5.6.7 UART . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2405
5.6.8 I2C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2406
5.6.9 SPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2406
5.6.10 SDMMC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2406
5.6.11 LEDC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2406
5.6.12 Pulse Counter Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2406
5.6.13 RMT Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2407
5.6.14 LCD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2409
5.6.15 MCPWM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2409
5.6.16 I2S driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2409
5.6.17 Register access macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2411
5.7 Migration of Protocol Components to ESP-IDF 5.0 . . . . . . . . . . . . . . . . . . . . . . . . . 2412
5.7.1 Mbed TLS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2412
5.7.2 Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2413
5.7.3 HTTPS Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2413
5.7.4 ESP HTTPS OTA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2413
5.7.5 ESP-TLS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2414
5.7.6 HTTP Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2414
5.7.7 ESP HTTP Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2414
5.7.8 TCP Transport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2414
5.8 Migrate Provisioning to ESP-IDF 5.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2415
5.8.1 Protocomm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2415
5.8.2 Wi-Fi Provisioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2415
5.8.3 ESP Local Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2415
5.9 Removed or deprecated components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2415
5.9.1 Components moved to IDF Component Registry . . . . . . . . . . . . . . . . . . . . . . 2415
5.9.2 Deprecated Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2416
5.10 Migrate Storage to ESP-IDF 5.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2416
5.10.1 Breaking changes: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2416
5.11 Migrate System to ESP-IDF 5.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2417
5.11.1 Inter-Processor Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2417
5.11.2 ESP Clock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2418
5.11.3 Cache Error Interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2418
5.11.4 Brownout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2418
5.11.5 Trax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2418
5.11.6 ROM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2418
5.11.7 ESP HW Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2418
5.11.8 ESP Common . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2419
5.11.9 ESP System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2419
5.11.10 SOC dependency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2419
5.11.11 APP Trace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2419
5.11.12 ESP Timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2419
5.11.13 ESP image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2419
5.11.14 Task Watchdog Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2420
5.11.15 Efuse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2420
5.12 Migrate Tools to ESP-IDF 5.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2420
5.12.1 IDF Monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2420
5.12.2 Deprecated commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2420
5.12.3 Esptool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2420
ix
5.13 TCP/IP Adapter Migration Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2420
5.13.1 Updating network connection code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2421
5.14 Migrate IDF Code to GCC 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2422
5.14.1 Official GNU porting guides for your code . . . . . . . . . . . . . . . . . . . . . . . . . 2422
5.14.2 Espressif Toolchain changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2422
5.14.3 Common cases in code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2422
9 Resources 2465
9.1 PlatformIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2465
x
9.1.1 What is PlatformIO? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2465
9.1.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2465
9.1.3 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2466
9.1.4 Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2466
9.1.5 Project Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2466
9.1.6 Next Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2466
9.2 Useful Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2466
11 About 2471
Index 2475
Index 2475
xi
xii
Table of contents
This is the documentation for Espressif IoT Development Framework (esp-idf). ESP-IDF is the official development
framework for the ESP32, ESP32-S and ESP32-C Series SoCs.
This document describes using ESP-IDF with the ESP32 SoC.
Get Started
This document is intended to help you set up the software development environment for the hardware based on the
ESP32 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 ESP32 board.
Note: This is documentation for the master branch (latest version) of ESP-IDF. This version is under continual
development. Stable version documentation is available, as well as other ESP-IDF Versions.
1.1 Introduction
ESP32 is a system on a chip that integrates the following features:
• Wi-Fi (2.4 GHz band)
• Bluetooth
• Dual high performance Xtensa® 32-bit LX6 CPU cores
• Ultra Low Power co-processor
• Multiple peripherals
Powered by 40 nm technology, ESP32 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
ESP32 series hardware. 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.
1.2.1 Hardware
• An ESP32 board.
• USB cable - USB A / micro USB B.
• Computer running Windows, Linux, or macOS.
Note: Currently, some of the development boards are using USB Type C connectors. Be sure you have the correct
cable to connect your board!
3
Chapter 1. Get Started
If you have one of ESP32 official development boards listed below, you can click on the link to learn more about the
hardware.
This guide shows how to start using the ESP32-DevKitC V4 development board.
Functional Description The following figure and the table below describe the key components, interfaces and
controls of the ESP32-DevKitC V4 board.
Note: The pins D0, D1, D2, D3, CMD and CLK are used internally for communication between ESP32 and SPI
flash memory. They are grouped on both sides near the USB connector. Avoid using these pins, as it may disrupt
Note: The pins GPIO16 and GPIO17 are available for use only on the boards with the modules ESP32-WROOM
and ESP32-SOLO-1. The boards with ESP32-WROVER modules have the pins reserved for internal use.
Power Supply Options There are three mutually exclusive ways to provide power to the board:
• Micro USB port, default power supply
• 5V / GND header pins
• 3V3 / GND header pins
Warning: The power supply must be provided using one and only one of the options above, otherwise the
board and/or the power supply source can be damaged.
Header Block The two tables below provide the Name and Function of I/O header pins on both sides of the board,
as shown in ESP32-DevKitC V4 with ESP32-WROOM-32 module soldered. The numbering and names are the same
as in the ESP32-DevKitC V4 schematics (PDF).
J1
No. Name Type Function
1 3V3 P 3.3 V power supply
2 EN I CHIP_PU, Reset
3 IO36 I GPIO36, ADC1_CH0, S_VP
4 IO39 I GPIO39, ADC1_CH3, S_VN
5 IO34 I GPIO34, ADC1_CH6, VDET_1
6 IO35 I GPIO35, ADC1_CH7, VDET_2
7 IO32 I/O GPIO32, ADC1_CH4, TOUCH_CH9, XTAL_32K_P
8 IO33 I/O GPIO33, ADC1_CH5, TOUCH_CH8, XTAL_32K_N
9 IO25 I/O GPIO25, ADC1_CH8, DAC_1
10 IO26 I/O GPIO26, ADC2_CH9, DAC_2
11 IO27 I/O GPIO27, ADC2_CH7, TOUCH_CH7
12 IO14 I/O GPIO14, ADC2_CH6, TOUCH_CH6, MTMS
13 IO12 I/O GPIO12, ADC2_CH5, TOUCH_CH5, MTDI
14 GND G Ground
15 IO13 I/O GPIO13, ADC2_CH4, TOUCH_CH4, MTCK
16 IO9 I/O GPIO9, D2
17 IO10 I/O GPIO10, D3
18 IO11 I/O GPIO11, CMD
19 5V0 P 5 V power supply
J3
No. Name Type Function
1 GND G Ground
2 IO23 I/O GPIO23
3 IO22 I/O GPIO22
4 IO1 I/O GPIO1, U0TXD
5 IO3 I/O GPIO3, U0RXD
6 IO21 I/O GPIO21
7 GND G Ground
8 IO19 I/O GPIO19
9 IO18 I/O GPIO18
10 IO5 I/O GPIO5
11 IO17 I/O GPIO17
12 IO16 I/O GPIO16
13 IO4 I/O GPIO4, ADC2_CH0, TOUCH_CH0
14 IO0 I/O GPIO0, ADC2_CH1, TOUCH_CH1, Boot
16 IO2 I/O GPIO2, ADC2_CH2, TOUCH_CH2
17 IO15 I/O GPIO15, ADC2_CH3, TOUCH_CH3, MTDO
17 IO8 I/O GPIO8, D1
18 IO7 I/O GPIO7, D0
19 IO6 I/O GPIO6, SCK
Pin Layout
Note on C15 The component C15 may cause the following issues on earlier ESP32-DevKitC V4 boards:
• The board may boot into Download mode
• If you output clock on GPIO0, C15 may impact the signal
In case these issues occur, please remove the component. The figure below shows the location of C15 highlighted in
yellow.
Start Application Development Before powering up your ESP32-DevKitC V4, please make sure that the board
is in good condition with no obvious signs of damage.
After that, proceed to Get Started, where Section Installation will quickly help you set up the development environment
and then flash an example project onto your board.
Fig. 4: Dimensions of ESP32-DevKitC board with ESP32-WROOM-32 module soldered - back (click to enlarge)
Board Dimensions
Related Documents
• ESP32-DevKitC V4 schematics (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROOM-32 Datasheet (PDF)
• ESP32-WROOM-32D and ESP32-WROOM-32U Datasheet (PDF)
• ESP32-WROOM-DA Datasheet (PDF)
• ESP32-WROVER Datasheet (PDF)
• ESP32-WROVER-B Datasheet (PDF)
• ESP Product Selector
For further design documentation for the board, please contact us at [email protected].
Functional Description The following figure and the table below describe the key components, interfaces and
controls of the ESP32-DevKitC V2 board.
Power Supply Options There are three mutually exclusive ways to provide power to the board:
• Micro USB port, default power supply
• 5V / GND header pins
• 3V3 / GND header pins
Warning: The power supply must be provided using one and only one of the options above, otherwise the
board and/or the power supply source can be damaged.
Start Application Development Before powering up your ESP32-DevKitC V2, please make sure that the board
is in good condition with no obvious signs of damage.
After that, proceed to Get Started, where Section Installation will quickly help you set up the development environment
and then flash an example project onto your board.
Related Documents
• ESP32-DevKitC schematics (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROOM-32 Datasheet (PDF)
This guide shows how to get started with the ESP-WROVER-KIT V4.1 development board and also provides infor-
mation about its functionality and configuration options.
Note: ESP32’s GPIO16 and GPIO17 are used as chip select and clock signals for PSRAM. By default, the two
GPIOs are not broken out to the board’s pin headers in order to ensure reliable performance.
Functionality Overview The block diagram below shows the main components of ESP-WROVER-KIT and their
interconnections.
Functional Description The following two figures and the table below describe the key components, interfaces,
and controls of the ESP-WROVER-KIT board.
The table below provides description in the following manner:
• Starting from the first picture’s top right corner and going clockwise
• Then moving on to the second picture
Setup Options There are three jumper blocks available to set up the board functionality. The most frequently
required options are listed in the table below.
Allocation of ESP32 Pins Some pins or terminals of ESP32 are allocated for use with the onboard or external
hardware. If that hardware is not used, e.g., nothing is plugged into the Camera (JP4) header, then these GPIOs can
be used for other purposes.
Some of the pins, such as GPIO0 or GPIO2, have multiple functions and some of them are shared among onboard
and external peripheral devices. Certain combinations of peripherals cannot work together. For example, it is not
possible to do JTAG debugging of an application that is using SD card, because several pins are shared by JTAG and
the SD card slot.
In other cases, peripherals can coexist under certain conditions. This is applicable to, for example, LCD screen and
SD card that share only a single pin GPIO21. This pin is used to provide D/C (Data/Control) signal for the LCD as
well as the Card Detect signal read from the SD card slot. If the card detect functionality is not essential, then it may
be disabled by removing R167, so both LCD and SD may operate together.
For more details on which pins are shared among which peripherals, please refer to the table in the next section.
Main I/O Connector / JP1 The JP1 connector consists of 14x2 male pins whose functions are shown in the middle
two “I/O”columns of the table below. The two “Shared With”columns on both sides describe where else on the
board a certain GPIO is used.
Legend:
• NC/XTAL - 32.768 kHz Oscillator
• JTAG - JTAG / JP2
• Boot - Boot button / SW2
• Camera - Camera / JP4
• LED - RGB LED
• microSD - microSD Card / J4
• LCD - LCD / U5
• PSRAM - ESP32-WROVER-E’s PSRAM
Note: Since GPIO32 and GPIO33 are connected to the oscillator by default, they are not connected to the JP1 I/O
connector to maintain signal integrity. This allocation may be changed from the oscillator to JP1 by desoldering the
zero-ohm resistors from positions R11 or R23 and re-soldering them to positions R12 or R24.
Important: The module’s flash bus is connected to the jumper block JP2 through zero-ohm resistors R140 ~
R145. If the flash memory needs to operate at the frequency of 80 MHz, for reasons such as improving the integrity
of bus signals, you can desolder these resistors to disconnect the module’s flash bus from the pin header JP2.
JTAG / JP2
. ESP32 Pin JTAG Signal
1 EN TRST_N
2 MTMS / GPIO14 TMS
3 MTDO / GPIO15 TDO
4 MTDI / GPIO12 TDI
5 MTCK / GPIO13 TCK
Camera / JP4
. ESP32 Pin Camera Signal
1 n/a 3.3V
2 n/a Ground
3 GPIO27 SIO_C / SCCB Clock
4 GPIO26 SIO_D / SCCB Data
5 GPIO25 VSYNC / Vertical Sync
6 GPIO23 HREF / Horizontal Reference
7 GPIO22 PCLK / Pixel Clock
8 GPIO21 XCLK / System Clock
9 GPIO35 D7 / Pixel Data Bit 7
10 GPIO34 D6 / Pixel Data Bit 6
11 GPIO39 D5 / Pixel Data Bit 5
12 GPIO36 D4 / Pixel Data Bit 4
13 GPIO19 D3 / Pixel Data Bit 3
14 GPIO18 D2 / Pixel Data Bit 2
15 GPIO5 D1 / Pixel Data Bit 1
16 GPIO4 D0 / Pixel Data Bit 0
17 GPIO0 RESET / Camera Reset
18 n/a PWDN / Camera Power Down
RGB LED
. ESP32 Pin RGB LED
1 GPIO0 Red
2 GPIO2 Green
3 GPIO4 Blue
microSD Card
. ESP32 Pin microSD Signal
1 MTDI / GPIO12 DATA2
2 MTCK / GPIO13 CD / DATA3
3 MTDO / GPIO15 CMD
4 MTMS / GPIO14 CLK
5 GPIO2 DATA0
6 GPIO4 DATA1
7 GPIO21 Card Detect
LCD / U5
. ESP32 Pin LCD Signal
1 GPIO18 RESET
2 GPIO19 SCL
3 GPIO21 D/C
4 GPIO22 CS
5 GPIO23 SDA
6 GPIO25 SDO
7 GPIO5 Backlight
Start Application Development Before powering up your ESP-WROVER-KIT, please make sure that the board
is in good condition with no obvious signs of damage.
Initial Setup Please set only the following jumpers shown in the pictures below:
• Select USB as the power source using the jumper block JP7.
• Enable UART communication using the jumper block JP2.
Now to Development Please proceed to Get Started, where Section Installation will quickly help you set up the
development environment and then flash an example project onto your board.
A Board Support Package can be found in IDF Component Registry.
The application examples that use some hardware specific to your ESP-WROVER-KIT can be found below.
• On-board LCD example: peripherals/spi_master/lcd
• SD card slot example: storage/sd_card
• Camera connector example: https://github.com/espressif/esp32-camera
Related Documents
• ESP-WROVER-KIT V4.1 schematic (PDF)
• ESP-WROVER-KIT V4.1 layout (DXF) may be opened online with Autodesk Viewer
• ESP32 Datasheet (PDF)
• ESP32-WROVER-E Datasheet (PDF)
• JTAG Debugging
• ESP32 Hardware Reference
Overview ESP-WROVER-KIT is an ESP32-based development board produced by Espressif. This board features
an integrated LCD screen and microSD card slot.
ESP-WROVER-KIT comes with the following ESP32 modules:
• ESP32-WROOM-32
• ESP32-WROVER series
Its another distinguishing feature is the embedded FTDI FT2232HL chip - an advanced multi-interface USB bridge.
This chip enables to use JTAG for direct debugging of ESP32 through the USB interface without a separate JTAG
debugger. ESP-WROVER-KIT makes development convenient, easy, and cost-effective.
Most of the ESP32 I/O pins are broken out to the board’s pin headers for easy access.
Note: The version with the ESP32-WROVER module uses ESP32’s GPIO16 and GPIO17 as chip
select and clock signals for PSRAM. By default, the two GPIOs are not broken out to the board’s pin
headers in order to ensure reliable performance.
Functionality Overview The block diagram below shows the main components of ESP-WROVER-KIT and their
interconnections.
Functional Description The following two figures and the table below describe the key components, interfaces,
and controls of the ESP-WROVER-KIT board.
The table below provides description in the following manner:
• Starting from the first picture’s top right corner and going clockwise
• Then moving on to the second picture
Setup Options There are five jumper blocks available to set up the board functionality. The most frequently
required options are listed in the table below.
Allocation of ESP32 Pins Some pins / terminals of ESP32 are allocated for use with the onboard or external
hardware. If that hardware is not used, e.g., nothing is plugged into the Camera (JP4) header, then these GPIOs can
be used for other purposes.
Some of the pins, such as GPIO0 or GPIO2, have multiple functions and some of them are shared among onboard
and external peripheral devices. Certain combinations of peripherals cannot work together. For example, it is not
possible to do JTAG debugging of an application that is using SD card, because several pins are shared by JTAG and
the SD card slot.
In other cases, peripherals can coexist under certain conditions. This is applicable to, for example, LCD screen and
SD card that share only a single pin GPIO21. This pin is used to provide D/C (Data / Control) signal for the LCD as
well as the CD (Card Detect) signal read from the SD card slot. If the card detect functionality is not essential, then
it may be disabled by removing R167, so both LCD and SD may operate together.
For more details on which pins are shared among which peripherals, please refer to the table in the next section.
Main I/O Connector / JP1 The JP1 connector consists of 14x2 male pins whose functions are shown in the middle
two “I/O”columns of the table below. The two “Shared With”columns on both sides describe where else on the
board a certain GPIO is used.
Legend:
• NC/XTAL - 32.768 kHz Oscillator
• JTAG - JTAG / JP8
• Boot - Boot button / SW2
• Camera - Camera / JP4
• LED - RGB LED
• microSD - microSD Card / J4
• LCD - LCD / U5
• PSRAM - only in case ESP32-WROVER is installed
Note: Since GPIO32 and GPIO33 are connected to the oscillator by default, they are not connected to the JP1 I/O
connector to maintain signal integrity. This allocation may be changed from the oscillator to JP1 by desoldering the
zero-ohm resistors from positions R11 / R23 and re-soldering them to positions R12 / R24.
Important: The module’s flash bus is connected to the jumper block JP13 through zero-ohm resistors R140 ~
R145. If the flash memory needs to operate at the frequency of 80 MHz, for reasons such as improving the integrity
of bus signals, you can desolder these resistors to disconnect the module’s flash bus from the pin header JP13.
JTAG / JP8
. ESP32 Pin JTAG Signal
1 EN TRST_N
2 MTMS / GPIO14 TMS
3 MTDO / GPIO15 TDO
4 MTDI / GPIO12 TDI
5 MTCK / GPIO13 TCK
Camera / JP4
. ESP32 Pin Camera Signal
1 n/a 3.3V
2 n/a Ground
3 GPIO27 SIO_C / SCCB Clock
4 GPIO26 SIO_D / SCCB Data
5 GPIO25 VSYNC / Vertical Sync
6 GPIO23 HREF / Horizontal Reference
7 GPIO22 PCLK / Pixel Clock
8 GPIO21 XCLK / System Clock
9 GPIO35 D7 / Pixel Data Bit 7
10 GPIO34 D6 / Pixel Data Bit 6
11 GPIO39 D5 / Pixel Data Bit 5
12 GPIO36 D4 / Pixel Data Bit 4
13 GPIO19 D3 / Pixel Data Bit 3
14 GPIO18 D2 / Pixel Data Bit 2
15 GPIO5 D1 / Pixel Data Bit 1
16 GPIO4 D0 / Pixel Data Bit 0
17 GPIO0 RESET / Camera Reset
18 n/a PWDN / Camera Power Down
RGB LED
. ESP32 Pin RGB LED
1 GPIO0 Red
2 GPIO2 Green
3 GPIO4 Blue
microSD Card
. ESP32 Pin microSD Signal
1 MTDI / GPIO12 DATA2
2 MTCK / GPIO13 CD / DATA3
3 MTDO / GPIO15 CMD
4 MTMS / GPIO14 CLK
5 GPIO2 DATA0
6 GPIO4 DATA1
7 GPIO21 CD
LCD / U5
. ESP32 Pin LCD Signal
1 GPIO18 RESET
2 GPIO19 SCL
3 GPIO21 D/C
4 GPIO22 CS
5 GPIO23 SDA
6 GPIO25 SDO
7 GPIO5 Backlight
Start Application Development Before powering up your ESP-WROVER-KIT, please make sure that the board
is in good condition with no obvious signs of damage.
Initial Setup Please set only the following jumpers shown in the pictures below:
• Select USB as the power source using the jumper block JP7.
• Enable UART communication using the jumper block JP11.
Now to Development Please proceed to Get Started, where Section Installation will quickly help you set up the
development environment and then flash an example project onto your board.
Related Documents
• ESP-WROVER-KIT V3 schematic (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROVER Datasheet (PDF)
• ESP32-WROOM-32 Datasheet (PDF)
• JTAG Debugging
• ESP32 Hardware Reference
Overview ESP-WROVER-KIT is an ESP32-based development board produced by Espressif. This board features
an integrated LCD screen and microSD card slot.
ESP-WROVER-KIT comes with the following ESP32 modules:
• ESP32-WROOM-32
• ESP32-WROVER series
Its another distinguishing feature is the embedded FTDI FT2232HL chip - an advanced multi-interface USB bridge.
This chip enables to use JTAG for direct debugging of ESP32 through the USB interface without a separate JTAG
debugger. ESP-WROVER-KIT makes development convenient, easy, and cost-effective.
Most of the ESP32 I/O pins are broken out to the board’s pin headers for easy access.
Note: The version with the ESP32-WROVER module uses ESP32’s GPIO16 and GPIO17 as chip
select and clock signals for PSRAM. By default, the two GPIOs are not broken out to the board’s pin
headers in order to ensure reliable performance.
Functionality Overview The block diagram below shows the main components of ESP-WROVER-KIT and their
interconnections.
Functional Description The following two figures and the table below describe the key components, interfaces,
and controls of the ESP-WROVER-KIT board.
The table below provides description in the following manner:
• Starting from the first picture’s top right corner and going clockwise
• Then moving on to the second picture
Setup Options There are five jumper blocks available to set up the board functionality. The most frequently
required options are listed in the table below.
Espressif
JP8 Systems Enable31JTAG functionality Release v5.0-dev-4037-g9b8c558e63
Submit Document Feedback
Chapter 1. Get Started
Start Application Development Before powering up your ESP-WROVER-KIT, please make sure that the board
is in good condition with no obvious signs of damage.
Initial Setup Please set only the following jumpers shown in the pictures below:
• Select USB as the power source using the jumper block JP7.
• Enable UART communication using the jumper block JP11.
Now to Development Please proceed to Get Started, where Section Installation will quickly help you set up the
development environment and then flash an example project onto your board.
Related Documents
• ESP-WROVER-KIT V2 schematic (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROVER Datasheet (PDF)
• ESP32-WROOM-32 Datasheet (PDF)
• JTAG Debugging
• ESP32 Hardware Reference
This guide shows how to get started with the ESP32-PICO-KIT V4/V4.1 mini development board. For the description
of other ESP32-PICO-KIT versions, please check ESP32 Hardware Reference.
This particular description covers ESP32-PICO-KIT V4 and V4.1. The difference is the upgraded USB-UART
bridge from CP2102 in V4 with up to 1 Mbps transfer rates to CP2102N in V4.1 with up to 3 Mbps transfer rates.
Note:
1. There are two versions of ESP32-PICO-KIT boards, respectively with male headers and female headers. In
this guide, the male header version is taken as an example.
2. The 2 x 3 pads not populated with pin headers are connected to the flash memory embedded in the ESP32-
PICO-D4 SiP module. For more details, see module’s datasheet in Related Documents.
Functionality Overview The block diagram below shows the main components of ESP32-PICO-KIT and their
interconnections.
Functional Description The following figure and the table below describe the key components, interfaces, and
controls of the ESP32-PICO-KIT board.
Below is the description of the items identified in the figure starting from the top left corner and going clockwise.
Power Supply Options There are three mutually exclusive ways to provide power to the board:
• Micro USB port, default power supply
• 5V / GND header pins
• 3V3 / GND header pins
Warning: The power supply must be provided using one and only one of the options above, otherwise the
board and/or the power supply source can be damaged.
Pin Descriptions The two tables below provide the Name and Function of I/O header pins on both sides of the
board, see ESP32-PICO-KIT board layout (with female headers). The pin numbering and header names are the same
as in the schematic given in Related Documents.
Header J2
4 IO21 I/O
GPIO21, VSPIHD,
EMAC_TX_EN
5 IO22 I/O
GPIO22, VSPIWP,
U0RTS, EMAC_TXD1
6 IO19 I/O
GPIO19, VSPIQ,
U0CTS, EMAC_TXD0
7 IO23 I/O
GPIO23, VSPID,
HS1_STROBE
8 IO18 I/O
GPIO18, VSPICLK,
HS1_DATA7
9 IO5 I/O
GPIO5, VSPICS0,
HS1_DATA6,
EMAC_RX_CLK
10 IO10 I/O
GPIO10, SD_DATA3,
SPIWP, HS1_DATA3,
U1TXD
11 IO9 I/O
GPIO9, SD_DATA2,
SPIHD, HS1_DATA2,
U1RXD
12 RXD0 I/O
Espressif Systems 37 Release v5.0-dev-4037-g9b8c558e63
Submit Document Feedback GPIO3, U0RXD (See 3) ,
CLK_OUT2
Chapter 1. Get Started
Header J3
4 SENSOR_VP (FSVP) I
GPIO36, ADC1_CH0,
RTC_GPIO0
5 SENSOR_VN (FSVN) I
GPIO39, ADC1_CH3,
RTC_GPIO3
6 IO25 I/O
GPIO25, DAC_1,
ADC2_CH8,
RTC_GPIO6,
EMAC_RXD0
7 IO26 I/O
GPIO26, DAC_2,
ADC2_CH9,
RTC_GPIO7,
EMAC_RXD1
8 IO32 I/O
32K_XP (See 2a) ,
ADC1_CH4, TOUCH9,
RTC_GPIO9
9 IO33 I/O
32K_XN (See 2b) ,
ADC1_CH5, TOUCH8,
RTC_GPIO8
10 IO27 I/O
GPIO27, ADC2_CH7,
TOUCH7,
RTC_GPIO17
EMAC_RX_DV
11
Espressif Systems IO14 39 I/O Release v5.0-dev-4037-g9b8c558e63
Submit Document Feedback
ADC2_CH6, TOUCH6,
RTC_GPIO16, MTMS,
HSPICLK,
Chapter 1. Get Started
Note:
1. This pin is connected to the flash pin of ESP32-PICO-D4.
2. 32.768 kHz crystal oscillator: a) input, b) output.
3. This pin is connected to the pin of the USB bridge chip on the board.
4. The operating voltage of ESP32-PICO-KIT’s embedded SPI flash is 3.3 V. Therefore, the strapping pin MTDI
should hold bit zero during the module power-on reset. If connected, please make sure that this pin is not held
up on reset.
Start Application Development Before powering up your ESP32-PICO-KIT, please make sure that the board is
in good condition with no obvious signs of damage.
After that, proceed to Get Started, where Section Installation will quickly help you set up the development environment
and then flash an example project onto your board.
For the board physical construction details, please refer to its Reference Design listed below.
Related Documents
• ESP32-PICO-KIT V4 schematic (PDF)
• ESP32-PICO-KIT V4.1 schematic (PDF)
• ESP32-PICO-KIT Reference Design containing OrCAD schematic, PCB layout, gerbers and BOM
• ESP32-PICO-D4 Datasheet (PDF)
• ESP32 Hardware Reference
Overview ESP32-PICO-KIT V3 is an ESP32-based mini development board produced by Espressif. The core of
this board is ESP32-PICO-D4 - a System-in-Package (SiP) module.
The development board features a USB-UART Bridge circuit, which allows developers to connect the board to a
computer’s USB port for flashing and debugging.
All the IO signals and system power on ESP32-PICO-D4 are led out to two rows of 20 x 0.1”header pads on both
sides of the development board for easy access.
Functional Description The following figure and the table below describe the key components, interfaces, and
controls of the ESP32-PICO-KIT V3 board.
Below is the description of the items identified in the figure starting from the top left corner and going clockwise.
Start Application Development Before powering up your ESP32-PICO-KIT V3, please make sure that the board
is in good condition with no obvious signs of damage.
After that, proceed to Get Started, where Section Installation will quickly help you set up the development environment
and then flash an example project onto your board.
Related Documents
• ESP32-PICO-KIT V3 schematic (PDF)
• ESP32-PICO-D4 Datasheet (PDF)
• ESP32 Hardware Reference
This guide shows how to get started with the ESP32-Ethernet-Kit development board and also provides information
about its functionality and configuration options.
The ESP32-Ethernet-Kit is an Ethernet-to-Wi-Fi development board that enables Ethernet devices to be intercon-
nected over Wi-Fi. At the same time, to provide more flexible power supply options, the ESP32-Ethernet-Kit also
supports power over Ethernet (PoE).
It consists of two development boards, the Ethernet board A and the PoE board B. The Ethernet board (A) con-
tains Bluetooth/Wi-Fi dual-mode ESP32-WROVER-E module and IP101GRI, a Single Port 10/100 Fast Ethernet
Transceiver (PHY). The PoE board (B) provides power over Ethernet functionality. The A board can work indepen-
dently, without the board B installed.
For the application loading and monitoring, the Ethernet board (A) also features FTDI FT2232H chip - an advanced
multi-interface USB bridge. This chip enables to use JTAG for direct debugging of ESP32 through the USB interface
without a separate JTAG debugger.
Functionality Overview The block diagram below shows the main components of ESP32-Ethernet-Kit and their
interconnections.
Functional Description The following figures and tables describe the key components, interfaces, and controls of
the ESP32-Ethernet-Kit.
Ethernet Board (A) The table below provides description starting from the picture’s top right corner and going
clockwise.
Note: Automatic firmware download is supported. If following steps and using software described in Section Start
Application Development, users don’t need to do any operation with BOOT button or EN button.
PoE Board (B) This board coverts power delivered over the Ethernet cable (PoE) to provide a power supply for the
Ethernet board (A). The main components of the PoE board (B) are shown on the block diagram under Functionality
Overview.
The PoE board (B) has the following features:
• Support for IEEE 802.3at
• Power output: 5 V, 1.4 A
To take advantage of the PoE functionality the RJ45 Port of the Ethernet board (A) should be connected with an
Ethernet cable to a switch that supports PoE. When the Ethernet board (A) detects 5 V power output from the PoE
board (B), the USB power will be automatically cut off.
Setup Options This section describes options to configure the ESP32-Ethernet-Kit hardware.
Function Switch When in On position, this DIP switch is routing listed GPIOs to FT2232H to provide JTAG
functionality. When in Off position, the GPIOs may be used for other purposes.
RMII Clock Selection The ethernet MAC and PHY under RMII working mode need a common 50 MHz refer-
ence clock (i.e. RMII clock) that can be provided either externally, or generated from internal ESP32 APLL (not
recommended).
Note: For additional information on the RMII clock selection, please refer to ESP32-Ethernet-Kit V1.2 Ethernet
board (A) schematic, sheet 2, location D2.
RMII Clock Sourced Externally by PHY By default, the ESP32-Ethernet-Kit is configured to provide RMII
clock for the IP101GRI PHY’s 50M_CLKO output. The clock signal is generated by the frequency multiplication
of 25 MHz crystal connected to the PHY. For details, please see the figure below.
Please note that the PHY is reset on power up by pulling the RESET_N signal down with a resistor. ESP32 should
assert RESET_N high with GPIO5 to enable PHY. Only this can ensure the power-up of system. Otherwise ESP32
may enter download mode (when the clock signal of REF_CLK_50M is at a high logic level during the GPIO0
power-up sampling phase).
RMII Clock Sourced Internally from ESP32’s APLL Another option is to source the RMII Clock from internal
ESP32 APLL, see figure below. The clock signal coming from GPIO0 is first inverted, to account for transmission
line delay, and then supplied to the PHY.
To implement this option, users need to remove or add some RC components on the board. For details please refer
to ESP32-Ethernet-Kit V1.2 Ethernet board (A) schematic, sheet 2, location D2. Please note that if the APLL is
already used for other purposes (e.g. I2S peripheral), then you have no choice but use an external RMII clock.
GPIO Allocation This section describes allocation of ESP32 GPIOs to specific interfaces or functions of the
ESP32-Ethernet-Kit.
IP101GRI (PHY) Interface The allocation of the ESP32 (MAC) pins to IP101GRI (PHY) is shown in the table
below. Implementation of ESP32-Ethernet-Kit defaults to Reduced Media-Independent Interface (RMII).
Note: The allocation of all pins under the ESP32’s RMII Interface is fixed and cannot be changed either through IO
MUX or GPIO Matrix. REF_CLK can only be selected from GPIO0, GPIO16 or GPIO17 and it can not be changed
through GPIO Matrix.
GPIO Header 1 This header exposes some GPIOs that are not used elsewhere on the ESP32-Ethernet-Kit.
GPIO Header 2 This header contains GPIOs that may be used for other purposes depending on scenarios described
in column “Comments”.
Note:
1. The ESP32 pins GPIO16 and GPIO17 are not broken out to the ESP32-WROVER-E module and therefore
not available for use. If you need to use these pins, please solder a module without PSRAM memory inside,
e.g. the ESP32-WROOM-32D or ESP32-SOLO-1.
2. Functionality depends on the settings of the Function Switch.
Note:
1. To prevent the power-on state of the GPIO0 from being affected by the clock output on the PHY side, the
RESET_N signal to PHY defaults to low, turning the clock output off. After power-on you can control RE-
SET_N with GPIO5 to turn the clock output on. See also RMII Clock Sourced Externally by PHY. For PHYs
that cannot turn off the clock output through RESET_N, it is recommended to use a crystal module that can be
disabled/enabled externally. Similarly like when using RESET_N, the oscillator module should be disabled by
default and turned on by ESP32 after power-up. For a reference design please see ESP32-Ethernet-Kit V1.2
Ethernet board (A) schematic.
2. The ESP32 pins GPIO16 and GPIO17 are not broken out to the ESP32-WROVER-E module and therefore
not available for use. If you need to use these pins, please solder a module without PSRAM memory inside,
e.g. the ESP32-WROOM-32D or ESP32-SOLO-1.
Start Application Development Before powering up your ESP32-Ethernet-Kit, please make sure that the board
is in good condition with no obvious signs of damage.
Initial Setup
1. Set the Function Switch on the Ethernet board (A) to its default position by turning all the switches to ON.
2. To simplify flashing and testing of the application, do not input extra signals to the board headers.
3. The PoE board (B) can now be plugged in, but do not connect external power to it.
4. Connect the Ethernet board (A) to the PC with a USB cable.
5. Turn the Power Switch from GND to 5V0 position, the 5V Power On LED should light up.
Now to Development Proceed to Get Started, where Section Installation will quickly help you set up the develop-
ment environment and then flash an example project onto your board.
Move on to the next section only if you have successfully completed all the above steps.
Configure and Load the Ethernet Example After setting up the development environment and testing the board,
you can configure and flash the ethernet/basic example. This example has been created for testing Ethernet function-
ality. It supports different PHY, including IP101GRI installed on ESP32-Ethernet-Kit V1.2 (click to enlarge).
Related Documents
• ESP32-Ethernet-Kit V1.2 Ethernet Board (A) Schematic (PDF)
• ESP32-Ethernet-Kit PoE Board (B) Schematic (PDF)
• ESP32-Ethernet-Kit V1.2 Ethernet Board (A) PCB Layout (PDF)
• ESP32-Ethernet-Kit PoE Board (B) PCB Layout (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROVER-E Datasheet (PDF)
• JTAG Debugging
• ESP32 Hardware Reference
For other design documentation for the board, please contact us at [email protected].
For the application loading and monitoring the Ethernet board (A) also features FTDI FT2232H chip - an advanced
multi-interface USB bridge. This chip enables to use JTAG for direct debugging of ESP32 through the USB interface
Functionality Overview The block diagram below shows the main components of ESP32-Ethernet-Kit and their
interconnections.
Functional Description The following two figures and tables describe the key components, interfaces, and controls
of the ESP32-Ethernet-Kit.
Ethernet Board (A) The table below provides description starting from the picture’s top right corner and going
clockwise.
Key Description
Com-
po-
nent
ESP32- This ESP32 module features 64-Mbit PSRAM for flexible extended storage and data processing capabil-
WROVER- ities.
B
GPIO Five unpopulated through-hole solder pads to provide access to selected GPIOs of ESP32. For details,
Header see GPIO Header 2.
2
Flow A jumper header with access to the board signals. For details, see Flow Control.
Con-
trol
Func- A DIP switch used to configure the functionality of selected GPIOs of ESP32. For details, see Function
tion Switch.
Switch
Tx/Rx Two LEDs to show the status of UART transmission.
LEDs
GPIO Provides access to some GPIOs of ESP32 that can be used depending on the position of the Function
Header Switch.
3
FT2232H The FT2232H chip serves as a multi-protocol USB-to-serial bridge which can be programmed and con-
trolled via USB to provide communication with ESP32. FT2232H also features USB-to-JTAG interface
which is available on channel A of the chip, while USB-to-serial is on channel B. The FT2232H chip
enhances user-friendliness in terms of application development and debugging. See ESP32-Ethernet-Kit
V1.0 Ethernet board (A) schematic.
USB USB interface. Power supply for the board as well as the communication interface between a computer
Port and the board.
Power Power On/Off Switch. Toggling toward the Boot button powers the board on, toggling away from Boot
Switch powers the board off.
5V The 5V power supply interface can be more convenient when the board is operating autonomously (not
In- connected to a computer).
put
Espressif Systems 55 Release v5.0-dev-4037-g9b8c558e63
5V This red LED turns on when power is supplied to the board, either from USB or 5V Input.
Submit Document Feedback
Power
On
LED
Chapter 1. Get Started
PoE Board (B) This board coverts power delivered over the Ethernet cable (PoE) to provide a power supply for the
Ethernet board (A). The main components of the PoE board (B) are shown on the block diagram under Functionality
Overview.
The PoE board (B) has the following features:
• Support for IEEE 802.3at
• Power output: 5 V, 1.4 A
To take advantage of the PoE functionality the RJ45 Port of the Ethernet board (A) should be connected with an
Ethernet cable to a switch that supports PoE. When the Ethernet board (A) detects 5 V power output from the PoE
board (B), the USB power will be automatically cut off.
Setup Options This section describes options to configure the ESP32-Ethernet-Kit hardware.
Function Switch The functions for specific GPIO pins can be selected with the Function Switch.
You can make a certain GPIO pin available for other purposes by putting its DIP SW to the Off position.
Flow Control This is a 2 x 2 jumper pin header intended for the UART flow control.
. Signal Comment
1 MTDO GPIO13, see also Function Switch
2 MTCK GPIO15, see also Function Switch
3 RTS RTS signal of FT2232H
4 CTS CTS signal of FT2232H
GPIO Allocation This section describes allocation of ESP32 GPIOs to specific interfaces or functions of the
ESP32-Ethernet-Kit.
IP101GRI (PHY) Interface The allocation of the ESP32 (MAC) pins to IP101GRI (PHY) is shown in the table
below. Implementation of ESP32-Ethernet-Kit defaults to Reduced Media-Independent Interface (RMII).
Note: Except for REF_CLK, the allocation of all pins under the RMII Interface is fixed and cannot be changed either
through IOMUX or GPIO Matrix.
GPIO Header 1 This header exposes some GPIOs that are not used elsewhere on the ESP32-Ethernet-Kit.
. ESP32 Pin
1 GPIO32
2 GPIO33
3 GPIO34
4 GPIO35
5 GPIO36
6 GPIO39
GPIO Header 2 This header contains the GPIOs with specific MII functionality (except GPIO2), as opposed to
Reduced Media-Independent Interface (RMII) functionality implemented on ESP32-Ethernet-Kit board by default,
see IP101GRI (PHY) Interface. Depending on the situation, if MMI is used, specific Ethernet applications might
require this functionality.
Note:
1. The ESP32 pins GPIO16 and GPIO17 are not broken out to the ESP32-WROVER-B module and therefore
not available for use. If you need to use these pins, please solder a module without SPIRAM memory inside,
e.g. the ESP32-WROOM-32D or ESP32-SOLO-1.
2. Functionality depends on the settings of the Function Switch.
GPIO Header 3 The functionality of GPIOs connected to this header depends on the settings of the Function
Switch.
. ESP32 Pin
1 GPIO15
2 GPIO13
3 GPIO12
4 GPIO14
5 GND
6 3V3
Note:
1. GPIO2 is used to enable external oscillator of the PHY.
2. GPIO0 is a source of 50 MHz reference clock for the PHY. The clock signal is first inverted, to account for
transmission line delay, and then supplied to the PHY.
3. To prevent affecting the power-on state of GPIO0 by the clock output on the PHY side, the PHY external
oscillator is enabled using GPIO2 after ESP32 is powered up.
4. The ESP32 pins GPIO16 and GPIO17 are not broken out to the ESP32-WROVER-B module and therefore
not available for use. If you need to use these pins, please solder a module without SPIRAM memory inside,
e.g. the ESP32-WROOM-32D or ESP32-SOLO-1.
Start Application Development Before powering up your ESP32-Ethernet-Kit, please make sure that the board
is in good condition with no obvious signs of damage.
Initial Setup
1. Set the Function Switch on the Ethernet board (A) to its default position by turning all the switches to ON.
2. To simplify flashing and testing the application, do not install any jumpers and do not connect any signals to
the board headers.
3. The PoE board (B) can now be plugged in, but do not connect external power to it.
4. Connect the Ethernet board (A) to the PC with a USB cable.
5. Turn the Power Switch from GND to 5V0 position, the 5V Power On LED should light up.
Now to Development Proceed to Get Started, where Section Installation will quickly help you set up the develop-
ment environment and then flash an example project onto your board.
To use the older GNU Make compilation system, please refer to Installation section.
Move on to the next section only if you have successfully completed all the above steps.
Configure and Load the Ethernet Example After setting up the development environment and testing the board,
you can configure and flash the ethernet/basic example. This example has been created for testing Ethernet function-
ality. It supports different PHY, including IP101GRI installed on ESP32-Ethernet-Kit V1.0 board.
Related Documents
• ESP32-Ethernet-Kit V1.0 Ethernet board (A) schematic (PDF)
• ESP32-Ethernet-Kit V1.0 PoE board (B) schematic (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROVER-B Datasheet (PDF)
• JTAG Debugging
• ESP32 Hardware Reference
For other design documentation for the board, please contact us at [email protected].
Functionality Overview The block diagram below shows the main components of ESP32-Ethernet-Kit and their
interconnections.
Functional Description The following figures and tables describe the key components, interfaces, and controls of
the ESP32-Ethernet-Kit.
Ethernet Board (A) The table below provides description starting from the picture’s top right corner and going
clockwise.
PoE Board (B) This board coverts power delivered over the Ethernet cable (PoE) to provide a power supply for the
Ethernet board (A). The main components of the PoE board (B) are shown on the block diagram under Functionality
Overview.
The PoE board (B) has the following features:
• Support for IEEE 802.3at
• Power output: 5 V, 1.4 A
To take advantage of the PoE functionality the RJ45 Port of the Ethernet board (A) should be connected with an
Ethernet cable to a switch that supports PoE. When the Ethernet board (A) detects 5 V power output from the PoE
board (B), the USB power will be automatically cut off.
Setup Options This section describes options to configure the ESP32-Ethernet-Kit hardware.
Function Switch When in On position, this DIP switch is routing listed GPIOs to FT2232H to provide JTAG
functionality. When in Off position, the GPIOs may be used for other purposes.
Note: Placement of GPIO pin number marking on the board’s silkscreen besides the DIP switch is incorrect.
Please use instead the pin order as in the table above.
RMII Clock Selection The ethernet MAC and PHY under RMII working mode need a common 50 MHz reference
clock (i.e. RMII clock) that can be provided either externally, or generated from internal ESP32 APLL.
Note: For additional information on the RMII clock selection, please refer to ESP32-Ethernet-Kit V1.1 Ethernet
board (A) schematic, sheet 2, location D2.
RMII Clock Sourced Externally by PHY By default, the ESP32-Ethernet-Kit is configured to provide RMII
clock for the IP101GRI PHY’s 50M_CLKO output. The clock signal is generated by the frequency multiplication
of 25 MHz crystal connected to the PHY. For details, please see the figure below.
Please note that the PHY is reset on power up by pulling the RESET_N signal down with a resistor. ESP32 should
assert RESET_N high with GPIO5 to enable PHY. Only this can ensure the power-up of system. Otherwise ESP32
may enter download mode (when the clock signal of REF_CLK_50M is at a high logic level during the GPIO0
power-up sampling phase).
RMII Clock Sourced Internally from ESP32’s APLL Another option is to source the RMII Clock from internal
ESP32 APLL, see figure below. The clock signal coming from GPIO0 is first inverted, to account for transmission
line delay, and then supplied to the PHY.
To implement this option, users need to remove or add some RC components on the board. For details please refer
to ESP32-Ethernet-Kit V1.1 Ethernet board (A) schematic, sheet 2, location D2. Please note that if the APLL is
already used for other purposes (e.g. I2S peripheral), then you have no choice but use an external RMII clock.
GPIO Allocation This section describes allocation of ESP32 GPIOs to specific interfaces or functions of the
ESP32-Ethernet-Kit.
IP101GRI (PHY) Interface The allocation of the ESP32 (MAC) pins to IP101GRI (PHY) is shown in the table
below. Implementation of ESP32-Ethernet-Kit defaults to Reduced Media-Independent Interface (RMII).
Note: Except for REF_CLK, the allocation of all pins under the ESP32’s RMII Interface is fixed and cannot be
changed either through IOMUX or GPIO Matrix.
GPIO Header 1 This header exposes some GPIOs that are not used elsewhere on the ESP32-Ethernet-Kit.
. ESP32 Pin
1 GPIO32
2 GPIO33
3 GPIO34
4 GPIO35
5 GPIO36
6 GPIO39
GPIO Header 2 This header contains GPIOs that may be used for other purposes depending on scenarios described
in column “Comments”.
Note:
1. The ESP32 pins GPIO16 and GPIO17 are not broken out to the ESP32-WROVER-B module and therefore
not available for use. If you need to use these pins, please solder a module without PSRAM memory inside,
e.g. the ESP32-WROOM-32D or ESP32-SOLO-1.
2. Functionality depends on the settings of the Function Switch.
Note:
1. To prevent the power-on state of the GPIO0 from being affected by the clock output on the PHY side, the
RESET_N signal to PHY defaults to low, turning the clock output off. After power-on you can control RE-
SET_N with GPIO5 to turn the clock output on. See also RMII Clock Sourced Externally by PHY. For PHYs
that cannot turn off the clock output through RESET_N, it is recommended to use a crystal module that can be
disabled / enabled externally. Similarly like when using RESET_N, the oscillator module should be disabled
by default and turned on by ESP32 after power-up. For a reference design please see ESP32-Ethernet-Kit
V1.1 Ethernet board (A) schematic.
2. The ESP32 pins GPIO16 and GPIO17 are not broken out to the ESP32-WROVER-B module and therefore
not available for use. If you need to use these pins, please solder a module without PSRAM memory inside,
e.g. the ESP32-WROOM-32D or ESP32-SOLO-1.
Start Application Development Before powering up your ESP32-Ethernet-Kit, please make sure that the board
is in good condition with no obvious signs of damage.
Initial Setup
1. Set the Function Switch on the Ethernet board (A) to its default position by turning all the switches to ON.
2. To simplify flashing and testing of the application, do not input extra signals to the board headers.
3. The PoE board (B) can now be plugged in, but do not connect external power to it.
4. Connect the Ethernet board (A) to the PC with a USB cable.
5. Turn the Power Switch from GND to 5V0 position, the 5V Power On LED should light up.
Now to Development Proceed to Get Started, where Section Installation will quickly help you set up the develop-
ment environment and then flash an example project onto your board.
Move on to the next section only if you have successfully completed all the above steps.
Configure and Load the Ethernet Example After setting up the development environment and testing the board,
you can configure and flash the ethernet/basic example. This example has been created for testing Ethernet function-
ality. It supports different PHY, including IP101GRI installed on ESP32-Ethernet-Kit V1.1.
Related Documents
• ESP32-Ethernet-Kit V1.1 Ethernet board (A) schematic (PDF)
• ESP32-Ethernet-Kit V1.0 PoE board (B) schematic (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROVER-B Datasheet (PDF)
• JTAG Debugging
• ESP32 Hardware Reference
For other design documentation for the board, please contact us at [email protected].
ESP32-DevKitS(-R)
This user guide provides information on ESP32-DevKitS(-R), an ESP32-based flashing board produced by Espressif.
ESP32-DevKitS(-R) is a combination of two board names: ESP32-DevKitS and ESP32-DevKitS-R. S stands for
springs, and R stands for WROVER.
ESP32-DevKitS ESP32-DevKitS-R
Getting Started This section describes how to get started with ESP32-DevKitS(-R). It begins with a few introduc-
tory sections about ESP32-DevKitS(-R), then Section How to Flash a Board provides instructions on how to mount
a module onto ESP32-DevKitS(-R), get it ready, and flash firmware onto it.
Overview ESP32-DevKitS(-R) is Espressif’s flashing board designed specifically for ESP32. It can be used to
flash an ESP32 module without soldering the module to the power supply and signal lines. With a module mounted,
ESP32-DevKitS(-R) can also be used as a mini development board like ESP32-DevKitC.
ESP32-DevKitS and ESP32-DevKitS-R boards vary only in layout of spring pins to fit the following ESP32 modules.
• ESP32-DevKitS:
– ESP32-WROOM-32
– ESP32-WROOM-32D
– ESP32-WROOM-32U
– ESP32-SOLO-1
– ESP32-WROOM-32E
– ESP32-WROOM-32UE
• ESP32-DevKitS-R:
– ESP32-WROVER (PCB & IPEX)
– ESP32-WROVER-B (PCB & IPEX)
– ESP32-WROVER-E
– ESP32-WROVER-IE
For information about above modules, please refer to ESP32 Series Modules.
Description of Components
How to Flash a Board Before powering up your ESP32-DevKitS(-R), please make sure that it is in good condition
with no obvious signs of damage.
Required Hardware
• An ESP32 module of your choice
• USB 2.0 cable (Standard-A to Micro-B)
• Computer running Windows, Linux, or macOS
Hardware Setup Please mount a module of your choice onto your ESP32-DevKitS(-R) according to the following
steps:
• Gently put your module on the ESP32-DevKitS(-R) board. Make sure that castellated holes on your module
are aligned with spring pins on the board.
• Press your module down into the board until it clicks.
• Check whether all spring pins are inserted into castellated holes. If there are some misaligned spring pins,
place them into castellated holes with tweezers.
Software Setup
Preferred Method The ESP-IDF development framework provides a preferred way of flashing binaries onto
ESP32-DevKitS(-R). Please proceed to Get Started, where Section Installation will quickly help you set up the de-
velopment environment and then flash an application example onto your ESP32-DevKitS(-R).
Alternative Method As an alternative, Windows users can flash binaries using the Flash Download Tool. Just
download it, unzip it, and follow the instructions inside the doc folder.
Note:
1. To flash binary files, ESP32 should be set to Firmware Download mode. This can be done either
by the flash tool automatically, or by holding down the Boot button and tapping the EN button.
2. After flashing binary files, the Flash Download Tool restarts your ESP32 module and boots the
flashed application by default.
Board Dimensions
Retail orders If you order a few samples, each ESP32-DevKitS(-R) comes in an individual package in either
antistatic bag or any packaging depending on a retailer.
For retail orders, please go to https://www.espressif.com/en/contact-us/get-samples.
Wholesale Orders If you order in bulk, the boards come in large cardboard boxes.
For wholesale orders, please go to https://www.espressif.com/en/contact-us/sales-questions.
Hardware Reference
Block Diagram A block diagram below shows the components of ESP32-DevKitS(-R) and their interconnections.
Power Supply Options There are three mutually exclusive ways to provide power to the board:
• Micro USB port, default power supply
• 5V and GND header pins
• 3V3 and GND header pins
It is advised to use the first option: micro USB port.
. Label Signal
L1 3V3 VDD 3V3
L2 EN CHIP_PU
L3 VP SENSOR_VP
L4 VN SENSOR_VN
L5 34 GPIO34
L6 35 GPIO35
L7 32 GPIO32
L8 33 GPIO33
continues on next page
Header Blocks For the image of header blocks, please refer to Description of Components.
Related Documents
• ESP32-DevKitS(-R) Schematics (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROOM-32 Datasheet (PDF)
• ESP32-WROOM-32D & ESP32-WROOM-32U Datasheet (PDF)
• ESP32-SOLO-1 Datasheet (PDF)
• ESP32-WROVER Datasheet (PDF)
• ESP32-WROVER-B Datasheet (PDF)
• ESP Product Selector
ESP32-PICO-KIT-1
ESP32-PICO-KIT-1 provides the users with hardware for development of applications based on the ESP32, making
it easier for users to explore ESP32 functionalities.
This guide covers:
• Getting Started: Provides an overview of the ESP32-PICO-KIT-1 and software setup instructions to get started.
• Contents and Packaging: Provides information about packaging and contents for retail and wholesale orders.
• Hardware Reference: Provides more detailed information about the ESP32-PICO-KIT-1’s hardware.
• Hardware Revision Details: Covers revision history, known issues, and links to user guides for previous versions
of the ESP32-PICO-KIT-1.
• Related Documents: Gives links to related documentation.
Getting Started This section describes how to get started with the ESP32-PICO-KIT-1. It begins with a few
introductory sections about the ESP32-PICO-KIT-1, then Section Start Application Development provides instructions
on how to flash firmware onto the ESP32-PICO-KIT-1.
Description of Components The following figure and the table below describe the key components, interfaces,
and controls of the ESP32-PICO-KIT-1 board.
Below is the description of the items identified in the figure starting from the top left corner and going clockwise.
Start Application Development Before powering up your ESP32-PICO-KIT-1, please make sure that the board
is in good condition with no obvious signs of damage.
Required Hardware
• 1 x ESP32-PICO-KIT-1
• 1 x USB 2.0 A to Micro B cable
• 1 x Computer running Windows, Linux, or macOS
Software Setup Please proceed to Get Started, where Section Installation will quickly help you set up the develop-
ment environment.
Retail Orders If you order one or several samples of the board, each ESP32-PICO-KIT-1 development board
comes in an individual package.
For retail orders, please go to https://www.espressif.com/en/contact-us/get-samples.
Wholesale Orders If you order in bulk, the boards come in large cardboard boxes.
For wholesale orders, please go to https://www.espressif.com/en/contact-us/sales-questions.
Hardware Reference
Block Diagram The block diagram below shows the main components of ESP32-PICO-KIT-1 and their intercon-
nections.
Power Supply Options There are three mutually exclusive ways to provide power to the board:
• Micro USB port, default power supply
• 5V/GND header pins
• 3V3/GND header pins
Warning: The power supply must be provided using one and only one of the options above, otherwise the
board and/or the power supply source can be damaged.
Pin Descriptions The two tables below provide the Name and Function of I/O header pins on both sides of the
board, see Description of Components. The pin numbering and header names are the same as in the schematic given
in Related Documents.
Header J2
Header J3
Note:
1. This pin is connected to the pin of the USB bridge chip on the board.
2. 32.768 kHz crystal oscillator: a) input b) output
3. The operating voltage of ESP32-PICO-KIT-1’s embedded SPI flash is 3.3 V. Therefore, the strapping pin
MTDI should be pulled down during the module power-on reset. If connected, please make sure that this pin
is not held up on reset.
Pin Layout
Related Documents
• ESP32-PICO-V3 Datasheet (PDF)
• ESP Product Selector
• ESP32-PICO-KIT-1 Schematic (PDF)
• ESP32-PICO-KIT-1 PCB Layout (PDF)
For other design documentation for the board, please contact us at [email protected].
ESP32-PICO-DevKitM-2
ESP32-PICO-DevKitM-2 provides the users with hardware for development of applications based on the ESP32,
making it easier for users to explore ESP32 functionalities.
This guide covers:
• Getting Started: Provides an overview of the ESP32-PICO-DevKitM-2 and software setup instructions to get
started.
• Contents and Packaging: Provides information about packaging and contents for retail and wholesale orders.
• Hardware Reference: Provides more detailed information about the ESP32-PICO-DevKitM-2’s hardware.
• Hardware Revision Details: Covers revision history, known issues, and links to user guides for previous versions
(if any) of the ESP32-PICO-DevKitM-2.
• Related Documents: Gives links to related documentation.
Getting Started This section describes how to get started with the ESP32-PICO-DevKitM-2. It begins with a
few introductory sections about the ESP32-PICO-DevKitM-2, then Section Start Application Development provides
instructions on how to flash firmware onto the ESP32-PICO-DevKitM-2.
Description of Components The following figure and the table below describe the key components, interfaces,
and controls of the ESP32-PICO-DevKitM-2 board. We take the board with a ESP32-PICO-MINI-02 module as an
example in the following sections.
Below is the description of the items identified in the figure starting from the top left corner and going clockwise.
Start Application Development Before powering up your ESP32-PICO-DevKitM-2, please make sure that the
board is in good condition with no obvious signs of damage.
Required Hardware
• 1 x ESP32-PICO-DevKitM-2
• 1 x USB 2.0 A to Micro B cable
• 1 x Computer running Windows, Linux, or macOS
Software Setup Please proceed to Get Started, where Section Installation will quickly help you set up the develop-
ment environment.
Retail Orders If you order one or several samples of the board, each ESP32-PICO-DevKitM-2 development board
comes in an individual package.
For retail orders, please go to https://www.espressif.com/en/contact-us/get-samples.
Wholesale Orders If you order in bulk, the boards come in large cardboard boxes.
For wholesale orders, please go to https://www.espressif.com/en/contact-us/sales-questions.
Hardware Reference
Block Diagram The block diagram below shows the main components of ESP32-PICO-DevKitM-2 and their
interconnections.
Power Supply Options There are three mutually exclusive ways to provide power to the board:
• Micro USB port, default power supply
• 5V/GND header pins
• 3V3/GND header pins
Warning: The power supply must be provided using one and only one of the options above, otherwise the
board and/or the power supply source can be damaged.
Pin Descriptions The two tables below provide the Name and Function of I/O header pins on both sides of the
board, see Description of Components. The pin numbering and header names are the same as in the schematic given
in Related Documents.
Header J2
Header J3
Note:
1. This pin is connected to the pin of the USB bridge chip on the board.
2. 32.768 kHz crystal oscillator: a) input b) output
3. The operating voltage of ESP32-PICO-DevKitM-2’s embedded SPI flash is 3.3 V. Therefore, the strapping
pin MTDI should be pulled down during the module power-on reset. If connected, please make sure that this
pin is not held up on reset.
Pin Layout
Related Documents
• ESP32-PICO-MINI-02 & ESP32-PICO-MINI-1U Datasheet (PDF)
• ESP Product Selector
• ESP32-PICO-DevKitM-2 Schematic (PDF)
• ESP32-PICO-DevKitM-2 PCB Layout (PDF)
For other design documentation for the board, please contact us at [email protected].
ESP32-DevKitM-1
This user guide will help you get started with ESP32-DevKitM-1 and will also provide more in-depth information.
ESP32-DevKitM-1 is an ESP32-MINI-1(1U)-based development board produced by Espressif. Most of the I/O pins
are broken out to the pin headers on both sides for easy interfacing. Users can either connect peripherals with jumper
wires or mount ESP32-DevKitM-1 on a breadboard.
Getting Started This section describes how to get started with ESP32-DevKitM-1. It begins with a few introduc-
tory sections about the ESP32-DevKitM-1, then Section Start Application Development provides instructions on how
to do the initial hardware setup and then how to flash firmware onto the ESP32-DevKitM-1.
Retail orders If you order a few samples, each ESP32-DevKitM-1 comes in an individual package in either anti-
static bag or any packaging depending on your retailer.
For retail orders, please go to https://www.espressif.com/en/contact-us/get-samples.
Wholesale Orders If you order in bulk, the boards come in large cardboard boxes.
For wholesale orders, please go to https://www.espressif.com/en/contact-us/sales-questions.
Description of Components The following figure and the table below describe the key components, interfaces and
controls of the ESP32-DevKitM-1 board. We take the board with a ESP32-MINI-1 module as an example in the
following sections.
Start Application Development Before powering up your ESP32-DevKitM-1, please make sure that it is in good
condition with no obvious signs of damage.
Required Hardware
• ESP32-DevKitM-1
• USB 2.0 cable (Standard-A to Micro-B)
• Computer running Windows, Linux, or macOS
Software Setup Please proceed to Get Started, where Section Installation will quickly help you set up the develop-
ment environment and then flash an application example onto your ESP32-DevKitM-1.
Attention: ESP32-DevKitM-1 is a board with a single core module, please enable single core mode (CON-
FIG_FREERTOS_UNICORE) in menuconfig before flashing your applications.
Hardware Reference
Block Diagram A block diagram below shows the components of ESP32-DevKitM-1 and their interconnections.
Power Source Select There are three mutually exclusive ways to provide power to the board:
• Micro USB port, default power supply
• 5V and GND header pins
• 3V3 and GND header pins
Warning:
• The power supply must be provided using one and only one of the options above, otherwise the board
and/or the power supply source can be damaged.
• Power supply by micro USB port is recommended.
Pin Descriptions The table below provides the Name and Function of pins on both sides of the board. For pe-
ripheral pin configurations, please refer to ESP32 Datasheet.
Related Documents
• ESP32-MINI-1 & ESP32-MINI-1U Datasheet (PDF)
• ESP32-DevKitM-1 Schematics (PDF)
• ESP32-DevKitM-1 PCB layout (PDF)
• ESP32-DevKitM-1 layout (DXF) - You can view it with Autodesk Viewer online
• ESP32 Datasheet (PDF)
• ESP Product Selector
For other design documentation for the board, please contact us at [email protected].
1.2.2 Software
1.3 Installation
To install all the required software, we offer some different ways to facilitate this task. Choose from one of the
available options.
1.3.1 IDE
Note: We highly recommend installing the ESP-IDF through your favorite IDE.
ESP-IDF V4.0 has a new CMake-based build system as the default build system.
There is a new ESP-IDF Eclipse Plugin that works with the CMake-based build system. Please refer to Espressif
IDF Eclipse Plugins IDF for further instructions.
Note: In Espressif IDF Eclipse Plugins, though screenshots are captured from macOS, installation instructions are
applicable for Windows, Linux and macOS.
We have official support for Visual Studio Code and we aim to provide complete end-to-end support for all actions
related to ESP-IDF: namely build, flash, monitor, debug, tracing, core-dump, System Trace Viewer, etc.
Quick Install Guide The recommended way to install the ESP-IDF Visual Studio Code Extension is by down-
loading it from VS Code Marketplace or following Quick Installation Guide.
Review the tutorials for the ESP-IDF Visual Studio Code Extension to learn how to use all of the features.
Supported Features
• Setup, will help you to quickly install ESP-IDF and its relevant toolchain with just a few clicks.
• Build, with one-click build and multi-target build, you can easily build and deploy your applications.
• Flash, with both UART and JTAG flash out-of-the-box.
• Monitoring, comes with a built-in terminal, you can trigger IDF Monitor Commands from within VS Code
as you are used to in traditional terminals.
• Debugging, with out-of-the-box hardware debugging.
• GUI Menu Config, provides a simplified UI for configuring your chip.
• App & Heap Tracing, provides support for collecting traces from your application, and a simplified UI for
analyzing them.
• System View Tracing Viewer, aims to read and display the .svdat files into the trace UI (we also support
multiple core tracing views).
• IDF Size Analysis Overview presents a UI for binary size analysis.
• Rainmaker Cloud, inbuilt Rainmaker Cloud support where you can edit/read the state of your connected IoT
devices easily. For more information see the ESP Rainmaker page.
• Code Coverage, inbuilt code coverage support with color highlights showing which lines have been covered.
The HTML report renders directly inside the IDE.
Bugs & Feature Requests If you face an issue with certain feature of VS Code or VS Code in general we recom-
mend you ask your question in the forum, or open a GitHub Issue for our dev teams to review.
We also welcome new feature requests. Most of the features we have today are a result of people asking for them to
be implemented. To improve certain aspects of the extension, raise your feature request on GitHub.
For the manual procedure, please select according to your operating system.
Introduction ESP-IDF requires some prerequisite tools to be installed so you can build firmware for supported
chips. The prerequisite tools include Python, Git, cross-compilers, CMake and Ninja build tools.
For this Getting Started we’re going to use the Command Prompt, but after ESP-IDF is installed you can use Eclipse
or another graphical IDE with CMake support instead.
Note: Limitations: - The installation path of ESP-IDF and ESP-IDF Tools must not be longer than 90 characters.
Too long installation paths might result in a failed build. - The installation path of Python or ESP-IDF must not contain
white spaces or parentheses. - The installation path of Python or ESP-IDF should not contain special characters (non-
ASCII) unless the operating system is configured with “Unicode UTF-8”support.
System Administrator can enable the support via Control Panel - Change date, time, or number formats - Adminis-
trative tab - Change system locale - check the option “Beta: Use Unicode UTF-8 for worldwide language support”
- Ok and reboot the computer.
ESP-IDF Tools Installer The easiest way to install ESP-IDF’s prerequisites is to download one of ESP-IDF
Tools Installers.
What is the usecase for Online and Offline Installer Online Installer is very small and allows the installation of all
available releases of ESP-IDF. The installer will download only necessary dependencies including Git For Windows
during the installation process. The installer stores downloaded files in the cache directory %userprofile%\.
espressif
Offline Installer does not require any network connection. The installer contains all required dependencies including
Git For Windows .
Launching ESP-IDF Environment At the end of the installation process you can check out option Run
ESP-IDF PowerShell Environment or Run ESP-IDF Command Prompt (cmd.exe). The
installer will launch ESP-IDF environment in selected prompt.
Run ESP-IDF PowerShell Environment:
Run ESP-IDF Command Prompt (cmd.exe):
Using the Command Prompt For the remaining Getting Started steps, we’re going to use the Windows Command
Prompt.
Fig. 52: Completing the ESP-IDF Tools Setup Wizard with Run ESP-IDF PowerShell Environment
Fig. 54: Completing the ESP-IDF Tools Setup Wizard with Run ESP-IDF Command Prompt (cmd.exe)
ESP-IDF Tools Installer also creates a shortcut in the Start menu to launch the ESP-IDF Command Prompt. This
shortcut launches the Command Prompt (cmd.exe) and runs export.bat script to set up the environment variables
(PATH, IDF_PATH and others). Inside this command prompt, all the installed tools are available.
Note that this shortcut is specific to the ESP-IDF directory selected in the ESP-IDF Tools Installer. If you have
multiple ESP-IDF directories on the computer (for example, to work with different versions of ESP-IDF), you have
two options to use them:
1. Create a copy of the shortcut created by the ESP-IDF Tools Installer, and change the working directory of the
new shortcut to the ESP-IDF directory you wish to use.
2. Alternatively, run cmd.exe, then change to the ESP-IDF directory you wish to use, and run export.bat.
Note that unlike the previous option, this way requires Python and Git to be present in PATH. If you get errors
related to Python or Git not being found, use the first option.
First Steps on ESP-IDF Now since all requirements are met, the next topic will guide you on how to start your
first project.
This guide will help you on the first steps using ESP-IDF. Follow this guide to start a new project on the ESP32 and
build, flash, and monitor the device output.
Note: If you have not yet installed ESP-IDF, please go to Installation and follow the instruction in order to get all
the software needed to use this guide.
Start a Project Now you are ready to prepare your application for ESP32. You can start with get-
started/hello_world project from examples directory in ESP-IDF.
Important: The ESP-IDF build system does not support spaces in the paths to either ESP-IDF or to projects.
cd %userprofile%\esp
xcopy /e /i %IDF_PATH%\examples\get-started\hello_world hello_world
Note: There is a range of example projects in the examples directory in ESP-IDF. You can copy any project in the
same way as presented above and run it. It is also possible to build examples in-place without copying them first.
Connect Your Device Now connect your ESP32 board to the computer and check under which serial port the
board is visible.
Serial port names start with COM in Windows.
If you are not sure how to check the serial port name, please refer to Establish Serial Connection with ESP32 for full
details.
Note: Keep the port name handy as you will need it in the next steps.
Configure Your Project Navigate to your hello_world directory, set ESP32 as the target, and run the project
configuration utility menuconfig.
Windows
cd %userprofile%\esp\hello_world
idf.py set-target esp32
idf.py menuconfig
After opening a new project, you should first set the target with idf.py set-target esp32. Note that existing
builds and configurations in the project, if any, will be cleared and initialized in this process. The target may be saved
in the environment variable to skip this step at all. See Select the Target Chip: set-target for additional information.
If the previous steps have been done correctly, the following menu appears:
You are using this menu to set up project specific variables, e.g., Wi-Fi network name and password, the processor
speed, etc. Setting up the project with menuconfig may be skipped for “hello_word”, since this example runs with
default configuration.
Attention: If you use ESP32-DevKitC board with the ESP32-SOLO-1 module, or ESP32-DevKitM-1 board
with the ESP32-MIN1-1(1U) module, please enable single core mode (CONFIG_FREERTOS_UNICORE) in
menuconfig before flashing examples.
Note: The colors of the menu could be different in your terminal. You can change the appearance with the option
--style. Please run idf.py menuconfig --help for further information.
If you are using one of the supported development boards, you can speed up your development by using Board Support
Package. See Additional Tips for more information.
idf.py build
This command will compile the application and all ESP-IDF components, then it will generate the bootloader, par-
tition table, and application binaries.
$ idf.py build
Running cmake in directory /path/to/hello_world/build
(continues on next page)
If there are no errors, the build will finish by generating the firmware binary .bin files.
Flash onto the Device Flash the binaries that you just built (bootloader.bin, partition-table.bin and hello_world.bin)
onto your ESP32 board by running:
Note: The option flash automatically builds and flashes the project, so running idf.py build is not necessary.
Encountered Issues While Flashing? If you run the given command and see errors such as“Failed to connect”,
there might be several reasons for this. One of the reasons might be issues encountered by esptool.py, the utility
that is called by the build system to reset the chip, interact with the ROM bootloader, and flash firmware. One simple
solution to try is manual reset described below, and if it does not help you can find more details about possible issues
in Troubleshooting.
esptool.py resets ESP32 automatically by asserting DTR and RTS control lines of the USB to serial converter
chip, i.e., FTDI or CP210x (for more information, see Establish Serial Connection with ESP32). The DTR and RTS
control lines are in turn connected to GPIO0 and CHIP_PU (EN) pins of ESP32, thus changes in the voltage levels
of DTR and RTS will boot ESP32 into Firmware Download mode. As an example, check the schematic for the
ESP32 DevKitC development board.
In general, you should have no problems with the official esp-idf development boards. However, esptool.py is
not able to reset your hardware automatically in the following cases:
• Your hardware does not have the DTR and RTS lines connected to GPIO0 and CHIP_PU
• The DTR and RTS lines are configured differently
• There are no such serial control lines at all
Depending on the kind of hardware you have, it may also be possible to manually put your ESP32 board into Firmware
Download mode (reset).
• For development boards produced by Espressif, this information can be found in the respective getting started
guides or user guides. For example, to manually reset an ESP-IDF development board, hold down the Boot
button (GPIO0) and press the EN button (CHIP_PU).
• For other types of hardware, try pulling GPIO0 down.
Normal Operation When flashing, you will see the output log similar to the following:
...
esptool.py --chip esp32 -p /dev/ttyUSB0 -b 460800 --before=default_reset --
,→after=hard_reset write_flash --flash_mode dio --flash_freq 40m --flash_size 2MB␣
,→0x10000 hello_world.bin
esptool.py v3.0-dev
Serial port /dev/ttyUSB0
Connecting........_
Chip is ESP32D0WDQ6 (revision 0)
Features: WiFi, BT, Dual Core, Coding Scheme None
Crystal is 40MHz
MAC: 24:0a:c4:05:b9:14
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 460800
Changed.
Configuring flash size...
Compressed 3072 bytes to 103...
Writing at 0x00008000... (100 %)
Wrote 3072 bytes (103 compressed) at 0x00008000 in 0.0 seconds (effective 5962.8␣
,→kbit/s)...
Leaving...
Hard resetting via RTS pin...
Done
If there are no issues by the end of the flash process, the board will reboot and start up the“hello_world”application.
If you’d like to use the Eclipse or VS Code IDE instead of running idf.py, check out the Eclipse guide, VS Code
guide.
Monitor the Output To check if “hello_world”is indeed running, type idf.py -p PORT monitor (Do
not forget to replace PORT with your serial port name).
This command launches the IDF Monitor application:
$ idf.py -p <PORT> monitor
Running idf_monitor in directory [...]/esp/hello_world/build
(continues on next page)
After startup and diagnostic logs scroll up, you should see “Hello world!”printed out by the application.
...
Hello world!
Restarting in 10 seconds...
This is esp32 chip with 2 CPU core(s), WiFi/BT/BLE, silicon revision 1, 2MB␣
,→external flash
Note: You can combine building, flashing and monitoring into one step by running:
See also:
• IDF Monitor for handy shortcuts and more details on using IDF monitor.
• idf.py for a full reference of idf.py commands and options.
That’s all that you need to get started with ESP32!
Now you are ready to try some other examples, or go straight to developing your own applications.
Important: Some of examples do not support ESP32 because required hardware is not included in ESP32 so it
cannot be supported.
If building an example, please check the README file for the Supported Targets table. If this is present
including ESP32 target, or the table does not exist at all, the example will work on ESP32.
Additional Tips
Permission issues /dev/ttyUSB0 With some Linux distributions, you may get the Failed to open port
/dev/ttyUSB0 error message when flashing the ESP32. This can be solved by adding the current user to the dialout
group.
Python compatibility ESP-IDF supports Python 3.7 or newer. It is recommended to upgrade your operating
system to a recent version satisfying this requirement. Other options include the installation of Python from sources
or the use of a Python version management system such as pyenv.
Start with Board Support Package To speed up prototyping on some development boards, you can use Board
Support Packages (BSPs), which makes initialization of a particular board as easy as few function calls.
A BSP typically supports all of the hardware components provided on development board. Apart from the pinout
definition and initialization functions, a BSP ships with drivers for the external components such as sensors, displays,
audio codecs etc.
The BSPs are distributed via IDF Component Manager, so they can be found in IDF Component Registry.
Here’s an example of how to add ESP-WROVER-KIT BSP to your project:
Related Documents For advanced users who want to customize the install process:
Install ESP-IDF tools using a script From the Windows Command Prompt, change to the directory where ESP-
IDF is installed. Then run:
install.bat
For Powershell, change to the directory where ESP-IDF is installed. Then run:
install.ps1
This will download and install the tools necessary to use ESP-IDF. If the specific version of the tool is already
installed, no action will be taken. The tools are downloaded and installed into a directory specified during ESP-IDF
Tools Installer process. By default, this is C:\Users\username\.espressif.
Add ESP-IDF tools to PATH using an export script ESP-IDF tools installer creates a Start menu shortcut for
“ESP-IDF Command Prompt”. This shortcut opens a Command Prompt window where all the tools are already
available.
In some cases, you may want to work with ESP-IDF in a Command Prompt window which wasn’t started using that
shortcut. If this is the case, follow the instructions below to add ESP-IDF tools to PATH.
In the command prompt where you need to use ESP-IDF, change to the directory where ESP-IDF is installed, then
execute export.bat:
cd %userprofile%\esp\esp-idf
export.bat
Alternatively in the Powershell where you need to use ESP-IDF, change to the directory where ESP-IDF is installed,
then execute export.ps1:
cd ~/esp/esp-idf
export.ps1
When this is done, the tools will be available in this command prompt.
Connect ESP32 to PC Connect the ESP32 board to the PC using the USB cable. If device driver does not install
automatically, identify USB to serial converter chip on your ESP32 board (or external converter dongle), search for
drivers in internet and install them.
Below is the list of USB to serial converter chips installed on most of the ESP32 boards produced by Espressif together
with links to the drivers:
• CP210x: CP210x USB to UART Bridge VCP Drivers
• FTDI: FTDI Virtual COM Port Drivers
Please check the board user guide for specific USB to serial converter chip used. The drivers above are primarily for
reference. Under normal circumstances, the drivers should be bundled with an operating system and automatically
installed upon connecting the board to the PC.
Check port on Windows Check the list of identified COM ports in the Windows Device Manager. Disconnect
ESP32 and connect it back, to verify which port disappears from the list and then shows back again.
Figures below show serial port for ESP32 DevKitC and ESP32 WROVER KIT
Fig. 58: Two USB Serial Ports of ESP-WROVER-KIT in Windows Device Manager
Check port on Linux and macOS To check the device name for the serial port of your ESP32 board (or external
converter dongle), run this command two times, first with the board / dongle unplugged, then with plugged in. The
port which appears the second time is the one you need:
Linux
ls /dev/tty*
macOS
ls /dev/cu.*
Note: macOS users: if you don’t see the serial port then check you have the USB/serial drivers installed. See
Section Connect ESP32 to PC for links to drivers. For macOS High Sierra (10.13), you may also have to explicitly
allow the drivers to load. Open System Preferences -> Security & Privacy -> General and check if there is a message
shown here about “System Software from developer …”where the developer name is Silicon Labs or FTDI.
Adding user to dialout on Linux The currently logged user should have read and write access the serial port
over USB. On most Linux distributions, this is done by adding the user to dialout group with the following
command:
on Arch Linux this is done by adding the user to uucp group with the following command:
Make sure you re-login to enable read and write permissions for the serial port.
Verify serial connection Now verify that the serial connection is operational. You can do this using a serial terminal
program by checking if you get any output on the terminal after resetting ESP32.
Windows and Linux In this example we will use PuTTY SSH Client that is available for both Windows and Linux.
You can use other serial programs and set communication parameters like below.
Run terminal, set identified serial port, baud rate = 115200, data bits = 8, stop bits = 1, and parity = N. Below are
example screen shots of setting the port and such transmission parameters (in short described as 115200-8-1-N) on
Windows and Linux. Remember to select exactly the same serial port you have identified in steps above.
Then open serial port in terminal and check, if you see any log printed out by ESP32. The log contents will depend
on application loaded to ESP32, see Example Output.
Note: Close the serial terminal after verification that communication is working. If you keep the terminal session
open, the serial port will be inaccessible for uploading firmware later.
macOS To spare you the trouble of installing a serial terminal program, macOS offers the screen command.
• As discussed in Check port on Linux and macOS, run:
ls /dev/cu.*
• The output will vary depending on the type and the number of boards connected to your PC. Then pick the
device name of your board and run:
Note: Do not forget to exit the screen session after verifying that the communication is working. If you fail to do
it and just close the terminal window, the serial port will be inaccessible for uploading firmware later.
Example Output An example log is shown below. Reset the board if you do not see anything.
...
If you can see readable log output, it means serial connection is working and you are ready to proceed with installation
and finally upload of application to ESP32.
Note: For some serial port wiring configurations, the serial RTS & DTR pins need to be disabled in the terminal
program before the ESP32 will boot and produce serial output. This depends on the hardware itself, most development
boards (including all Espressif boards) do not have this issue. The issue is present if RTS & DTR are wired directly
to the EN & GPIO0 pins. See the esptool documentation for more details.
If you got here from Step 5. First Steps on ESP-IDF when installing s/w for ESP32 development, then you can continue
with Step 5. First Steps on ESP-IDF.
IDF Monitor
IDF Monitor is mainly a serial terminal program which relays serial data to and from the target device’s serial port.
It also provides some IDF-specific features.
IDF Monitor can be launched from an IDF project by running idf.py monitor.
Keyboard Shortcuts For easy interaction with IDF Monitor, use the keyboard shortcuts given in the table.
Ctrl+C Interrupt running applica- Pauses IDF Monitor and run GDB project debug-
tion ger to debug the application at runtime. This requires
:ref:CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME option
to be enabled.
Any keys pressed, other than Ctrl-] and Ctrl-T, will be sent through the serial port.
IDF-specific features
Automatic Address Decoding Whenever ESP-IDF outputs a hexadecimal code address of the form
0x4_______, IDF Monitor uses addr2line_ to look up the location in the source code and find the function
name.
If an ESP-IDF app crashes and panics, a register dump and backtrace is produced, such as the following:
Register dump:
PC : 0x400f360d PS : 0x00060330 A0 : 0x800dbf56 A1 :␣
,→0x3ffb7e00
Register dump:
PC : 0x400f360d PS : 0x00060330 A0 : 0x800dbf56 A1 :␣
,→0x3ffb7e00
To decode each address, IDF Monitor runs the following command in the background:
Note: Set environment variable ESP_MONITOR_DECODE to 0 or call idf_monitor.py with specific command line
Target Reset on Connection By default, IDF Monitor will reset the target when connecting to it. The reset of the
target chip is performed using the DTR and RTS serial lines. To prevent IDF Monitor from automatically resetting the
target on connection, call IDF Monitor with the --no-reset option (e.g., idf_monitor.py --no-reset).
Note: The --no-reset option applies the same behavior even when connecting IDF Monitor to a particular port
(e.g., idf.py monitor --no-reset -p [PORT]).
Launching GDB with GDBStub GDBStub is a useful runtime debugging feature that runs on the target and
connects to the host over the serial port to receive debugging commands. GDBStub supports commands such as
reading memory and variables, examining call stack frames etc. Although GDBStub is less versatile than JTAG
debugging, it does not require any special hardware (such as a JTAG to USB bridge) as communication is done
entirely over the serial port.
A target can be configured to run GDBStub in the background by setting the CONFIG_ESP_SYSTEM_PANIC to
GDBStub on runtime. GDBStub will run in the background until a Ctrl+C message is sent over the serial
port and causes the GDBStub to break (i.e., stop the execution of) the program, thus allowing GDBStub to handle
debugging commands.
Furthermore, the panic handler can be configured to run GDBStub on a crash by setting the CON-
FIG_ESP_SYSTEM_PANIC to GDBStub on panic. When a crash occurs, GDBStub will output a special string
pattern over the serial port to indicate that it is running.
In both cases (i.e., sending the Ctrl+C message, or receiving the special string pattern), IDF Monitor will automat-
ically launch GDB in order to allow the user to send debugging commands. After GDB exits, the target is reset via
the RTS serial line. If this line is not connected, users can reset their target (by pressing the board’s Reset button).
Note: In the background, IDF Monitor runs the following command to launch GDB:
xtensa-esp32-elf-gdb -ex "set serial baud BAUD" -ex "target remote PORT" -ex␣
,→interrupt build/PROJECT.elf :idf_target:`Hello NAME chip`
Output Filtering IDF monitor can be invoked as idf.py monitor --print-filter="xyz", where
--print-filter is the parameter for output filtering. The default value is an empty string, which means that
everything is printed.
Restrictions on what to print can be specified as a series of <tag>:<log_level> items where <tag> is the tag
string and <log_level> is a character from the set {N, E, W, I, D, V, *} referring to a level for logging.
For example, PRINT_FILTER="tag1:W" matches and prints only the outputs written with
ESP_LOGW("tag1", ...) or at lower verbosity level, i.e. ESP_LOGE("tag1", ...). Not speci-
fying a <log_level> or using * defaults to Verbose level.
Note: Use primary logging to disable at compilation the outputs you do not need through the logging library. Output
filtering with IDF monitor is a secondary solution which can be useful for adjusting the filtering options without
recompiling the application.
Your app tags must not contain spaces, asterisks *, or colons : to be compatible with the output filtering feature.
If the last line of the output in your app is not followed by a carriage return, the output filtering might get confused, i.e.,
the monitor starts to print the line and later finds out that the line should not have been written. This is a known issue
and can be avoided by always adding a carriage return (especially when no output follows immediately afterwards).
A More Complex Filtering Example The following log snippet was acquired without any filtering options:
load:0x40078000,len:13564
entry 0x40078d4c
E (31) esp_image: image at 0x30000 has invalid magic byte
W (31) esp_image: image at 0x30000 has invalid SPI mode 255
E (39) boot: Factory app partition is not bootable
I (568) cpu_start: Pro cpu up.
I (569) heap_init: Initializing. RAM available for dynamic allocation:
I (603) cpu_start: Pro cpu start user code
D (309) light_driver: [light_init, 74]:status: 1, mode: 2
D (318) vfs: esp_vfs_register_fd_range is successful for range <54; 64) and VFS ID␣
,→1
The captured output for the filtering options PRINT_FILTER="wifi esp_image:E light_driver:I"
is given below:
load:0x40078000,len:13564
entry 0x40078d4c
I (569) heap_init: Initializing. RAM available for dynamic allocation:
D (309) light_driver: [light_init, 74]:status: 1, mode: 2
Installation Step by Step This is a detailed roadmap to walk you through the installation process.
Setting up Development Environment These are the steps for setting up the ESP-IDF for your ESP32.
• Step 1. Install Prerequisites
• Step 2. Get ESP-IDF
• Step 3. Set up the tools
• Step 4. Set up the environment variables
• Step 5. First Steps on ESP-IDF
Step 1. Install Prerequisites In order to use ESP-IDF with the ESP32, you need to install some software packages
based on your Operating System. This setup guide will help you on getting everything installed on Linux and macOS
based systems.
For Linux Users To compile using ESP-IDF you will need to get the following packages. The command to run
depends on which distribution of Linux you are using:
• Ubuntu and Debian:
sudo apt-get install git wget flex bison gperf python3 python3-venv cmake␣
,→ninja-build ccache libffi-dev libssl-dev dfu-util libusb-1.0-0
• CentOS 7 & 8:
sudo yum -y update && sudo yum install git wget flex bison gperf python3 cmake␣
,→ninja-build ccache dfu-util libusbx
CentOS 7 is still supported but CentOS version 8 is recommended for a better user experience.
• Arch:
sudo pacman -S --needed gcc git make flex bison gperf python cmake ninja␣
,→ccache dfu-util libusb
Note:
• CMake version 3.16 or newer is required for use with ESP-IDF. Run “tools/idf_tools.py install cmake”to
install a suitable version if your OS versions doesn’t have one.
• If you do not see your Linux distribution in the above list then please check its documentation to find out which
command to use for package installation.
For macOS Users ESP-IDF will use the version of Python installed by default on macOS.
• Install CMake & Ninja build:
– If you have HomeBrew, you can run:
– Otherwise, consult the CMake and Ninja home pages for macOS installation downloads.
• It is strongly recommended to also install ccache for faster builds. If you have HomeBrew, this can be done
via brew install ccache or sudo port install ccache on MacPorts.
Then you will need to install the XCode command line tools to continue. You can install these by running
xcode-select --install.
Installing Python 3 Based on macOS Catalina 10.15 release notes, use of Python 2.7 is not recommended and
Python 2.7 will not be included by default in future versions of macOS. Check what Python you currently have:
python --version
If the output is like Python 2.7.17, your default interpreter is Python 2.7. If so, also check if Python 3 isn’t
already installed on your computer:
python3 --version
Step 2. Get ESP-IDF To build applications for the ESP32, you need the software libraries provided by Espressif
in ESP-IDF repository.
To get ESP-IDF, navigate to your installation directory and clone the repository with git clone, following in-
structions below specific to your operating system.
Open Terminal, and run the following commands:
mkdir -p ~/esp
cd ~/esp
git clone --recursive https://github.com/espressif/esp-idf.git
Step 3. Set up the tools Aside from the ESP-IDF, you also need to install the tools used by ESP-IDF, such as the
compiler, debugger, Python packages, etc, for projects supporting ESP32.
cd ~/esp/esp-idf
./install.sh esp32
cd ~/esp/esp-idf
./install.fish esp32
The above commands install tools for ESP32 only. If you intend to develop projects for more chip targets then you
should list all of them and run for example:
cd ~/esp/esp-idf
./install.sh esp32,esp32s2
cd ~/esp/esp-idf
./install.fish esp32,esp32s2
In order to install tools for all supported targets please run the following command:
cd ~/esp/esp-idf
./install.sh all
cd ~/esp/esp-idf
./install.fish all
Alternative File Downloads The tools installer downloads a number of files attached to GitHub Releases. If
accessing GitHub is slow then it is possible to set an environment variable to prefer Espressif’s download server for
GitHub asset downloads.
Note: This setting only controls individual tools downloaded from GitHub releases, it doesn’t change the URLs
used to access any Git repositories.
To prefer the Espressif download server when installing tools, use the following sequence of commands when running
install.sh:
cd ~/esp/esp-idf
export IDF_GITHUB_ASSETS="dl.espressif.com/github_assets"
./install.sh
Customizing the tools installation path The scripts introduced in this step install compilation tools required by
ESP-IDF inside the user home directory: $HOME/.espressif on Linux. If you wish to install the tools into a
different directory, set the environment variable IDF_TOOLS_PATH before running the installation scripts. Make
sure that your user account has sufficient permissions to read and write this path.
If changing the IDF_TOOLS_PATH, make sure it is set to the same value every time the Install script (install.
bat, install.ps1 or install.sh) and an Export script (export.bat, export.ps1 or export.sh)
are executed.
Step 4. Set up the environment variables The installed tools are not yet added to the PATH environment variable.
To make the tools usable from the command line, some environment variables must be set. ESP-IDF provides another
script which does that.
In the terminal where you are going to use ESP-IDF, run:
. $HOME/esp/esp-idf/export.sh
. $HOME/esp/esp-idf/export.fish
Note the space between the leading dot and the path!
If you plan to use esp-idf frequently, you can create an alias for executing export.sh:
1. Copy and paste the following command to your shell’s profile (.profile, .bashrc, .zprofile, etc.)
2. Refresh the configuration by restarting the terminal session or by running source [path to profile],
for example, source ~/.bashrc.
Now you can run get_idf to set up or refresh the esp-idf environment in any terminal session.
Technically, you can add export.sh to your shell’s profile directly; however, it is not recommended. Doing so
activates IDF virtual environment in every terminal session (including those where IDF is not needed), defeating the
purpose of the virtual environment and likely affecting other software.
Step 5. First Steps on ESP-IDF Now since all requirements are met, the next topic will guide you on how to start
your first project.
This guide will help you on the first steps using ESP-IDF. Follow this guide to start a new project on the ESP32 and
build, flash, and monitor the device output.
Note: If you have not yet installed ESP-IDF, please go to Installation and follow the instruction in order to get all
the software needed to use this guide.
Start a Project Now you are ready to prepare your application for ESP32. You can start with get-
started/hello_world project from examples directory in ESP-IDF.
Important: The ESP-IDF build system does not support spaces in the paths to either ESP-IDF or to projects.
cd ~/esp
cp -r $IDF_PATH/examples/get-started/hello_world .
Note: There is a range of example projects in the examples directory in ESP-IDF. You can copy any project in the
same way as presented above and run it. It is also possible to build examples in-place without copying them first.
Connect Your Device Now connect your ESP32 board to the computer and check under which serial port the
board is visible.
Serial ports have the following naming patterns:
• Linux: starting with /dev/tty
• macOS: starting with /dev/cu.
If you are not sure how to check the serial port name, please refer to Establish Serial Connection with ESP32 for full
details.
Note: Keep the port name handy as you will need it in the next steps.
Configure Your Project Navigate to your hello_world directory, set ESP32 as the target, and run the project
configuration utility menuconfig.
cd ~/esp/hello_world
idf.py set-target esp32
idf.py menuconfig
After opening a new project, you should first set the target with idf.py set-target esp32. Note that existing
builds and configurations in the project, if any, will be cleared and initialized in this process. The target may be saved
in the environment variable to skip this step at all. See Select the Target Chip: set-target for additional information.
If the previous steps have been done correctly, the following menu appears:
You are using this menu to set up project specific variables, e.g., Wi-Fi network name and password, the processor
speed, etc. Setting up the project with menuconfig may be skipped for “hello_word”, since this example runs with
default configuration.
Attention: If you use ESP32-DevKitC board with the ESP32-SOLO-1 module, or ESP32-DevKitM-1 board
with the ESP32-MIN1-1(1U) module, please enable single core mode (CONFIG_FREERTOS_UNICORE) in
menuconfig before flashing examples.
Note: The colors of the menu could be different in your terminal. You can change the appearance with the option
--style. Please run idf.py menuconfig --help for further information.
If you are using one of the supported development boards, you can speed up your development by using Board Support
Package. See Additional Tips for more information.
idf.py build
This command will compile the application and all ESP-IDF components, then it will generate the bootloader, par-
tition table, and application binaries.
$ idf.py build
Running cmake in directory /path/to/hello_world/build
Executing "cmake -G Ninja --warn-uninitialized /path/to/hello_world"...
Warn about uninitialized values.
-- Found Git: /usr/bin/git (found version "2.17.0")
-- Building empty aws_iot component due to configuration
-- Component names: ...
-- Component paths: ...
If there are no errors, the build will finish by generating the firmware binary .bin files.
Flash onto the Device Flash the binaries that you just built (bootloader.bin, partition-table.bin and hello_world.bin)
onto your ESP32 board by running:
Note: The option flash automatically builds and flashes the project, so running idf.py build is not necessary.
Encountered Issues While Flashing? If you run the given command and see errors such as“Failed to connect”,
there might be several reasons for this. One of the reasons might be issues encountered by esptool.py, the utility
that is called by the build system to reset the chip, interact with the ROM bootloader, and flash firmware. One simple
solution to try is manual reset described below, and if it does not help you can find more details about possible issues
in Troubleshooting.
esptool.py resets ESP32 automatically by asserting DTR and RTS control lines of the USB to serial converter
chip, i.e., FTDI or CP210x (for more information, see Establish Serial Connection with ESP32). The DTR and RTS
control lines are in turn connected to GPIO0 and CHIP_PU (EN) pins of ESP32, thus changes in the voltage levels
of DTR and RTS will boot ESP32 into Firmware Download mode. As an example, check the schematic for the
ESP32 DevKitC development board.
In general, you should have no problems with the official esp-idf development boards. However, esptool.py is
not able to reset your hardware automatically in the following cases:
• Your hardware does not have the DTR and RTS lines connected to GPIO0 and CHIP_PU
• The DTR and RTS lines are configured differently
• There are no such serial control lines at all
Depending on the kind of hardware you have, it may also be possible to manually put your ESP32 board into Firmware
Download mode (reset).
• For development boards produced by Espressif, this information can be found in the respective getting started
guides or user guides. For example, to manually reset an ESP-IDF development board, hold down the Boot
button (GPIO0) and press the EN button (CHIP_PU).
• For other types of hardware, try pulling GPIO0 down.
Normal Operation When flashing, you will see the output log similar to the following:
...
esptool.py --chip esp32 -p /dev/ttyUSB0 -b 460800 --before=default_reset --
,→after=hard_reset write_flash --flash_mode dio --flash_freq 40m --flash_size 2MB␣
,→0x10000 hello_world.bin
esptool.py v3.0-dev
Serial port /dev/ttyUSB0
Connecting........_
Chip is ESP32D0WDQ6 (revision 0)
Features: WiFi, BT, Dual Core, Coding Scheme None
Crystal is 40MHz
MAC: 24:0a:c4:05:b9:14
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 460800
Changed.
Configuring flash size...
Compressed 3072 bytes to 103...
Writing at 0x00008000... (100 %)
Wrote 3072 bytes (103 compressed) at 0x00008000 in 0.0 seconds (effective 5962.8␣
,→kbit/s)...
Leaving...
Hard resetting via RTS pin...
Done
If there are no issues by the end of the flash process, the board will reboot and start up the“hello_world”application.
If you’d like to use the Eclipse or VS Code IDE instead of running idf.py, check out the Eclipse guide, VS Code
guide.
Monitor the Output To check if “hello_world”is indeed running, type idf.py -p PORT monitor (Do
not forget to replace PORT with your serial port name).
This command launches the IDF Monitor application:
$ idf.py -p <PORT> monitor
Running idf_monitor in directory [...]/esp/hello_world/build
(continues on next page)
After startup and diagnostic logs scroll up, you should see “Hello world!”printed out by the application.
...
Hello world!
Restarting in 10 seconds...
This is esp32 chip with 2 CPU core(s), WiFi/BT/BLE, silicon revision 1, 2MB␣
,→external flash
Note: You can combine building, flashing and monitoring into one step by running:
See also:
• IDF Monitor for handy shortcuts and more details on using IDF monitor.
• idf.py for a full reference of idf.py commands and options.
That’s all that you need to get started with ESP32!
Now you are ready to try some other examples, or go straight to developing your own applications.
Important: Some of examples do not support ESP32 because required hardware is not included in ESP32 so it
cannot be supported.
If building an example, please check the README file for the Supported Targets table. If this is present
including ESP32 target, or the table does not exist at all, the example will work on ESP32.
Additional Tips
Permission issues /dev/ttyUSB0 With some Linux distributions, you may get the Failed to open port
/dev/ttyUSB0 error message when flashing the ESP32. This can be solved by adding the current user to the dialout
group.
Python compatibility ESP-IDF supports Python 3.7 or newer. It is recommended to upgrade your operating
system to a recent version satisfying this requirement. Other options include the installation of Python from sources
or the use of a Python version management system such as pyenv.
Start with Board Support Package To speed up prototyping on some development boards, you can use Board
Support Packages (BSPs), which makes initialization of a particular board as easy as few function calls.
A BSP typically supports all of the hardware components provided on development board. Apart from the pinout
definition and initialization functions, a BSP ships with drivers for the external components such as sensors, displays,
audio codecs etc.
The BSPs are distributed via IDF Component Manager, so they can be found in IDF Component Registry.
Here’s an example of how to add ESP-WROVER-KIT BSP to your project:
Tip: Updating ESP-IDF It is recommended to update ESP-IDF from time to time, as newer versions fix bugs
and/or provide new features. Please note that each ESP-IDF major and minor release version has an associated
support period, and when one release branch is approaching end of life (EOL), all users are encouraged to upgrade
their projects to more recent ESP-IDF releases, to find out more about support periods, see ESP-IDF Versions.
The simplest way to do the update is to delete the existing esp-idf folder and clone it again, as if performing the
initial installation described in Step 2. Get ESP-IDF.
Another solution is to update only what has changed. The update procedure depends on the version of ESP-IDF you
are using.
After updating ESP-IDF, execute the Install script again, in case the new ESP-IDF version requires different versions
of tools. See instructions at Step 3. Set up the tools.
Once the new tools are installed, update the environment using the Export script. See instructions at Step 4. Set up
the environment variables.
Related Documents
API Reference
Most ESP-IDF APIs return error codes defined with esp_err_t type. See Error Handling section for more infor-
mation about error handling approaches. Error Code Reference contains the list of error codes returned by ESP-IDF
components.
Important: Correct initialization of configuration structures is an important part in making the application com-
patible with future versions of ESP-IDF.
Most initialization or configuration functions in ESP-IDF take as an argument a pointer to a configuration structure.
For example:
121
Chapter 2. API Reference
Initialization functions never store the pointer to the configuration structure, so it is safe to allocate the structure on
the stack.
The application must initialize all fields of the structure. The following is incorrect:
esp_timer_create_args_t my_timer_args;
my_timer_args.callback = &my_timer_callback;
/* Incorrect! Fields .arg and .name are not initialized */
esp_timer_create(&my_timer_args, &my_timer);
Most ESP-IDF examples use C99 designated initializers for structure initialization, since they provide a concise way
of setting a subset of fields, and zero-initializing the remaining fields:
const esp_timer_create_args_t my_timer_args = {
.callback = &my_timer_callback,
/* Correct, fields .arg and .name are zero-initialized */
};
C++ language doesn’t support the designated initializers syntax until C++20, however GCC compiler partially
supports it as an extension. When using ESP-IDF APIs in C++ code, you may consider using the following pattern:
esp_timer_create_args_t my_timer_args = {};
/* All the fields are zero-initialized */
my_timer_args.callback = &my_timer_callback;
Default initializers
For some configuration structures, ESP-IDF provides macros for setting default values of fields:
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
/* HTTPD_DEFAULT_CONFIG expands to a designated initializer.
Now all fields are set to the default values.
Any field can still be modified: */
config.server_port = 8081;
httpd_handle_t server;
esp_err_t err = httpd_start(&server, &config);
It is recommended to use default initializer macros whenever they are provided for a particular configuration structure.
Certain header files in ESP-IDF contain APIs intended to be used only in ESP-IDF source code, and not by the appli-
cations. Such header files often contain private or esp_private in their name or path. Certain components,
such as hal only contain private APIs.
Private APIs may be removed or changed in an incompatible way between minor or patch releases.
ESP-IDF examples contain a variety of projects demonstrating usage of ESP-IDF APIs. In order to reduce code
duplication in the examples, a few common helpers are defined inside components that are used by multiple examples.
This includes components located in common_components directory, as well as some of the components located in
the examples themselves. These components are not considered to be part of the ESP-IDF API.
It is not recommended to reference these components directly in custom projects (via EXTRA_COMPONENT_DIRS
build system variable), as they may change significantly between ESP-IDF versions. When starting a new project
based on an ESP-IDF example, copy both the project and the common components it depends on out of ESP-IDF,
and treat the common components as part of the project. Note that the common components are written with examples
in mind, and might not include all the error handling required for production applications. Take time to read the code
and understand if it applicable to your use case.
ESP-IDF guarantees source level compatibility of C functions, structures, enums, type definitions and preprocessor
macros declared in public header files of ESP-IDF components. Source level compatibility implies that the application
can be recompiled with the newer version of ESP-IDF without changes.
The following changes are allowed between minor versions and do not break source level compatibility:
• Deprecating functions (using the deprecated attribute) and header files (using a preprocessor #warning).
Deprecations are listed in ESP-IDF relese notes. It is recommended to update the source code to use the newer
functions or files that replace the deprecated ones, however this is not mandatory. Deprecated functions and
files can be removed in major versions of ESP-IDF.
• Renaming components, moving source and header files between components —provided that the build system
ensures that correct files are still found.
• Renaming Kconfig options. Kconfig system renaming mechanism ensures that the original Kconfig option
names can still be used by the application in sdkconfig file, CMake files and source code.
ESP-IDF does not guarantee binary compatibility between releases. This means that if a precompiled library is built
with one ESP-IDF version, it is not guaranteed to work the same way with the next minor or bugfix release. The
following are the possible changes that keep source level compatibility but not binary compatibility:
• Changing numerical values for C enum members.
• Adding new structure members or changing the order of members. See Configuration structures for tips that
help ensure compatibility.
• Replacing an extern function with a static inline one with the same signature, or vice versa.
• Replacing a function-like macro with a compatible C function.
While we try to make upgrading to a new ESP-IDF version easy, there are parts of ESP-IDF that may change between
minor versions in an incompatible way. We appreciate issue reports about any unintended breaking changes that don’
t fall into the categories below.
• Private APIs.
• Components in example projects.
• Features clearly marked as “beta”, “preview”, or “experimental”.
• Changes made to mitigate security issues or to replace insecure default behaviors with a secure ones.
• Features which were never functional. For example, if it was never possible to use a certain function or an
enumeration value, it may get renamed (as part of fixing it) or removed. This includes software features which
depend on non-functional chip hardware features.
• Unexpected or undefined behavior (for example, due to missing validation of argument ranges) that is not
documented explicitly may be fixed/changed.
• Location of Kconfig options in menuconfig.
• Location and names of example projects.
Asio is a cross-platform C++ library, see https://think-async.com/Asio/. It provides a consistent asynchronous model
using a modern C++ approach.
The ESP-IDF component ASIO has been moved from ESP-IDF since version v5.0 to a separate repository:
• ASIO component on GitHub
Hosted Documentation
2.2.2 ESP-Modbus
The Espressif ESP-Modbus Library (esp-modbus) supports Modbus communication in the networks based on RS485,
Wi-Fi, Ethernet interfaces. The ESP-IDF component freemodbus has been moved from ESP-IDF since version v5.0
to a separate repository:
• ESP-Modbus component on GitHub
Hosted Documentation
Application Example
The examples below demonstrate the ESP-Modbus library of serial, TCP ports for slave and master implementations
accordingly.
• protocols/modbus/serial/mb_slave
• protocols/modbus/serial/mb_master
• protocols/modbus/tcp/mb_tcp_slave
• protocols/modbus/tcp/mb_tcp_master
Please refer to the specific example README.md for details.
Protocol References
2.2.3 ESP-MQTT
Overview
Features
• Supports MQTT over TCP, SSL with mbedtls, MQTT over Websocket, MQTT over Websocket Secure.
• Easy to setup with URI
• Multiple instances (Multiple clients in one application)
• Support subscribing, publishing, authentication, last will messages, keep alive pings and all 3 QoS levels (it
should be a fully functional client).
Application Example
Configuration
URI
• Curently support mqtt, mqtts, ws, wss schemes
• MQTT over TCP samples:
– mqtt://mqtt.eclipseprojects.io: MQTT over TCP, default port 1883:
– mqtt://mqtt.eclipseprojects.io:1884 MQTT over TCP, port 1884:
– mqtt://username:[email protected]:1884 MQTT over TCP,
port 1884, with username and password
• MQTT over SSL samples:
– mqtts://mqtt.eclipseprojects.io: MQTT over SSL, port 8883
– mqtts://mqtt.eclipseprojects.io:8884: MQTT over SSL, port 8884
• MQTT over Websocket samples:
– ws://mqtt.eclipseprojects.io:80/mqtt
• MQTT over Websocket Secure samples:
– wss://mqtt.eclipseprojects.io:443/mqtt
• Minimal configurations:
esp_mqtt_client_start(client);
• Note: By default mqtt client uses event loop library to post related mqtt events (connected, subscribed, pub-
lished, etc.)
SSL
• Get certificate from server, example: mqtt.eclipseprojects.io openssl s_client
-showcerts -connect mqtt.eclipseprojects.io:8883 </dev/null 2>/dev/
null|openssl x509 -outform PEM >mqtt_eclipse_org.pem
• Check the sample application: examples/mqtt_ssl
• Configuration:
If the certificate is not null-terminated then cert_len should also be set. Other SSL related configuration param-
eters are:
• use_global_ca_store: use the global certificate store to verify server certificate, see esp-tls/esp_tls.h
for more information
• client_cert_pem: pointer to certificate data in PEM or DER format for SSL mutual authentication,
default is NULL, not required if mutual authentication is not needed.
• client_cert_len: length of the buffer pointed to by client_cert_pem. May be 0 for null-terminated pem.
• client_key_pem: pointer to private key data in PEM or DER format for SSL mutual authentication,
default is NULL, not required if mutual authentication is not needed.
• client_key_len: length of the buffer pointed to by client_key_pem. May be 0 for null-terminated pem.
• psk_hint_key: pointer to PSK struct defined in esp_tls.h to enable PSK authentication (as alternative to
certificate verification). If not NULL and server/client certificates are NULL, PSK is enabled
• alpn_protos: NULL-terminated list of protocols to be used for ALPN.
Last Will and Testament MQTT allows for a last will and testament (LWT) message to notify other clients when a
client ungracefully disconnects. This is configured by the following fields in the esp_mqtt_client_config_t-
struct.
• lwt_topic: pointer to the LWT message topic
• lwt_msg: pointer to the LWT message
• lwt_msg_len: length of the LWT message, required if lwt_msg is not null-terminated
• lwt_qos: quality of service for the LWT message
• lwt_retain: specifies the retain flag of the LWT message
• host: MQTT broker domain (ipv4 as string), setting the uri will override this
• port: MQTT broker port, specifying the port in the uri will override this
• transport: sets the transport protocol, setting the uri will override this
• refresh_connection_after_ms: refresh connection after this value (in milliseconds)
• event_handle: handle for MQTT events as a callback in legacy mode
• event_loop_handle: handle for MQTT event loop library
For more options on esp_mqtt_client_config_t, please refer to API reference below
Change settings in Project Configuration Menu The settings for MQTT can be found using idf.py menu-
config, under Component config -> ESP-MQTT Configuration
The following settings are available:
• CONFIG_MQTT_PROTOCOL_311: Enables 3.1.1 version of MQTT protocol
• CONFIG_MQTT_TRANSPORT_SSL, CONFIG_MQTT_TRANSPORT_WEBSOCKET: Enables specific MQTT
transport layer, such as SSL, WEBSOCKET, WEBSOCKET_SECURE
• CONFIG_MQTT_CUSTOM_OUTBOX: Disables default implementation of mqtt_outbox, so a specific imple-
mentaion can be supplied
Events
API Reference
Header File
• components/mqtt/esp-mqtt/include/mqtt_client.h
Functions
esp_mqtt_client_handle_t esp_mqtt_client_init(const esp_mqtt_client_config_t *config)
Creates mqtt client handle based on the configuration.
Parameters config –mqtt configuration structure
Returns mqtt_client_handle if successfully created, NULL on error
• Notes:
• Cannot be called from the mqtt event handler
Parameters
• client –mqtt client handle
• topic –
• qos –
Returns message_id of the subscribe message on success -1 on failure
Parameters
int esp_mqtt_client_publish(esp_mqtt_client_handle_t client, const char *topic, const char *data, int len,
int qos, int retain)
Client to send a publish message to the broker.
Notes:
• This API might block for several seconds, either due to network timeout (10s) or if publishing payloads
longer than internal buffer (due to message fragmentation)
• Client doesn’t have to be connected for this API to work, enqueueing the messages with qos>1 (returning
-1 for all the qos=0 messages if disconnected). If MQTT_SKIP_PUBLISH_IF_DISCONNECTED is
enabled, this API will not attempt to publish when the client is not connected and will always return -1.
• It is thread safe, please refer to esp_mqtt_client_subscribe for details
Parameters
• client –mqtt client handle
• topic –topic string
• data –payload string (set to NULL, sending empty payload message)
• len –data length, if set to 0, length is calculated from payload string
• qos –qos of publish message
• retain –retain flag
Returns message_id of the publish message (for QoS 0 message_id will always be zero) on success.
-1 on failure.
int esp_mqtt_client_enqueue(esp_mqtt_client_handle_t client, const char *topic, const char *data, int len,
int qos, int retain, bool store)
Enqueue a message to the outbox, to be sent later. Typically used for messages with qos>0, but could be also
used for qos=0 messages if store=true.
This API generates and stores the publish message into the internal outbox and the actual sending to the net-
work is performed in the mqtt-task context (in contrast to the esp_mqtt_client_publish() which sends the pub-
lish message immediately in the user task’s context). Thus, it could be used as a non blocking version of
esp_mqtt_client_publish().
Parameters
• client –mqtt client handle
• topic –topic string
• data –payload string (set to NULL, sending empty payload message)
• len –data length, if set to 0, length is calculated from payload string
• qos –qos of publish message
• retain –retain flag
• store –if true, all messages are enqueued; otherwise only qos1 and qos 2 are enqueued
Returns message_id if queued successfully, -1 otherwise
esp_err_t esp_mqtt_client_destroy(esp_mqtt_client_handle_t client)
Destroys the client handle.
Notes:
• Cannot be called from the mqtt event handler
Structures
struct esp_mqtt_error_codes
MQTT error code structure to be passed as a contextual information into ERROR event.
Important: This structure extends esp_tls_last_error error structure and is backward compatible with
it (so might be down-casted and treated as esp_tls_last_error error, but recommended to update
applications if used this way previously)
Use this structure directly checking error_type first and then appropriate error code depending on the source
of the error:
| error_type | related member variables | note | | MQTT_ERROR_TYPE_TCP_TRANSPORT |
esp_tls_last_esp_err, esp_tls_stack_err, esp_tls_cert_verify_flags, sock_errno | Error reported from
tcp_transport/esp-tls | | MQTT_ERROR_TYPE_CONNECTION_REFUSED | connect_return_code | Inter-
nal error reported from MQTT broker on connection |
Public Members
esp_err_t esp_tls_last_esp_err
last esp_err code reported from esp-tls component
int esp_tls_stack_err
tls specific error code reported from underlying tls stack
int esp_tls_cert_verify_flags
tls flags reported from underlying tls stack during certificate verification
esp_mqtt_error_type_t error_type
error type referring to the source of the error
esp_mqtt_connect_return_code_t connect_return_code
connection refused error code reported from MQTT broker on connection
int esp_transport_sock_errno
errno from the underlying socket
struct esp_mqtt_event_t
MQTT event configuration structure
Public Members
esp_mqtt_event_id_t event_id
MQTT event type
esp_mqtt_client_handle_t client
MQTT client handle for this event
void *user_context
User context passed from MQTT client config
char *data
Data associated with this event
int data_len
Length of the data for this event
int total_data_len
Total length of the data (longer data are supplied with multiple events)
int current_data_offset
Actual offset for the data associated with this event
char *topic
Topic associated with this event
int topic_len
Length of the topic for this event associated with this event
int msg_id
MQTT messaged id of message
int session_present
MQTT session_present flag for connection event
esp_mqtt_error_codes_t *error_handle
esp-mqtt error handle including esp-tls errors as well as internal mqtt errors
bool retain
Retained flag of the message associated with this event
int qos
qos of the messages associated with this event
bool dup
dup flag of the message associated with this event
esp_mqtt_protocol_ver_t protocol_ver
MQTT protocol version used for connection, defaults to value from menuconfig
struct esp_mqtt_client_config_t
MQTT client configuration structure
Public Members
esp_mqtt_transport_t transport
Selects transport, is overrided by URI transport
uint32_t port
MQTT broker port
bool use_global_ca_store
Use a global ca_store, look esp-tls documentation for details.
size_t cert_len
Length of the buffer pointed to by cert_pem. May be 0 for null-terminated pem
bool skip_cert_common_name_check
Skip any validation of server certificate CN field, this reduces the security of TLS and makes the mqtt
client susceptible to MITM attacks
size_t client_cert_len
Length of the buffer pointed to by client_cert_pem. May be 0 for null-terminated pem
size_t client_key_len
Length of the buffer pointed to by client_key_pem. May be 0 for null-terminated pem
int clientkey_password_len
String length of the password pointed to by clientkey_password
bool use_secure_element
enable secure element for enabling SSL connection
void *ds_data
carrier of handle for digital signature parameters
bool set_null_client_id
Selects a NULL client id
mqtt_event_callback_t event_handle
handle for MQTT events as a callback in legacy mode
esp_event_loop_handle_t event_loop_handle
handle for MQTT event loop library
int task_prio
MQTT task priority, default is 5, can be changed in make menuconfig
int task_stack
MQTT task stack size, default is 6144 bytes, can be changed in make menuconfig
int lwt_qos
LWT message qos
int lwt_retain
LWT retained message flag
int lwt_msg_len
LWT message length
int disable_clean_session
mqtt clean session, default clean_session is true
int keepalive
mqtt keepalive, default is 120 seconds
bool disable_keepalive
Set disable_keepalive=true to turn off keep-alive mechanism, false by default (keepalive is active by
default). Note: setting the config value keepalive to 0 doesn’t disable keepalive feature, but uses a
default keepalive period
esp_mqtt_protocol_ver_t protocol_ver
MQTT protocol version used for connection, defaults to value from menuconfig
int message_retransmit_timeout
timeout for retansmit of failded packet
int reconnect_timeout_ms
Reconnect to the broker after this value in miliseconds if auto reconnect is not disabled (defaults to 10s)
int network_timeout_ms
Abort network operation if it is not completed after this value, in milliseconds (defaults to 10s)
int refresh_connection_after_ms
Refresh connection after this value (in milliseconds)
bool disable_auto_reconnect
this mqtt client will reconnect to server (when errors/disconnect). Set disable_auto_reconnect=true to
disable
void *user_context
pass user context to this option, then can receive that context in event->user_context
int buffer_size
size of MQTT send/receive buffer, default is 1024 (only receive buffer size if out_buffer_size
defined)
int out_buffer_size
size of MQTT output buffer. If not defined, both output and input buffers have the same size defined as
buffer_size
Macros
MQTT_ERROR_TYPE_ESP_TLS
MQTT_ERROR_TYPE_TCP_TRANSPORT error type hold all sorts of transport layer errors, including ESP-
TLS error, but in the past only the errors from MQTT_ERROR_TYPE_ESP_TLS layer were reported, so the
ESP-TLS error type is re-defined here for backward compatibility
Type Definitions
Enumerations
enum esp_mqtt_event_id_t
MQTT event types.
User event handler receives context data in esp_mqtt_event_t structure with
• user_context - user data from esp_mqtt_client_config_t
• client - mqtt client handle
• various other data depending on event type
Values:
enumerator MQTT_EVENT_ANY
enumerator MQTT_EVENT_ERROR
on error event, additional context: connection return code, error handle from esp_tls (if supported)
enumerator MQTT_EVENT_CONNECTED
connected event, additional context: session_present flag
enumerator MQTT_EVENT_DISCONNECTED
disconnected event
enumerator MQTT_EVENT_SUBSCRIBED
subscribed event, additional context:
• msg_id message id
• data pointer to the received data
• data_len length of the data for this event
enumerator MQTT_EVENT_UNSUBSCRIBED
unsubscribed event
enumerator MQTT_EVENT_PUBLISHED
published event, additional context: msg_id
enumerator MQTT_EVENT_DATA
data event, additional context:
• msg_id message id
• topic pointer to the received topic
• topic_len length of the topic
• data pointer to the received data
• data_len length of the data for this event
• current_data_offset offset of the current data for this event
• total_data_len total length of the data received
• retain retain flag of the message
• qos qos level of the message
• dup dup flag of the message Note: Multiple MQTT_EVENT_DATA could be fired for one message,
if it is longer than internal buffer. In that case only first event contains topic pointer and length, other
contain data only with current data length and current data offset updating.
enumerator MQTT_EVENT_BEFORE_CONNECT
The event occurs before connecting
enumerator MQTT_EVENT_DELETED
Notification on delete of one message from the internal outbox, if the message couldn’t have been sent
and acknowledged before expiring defined in OUTBOX_EXPIRED_TIMEOUT_MS. (events are not
posted upon deletion of successfully acknowledged messages)
• This event id is posted only if MQTT_REPORT_DELETED_MESSAGES==1
• Additional context: msg_id (id of the deleted message).
enum esp_mqtt_connect_return_code_t
MQTT connection error codes propagated via ERROR event
Values:
enumerator MQTT_CONNECTION_ACCEPTED
Connection accepted
enumerator MQTT_CONNECTION_REFUSE_PROTOCOL
MQTT connection refused reason: Wrong protocol
enumerator MQTT_CONNECTION_REFUSE_ID_REJECTED
MQTT connection refused reason: ID rejected
enumerator MQTT_CONNECTION_REFUSE_SERVER_UNAVAILABLE
MQTT connection refused reason: Server unavailable
enumerator MQTT_CONNECTION_REFUSE_BAD_USERNAME
MQTT connection refused reason: Wrong user
enumerator MQTT_CONNECTION_REFUSE_NOT_AUTHORIZED
MQTT connection refused reason: Wrong username or password
enum esp_mqtt_error_type_t
MQTT connection error codes propagated via ERROR event
Values:
enumerator MQTT_ERROR_TYPE_NONE
enumerator MQTT_ERROR_TYPE_TCP_TRANSPORT
enumerator MQTT_ERROR_TYPE_CONNECTION_REFUSED
enum esp_mqtt_transport_t
Values:
enumerator MQTT_TRANSPORT_UNKNOWN
enumerator MQTT_TRANSPORT_OVER_TCP
MQTT over TCP, using scheme: mqtt
enumerator MQTT_TRANSPORT_OVER_SSL
MQTT over SSL, using scheme: mqtts
enumerator MQTT_TRANSPORT_OVER_WS
MQTT over Websocket, using scheme:: ws
enumerator MQTT_TRANSPORT_OVER_WSS
MQTT over Websocket Secure, using scheme: wss
enum esp_mqtt_protocol_ver_t
MQTT protocol version used for connection
Values:
enumerator MQTT_PROTOCOL_UNDEFINED
enumerator MQTT_PROTOCOL_V_3_1
enumerator MQTT_PROTOCOL_V_3_1_1
enumerator MQTT_PROTOCOL_V_5
2.2.4 ESP-TLS
Overview
The ESP-TLS component provides a simplified API interface for accessing the commonly used TLS functionality.
It supports common scenarios like CA certification validation, SNI, ALPN negotiation, non-blocking connection
among others. All the configuration can be specified in the esp_tls_cfg_t data structure. Once done, TLS
communication can be conducted using the following APIs:
• esp_tls_init(): for initializing the TLS connection handle.
• esp_tls_conn_new_sync(): for opening a new blocking TLS connection.
• esp_tls_conn_new_async(): for opening a new non-blocking TLS connection.
• esp_tls_conn_read(): for reading from the connection.
• esp_tls_conn_write(): for writing into the connection.
• esp_tls_conn_destroy(): for freeing up the connection.
Any application layer protocol like HTTP1, HTTP2 etc can be executed on top of this layer.
Application Example
Simple HTTPS example that uses ESP-TLS to establish a secure socket connection: protocols/https_request.
├── esp_tls.c
├── esp_tls.h
├── esp_tls_mbedtls.c
├── esp_tls_wolfssl.c
└── private_include
├── esp_tls_mbedtls.h
└── esp_tls_wolfssl.h
The ESP-TLS component has a file esp-tls/esp_tls.h which contain the public API headers for the component. Inter-
nally ESP-TLS component uses one of the two SSL/TLS Libraries between mbedtls and wolfssl for its operation. API
specific to mbedtls are present in esp-tls/private_include/esp_tls_mbedtls.h and API specific to wolfssl are present in
esp-tls/private_include/esp_tls_wolfssl.h.
The ESP-TLS provides multiple options for TLS server verification on the client side. The ESP-TLS client can verify
the server by validating the peer’s server certificate or with the help of pre-shared keys. The user should select only
one of the following options in the esp_tls_cfg_t structure for TLS server verification. If no option is selected
then client will return a fatal error by default at the time of the TLS connection setup.
• cacert_buf and cacert_bytes: The CA certificate can be provided in a buffer to the esp_tls_cfg_t struc-
ture. The ESP-TLS will use the CA certificate present in the buffer to verify the server. The following variables
in esp_tls_cfg_t structure must be set.
– cacert_buf - pointer to the buffer which contains the CA cert.
– cacert_bytes - size of the CA certificate in bytes.
• use_global_ca_store: The global_ca_store can be initialized and set at once. Then it can be used
to verify the server for all the ESP-TLS connections which have set use_global_ca_store = true
in their respective esp_tls_cfg_t structure. See API Reference section below on information regarding
different API used for initializing and setting up the global_ca_store.
• crt_bundle_attach: The ESP x509 Certificate Bundle API provides an easy way to include a bundle of custom
x509 root certificates for TLS server verification. More details can be found at ESP x509 Certificate Bundle
• psk_hint_key: To use pre-shared keys for server verification, CONFIG_ESP_TLS_PSK_VERIFICATION
should be enabled in the ESP-TLS menuconfig. Then the pointer to PSK hint and key should be provided
to the esp_tls_cfg_t structure. The ESP-TLS will use the PSK for server verification only when no other
option regarding the server verification is selected.
• skip server verification: This is an insecure option provided in the ESP-TLS for test-
ing purpose. The option can be set by enabling CONFIG_ESP_TLS_INSECURE and CON-
FIG_ESP_TLS_SKIP_SERVER_CERT_VERIFY in the ESP-TLS menuconfig. When this option is enabled the
ESP-TLS will skip server verification by default when no other options for server verification are selected in
the esp_tls_cfg_t structure. WARNING:Enabling this option comes with a potential risk of establishing a
TLS connection with a server which has a fake identity, provided that the server certificate is not provided either
through API or other mechanism like ca_store etc.
The ESP-TLS component has an option to use mbedtls or wolfssl as their underlying SSL/TLS library. By default
only mbedtls is available and is used, wolfssl SSL/TLS library is available publicly at https://github.com/espressif/
esp-wolfssl. The repository provides wolfssl component in binary format, it also provides few examples which are
useful for understanding the API. Please refer the repository README.md for information on licensing and other
options. Please see below option for using wolfssl in your project.
Note: As the library options are internal to ESP-TLS, switching the libraries will not change ESP-TLS specific code
for a project.
idf.py menuconfig -> ESP-TLS -> choose SSL/TLS Library -> mbedtls/wolfssl
The following table shows a typical comparison between wolfssl and mbedtls when protocols/https_request exam-
ple (which has server authentication) was run with both SSL/TLS libraries and with all respective configurations
set to default. (mbedtls IN_CONTENT length and OUT_CONTENT length were set to 16384 bytes and 4096 bytes
respectively)
Note: These values are subject to change with change in configuration options and version of respective libraries.
ESP-TLS provides support for using ATECC608A cryptoauth chip with ESP32-WROOM-32SE. Use of
ATECC608A is supported only when ESP-TLS is used with mbedTLS as its underlying SSL/TLS stack. ESP-TLS
uses mbedtls as its underlying TLS/SSL stack by default unless changed manually.
Note: ATECC608A chip on ESP32-WROOM-32SE must be already configured and provisioned, for details refer
esp_cryptoauth_utility
To enable the secure element support, and use it in you project for TLS connection, you will have to follow below
steps
1) Add esp-cryptoauthlib in your project, for details please refer esp-cryptoauthlib with ESP_IDF
2) Enable following menuconfig option:
to know more about different types of ATECC608A chips and how to obtain type of ATECC608A connected to
your ESP module please visit ATECC608A chip type
4) Enable use of ATECC608A in ESP-TLS by providing following config option in esp_tls_cfg_t
esp_tls_cfg_t cfg = {
/* other configurations options */
.use_secure_element = true,
};
API Reference
Header File
• components/esp-tls/esp_tls.h
Functions
esp_tls_t *esp_tls_init(void)
Create TLS connection.
This function allocates and initializes esp-tls structure handle.
Returns tls Pointer to esp-tls as esp-tls handle if successfully initialized, NULL if allocation error
esp_tls_t *esp_tls_conn_http_new(const char *url, const esp_tls_cfg_t *cfg)
Create a new blocking TLS/SSL connection with a given “HTTP”url.
Note: This API is present for backward compatibility reasons. Alternative function with
the same functionality is esp_tls_conn_http_new_sync (and its asynchronous version
esp_tls_conn_http_new_async)
Parameters
• url –[in] url of host.
• cfg –[in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection,
keep this NULL. For TLS connection, a pass pointer to‘esp_tls_cfg_t’. At a minimum,
this structure should be zero-initialized.
Returns pointer to esp_tls_t, or NULL if connection couldn’t be opened.
int esp_tls_conn_new_sync(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t
*tls)
Create a new blocking TLS/SSL connection.
This function establishes a TLS/SSL connection with the specified host in blocking manner.
Parameters
• hostname –[in] Hostname of the host.
• hostlen –[in] Length of hostname.
• port –[in] Port number of the host.
• cfg –[in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection,
keep this NULL. For TLS connection, a pass pointer to esp_tls_cfg_t. At a minimum, this
structure should be zero-initialized.
• tls –[in] Pointer to esp-tls as esp-tls handle.
Returns
• -1 If connection establishment fails.
• 1 If connection establishment is successful.
• 0 If connection state is in progress.
int esp_tls_conn_http_new_sync(const char *url, const esp_tls_cfg_t *cfg, esp_tls_t *tls)
Create a new blocking TLS/SSL connection with a given “HTTP”url.
The behaviour is same as esp_tls_conn_new_sync() API. However this API accepts host’s url.
Parameters
• url –[in] url of host.
• cfg –[in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection,
keep this NULL. For TLS connection, a pass pointer to‘esp_tls_cfg_t’. At a minimum,
this structure should be zero-initialized.
• tls –[in] Pointer to esp-tls as esp-tls handle.
Returns
• -1 If connection establishment fails.
• 1 If connection establishment is successful.
• 0 If connection state is in progress.
int esp_tls_conn_new_async(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t
*tls)
Create a new non-blocking TLS/SSL connection.
This function initiates a non-blocking TLS/SSL connection with the specified host, but due to its non-blocking
nature, it doesn’t wait for the connection to get established.
Parameters
• hostname –[in] Hostname of the host.
• hostlen –[in] Length of hostname.
• port –[in] Port number of the host.
• cfg –[in] TLS configuration as esp_tls_cfg_t. non_block member of this structure
should be set to be true.
• tls –[in] pointer to esp-tls as esp-tls handle.
Returns
• -1 If connection establishment fails.
• 0 If connection establishment is in progress.
• 1 If connection establishment is successful.
int esp_tls_conn_http_new_async(const char *url, const esp_tls_cfg_t *cfg, esp_tls_t *tls)
Create a new non-blocking TLS/SSL connection with a given “HTTP”url.
The behaviour is same as esp_tls_conn_new_async() API. However this API accepts host’s url.
Parameters
• url –[in] url of host.
• cfg –[in] TLS configuration as esp_tls_cfg_t.
• tls –[in] pointer to esp-tls as esp-tls handle.
Returns
• -1 If connection establishment fails.
• 0 If connection establishment is in progress.
• 1 If connection establishment is successful.
ssize_t esp_tls_conn_write(esp_tls_t *tls, const void *data, size_t datalen)
Write from buffer ‘data’into specified tls connection.
Parameters
• tls –[in] pointer to esp-tls as esp-tls handle.
• data –[in] Buffer from which data will be written.
• datalen –[in] Length of data buffer.
Returns
• >=0 if write operation was successful, the return value is the number of bytes actually
written to the TLS/SSL connection.
• <0 if write operation was not successful, because either an error occured or an action must
be taken by the calling process.
• ESP_TLS_ERR_SSL_WANT_READ/ ESP_TLS_ERR_SSL_WANT_WRITE. if the
handshake is incomplete and waiting for data to be available for reading. In this case this
functions needs to be called again when the underlying transport is ready for operation.
ssize_t esp_tls_conn_read(esp_tls_t *tls, void *data, size_t datalen)
Read from specified tls connection into the buffer ‘data’.
Parameters
• tls –[in] pointer to esp-tls as esp-tls handle.
• data –[in] Buffer to hold read data.
• datalen –[in] Length of data buffer.
Returns
• >0 if read operation was successful, the return value is the number of bytes actually read
from the TLS/SSL connection.
• 0 if read operation was not successful. The underlying connection was closed.
• <0 if read operation was not successful, because either an error occured or an action must
be taken by the calling process.
int esp_tls_conn_destroy(esp_tls_t *tls)
Close the TLS/SSL connection and free any allocated resources.
This function should be called to close each tls connection opened with esp_tls_conn_new_sync() (or
esp_tls_conn_http_new_sync()) and esp_tls_conn_new_async() (or esp_tls_conn_http_new_async()) APIs.
Parameters tls –[in] pointer to esp-tls as esp-tls handle.
Returns - 0 on success
• -1 if socket error or an invalid argument
ssize_t esp_tls_get_bytes_avail(esp_tls_t *tls)
Return the number of application data bytes remaining to be read from the current record.
This API is a wrapper over mbedtls’s mbedtls_ssl_get_bytes_avail() API.
Parameters tls –[in] pointer to esp-tls as esp-tls handle.
Returns
• -1 in case of invalid arg
• bytes available in the application data record read buffer
esp_err_t esp_tls_get_conn_sockfd(esp_tls_t *tls, int *sockfd)
Returns the connection socket file descriptor from esp_tls session.
Parameters
Note: Modifying the pointer might cause a failure in verifying the certificates.
Returns
• Pointer to the global CA store currently being used if successful.
• NULL if there is no global CA store set.
esp_err_t esp_tls_plain_tcp_connect(const char *host, int hostlen, int port, const esp_tls_cfg_t *cfg,
esp_tls_error_handle_t error_handle, int *sockfd)
Creates a plain TCP connection, returning a valid socket fd on success or an error handle.
Parameters
• host –[in] Hostname of the host.
• hostlen –[in] Length of hostname.
• port –[in] Port number of the host.
• cfg –[in] ESP-TLS configuration as esp_tls_cfg_t.
• error_handle –[out] ESP-TLS error handle holding potential errors occurred during
connection
• sockfd –[out] Socket descriptor if successfully connected on TCP layer
Returns ESP_OK on success ESP_ERR_INVALID_ARG if invalid output parameters ESP-TLS
based error codes on failure
Structures
struct psk_key_hint
ESP-TLS preshared key and hint structure.
Public Members
struct tls_keep_alive_cfg
esp-tls client session ticket ctx
Keep alive parameters structure
Public Members
bool keep_alive_enable
Enable keep-alive timeout
int keep_alive_idle
Keep-alive idle time (second)
int keep_alive_interval
Keep-alive interval time (second)
int keep_alive_count
Keep-alive packet retry send count
struct esp_tls_cfg
ESP-TLS configuration parameters.
Public Members
bool non_block
Configure non-blocking mode. If set to true the underneath socket will be configured in non blocking
mode after tls session is established
bool use_secure_element
Enable this option to use secure element or atecc608a chip ( Integrated with ESP32-WROOM-32SE )
int timeout_ms
Network timeout in milliseconds. Note: If this value is not set, by default the timeout is set to 10 seconds.
If you wish that the session should wait indefinitely then please use a larger value e.g., INT32_MAX
bool use_global_ca_store
Use a global ca_store for all the connections in which this bool is set.
bool skip_common_name
Skip any validation of server certificate CN field
tls_keep_alive_cfg_t *keep_alive_cfg
Enable TCP keep-alive timeout for SSL connection
void *ds_data
Pointer for digital signature peripheral context
bool is_plain_tcp
Use non-TLS connection: When set to true, the esp-tls uses plain TCP transport rather then
TLS/SSL connection. Note, that it is possible to connect using a plain tcp transport directly with
esp_tls_plain_tcp_connect() API
Type Definitions
Enumerations
enum esp_tls_conn_state
ESP-TLS Connection State.
Values:
enumerator ESP_TLS_INIT
enumerator ESP_TLS_CONNECTING
enumerator ESP_TLS_HANDSHAKE
enumerator ESP_TLS_FAIL
enumerator ESP_TLS_DONE
enum esp_tls_role
Values:
enumerator ESP_TLS_CLIENT
enumerator ESP_TLS_SERVER
Header File
• components/esp-tls/esp_tls_errors.h
Structures
struct esp_tls_last_error
Error structure containing relevant errors in case tls error occurred.
Public Members
esp_err_t last_error
error code (based on ESP_ERR_ESP_TLS_BASE) of the last occurred error
int esp_tls_error_code
esp_tls error code from last esp_tls failed api
int esp_tls_flags
last certification verification flags
Macros
ESP_ERR_ESP_TLS_BASE
Starting number of ESP-TLS error codes
ESP_ERR_ESP_TLS_CANNOT_RESOLVE_HOSTNAME
Error if hostname couldn’t be resolved upon tls connection
ESP_ERR_ESP_TLS_CANNOT_CREATE_SOCKET
Failed to create socket
ESP_ERR_ESP_TLS_UNSUPPORTED_PROTOCOL_FAMILY
Unsupported protocol family
ESP_ERR_ESP_TLS_FAILED_CONNECT_TO_HOST
Failed to connect to host
ESP_ERR_ESP_TLS_SOCKET_SETOPT_FAILED
failed to set/get socket option
ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT
new connection in esp_tls_low_level_conn connection timeouted
ESP_ERR_ESP_TLS_SE_FAILED
ESP_ERR_ESP_TLS_TCP_CLOSED_FIN
ESP_ERR_MBEDTLS_CERT_PARTLY_OK
mbedtls parse certificates was partly successful
ESP_ERR_MBEDTLS_CTR_DRBG_SEED_FAILED
mbedtls api returned error
ESP_ERR_MBEDTLS_SSL_SET_HOSTNAME_FAILED
mbedtls api returned error
ESP_ERR_MBEDTLS_SSL_CONFIG_DEFAULTS_FAILED
mbedtls api returned error
ESP_ERR_MBEDTLS_SSL_CONF_ALPN_PROTOCOLS_FAILED
mbedtls api returned error
ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED
mbedtls api returned error
ESP_ERR_MBEDTLS_SSL_CONF_OWN_CERT_FAILED
mbedtls api returned error
ESP_ERR_MBEDTLS_SSL_SETUP_FAILED
mbedtls api returned error
ESP_ERR_MBEDTLS_SSL_WRITE_FAILED
mbedtls api returned error
ESP_ERR_MBEDTLS_PK_PARSE_KEY_FAILED
mbedtls api returned failed
ESP_ERR_MBEDTLS_SSL_HANDSHAKE_FAILED
mbedtls api returned failed
ESP_ERR_MBEDTLS_SSL_CONF_PSK_FAILED
mbedtls api returned failed
ESP_ERR_MBEDTLS_SSL_TICKET_SETUP_FAILED
mbedtls api returned failed
ESP_ERR_WOLFSSL_SSL_SET_HOSTNAME_FAILED
wolfSSL api returned error
ESP_ERR_WOLFSSL_SSL_CONF_ALPN_PROTOCOLS_FAILED
wolfSSL api returned error
ESP_ERR_WOLFSSL_CERT_VERIFY_SETUP_FAILED
wolfSSL api returned error
ESP_ERR_WOLFSSL_KEY_VERIFY_SETUP_FAILED
wolfSSL api returned error
ESP_ERR_WOLFSSL_SSL_HANDSHAKE_FAILED
wolfSSL api returned failed
ESP_ERR_WOLFSSL_CTX_SETUP_FAILED
wolfSSL api returned failed
ESP_ERR_WOLFSSL_SSL_SETUP_FAILED
wolfSSL api returned failed
ESP_ERR_WOLFSSL_SSL_WRITE_FAILED
wolfSSL api returned failed
ESP_TLS_ERR_SSL_WANT_READ
Definition of errors reported from IO API (potentially non-blocking) in case of error:
• esp_tls_conn_read()
• esp_tls_conn_write()
ESP_TLS_ERR_SSL_WANT_WRITE
ESP_TLS_ERR_SSL_TIMEOUT
Type Definitions
Enumerations
enum esp_tls_error_type_t
Definition of different types/sources of error codes reported from different components
Values:
enumerator ESP_TLS_ERR_TYPE_UNKNOWN
enumerator ESP_TLS_ERR_TYPE_SYSTEM
System error — errno
enumerator ESP_TLS_ERR_TYPE_MBEDTLS
Error code from mbedTLS library
enumerator ESP_TLS_ERR_TYPE_MBEDTLS_CERT_FLAGS
Certificate flags defined in mbedTLS
enumerator ESP_TLS_ERR_TYPE_ESP
ESP-IDF error type — esp_err_t
enumerator ESP_TLS_ERR_TYPE_WOLFSSL
Error code from wolfSSL library
enumerator ESP_TLS_ERR_TYPE_WOLFSSL_CERT_FLAGS
Certificate flags defined in wolfSSL
enumerator ESP_TLS_ERR_TYPE_MAX
Last err type — invalid entry
Overview
esp_http_client provides an API for making HTTP/S requests from ESP-IDF applications. The steps to use
this API are as follows:
• esp_http_client_init(): Creates an esp_http_client_config_t instance i.e. a HTTP
client handle based on the given esp_http_client_config_t configuration. This function must be
the first to be called; default values will be assumed for the configuration values that are not explicitly defined
by the user.
• esp_http_client_perform(): Performs all operations of the esp_http_client - opening the con-
nection, exchanging data and closing the connection (as required), while blocking the current task
until its completion. All related events will be invoked through the event handler (as specified in
esp_http_client_config_t).
• esp_http_client_cleanup(): Closes the connection (if any) and frees up all the memory allocated
to the HTTP client instance. This must be the last function to be called after the completion of operations.
Application Example
Simple example that uses ESP HTTP Client to make HTTP/S requests at protocols/esp_http_client.
Persistent Connections
Persistent connection means that the HTTP client can re-use the same connection for several exchanges. If the server
does not request to close the connection with the Connection: close header, the connection is not dropped
but is instead kept open and used for further requests.
To allow ESP HTTP client to take full advantage of persistent connections, one should make as many requests as
possible using the same handle instance.
Check out the example functions http_rest_with_url and http_rest_with_hostname_path in the
application example. Here, once the connection is created, multiple requests (GET, POST, PUT, etc.) are made
before the connection is closed.
HTTPS Request
ESP HTTP client supports SSL connections using mbedTLS, with the url configuration starting with https
scheme or transport_type set to HTTP_TRANSPORT_OVER_SSL. HTTPS support can be configured via
CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS (enabled by default).
Note: While making HTTPS requests, if server verification is needed, additional root certificate (in PEM format)
needs to be provided to the cert_pem member in esp_http_client_config_t configuration. Users can
also use the ESP x509 Certificate Bundle for server verification using the crt_bundle_attach
member of the esp_http_client_config_t configuration.
Check out the example functions https_with_url and https_with_hostname_path in the application
example. (Implementation details of the above note are found here)
HTTP Stream
Some applications need to open the connection and control the exchange of data actively (data streaming). In such
cases, the application flow is different from regular requests. Example flow is given below:
• esp_http_client_init(): Create a HTTP client handle
• esp_http_client_set_* or esp_http_client_delete_*: Modify the HTTP connection pa-
rameters (optional)
• esp_http_client_open(): Open the HTTP connection with write_len parameter (content length
that needs to be written to server), set write_len=0 for read-only connection
• esp_http_client_write(): Write data to server with a maximum length equal to write_len of
esp_http_client_open() function; no need to call this function for write_len=0
• esp_http_client_fetch_headers(): Read the HTTP Server response headers, after sending the
request headers and server data (if any). Returns the content-length from the server and can be suc-
ceeded by esp_http_client_get_status_code() for getting the HTTP status of the connection.
• esp_http_client_read(): Read the HTTP stream
• esp_http_client_close(): Close the connection
• esp_http_client_cleanup(): Release allocated resources
Check out the example function http_perform_as_stream_reader in the application example for imple-
mentation details.
HTTP Authentication
API Reference
Header File
• components/esp_http_client/include/esp_http_client.h
Functions
esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *config)
Start a HTTP session This function must be the first function to call, and it returns a esp_http_client_handle_t
that you must use as input to other functions in the interface. This call MUST have a corresponding call to
esp_http_client_cleanup when the operation is complete.
Parameters config –[in] The configurations, see http_client_config_t
Returns
• esp_http_client_handle_t
• NULL if any errors
esp_err_t esp_http_client_perform(esp_http_client_handle_t client)
Invoke this function after esp_http_client_init and all the options calls are made, and will perform
the transfer as described in the options. It must be called with the same esp_http_client_handle_t as input as
the esp_http_client_init call returned. esp_http_client_perform performs the entire request in either blocking
or non-blocking manner. By default, the API performs request in a blocking manner and returns when done,
or if it failed, and in non-blocking manner, it returns if EAGAIN/EWOULDBLOCK or EINPROGRESS is
encountered, or if it failed. And in case of non-blocking request, the user may call this API multiple times
unless request & response is complete or there is a failure. To enable non-blocking esp_http_client_perform(),
is_async member of esp_http_client_config_t must be set while making a call to esp_http_client_init() API.
You can do any amount of calls to esp_http_client_perform while using the same esp_http_client_handle_t.
The underlying connection may be kept open if the server allows it. If you intend to transfer more than one
file, you are even encouraged to do so. esp_http_client will then attempt to re-use the same connection for
the following transfers, thus making the operations faster, less CPU intense and using less network resources.
Just note that you will have to use esp_http_client_set_** between the invokes to set options for the
following esp_http_client_perform.
Note: You must never call this function simultaneously from two places using the same client han-
dle. Let the function return first before invoking it another time. If you want parallel transfers,
you must use several esp_http_client_handle_t. This function include esp_http_client_open
-> esp_http_client_write -> esp_http_client_fetch_headers ->
esp_http_client_read (and option) esp_http_client_close.
• ESP_FAIL
esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t client, const char *data, int len)
Set post data, this function must be called before esp_http_client_perform. Note: The data param-
eter passed to this function is a pointer and this function will not copy the data.
Parameters
• client –[in] The esp_http_client handle
• data –[in] post data pointer
• len –[in] post length
Returns
• ESP_OK
• ESP_FAIL
int esp_http_client_get_post_field(esp_http_client_handle_t client, char **data)
Get current post field information.
Parameters
• client –[in] The client
• data –[out] Point to post data pointer
Returns Size of post data
esp_err_t esp_http_client_set_header(esp_http_client_handle_t client, const char *key, const char
*value)
Set http request header, this function must be called after esp_http_client_init and before any perform function.
Parameters
• client –[in] The esp_http_client handle
• key –[in] The header key
• value –[in] The header value
Returns
• ESP_OK
• ESP_FAIL
esp_err_t esp_http_client_get_header(esp_http_client_handle_t client, const char *key, char **value)
Get http request header. The value parameter will be set to NULL if there is no header which is same as the
key specified, otherwise the address of header value will be assigned to value parameter. This function must
be called after esp_http_client_init.
Parameters
• client –[in] The esp_http_client handle
• key –[in] The header key
• value –[out] The header value
Returns
• ESP_OK
• ESP_FAIL
esp_err_t esp_http_client_get_username(esp_http_client_handle_t client, char **value)
Get http request username. The address of username buffer will be assigned to value parameter. This function
must be called after esp_http_client_init.
Parameters
• client –[in] The esp_http_client handle
• value –[out] The username value
Returns
• ESP_OK
• ESP_ERR_INVALID_ARG
esp_err_t esp_http_client_set_username(esp_http_client_handle_t client, const char *username)
Set http request username. The value of username parameter will be assigned to username buffer. If the
username parameter is NULL then username buffer will be freed.
Parameters
Note: (-ESP_ERR_HTTP_EAGAIN = -0x7007) is returned when call is timed-out before any data was ready
Parameters
• client –[in] The esp_http_client handle
Note: There is a possibility of receiving body message with redirection status codes, thus make sure to flush
off body data after calling this API.
Structures
struct esp_http_client_event
HTTP Client events data.
Public Members
esp_http_client_event_id_t event_id
event_id, to know the cause of the event
esp_http_client_handle_t client
esp_http_client_handle_t context
void *data
data of the event
int data_len
data length of data
void *user_data
user_data context, from esp_http_client_config_t user_data
char *header_key
For HTTP_EVENT_ON_HEADER event_id, it’s store current http header key
char *header_value
For HTTP_EVENT_ON_HEADER event_id, it’s store current http header value
struct esp_http_client_config_t
HTTP configuration.
Public Members
int port
Port to connect, default depend on esp_http_client_transport_t (80 or 443)
esp_http_client_auth_type_t auth_type
Http authentication type, see esp_http_client_auth_type_t
size_t cert_len
Length of the buffer pointed to by cert_pem. May be 0 for null-terminated pem
size_t client_cert_len
Length of the buffer pointed to by client_cert_pem. May be 0 for null-terminated pem
size_t client_key_len
Length of the buffer pointed to by client_key_pem. May be 0 for null-terminated pem
size_t client_key_password_len
String length of the password pointed to by client_key_password
esp_http_client_method_t method
HTTP Method
int timeout_ms
Network timeout in milliseconds
bool disable_auto_redirect
Disable HTTP automatic redirects
int max_redirection_count
Max number of redirections on receiving HTTP redirect status code, using default value if zero
int max_authorization_retries
Max connection retries on receiving HTTP unauthorized status code, using default value if zero. Disables
authorization retry if -1
http_event_handle_cb event_handler
HTTP Event Handle
esp_http_client_transport_t transport_type
HTTP transport type, see esp_http_client_transport_t
int buffer_size
HTTP receive buffer size
int buffer_size_tx
HTTP transmit buffer size
void *user_data
HTTP user_data context
bool is_async
Set asynchronous mode, only supported with HTTPS for now
bool use_global_ca_store
Use a global ca_store for all the connections in which this bool is set.
bool skip_cert_common_name_check
Skip any validation of server certificate CN field
bool keep_alive_enable
Enable keep-alive timeout
int keep_alive_idle
Keep-alive idle time. Default is 5 (second)
int keep_alive_interval
Keep-alive interval time. Default is 5 (second)
int keep_alive_count
Keep-alive packet retry send count. Default is 3 counts
Macros
DEFAULT_HTTP_BUF_SIZE
ESP_ERR_HTTP_BASE
Starting number of HTTP error codes
ESP_ERR_HTTP_MAX_REDIRECT
The error exceeds the number of HTTP redirects
ESP_ERR_HTTP_CONNECT
Error open the HTTP connection
ESP_ERR_HTTP_WRITE_DATA
Error write HTTP data
ESP_ERR_HTTP_FETCH_HEADER
Error read HTTP header from server
ESP_ERR_HTTP_INVALID_TRANSPORT
There are no transport support for the input scheme
ESP_ERR_HTTP_CONNECTING
HTTP connection hasn’t been established yet
ESP_ERR_HTTP_EAGAIN
Mapping of errno EAGAIN to esp_err_t
ESP_ERR_HTTP_CONNECTION_CLOSED
Read FIN from peer and the connection closed
Type Definitions
Enumerations
enum esp_http_client_event_id_t
HTTP Client events id.
Values:
enumerator HTTP_EVENT_ERROR
This event occurs when there are any errors during execution
enumerator HTTP_EVENT_ON_CONNECTED
Once the HTTP has been connected to the server, no data exchange has been performed
enumerator HTTP_EVENT_HEADERS_SENT
After sending all the headers to the server
enumerator HTTP_EVENT_HEADER_SENT
This header has been kept for backward compatability and will be deprecated in future versions esp-idf
enumerator HTTP_EVENT_ON_HEADER
Occurs when receiving each header sent from the server
enumerator HTTP_EVENT_ON_DATA
Occurs when receiving data from the server, possibly multiple portions of the packet
enumerator HTTP_EVENT_ON_FINISH
Occurs when finish a HTTP session
enumerator HTTP_EVENT_DISCONNECTED
The connection has been disconnected
enumerator HTTP_EVENT_REDIRECT
Intercepting HTTP redirects to handle them manually
enum esp_http_client_transport_t
HTTP Client transport.
Values:
enumerator HTTP_TRANSPORT_UNKNOWN
Unknown
enumerator HTTP_TRANSPORT_OVER_TCP
Transport over tcp
enumerator HTTP_TRANSPORT_OVER_SSL
Transport over ssl
enum esp_http_client_method_t
HTTP method.
Values:
enumerator HTTP_METHOD_GET
HTTP GET Method
enumerator HTTP_METHOD_POST
HTTP POST Method
enumerator HTTP_METHOD_PUT
HTTP PUT Method
enumerator HTTP_METHOD_PATCH
HTTP PATCH Method
enumerator HTTP_METHOD_DELETE
HTTP DELETE Method
enumerator HTTP_METHOD_HEAD
HTTP HEAD Method
enumerator HTTP_METHOD_NOTIFY
HTTP NOTIFY Method
enumerator HTTP_METHOD_SUBSCRIBE
HTTP SUBSCRIBE Method
enumerator HTTP_METHOD_UNSUBSCRIBE
HTTP UNSUBSCRIBE Method
enumerator HTTP_METHOD_OPTIONS
HTTP OPTIONS Method
enumerator HTTP_METHOD_COPY
HTTP COPY Method
enumerator HTTP_METHOD_MOVE
HTTP MOVE Method
enumerator HTTP_METHOD_LOCK
HTTP LOCK Method
enumerator HTTP_METHOD_UNLOCK
HTTP UNLOCK Method
enumerator HTTP_METHOD_PROPFIND
HTTP PROPFIND Method
enumerator HTTP_METHOD_PROPPATCH
HTTP PROPPATCH Method
enumerator HTTP_METHOD_MKCOL
HTTP MKCOL Method
enumerator HTTP_METHOD_MAX
enum esp_http_client_auth_type_t
HTTP Authentication type.
Values:
enumerator HTTP_AUTH_TYPE_NONE
No authention
enumerator HTTP_AUTH_TYPE_BASIC
HTTP Basic authentication
enumerator HTTP_AUTH_TYPE_DIGEST
HTTP Disgest authentication
enum HttpStatus_Code
Enum for the HTTP status codes.
Values:
enumerator HttpStatus_Ok
enumerator HttpStatus_MultipleChoices
enumerator HttpStatus_MovedPermanently
enumerator HttpStatus_Found
enumerator HttpStatus_SeeOther
enumerator HttpStatus_TemporaryRedirect
enumerator HttpStatus_PermanentRedirect
enumerator HttpStatus_BadRequest
enumerator HttpStatus_Unauthorized
enumerator HttpStatus_Forbidden
enumerator HttpStatus_NotFound
enumerator HttpStatus_InternalError
Overview
ESP Local Control (esp_local_ctrl) component in ESP-IDF provides capability to control an ESP device over Wi-Fi
+ HTTPS or BLE. It provides access to application defined properties that are available for reading / writing via a
set of configurable handlers.
Initialization of the esp_local_ctrl service over BLE transport is performed as follows:
esp_local_ctrl_config_t config = {
.transport = ESP_LOCAL_CTRL_TRANSPORT_BLE,
.transport_config = {
.ble = & (protocomm_ble_config_t) {
.device_name = SERVICE_NAME,
.service_uuid = {
/* LSB <---------------------------------------
* ---------------------------------------> MSB */
0x21, 0xd5, 0x3b, 0x8d, 0xbd, 0x75, 0x68, 0x8a,
0xb4, 0x42, 0xeb, 0x31, 0x4a, 0x1e, 0x98, 0x3d
}
}
},
.proto_sec = {
.version = PROTOCOM_SEC0,
.custom_handle = NULL,
.pop = NULL,
},
.handlers = {
/* User defined handler functions */
.get_prop_values = get_property_values,
.set_prop_values = set_property_values,
.usr_ctx = NULL,
.usr_ctx_free_fn = NULL
},
/* Maximum number of properties that may be set */
.max_properties = 10
};
https_conf.servercert = servercert_start;
https_conf.servercert_len = servercert_end - servercert_start;
https_conf.prvtkey_pem = prvtkey_pem_start;
https_conf.prvtkey_len = prvtkey_pem_end - prvtkey_pem_start;
esp_local_ctrl_config_t config = {
.transport = ESP_LOCAL_CTRL_TRANSPORT_HTTPD,
.transport_config = {
.httpd = &https_conf
},
.proto_sec = {
.version = PROTOCOM_SEC0,
.custom_handle = NULL,
.pop = NULL,
(continues on next page)
You may set security for transport in ESP local control using following options:
1. PROTOCOM_SEC2: specifies that SRP6a based key exchange and end to end encryption based on AES-GCM
is used. This is the most preffered option as it adds a robust security with Augmented PAKE protocol i.e.
SRP6a.
2. PROTOCOM_SEC1: specifies that Curve25519 based key exchange and end to end encryption based on AES-
CTR is used.
3. PROTOCOM_SEC0: specifies that data will be exchanged as a plain text (no security).
4. PROTOCOM_SEC_CUSTOM: you can define your own security requirement. Please note that you will also
have to provide custom_handle of type protocomm_security_t * in this context.
Note: The respective security schemes need to be enabled through the project configuration menu. Please refer to
the Enabling protocom security version section in Protocol Communication for more details.
Creating a property
Now that we know how to start the esp_local_ctrl service, let’s add a property to it. Each property must have a
unique name (string), a type (e.g. enum), flags (bit fields) and size.
The size is to be kept 0, if we want our property value to be of variable length (e.g. if its a string or bytestream). For
fixed length property value data-types, like int, float, etc., setting the size field to the right value, helps esp_local_ctrl
to perform internal checks on arguments received with write requests.
The interpretation of type and flags fields is totally upto the application, hence they may be used as enumerations, bit-
fields, or even simple integers. One way is to use type values to classify properties, while flags to specify characteristics
of a property.
Here is an example property which is to function as a timestamp. It is assumed that the application defines
TYPE_TIMESTAMP and READONLY, which are used for setting the type and flags fields here.
Also notice that there is a ctx field, which is set to point to some custom func_get_time(). This can be used inside the
property get / set handlers to retrieve timestamp.
Here is an example of get_prop_values() handler, which is used for retrieving the timestamp.
static esp_err_t get_property_values(size_t props_count,
const esp_local_ctrl_prop_t *props,
esp_local_ctrl_prop_val_t *prop_
,→values,
void *usr_ctx)
{
for (uint32_t i = 0; i < props_count; i++) {
ESP_LOGI(TAG, "Reading %s", props[i].name);
if (props[i].type == TYPE_TIMESTAMP) {
/* Obtain the timer function from ctx */
int32_t (*func_get_time)(void) = props[i].ctx;
Here is an example of set_prop_values() handler. Notice how we restrict from writing to read-only properties.
static esp_err_t set_property_values(size_t props_count,
const esp_local_ctrl_prop_t *props,
const esp_local_ctrl_prop_val_t␣
,→*prop_values,
void *usr_ctx)
{
for (uint32_t i = 0; i < props_count; i++) {
if (props[i].flags & READONLY) {
ESP_LOGE(TAG, "Cannot write to read-only property %s",␣
,→props[i].name);
return ESP_ERR_INVALID_ARG;
} else {
ESP_LOGI(TAG, "Setting %s", props[i].name);
The client side implementation will have establish a protocomm session with the device first, over the supported mode
of transport, and then send and receive protobuf messages understood by the esp_local_ctrl service. The service will
translate these messages into requests and then call the appropriate handlers (set / get). Then, the generated response
for each handler is again packed into a protobuf message and transmitted back to the client.
See below the various protobuf messages understood by the esp_local_ctrl service:
1. get_prop_count : This should simply return the total number of properties supported by the service
2. get_prop_values : This accepts an array of indices and should return the information (name, type, flags) and
values of the properties corresponding to those indices
3. set_prop_values : This accepts an array of indices and an array of new values, which are used for setting the
values of the properties corresponding to the indices
Note that indices may or may not be the same for a property, across multiple sessions. Therefore, the client must
only use the names of the properties to uniquely identify them. So, every time a new session is established, the client
should first call get_prop_count and then get_prop_values, hence form an index to name mapping for all properties.
Now when calling set_prop_values for a set of properties, it must first convert the names to indexes, using the created
mapping. As emphasized earlier, the client must refresh the index to name mapping every time a new session is
established with the same device.
The various protocomm endpoints provided by esp_local_ctrl are listed below:
API Reference
Header File
• components/esp_local_ctrl/include/esp_local_ctrl.h
Functions
const esp_local_ctrl_transport_t *esp_local_ctrl_get_transport_ble(void)
Function for obtaining BLE transport mode.
const esp_local_ctrl_transport_t *esp_local_ctrl_get_transport_httpd(void)
Function for obtaining HTTPD transport mode.
esp_err_t esp_local_ctrl_start(const esp_local_ctrl_config_t *config)
Start local control service.
Parameters config –[in] Pointer to configuration structure
Returns
• ESP_OK : Success
• ESP_FAIL : Failure
esp_err_t esp_local_ctrl_stop(void)
Stop local control service.
esp_err_t esp_local_ctrl_add_property(const esp_local_ctrl_prop_t *prop)
Add a new property.
This adds a new property and allocates internal resources for it. The total number of properties that could be
added is limited by configuration option max_properties
Parameters prop –[in] Property description structure
Returns
• ESP_OK : Success
• ESP_FAIL : Failure
Note: In case of BLE transport the names and uuids of all custom endpoints must be provided beforehand as
a part of the protocomm_ble_config_t structure set in esp_local_ctrl_config_t, and passed
to esp_local_ctrl_start().
Parameters
• ep_name –[in] Name of the endpoint
• handler –[in] Endpoint handler function
• user_ctx –[in] User data
Returns
• ESP_OK : Success
• ESP_FAIL : Failure
Unions
union esp_local_ctrl_transport_config_t
#include <esp_local_ctrl.h> Transport mode (BLE / HTTPD) configuration.
Public Members
esp_local_ctrl_transport_config_ble_t *ble
This is same as protocomm_ble_config_t. See protocomm_ble.h for available configuration
parameters.
esp_local_ctrl_transport_config_httpd_t *httpd
This is same as httpd_ssl_config_t. See esp_https_server.h for available configuration
parameters.
Structures
struct esp_local_ctrl_prop
Property description data structure, which is to be populated and passed to the
esp_local_ctrl_add_property() function.
Once a property is added, its structure is available for read-only access inside get_prop_values() and
set_prop_values() handlers.
Public Members
char *name
Unique name of property
uint32_t type
Type of property. This may be set to application defined enums
size_t size
Size of the property value, which:
• if zero, the property can have values of variable size
• if non-zero, the property can have values of fixed size only, therefore, checks are performed internally
by esp_local_ctrl when setting the value of such a property
uint32_t flags
Flags set for this property. This could be a bit field. A flag may indicate property behavior, e.g. read-only
/ constant
void *ctx
Pointer to some context data relevant for this property. This will be available for use inside the
get_prop_values and set_prop_values handlers as a part of this property structure. When
set, this is valid throughout the lifetime of a property, till either the property is removed or the
esp_local_ctrl service is stopped.
struct esp_local_ctrl_prop_val
Property value data structure. This gets passed to the get_prop_values() and set_prop_values()
handlers for the purpose of retrieving or setting the present value of a property.
Public Members
void *data
Pointer to memory holding property value
size_t size
Size of property value
struct esp_local_ctrl_handlers
Handlers for receiving and responding to local control commands for getting and setting properties.
Public Members
Note: If any of the properties have fixed sizes, the size field of corresponding element in prop_values
need to be set
Note: If any of the properties have variable sizes, the size field of the corresponding element in
prop_values must be checked explicitly before making any assumptions on the size.
void *usr_ctx
Context pointer to be passed to above handler functions upon invocation. This is different from the
property level context, as this is valid throughout the lifetime of the esp_local_ctrl service, and
freed only when the service is stopped.
struct esp_local_ctrl_proto_sec_cfg
Protocom security configs
Public Members
esp_local_ctrl_proto_sec_t version
This sets protocom security version, sec0/sec1 or custom If custom, user must provide handle via
proto_sec_custom_handle below
void *custom_handle
Custom security handle if security is set custom via proto_sec above This handle must follow pro-
tocomm_security_t signature
struct esp_local_ctrl_config
Configuration structure to pass to esp_local_ctrl_start()
Public Members
esp_local_ctrl_transport_config_t transport_config
Transport layer over which service will be provided
esp_local_ctrl_proto_sec_cfg_t proto_sec
Security version and POP
esp_local_ctrl_handlers_t handlers
Register handlers for responding to get/set requests on properties
size_t max_properties
This limits the number of properties that are available at a time
Macros
ESP_LOCAL_CTRL_TRANSPORT_BLE
ESP_LOCAL_CTRL_TRANSPORT_HTTPD
Type Definitions
Enumerations
enum esp_local_ctrl_proto_sec
Security types for esp_local_control.
Values:
enumerator PROTOCOM_SEC0
enumerator PROTOCOM_SEC1
enumerator PROTOCOM_SEC2
enumerator PROTOCOM_SEC_CUSTOM
Overview
Espressif provides several chips that can work as slaves. These slave devices rely on some common buses, and have
their own communication protocols over those buses. The esp_serial_slave_link component is designed for the master
to communicate with ESP slave devices through those protocols over the bus drivers.
After an esp_serial_slave_link device is initialized properly, the application can use it to communicate with the ESP
slave devices conveniently.
For more details about Espressif device protocols, see the following documents.
Communication with ESP SDIO Slave This document describes the process of initialization of an ESP SDIO
Slave device and then provides details on the ESP SDIO Slave protocol - a non-standard protocol that allows an SDIO
Host to communicate with an ESP SDIO slave.
The ESP SDIO Slave protocol was created to implement the communication between SDIO host and slave, because
the SDIO specification only shows how to access the custom region of a card (by sending CMD52 and CMD53 to
Functions 1-7) without any details regarding the underlying hardware implementation.
SDIO Slave Capabilities of Espressif chips The services provided by the SDIO Slave peripheral of the ESP32
chip are listed in the table below:
Services ESP32
SDIO slave Y
Tohost intr 8
Frhost intr 8
TX DMA Y
RX DMA Y
Shared registers 56*
ESP SDIO Slave Initialization The host should initialize the ESP32 SDIO slave according to the standard SDIO
initialization process (Section 3.1.2 of SDIO Simplified Specification). In this specification as well as below, the
SDIO slave is called an (SD)IO card. Here is a brief example of an ESP SDIO Slave initialization process:
1. SDIO reset CMD52 (Write 0x6=0x8)
2. SD reset CMD0
3. Check whether IO card (optional) CMD8
4. Send SDIO op cond and wait for card ready CMD5 arg = 0x00000000
CMD5 arg = 0x00ff8000 (according to the response above, poll until ready)
Example: Arg of R4 after first CMD5 (arg=0x00000000) is 0xXXFFFF00.
Keep sending CMD5 with arg=0x00FFFF00 until the R4 shows card ready (arg bit 31=1).
5. Set address CMD3
6. Select card CMD7 (arg address according to CMD3 response)
Example: Arg of R6 after CMD3 is 0x0001xxxx.
Arg of CMD7 should be 0x00010000.
7. Select 4-bit mode (optional) CMD52 (Write 0x07=0x02)
8. Enable func1 CMD52 (Write 0x02=0x02)
9. Enable SDIO interrupt (required if interrupt line (DAT1) is used) CMD52 (Write 0x04=0x03)
10. Set Func0 blocksize (optional, default value is 512 (0x200)) CMD52/53 (Read 0x10~0x11)
CMD52/53 (Write 0x10=0x00)
CMD52/53 (Write 0x11=0x02)
CMD52/53 (Read 0x10~0x11, read to check the final value)
11. Set Func1 blocksize (optional, default value is 512 (0x200)) CMD52/53 (Read 0x110~0x111)
CMD52/53 (Write 0x110=0x00)
CMD52/53 (Write 0x111=0x02)
CMD52/53 (Read 0x110~0x111, read to check the final value)
ESP SDIO Slave Protocol The ESP SDIO Slave protocol is based on the SDIO Specification’s I/O Read/Write
commands, i.e., CMD52 and CMD53. The protocol offers the following services:
• Sending FIFO and receiving FIFO
• 52 8-bit R/W registers shared by host and slave (For details, see ESP32 Technical Reference Manual > SDIO
Slave Controller > Register Summary > SDIO SLC Host registers [PDF]
• 16 general purpose interrupt sources, 8 from host to slave and 8 from slave to host
To begin communication, the host needs to enable the I/O Function 1 in the slave and access its registers as described
below.
Check the code example peripherals/sdio.
The ESP Serial Slave Link component implements the logic of this protocol for ESP32 SDIO Host when communi-
cating with an ESP32 SDIO slave.
32-bit
• 0x044 (TOKEN_RDATA): in which bit 27-16 holds the number of the receiving buffer.
• 0x058 (INT_ST): holds the interrupt source bits from slave to host.
• 0x060 (PKT_LEN): holds the accumulated data length (in bytes) already read by host plus the data copied to
the buffer but yet to be read.
• 0x0D4 (INT_CLR): write 1 to clear interrupt bits corresponding to INT_ST.
• 0x0DC (INT_ENA): mask bits for interrupts from slave to host.
FIFO (sending and receiving) 0x090 - 0x1F7FF are reserved for FIFOs.
The address of CMD53 is related to the length requested to read from or write to the slave in a single transfer, as
demonstrated by the equation below:
requested length = 0x1F800-address
The slave will respond with data that has a length equal to the length field of CMD53. In cases where the data is longer
than the requested length, the data will be zero filled (when sending) or discarded (when receiving). This includes
both the block and the byte mode of CMD53.
Note: The function number should be set to 1, OP Code should be set to 1 (for CMD53).
In order to achieve higher efficiency when accessing the FIFO by an arbitrary length, the block and byte modes of
CMD53 can be used in combination. For example, given that the block size is set to 512 by default, you can write/get
1031 bytes of data from the FIFO by doing the following:
1. Send CMD53 in block mode, block count=2 (1024 bytes) to address 0x1F3F9=0x1F800-1031.
2. Then send CMD53 in byte mode, byte count=8 (or 7 if your controller supports that) to address
0x1F7F9=0x1F800-7.
Interrupts SDIO interrupts are “level sensitive”. For host interrupts, the slave sends an interrupt by pulling the
DAT1 line down at a proper time. The host detects when the interrupt line is pulled down and reads the INT_ST
register to determine the source of the interrupt. After that, the host can clear the interrupt bits by writing the
INT_CLR register and process the interrupt. The host can also mask unneeded sources by clearing the bits in the
INT_ENA register corresponding to the sources. If all the sources are cleared (or masked), the DAT1 line goes
inactive.
On ESP32, the corresponding host_int bits are: bit 0 to bit 7.
For slave interrupts, the host sends a transfer to write the SLAVE_INT register. Once a bit is set to 1, the slave
hardware and the driver will detect it and inform the application.
Receiving FIFO To write to the slave’s receiving FIFO, the host should complete the following steps:
1. Read the TOKEN1 field (bits 27-16) of the register TOKEN_RDATA (0x044). The buffer number re-
maining is TOKEN1 minus the number of buffers used by host.
2. Make sure the buffer number is sufficient (buffer_size x buffer_num is greater than the data to write,
buffer_size is pre-defined between the host and the slave before the communication starts). Otherwise, keep
returning to Step 1 until the buffer size is sufficient.
3. Write to the FIFO address with CMD53. Note that the requested length should not exceed the length
calculated at Step 2, and the FIFO address is related to requested length.
4. Calculate used buffers. Note that a partially used buffer at the tail is counted as used.
Sending FIFO To read the slave’s sending FIFO, the host should complete the following steps:
1. Wait for the interrupt line to become active (optional, low by default).
2. Read (poll) the interrupt bits in the INT_ST register to monitor if new packets exist.
3. If new packets are ready, read the PKT_LEN register. Before reading the packets, determine the length
of data to be read. As the host keeps the length of data already read from the slave, subtract this value from
PKT_LEN, the result will be the maximum length of data available for reading. If no data has been added to
the sending FIFO yet, wait and poll until the slave is ready and update PKT_LEN.
4. Read from the FIFO using CMD53. Note that the requested length should not be greater than calculated at
Step 3, and the FIFO address is related to requested length.
Introduction In the half duplex mode, the master has to use the protocol defined by the slave to communicate with
the slave. Each transaction may consist of the following phases (list by the order they should exist):
• Command: 8-bit, master to slave
This phase determines the rest phases of the transactions. See Supported Commands.
• Address: 8-bit, master to slave, optional
For some commands (WRBUF, RDBUF), this phase specifies the address of the shared buffer to
write to/read from. For other commands with this phase, they are meaningless but still have to exist
in the transaction.
• Dummy: 8-bit, floating, optional
This phase is the turnaround time between the master and the slave on the bus, and also provides
enough time for the slave to prepare the data to send to the master.
• Data: variable length, the direction is also determined by the command.
This may be a data OUT phase, in which the direction is slave to master, or a data IN phase, in
which the direction is master to slave.
The direction means which side (master or slave) controls the MOSI, MISO, WP, and HD pins.
Data IO Modes In some IO modes, more data wires can be used to send the data. As a result, the SPI clock cycles
required for the same amount of data will be less than in the 1-bit mode. For example, in QIO mode, address and
data (IN and OUT) should be sent on all 4 data wires (MOSI, MISO, WP, and HD). Here are the modes supported
by the ESP32-S2 SPI slave and the wire number used in corresponding modes.
Normally, which mode is used is determined by the command sent by the master (See Supported Commands), except
the QPI mode.
QPI Mode The QPI mode is a special state of the SPI Slave. The master can send the ENQPI command to put the
slave into the QPI mode state. In the QPI mode, the command is also sent in 4-bit, thus it’s not compatible with the
normal modes. The master should only send QPI commands when the slave is in QPI mode. To exit from the QPI
mode, master can send the EXQPI command.
Supported Commands
Note: The command name is in a master-oriented direction. For example, WRBUF means master writes the buffer
of slave.
Moreover, WRBUF, RDBUF, WRDMA, RDDMA commands have their 2-bit and 4-bit version. To do transactions
in 2-bit or 4-bit mode, send the original command ORed by the corresponding command mask below. For example,
command 0xA1 means WRBUF in QIO mode.
Mode Mask
1-bit 0x00
DOUT 0x10
DIO 0x50
QOUT 0x20
QIO 0xA0
QPI 0xA0
Segment Transaction Mode Segment transaction mode is the only mode supported by the SPI Slave HD driver
for now. In this mode, for a transaction the slave load onto the DMA, the master is allowed to read or write in
segments. This way the master doesn’t have to prepare a large buffer as the size of data provided by the slave. After
the master finishes reading/writing a buffer, it has to send the corresponding termination command to the slave as a
synchronization signal. The slave driver will update new data (if exist) onto the DMA upon seeing the termination
command.
The termination command is WR_DONE (0x07) for the WRDMA and CMD8 (0x08) for the RDDMA.
Here’s an example for the flow the master read data from the slave DMA:
1. The slave loads 4092 bytes of data onto the RDDMA
2. The master do seven RDDMA transactions, each of them is 512 bytes long, and reads the first 3584 bytes from
the slave
3. The master do the last RDDMA transaction of 512 bytes (equal, longer, or shorter than the total length loaded
by the slave are all allowed). The first 508 bytes are valid data from the slave, while the last 4 bytes are
meaningless bytes.
4. The master sends CMD8 to the slave
5. The slave loads another 4092 bytes of data onto the RDDMA
6. The master can start new reading transactions after it sends the CMD8
Terminology
• ESSL: Abbreviation for ESP Serial Slave Link, the component described by this document.
• Master: The device running the esp_serial_slave_link component.
• ESSL device: a virtual device on the master associated with an ESP slave device. The device context has the
knowledge of the slave protocol above the bus, relying on some bus drivers to communicate with the slave.
• ESSL device handle: a handle to ESSL device context containing the configuration, status and data required
by the ESSL component. The context stores the driver configurations, communication state, data shared by
master and slave, etc.
The context should be initialized before it is used, and get deinitialized if not used any more. The master
application operates on the ESSL device through this handle.
• ESP slave: the slave device connected to the bus, which ESSL component is designed to communicate with.
• Bus: The bus over which the master and the slave communicate with each other.
• Slave protocol: The special communication protocol specified by Espressif HW/SW over the bus.
• TX buffer num: a counter, which is on the slave and can be read by the master, indicates the accumulated
buffer numbers that the slave has loaded to the hardware to receive data from the master.
• RX data size: a counter, which is on the slave and can be read by the master, indicates the accumulated data
size that the slave has loaded to the hardware to send to the master.
ESP SDIO Slave The ESP SDIO slave link (ESSL SDIO) devices relies on the sdmmc component. It includes the
usage of communicating with ESP SDIO Slave device via SDSPI feature. The ESSL device should be initialized as
below:
1. Initialize a sdmmc card (see :doc:` Document of SDMMC driver </api-reference/storage/sdmmc>`) structure.
APIs
After the initialization process above is performed, you can call the APIs below to make use of the services provided
by the slave:
Frhost Interrupts
1. Call essl_send_slave_intr() to trigger general purpose interrupt of the slave.
TX FIFO
1. Call essl_get_tx_buffer_num() to know how many buffers the slave has prepared to receive data
from the master. This is optional. The master will poll tx_buffer_num when it try to send packets to the slave,
until the slave has enough buffer or timeout.
2. Call essl_send_packet() to send data to the slave.
RX FIFO
1. Call essl_get_rx_data_size() to know how many data the slave has prepared to send to the master.
This is optional. When the master tries to receive data from the slave, it will update the rx_data_size for once,
if the current rx_data_size is shorter than the buffer size the master prepared to receive. And it may poll the
rx_data_size if the rx_dat_size keeps 0, until timeout.
2. Call essl_get_packet() to receive data from the slave.
Reset counters (Optional) Call essl_reset_cnt() to reset the internal counter if you find the slave has reset
its counter.
Application Example
The example below shows how ESP32 SDIO host and slave communicate with each other. The host use the ESSL
SDIO.
peripherals/sdio.
API Reference
Header File
• components/esp_serial_slave_link/include/esp_serial_slave_link/essl.h
Functions
esp_err_t essl_init(essl_handle_t handle, uint32_t wait_ms)
Initialize the slave.
Parameters
• handle –Handle of an ESSL device.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK: If success
• ESP_ERR_NOT_SUPPORTED: Current device does not support this function.
• Other value returned from lower layer init.
esp_err_t essl_wait_for_ready(essl_handle_t handle, uint32_t wait_ms)
Wait for interrupt of an ESSL slave device.
Parameters
• handle –Handle of an ESSL device.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK: If success
• ESP_ERR_NOT_SUPPORTED: Current device does not support this function.
• One of the error codes from SDMMC host controller
esp_err_t essl_get_tx_buffer_num(essl_handle_t handle, uint32_t *out_tx_num, uint32_t wait_ms)
Get buffer num for the host to send data to the slave. The buffers are size of buffer_size.
Parameters
• handle –Handle of a ESSL device.
• out_tx_num –Output of buffer num that host can send data to ESSL slave.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK: Success
• ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode
• One of the error codes from SDMMC/SPI host controller
esp_err_t essl_get_rx_data_size(essl_handle_t handle, uint32_t *out_rx_size, uint32_t wait_ms)
Get the size, in bytes, of the data that the ESSL slave is ready to send
Parameters
• handle –Handle of an ESSL device.
• out_rx_size –Output of data size to read from slave, in bytes
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK: Success
• ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode
• One of the error codes from SDMMC/SPI host controller
esp_err_t essl_reset_cnt(essl_handle_t handle)
Reset the counters of this component. Usually you don’t need to do this unless you know the slave is reset.
Parameters handle –Handle of an ESSL device.
Returns
• ESP_OK: Success
Note: sdio 28-31 are reserved, the lower API helps to skip.
Parameters
• handle –Handle of an ESSL device.
• addr –Address of register to write. For SDIO, valid address: 0-59. For SPI, see
essl_spi.h
• value –Value to write to the register.
• value_o –Output of the returned written value.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK Success
• One of the error codes from SDMMC/SPI host controller
Type Definitions
Header File
• components/esp_serial_slave_link/include/esp_serial_slave_link/essl_sdio.h
Functions
esp_err_t essl_sdio_init_dev(essl_handle_t *out_handle, const essl_sdio_config_t *config)
Initialize the ESSL SDIO device and get its handle.
Parameters
• out_handle –Output of the handle.
• config –Configuration for the ESSL SDIO device.
Returns
• ESP_OK: on success
• ESP_ERR_NO_MEM: memory exhausted.
esp_err_t essl_sdio_deinit_dev(essl_handle_t handle)
Deinitialize and free the space used by the ESSL SDIO device.
Parameters handle –Handle of the ESSL SDIO device to deinit.
Returns
• ESP_OK: on success
• ESP_ERR_INVALID_ARG: wrong handle passed
Structures
struct essl_sdio_config_t
Configuration for the ESSL SDIO device.
Public Members
sdmmc_card_t *card
The initialized sdmmc card pointer of the slave.
int recv_buffer_size
The pre-negotiated recv buffer size used by both the host and the slave.
Header File
• components/esp_serial_slave_link/include/esp_serial_slave_link/essl_spi.h
Functions
esp_err_t essl_spi_init_dev(essl_handle_t *out_handle, const essl_spi_config_t *init_config)
Initialize the ESSL SPI device function list and get its handle.
Parameters
• out_handle –[out] Output of the handle
• init_config –Configuration for the ESSL SPI device
Returns
• ESP_OK: On success
• ESP_ERR_NO_MEM: Memory exhausted
• ESP_ERR_INVALID_STATE: SPI driver is not initialized
• ESP_ERR_INVALID_ARG: Wrong register ID
esp_err_t essl_spi_deinit_dev(essl_handle_t handle)
Deinitialize the ESSL SPI device and free the memory used by the device.
Parameters handle –Handle of the ESSL SPI device
Returns
• ESP_OK: On success
• ESP_ERR_INVALID_STATE: ESSL SPI is not in use
esp_err_t essl_spi_read_reg(void *arg, uint8_t addr, uint8_t *out_value, uint32_t wait_ms)
Read from the shared registers.
Note: The registers for Master/Slave synchronization are reserved. Do not use them. (see rx_sync_reg
in essl_spi_config_t)
Parameters
• arg –Context of the component. (Member arg from essl_handle_t)
• addr –Address of the shared registers. (Valid: 0 ~
SOC_SPI_MAXIMUM_BUFFER_SIZE, registers for M/S sync are reserved, see
note1).
• out_value –[out] Read buffer for the shared registers.
• wait_ms –Time to wait before timeout (reserved for future use, user should set this to
0).
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized.
• ESP_ERR_INVALID_ARG: The address argument is not valid. See note 1.
• or other return value from :cpp:func:spi_device_transmit.
Parameters
• arg –Context of the component. (Member arg from essl_handle_t)
• out_data –[out] Output data address
• size –The size of the output data.
• wait_ms –Time to wait before timeout (reserved for future use, user should set this to
0).
Returns
• ESP_OK: On Success
• ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized.
• ESP_ERR_INVALID_ARG: The output data address is neither DMA capable nor 4 byte-
aligned
• ESP_ERR_INVALID_SIZE: Master requires size bytes of data but Slave did not load
enough bytes.
esp_err_t essl_spi_write_reg(void *arg, uint8_t addr, uint8_t value, uint8_t *out_value, uint32_t
wait_ms)
Write to the shared registers.
Note: The registers for Master/Slave synchronization are reserved. Do not use them. (see tx_sync_reg
in essl_spi_config_t)
Note: Feature of checking the actual written value (out_value) is not supported.
Parameters
• arg –Context of the component. (Member arg from essl_handle_t)
• addr –Address of the shared registers. (Valid: 0 ~
SOC_SPI_MAXIMUM_BUFFER_SIZE, registers for M/S sync are reserved, see
note1)
• value –Buffer for data to send, should be align to 4.
• out_value –[out] Not supported, should be set to NULL.
• wait_ms –Time to wait before timeout (reserved for future use, user should set this to
0).
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized.
• ESP_ERR_INVALID_ARG: The address argument is not valid. See note 1.
• ESP_ERR_NOT_SUPPORTED: Should set out_value to NULL. See note 2.
• or other return value from :cpp:func:spi_device_transmit.
esp_err_t essl_spi_send_packet(void *arg, const void *data, size_t size, uint32_t wait_ms)
Send a packet to Slave.
Parameters
• arg –Context of the component. (Member arg from essl_handle_t)
• data –Address of the data to send
• size –Size of the data to send.
• wait_ms –Time to wait before timeout (reserved for future use, user should set this to
0).
Returns
• ESP_OK: On success
• ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized.
• ESP_ERR_INVALID_ARG: The data address is not DMA capable
• ESP_ERR_INVALID_SIZE: Master will send size bytes of data but Slave did not load
enough RX buffer
Note: Shall only be called if the slave has reset its counter. Else, Slave and Master would be desynchronized
esp_err_t essl_spi_rdbuf(spi_device_handle_t spi, uint8_t *out_data, int addr, int len, uint32_t flags)
Read the shared buffer from the slave in ISR way.
Note: The slave’s HW doesn’t guarantee the data in one SPI transaction is consistent. It sends data in unit
of byte. In other words, if the slave SW attempts to update the shared register when a rdbuf SPI transaction is
in-flight, the data got by the master will be the combination of bytes of different writes of slave SW.
Note: out_data should be prepared in words and in the DRAM. The buffer may be written in words by the
DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the len is
shorter than a word.
Parameters
• spi –SPI device handle representing the slave
• out_data –[out] Buffer for read data, strongly suggested to be in the DRAM and aligned
to 4
• addr –Address of the slave shared buffer
• len –Length to read
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: on success
• or other return value from :cpp:func:spi_device_transmit.
esp_err_t essl_spi_rdbuf_polling(spi_device_handle_t spi, uint8_t *out_data, int addr, int len, uint32_t
flags)
Read the shared buffer from the slave in polling way.
Note: out_data should be prepared in words and in the DRAM. The buffer may be written in words by the
DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the len is
shorter than a word.
Parameters
• spi –SPI device handle representing the slave
• out_data –[out] Buffer for read data, strongly suggested to be in the DRAM and aligned
to 4
• addr –Address of the slave shared buffer
• len –Length to read
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: on success
• or other return value from :cpp:func:spi_device_transmit.
esp_err_t essl_spi_wrbuf(spi_device_handle_t spi, const uint8_t *data, int addr, int len, uint32_t flags)
Write the shared buffer of the slave in ISR way.
Note: out_data should be prepared in words and in the DRAM. The buffer may be written in words by the
DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the len is
shorter than a word.
Parameters
• spi –SPI device handle representing the slave
• data –Buffer for data to send, strongly suggested to be in the DRAM
• addr –Address of the slave shared buffer,
• len –Length to write
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_transmit.
esp_err_t essl_spi_wrbuf_polling(spi_device_handle_t spi, const uint8_t *data, int addr, int len, uint32_t
flags)
Write the shared buffer of the slave in polling way.
Note: out_data should be prepared in words and in the DRAM. The buffer may be written in words by the
DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the len is
shorter than a word.
Parameters
• spi –SPI device handle representing the slave
• data –Buffer for data to send, strongly suggested to be in the DRAM
• addr –Address of the slave shared buffer,
• len –Length to write
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_polling_transmit.
esp_err_t essl_spi_rddma(spi_device_handle_t spi, uint8_t *out_data, int len, int seg_len, uint32_t flags)
Receive long buffer in segments from the slave through its DMA.
Parameters
• spi –SPI device handle representing the slave
• out_data –[out] Buffer to hold the received data, strongly suggested to be in the DRAM
and aligned to 4
• len –Total length of data to receive.
• seg_len –Length of each segment, which is not larger than the maximum transaction
length allowed for the spi device. Suggested to be multiples of 4. When set < 0, means
send all data in one segment (the rddma_done will still be sent.)
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_transmit.
Parameters
• spi –SPI device handle representing the slave
• out_data –[out] Buffer to hold the received data. strongly suggested to be in the DRAM
and aligned to 4
• seg_len –Length of this segment
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_transmit.
Note: This is required only when the slave is working in segment mode.
Parameters
• spi –SPI device handle representing the slave
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_transmit.
esp_err_t essl_spi_wrdma(spi_device_handle_t spi, const uint8_t *data, int len, int seg_len, uint32_t flags)
Send long buffer in segments to the slave through its DMA.
Parameters
• spi –SPI device handle representing the slave
• data –Buffer for data to send, strongly suggested to be in the DRAM
• len –Total length of data to send.
• seg_len –Length of each segment, which is not larger than the maximum transaction
length allowed for the spi device. Suggested to be multiples of 4. When set < 0, means
send all data in one segment (the wrdma_done will still be sent.)
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_transmit.
esp_err_t essl_spi_wrdma_seg(spi_device_handle_t spi, const uint8_t *data, int seg_len, uint32_t flags)
Send one data segment to the slave through its DMA.
Parameters
• spi –SPI device handle representing the slave
• data –Buffer for data to send, strongly suggested to be in the DRAM
• seg_len –Length of this segment
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_transmit.
Note: This is required only when the slave is working in segment mode.
Parameters
• spi –SPI device handle representing the slave
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_transmit.
Structures
struct essl_spi_config_t
Configuration of ESSL SPI device.
Public Members
spi_device_handle_t *spi
Pointer to SPI device handle.
uint32_t tx_buf_size
The pre-negotiated Master TX buffer size used by both the host and the slave.
uint8_t tx_sync_reg
The pre-negotiated register ID for Master-TX-SLAVE-RX synchronization. 1 word (4 Bytes) will be
reserved for the synchronization.
uint8_t rx_sync_reg
The pre-negotiated register ID for Master-RX-Slave-TX synchronization. 1 word (4 Bytes) will be re-
served for the synchronization.
Overview
The ESP x509 Certificate Bundle API provides an easy way to include a bundle of custom x509 root certificates for
TLS server verification.
The bundle comes with the complete list of root certificates from Mozilla’s NSS root certificate store. Using the
gen_crt_bundle.py python utility the certificates’subject name and public key are stored in a file and embedded in
the ESP32 binary.
When generating the bundle you may choose between:
• The full root certificate bundle from Mozilla, containing more than 130 certificates. The current bundle was
updated Tue Apr 26 03:12:05 2022 GMT.
• A pre-selected filter list of the name of the most commonly used root certificates, reducing the amount of
certificates to around 35 while still having around 90 % coverage according to market share statistics.
In addition it is possible to specify a path to a certificate file or a directory containing certificates which then will be
added to the generated bundle.
Note: Trusting all root certificates means the list will have to be updated if any of the certificates are retracted. This
includes removing them from cacrt_all.pem.
Configuration
Most configuration is done through menuconfig. CMake will generate the bundle according to the configuration and
embed it.
• CONFIG_MBEDTLS_CERTIFICATE_BUNDLE: automatically build and attach the bundle.
• CONFIG_MBEDTLS_DEFAULT_CERTIFICATE_BUNDLE: decide which certificates to include from the com-
plete root list.
• CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE_PATH: specify the path of any additional certifi-
cates to embed in the bundle.
To enable the bundle when using ESP-TLS simply pass the function pointer to the bundle attach function:
esp_tls_cfg_t cfg = {
.crt_bundle_attach = esp_crt_bundle_attach,
};
This is done to avoid embedding the certificate bundle unless activated by the user.
If using mbedTLS directly then the bundle may be activated by directly calling the attach function during the setup
process:
mbedtls_ssl_config conf;
mbedtls_ssl_config_init(&conf);
esp_crt_bundle_attach(&conf);
The list of root certificates comes from Mozilla’s NSS root certificate store, which can be found here The list can
be downloaded and created by running the script mk-ca-bundle.pl that is distributed as a part of curl. Another
alternative would be to download the finished list directly from the curl website: CA certificates extracted from
Mozilla
The common certificates bundle were made by selecting the authorities with a market share of more than 1 % from
w3tech’s SSL Survey. These authorities were then used to pick the names of the certificates for the filter list,
cmn_crt_authorities.csv, from this list provided by Mozilla.
The bundle is embedded into the app and can be updated along with the app by an OTA update. If you want to include
a more up-to-date bundle than the bundle currently included in ESP-IDF, then the certificate list can be downloaded
from Mozilla as described in Generating the List of Root Certificates.
Application Example
Simple HTTPS example that uses ESP-TLS to establish a secure socket connection using the certificate bundle with
two custom certificates added for verification: protocols/https_x509_bundle.
HTTPS example that uses ESP-TLS and the default bundle: protocols/https_request.
HTTPS example that uses mbedTLS and the default bundle: protocols/https_mbedtls.
API Reference
Header File
• components/mbedtls/esp_crt_bundle/include/esp_crt_bundle.h
Functions
esp_err_t esp_crt_bundle_attach(void *conf)
Attach and enable use of a bundle for certificate verification.
Attach and enable use of a bundle for certificate verification through a verification callback. If no specific bundle
has been set through esp_crt_bundle_set() it will default to the bundle defined in menuconfig and embedded in
the binary.
Parameters conf –[in] The config struct for the SSL connection.
Returns
• ESP_OK if adding certificates was successful.
• Other if an error occured or an action must be taken by the calling process.
void esp_crt_bundle_detach(mbedtls_ssl_config *conf)
Disable and dealloc the certification bundle.
Removes the certificate verification callback and deallocates used resources
Parameters conf –[in] The config struct for the SSL connection.
esp_err_t esp_crt_bundle_set(const uint8_t *x509_bundle, size_t bundle_size)
Set the default certificate bundle used for verification.
Overrides the default certificate bundle only in case of successful initialization. In most use cases the bundle
should be set through menuconfig. The bundle needs to be sorted by subject name since binary search is used
to find certificates.
Parameters
• x509_bundle –[in] A pointer to the certificate bundle.
• bundle_size –[in] Size of the certificate bundle in bytes.
Returns
• ESP_OK if adding certificates was successful.
• Other if an error occured or an action must be taken by the calling process.
Overview
The HTTP Server component provides an ability for running a lightweight web server on ESP32. Following are
detailed steps to use the API exposed by HTTP Server:
• httpd_start(): Creates an instance of HTTP server, allocate memory/resources for it depending upon
the specified configuration and outputs a handle to the server instance. The server has both, a listening socket
(TCP) for HTTP traffic, and a control socket (UDP) for control signals, which are selected in a round robin
fashion in the server task loop. The task priority and stack size are configurable during server instance creation
by passing httpd_config_t structure to httpd_start(). TCP traffic is parsed as HTTP requests and, depending
on the requested URI, user registered handlers are invoked which are supposed to send back HTTP response
packets.
• httpd_stop(): This stops the server with the provided handle and frees up any associated mem-
ory/resources. This is a blocking function that first signals a halt to the server task and then waits for the
task to terminate. While stopping, the task will close all open connections, remove registered URI handlers
and reset all session context data to empty.
• httpd_register_uri_handler(): A URI handler is registered by passing object of type
httpd_uri_t structure which has members including uri name, method type (eg. HTTPD_GET/
HTTPD_POST/HTTPD_PUT etc.), function pointer of type esp_err_t *handler (httpd_req_t
*req) and user_ctx pointer to user context data.
Application Example
Simple HTTP Server Example Check HTTP server example under protocols/http_server/simple where handling
of arbitrary content lengths, reading request headers and URL query parameters, and setting response headers is
demonstrated.
Persistent Connections
HTTP server features persistent connections, allowing for the re-use of the same connection (session) for several
transfers, all the while maintaining context specific data for the session. Context data may be allocated dynamically by
the handler in which case a custom function may need to be specified for freeing this data when the connection/session
is closed.
/* Respond */
...............
...............
...............
return ESP_OK;
}
Websocket Server
The HTTP server component provides websocket support. The websocket feature can be enabled in menuconfig us-
ing the CONFIG_HTTPD_WS_SUPPORT option. Please refer to the protocols/http_server/ws_echo_server example
which demonstrates usage of the websocket feature.
API Reference
Header File
• components/esp_http_server/include/esp_http_server.h
Functions
esp_err_t httpd_register_uri_handler(httpd_handle_t handle, const httpd_uri_t *uri_handler)
Registers a URI handler.
Example usage:
esp_err_t my_uri_handler(httpd_req_t* req)
{
// Recv , Process and Send
....
....
....
// Fail condition
(continues on next page)
// On success
return ESP_OK;
}
// Register handler
if (httpd_register_uri_handler(server_handle, &my_uri) != ESP_OK) {
// If failed to register handler
....
}
Note: URI handlers can be registered in real time as long as the server handle is valid.
Parameters
• handle –[in] handle to HTTPD server instance
• uri_handler –[in] pointer to handler that needs to be registered
Returns
• ESP_OK : On successfully registering the handler
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_HTTPD_HANDLERS_FULL : If no slots left for new handler
• ESP_ERR_HTTPD_HANDLER_EXISTS : If handler with same URI and method is al-
ready registered
esp_err_t httpd_unregister_uri_handler(httpd_handle_t handle, const char *uri, httpd_method_t
method)
Unregister a URI handler.
Parameters
• handle –[in] handle to HTTPD server instance
• uri –[in] URI string
• method –[in] HTTP method
Returns
• ESP_OK : On successfully deregistering the handler
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_NOT_FOUND : Handler with specified URI and method not found
esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char *uri)
Unregister all URI handlers with the specified uri string.
Parameters
• handle –[in] handle to HTTPD server instance
• uri –[in] uri string specifying all handlers that need to be deregisterd
Returns
• ESP_OK : On successfully deregistering all such handlers
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_NOT_FOUND : No handler registered with specified uri string
Parameters
• hd –[in] HTTPD instance handle
• sockfd –[in] Session socket FD
• recv_func –[in] The receive function to be set for this session
Returns
• ESP_OK : On successfully registering override
• ESP_ERR_INVALID_ARG : Null arguments
Parameters
• hd –[in] HTTPD instance handle
• sockfd –[in] Session socket FD
• send_func –[in] The send function to be set for this session
Returns
• ESP_OK : On successfully registering override
• ESP_ERR_INVALID_ARG : Null arguments
Parameters
• hd –[in] HTTPD instance handle
• sockfd –[in] Session socket FD
• pending_func –[in] The receive function to be set for this session
Returns
• ESP_OK : On successfully registering override
Note: This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• If an error is returned, the URI handler must further return an error. This will ensure that the erroneous
socket is closed and cleaned up by the web server.
• Presently Chunked Encoding is not supported
Parameters
• r –[in] The request being responded to
• buf –[in] Pointer to a buffer that the data will be read into
• buf_len –[in] Length of the buffer
Returns
• Bytes : Number of bytes read into the buffer successfully
• 0 : Buffer length parameter is zero / connection closed by peer
• HTTPD_SOCK_ERR_INVALID : Invalid arguments
• HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
• HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()
Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Once httpd_resp_send() API is called all request headers are purged, so request headers need be copied
into separate buffers if they are required later.
Parameters
esp_err_t httpd_req_get_hdr_value_str(httpd_req_t *r, const char *field, char *val, size_t val_size)
Get the value string of a field from the request headers.
Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Once httpd_resp_send() API is called all request headers are purged, so request headers need be copied
into separate buffers if they are required later.
• If output size is greater than input, then the value is truncated, accompanied by truncation error as return
value.
• Use httpd_req_get_hdr_value_len() to know the right buffer length
Parameters
• r –[in] The request being responded to
• field –[in] The field to be searched in the header
• val –[out] Pointer to the buffer into which the value will be copied if the field is found
• val_size –[in] Size of the user buffer “val”
Returns
• ESP_OK : Field found in the request header and value string copied
• ESP_ERR_NOT_FOUND : Key not found
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
• ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
Note: This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid
Note:
• Presently, the user can fetch the full URL query string, but decoding will have to be performed by the
user. Request headers can be read using httpd_req_get_hdr_value_str() to know the ‘Content-Type’
(eg. Content-Type: application/x-www-form-urlencoded) and then the appropriate decoding algorithm
needs to be applied.
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid
• If output size is greater than input, then the value is truncated, accompanied by truncation error as return
value
• Prior to calling this function, one can use httpd_req_get_url_query_len() to know the query string length
beforehand and hence allocate the buffer of right size (usually query string length + 1 for null termination)
for storing the query string
Parameters
• r –[in] The request being responded to
• buf –[out] Pointer to the buffer into which the query string will be copied (if found)
• buf_len –[in] Length of output buffer
Returns
• ESP_OK : Query is found in the request URL and copied to buffer
• ESP_ERR_NOT_FOUND : Query not found
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
• ESP_ERR_HTTPD_RESULT_TRUNC : Query string truncated
esp_err_t httpd_query_key_value(const char *qry, const char *key, char *val, size_t val_size)
Helper function to get a URL query tag from a query string of the type param1=val1¶m2=val2.
Note:
• The components of URL query string (keys and values) are not URLdecoded. The user must check for
‘Content-Type’field in the request headers and then depending upon the specified encoding (URLen-
coded or otherwise) apply the appropriate decoding algorithm.
• If actual value size is greater than val_size, then the value is truncated, accompanied by truncation error
as return value.
Parameters
• qry –[in] Pointer to query string
• key –[in] The key to be searched in the query string
• val –[out] Pointer to the buffer into which the value will be copied if the key is found
• val_size –[in] Size of the user buffer “val”
Returns
• ESP_OK : Key is found in the URL query string and copied to buffer
• ESP_ERR_NOT_FOUND : Key not found
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Once this API is called, the request has been responded to.
• No additional data can then be sent for the request.
• Once this API is called, all request headers are purged, so request headers need be copied into separate
buffers if they are required later.
Parameters
• r –[in] The request being responded to
• buf –[in] Buffer from where the content is to be fetched
• buf_len –[in] Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen()
Returns
• ESP_OK : On successfully sending the response packet
• ESP_ERR_INVALID_ARG : Null request pointer
• ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
• ESP_ERR_HTTPD_RESP_SEND : Error in raw send
• ESP_ERR_HTTPD_INVALID_REQ : Invalid request
If no status code and content-type were set, by default this will send 200 OK status code and content
type as text/html. You may call the following functions before this API to configure the response headers
httpd_resp_set_status() - for setting the HTTP status string, httpd_resp_set_type() - for setting the Content
Type, httpd_resp_set_hdr() - for appending any additional field value entries in the response header
Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• When you are finished sending all your chunks, you must call this function with buf_len as 0.
• Once this API is called, all request headers are purged, so request headers need be copied into separate
buffers if they are required later.
Parameters
• r –[in] The request being responded to
• buf –[in] Pointer to a buffer that stores the data
• buf_len –[in] Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen()
Returns
• ESP_OK : On successfully sending the response packet chunk
• ESP_ERR_INVALID_ARG : Null request pointer
• ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
• ESP_ERR_HTTPD_RESP_SEND : Error in raw send
• ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
This API sets the status of the HTTP response to the value specified. By default, the ‘200 OK’response is
sent as the response.
Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• This API only sets the status to this value. The status isn’t sent out until any of the send APIs is executed.
• Make sure that the lifetime of the status string is valid till send function is called.
Parameters
• r –[in] The request being responded to
• status –[in] The HTTP status code of this response
Returns
• ESP_OK : On success
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• This API only sets the content type to this value. The type isn’t sent out until any of the send APIs is
executed.
• Make sure that the lifetime of the type string is valid till send function is called.
Parameters
• r –[in] The request being responded to
• type –[in] The Content Type of the response
Returns
• ESP_OK : On success
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• The header isn’t sent out until any of the send APIs is executed.
• The maximum allowed number of additional headers is limited to value of max_resp_headers in config
structure.
• Make sure that the lifetime of the field value strings are valid till send function is called.
Parameters
• r –[in] The request being responded to
• field –[in] The field name of the HTTP header
Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Once this API is called, all request headers are purged, so request headers need be copied into separate
buffers if they are required later.
• If you wish to send additional data in the body of the response, please use the lower-level functions
directly.
Parameters
• req –[in] Pointer to the HTTP request for which the response needs to be sent
• error –[in] Error type to send
• msg –[in] Error message string (pass NULL for default message)
Returns
• ESP_OK : On successfully sending the response packet
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_HTTPD_RESP_SEND : Error in raw send
• ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer
Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Once this API is called, all request headers are purged, so request headers need be copied into separate
buffers if they are required later.
Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Once this API is called, all request headers are purged, so request headers need be copied into separate
buffers if they are required later.
Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Once this API is called, all request headers are purged, so request headers need be copied into separate
buffers if they are required later.
Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Unless the response has the correct HTTP structure (which the user must now ensure) it is not guaranteed
that it will be recognized by the client. For most cases, you wouldn’t have to call this API, but you would
rather use either of : httpd_resp_send(), httpd_resp_send_chunk()
Parameters
• r –[in] The request being responded to
• buf –[in] Buffer from where the fully constructed packet is to be read
• buf_len –[in] Length of the buffer
Returns
• Bytes : Number of bytes that were sent successfully
int httpd_socket_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags)
A low level API to send data on a given socket
This internally calls the default send function, or the function registered by httpd_sess_set_send_override().
Note: This API is not recommended to be used in any request handler. Use this only for advanced use cases,
wherein some asynchronous data is to be sent over a socket.
Parameters
• hd –[in] server instance
• sockfd –[in] session socket file descriptor
• buf –[in] buffer with bytes to send
• buf_len –[in] data size
• flags –[in] flags for the send() function
Returns
• Bytes : The number of bytes sent successfully
• HTTPD_SOCK_ERR_INVALID : Invalid arguments
• HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
• HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()
int httpd_socket_recv(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags)
A low level API to receive data from a given socket
This internally calls the default recv function, or the function registered by httpd_sess_set_recv_override().
Note: This API is not recommended to be used in any request handler. Use this only for advanced use cases,
wherein some asynchronous communication is required.
Parameters
• hd –[in] server instance
• sockfd –[in] session socket file descriptor
• buf –[in] buffer with bytes to send
• buf_len –[in] data size
• flags –[in] flags for the send() function
Returns
• Bytes : The number of bytes received successfully
• 0 : Buffer length parameter is zero / connection closed by peer
• HTTPD_SOCK_ERR_INVALID : Invalid arguments
• HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
• HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()
Parameters
• config –[in] Configuration for new instance of the server
• handle –[out] Handle to newly created instance of the server. NULL on error
Returns
• ESP_OK : Instance created successfully
• ESP_ERR_INVALID_ARG : Null argument(s)
• ESP_ERR_HTTPD_ALLOC_MEM : Failed to allocate memory for instance
• ESP_ERR_HTTPD_TASK : Failed to launch server task
Note: Some protocols require that the web server generate some asynchronous data and send it to the persis-
tently opened connection. This facility is for use by such protocols.
Parameters
• handle –[in] Handle to server returned by httpd_start
• work –[in] Pointer to the function to be executed in the HTTPD’s context
• arg –[in] Pointer to the arguments that should be passed to this function
Returns
• ESP_OK : On successfully queueing the work
• ESP_FAIL : Failure in ctrl socket
• ESP_ERR_INVALID_ARG : Null arguments
This context is used by the send/receive functions, for example to manage SSL context.
See also:
httpd_sess_get_ctx()
Parameters
• handle –[in] Handle to server returned by httpd_start
• sockfd –[in] The socket descriptor for which the context should be extracted.
Returns
See also:
httpd_sess_set_ctx()
Parameters
• handle –[in] Handle to server returned by httpd_start
• sockfd –[in] The socket descriptor for which the context should be extracted.
• ctx –[in] Transport context object to assign to the session
• free_fn –[in] Function that should be called to free the transport context
Note: Calling this API is only required in special circumstances wherein some application requires to close
an httpd client session asynchronously.
Parameters
• handle –[in] Handle to server returned by httpd_start
• sockfd –[in] The socket descriptor of the session to be closed
Returns
• ESP_OK : On successfully initiating closure
• ESP_FAIL : Failure to queue work
• ESP_ERR_NOT_FOUND : Socket fd not found
• ESP_ERR_INVALID_ARG : Null arguments
Note: Calling this API is only necessary if the LRU Purge Enable option is enabled.
Parameters
• handle –[in] Handle to server returned by httpd_start
• sockfd –[in] The socket descriptor of the session for which LRU counter is to be updated
Returns
• ESP_OK : Socket found and LRU counter updated
• ESP_ERR_NOT_FOUND : Socket not found
• ESP_ERR_INVALID_ARG : Null arguments
Note: Size of provided array has to be equal or greater then maximum number of opened sockets, configured
upon initialization with max_open_sockets field in httpd_config_t structure.
Parameters
• handle –[in] Handle to server returned by httpd_start
• fds –[inout] In: Size of provided client_fds array Out: Number of valid client fds re-
turned in client_fds,
• client_fds –[out] Array of client fds
Returns
• ESP_OK : Successfully retrieved session list
• ESP_ERR_INVALID_ARG : Wrong arguments or list is longer than provided array
Structures
struct httpd_config
HTTP Server Configuration Structure.
Note: Use HTTPD_DEFAULT_CONFIG() to initialize the configuration to a default value and then modify
only those fields that are specifically determined by the use case.
Public Members
unsigned task_priority
Priority of FreeRTOS task which runs the server
size_t stack_size
The maximum stack size allowed for the server task
BaseType_t core_id
The core the HTTP server task will run on
uint16_t server_port
TCP Port number for receiving and transmitting HTTP traffic
uint16_t ctrl_port
UDP Port number for asynchronously exchanging control signals between various components of the
server
uint16_t max_open_sockets
Max number of sockets/clients connected at any time
uint16_t max_uri_handlers
Maximum allowed uri handlers
uint16_t max_resp_headers
Maximum allowed additional headers in HTTP response
uint16_t backlog_conn
Number of backlog connections
bool lru_purge_enable
Purge “Least Recently Used”connection
uint16_t recv_wait_timeout
Timeout for recv function (in seconds)
uint16_t send_wait_timeout
Timeout for send function (in seconds)
void *global_user_ctx
Global user context.
This field can be used to store arbitrary user data within the server context. The value can be retrieved
using the server handle, available e.g. in the httpd_req_t struct.
When shutting down, the server frees up the user context by calling free() on the global_user_ctx field.
If you wish to use a custom function for freeing the global user context, please specify that here.
httpd_free_ctx_fn_t global_user_ctx_free_fn
Free function for global user context
void *global_transport_ctx
Global transport context.
Similar to global_user_ctx, but used for session encoding or encryption (e.g. to hold the SSL context). It
will be freed using free(), unless global_transport_ctx_free_fn is specified.
httpd_free_ctx_fn_t global_transport_ctx_free_fn
Free function for global transport context
httpd_open_func_t open_fn
Custom session opening callback.
Called on a new session socket just after accept(), but before reading any data.
This is an opportunity to set up e.g. SSL encryption using global_transport_ctx and the send/recv/pending
session overrides.
If a context needs to be maintained between these functions, store it in the session using
httpd_sess_set_transport_ctx() and retrieve it later with httpd_sess_get_transport_ctx()
Returning a value other than ESP_OK will immediately close the new socket.
httpd_close_func_t close_fn
Custom session closing callback.
Called when a session is deleted, before freeing user and transport contexts and before closing the socket.
This is a place for custom de-init code common to all sockets.
The server will only close the socket if no custom session closing callback is set. If a custom callback is
used, close(sockfd) should be called in here for most cases.
Set the user or transport context to NULL if it was freed here, so the server does not try to free it again.
This function is run for all terminated sessions, including sessions where the socket was closed by the
network stack - that is, the file descriptor may not be valid anymore.
httpd_uri_match_func_t uri_match_fn
URI matcher function.
Called when searching for a matching URI: 1) whose request handler is to be executed right after an HTTP
request is successfully parsed 2) in order to prevent duplication while registering a new URI handler using
httpd_register_uri_handler()
Available options are: 1) NULL : Internally do basic matching using strncmp() 2)
httpd_uri_match_wildcard() : URI wildcard matcher
Users can implement their own matching functions (See description of the
httpd_uri_match_func_t function prototype)
struct httpd_req
HTTP Request Data Structure.
Public Members
httpd_handle_t handle
Handle to server instance
int method
The type of HTTP request, -1 if unsupported method
size_t content_len
Length of the request body
void *aux
Internally used members
void *user_ctx
User context pointer passed during URI registration.
void *sess_ctx
Session Context Pointer
A session context. Contexts are maintained across ‘sessions’for a given open TCP connection. One
session could have multiple request responses. The web server will ensure that the context persists across
all these request and responses.
By default, this is NULL. URI Handlers can set this to any meaningful value.
If the underlying socket gets closed, and this pointer is non-NULL, the web server will free up the context
by calling free(), unless free_ctx function is set.
httpd_free_ctx_fn_t free_ctx
Pointer to free context hook
Function to free session context
If the web server’s socket closes, it frees up the session context by calling free() on the sess_ctx member.
If you wish to use a custom function for freeing the session context, please specify that here.
bool ignore_sess_ctx_changes
Flag indicating if Session Context changes should be ignored
By default, if you change the sess_ctx in some URI handler, the http server will internally free the
earlier context (if non NULL), after the URI handler returns. If you want to manage the alloca-
tion/reallocation/freeing of sess_ctx yourself, set this flag to true, so that the server will not perform
any checks on it. The context will be cleared by the server (by calling free_ctx or free()) only if the
socket gets closed.
struct httpd_uri
Structure for URI handler.
Public Members
httpd_method_t method
Method supported by the URI
void *user_ctx
Pointer to user context data which will be available to handler
Macros
HTTPD_MAX_REQ_HDR_LEN
HTTPD_MAX_URI_LEN
HTTPD_SOCK_ERR_FAIL
HTTPD_SOCK_ERR_INVALID
HTTPD_SOCK_ERR_TIMEOUT
HTTPD_200
HTTP Response 200
HTTPD_204
HTTP Response 204
HTTPD_207
HTTP Response 207
HTTPD_400
HTTP Response 400
HTTPD_404
HTTP Response 404
HTTPD_408
HTTP Response 408
HTTPD_500
HTTP Response 500
HTTPD_TYPE_JSON
HTTP Content type JSON
HTTPD_TYPE_TEXT
HTTP Content type text/HTML
HTTPD_TYPE_OCTET
HTTP Content type octext-stream
HTTPD_DEFAULT_CONFIG()
ESP_ERR_HTTPD_BASE
Starting number of HTTPD error codes
ESP_ERR_HTTPD_HANDLERS_FULL
All slots for registering URI handlers have been consumed
ESP_ERR_HTTPD_HANDLER_EXISTS
URI handler with same method and target URI already registered
ESP_ERR_HTTPD_INVALID_REQ
Invalid request pointer
ESP_ERR_HTTPD_RESULT_TRUNC
Result string truncated
ESP_ERR_HTTPD_RESP_HDR
Response header field larger than supported
ESP_ERR_HTTPD_RESP_SEND
Error occured while sending response packet
ESP_ERR_HTTPD_ALLOC_MEM
Failed to dynamically allocate memory for resource
ESP_ERR_HTTPD_TASK
Failed to launch server task/thread
HTTPD_RESP_USE_STRLEN
Type Definitions
typedef int (*httpd_send_func_t)(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags)
Prototype for HTTPDs low-level send function.
Note: User specified send function must handle errors internally, depending upon the set value of errno, and
return specific HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as return value of httpd_send()
function
typedef int (*httpd_recv_func_t)(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags)
Prototype for HTTPDs low-level recv function.
Note: User specified recv function must handle errors internally, depending upon the set value of er-
rno, and return specific HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as return value of
httpd_req_recv() function
Note: User specified pending function must handle errors internally, depending upon the set value of errno,
and return specific HTTPD_SOCK_ERR_ codes, which will be handled accordingly in the server task.
Note:
• If implemented, the server will not automatically send out HTTP error response codes, therefore,
httpd_resp_send_err() must be invoked inside this function if user wishes to generate HTTP error re-
sponses.
• When invoked, the validity of uri, method, content_len and user_ctx fields of the httpd_req_t
parameter is not guaranteed as the HTTP request may be partially received/parsed.
• The function must return ESP_OK if underlying socket needs to be kept open. Any other
value will ensure that the socket is closed. The return value is ignored when error is of type
HTTPD_500_INTERNAL_SERVER_ERROR and the socket closed anyway.
Param req [in] HTTP request for which the error needs to be handled
Param error [in] Error type
Return
• ESP_OK : error handled successful
• ESP_FAIL : failure indicates that the underlying socket needs to be closed
Note: It’s possible that the socket descriptor is invalid at this point, the function is called for all terminated
sessions. Ensure proper handling of return codes.
Note: Use HTTPD_DEFAULT_CONFIG() to initialize the configuration to a default value and then modify
only those fields that are specifically determined by the use case.
Enumerations
enum httpd_err_code_t
Error codes sent as HTTP response in case of errors encountered during processing of an HTTP request.
Values:
enumerator HTTPD_500_INTERNAL_SERVER_ERROR
enumerator HTTPD_501_METHOD_NOT_IMPLEMENTED
enumerator HTTPD_505_VERSION_NOT_SUPPORTED
enumerator HTTPD_400_BAD_REQUEST
enumerator HTTPD_401_UNAUTHORIZED
enumerator HTTPD_403_FORBIDDEN
enumerator HTTPD_404_NOT_FOUND
enumerator HTTPD_405_METHOD_NOT_ALLOWED
enumerator HTTPD_408_REQ_TIMEOUT
enumerator HTTPD_411_LENGTH_REQUIRED
enumerator HTTPD_414_URI_TOO_LONG
enumerator HTTPD_431_REQ_HDR_FIELDS_TOO_LARGE
enumerator HTTPD_ERR_CODE_MAX
Overview
This component is built on top of HTTP Server. The HTTPS server takes advantage of hook registration functions in
the regular HTTP server to provide callback function for SSL session.
All documentation for HTTP Server applies also to a server you create this way.
Used APIs
The following APIs of HTTP Server should not be used with HTTPS Server, as they are used internally to handle
secure sessions and to maintain internal state:
• “send”, “receive”and “pending”callback registration functions - secure socket handling
– httpd_sess_set_send_override()
– httpd_sess_set_recv_override()
– httpd_sess_set_pending_override()
• “transport context”- both global and session
– httpd_sess_get_transport_ctx() - returns SSL used for the session
– httpd_sess_set_transport_ctx()
Usage
Please see the example protocols/https_server to learn how to set up a secure server.
Basically, all you need is to generate a certificate, embed it into the firmware, and pass the init struct into the start
function after the certificate address and lengths are correctly configured in the init struct.
The server can be started with or without SSL by changing a flag in the init struct -
httpd_ssl_config::transport_mode. This could be used, e.g., for testing or in trusted environ-
ments where you prefer speed over security.
Performance
The initial session setup can take about two seconds, or more with slower clock speed or more verbose logging.
Subsequent requests through the open secure socket are much faster (down to under 100 ms).
API Reference
Header File
• components/esp_https_server/include/esp_https_server.h
Functions
esp_err_t httpd_ssl_start(httpd_handle_t *handle, httpd_ssl_config_t *config)
Create a SSL capable HTTP server (secure mode may be disabled in config)
Parameters
• config –[inout] - server config, must not be const. Does not have to stay valid after
calling this function.
• handle –[out] - storage for the server handle, must be a valid pointer
Returns success
esp_err_t httpd_ssl_stop(httpd_handle_t handle)
Stop the server. Blocks until the server is shut down.
Parameters handle –[in]
Returns
• ESP_OK: Server stopped successfully
• ESP_ERR_INVALID_ARG: Invalid argument
• ESP_FAIL: Failure to shut down server
Structures
struct esp_https_server_user_cb_arg
Callback data struct, contains the ESP-TLS connection handle and the connection state at which the callback
is executed.
Public Members
httpd_ssl_user_cb_state_t user_cb_state
State of user callback
esp_tls_t *tls
ESP-TLS connection handle
struct httpd_ssl_config
HTTPS server config struct
Please use HTTPD_SSL_CONFIG_DEFAULT() to initialize it.
Public Members
httpd_config_t httpd
Underlying HTTPD server config
Parameters like task stack size and priority can be adjusted here.
size_t servercert_len
Server certificate byte length
size_t cacert_len
CA certificate byte length
size_t prvtkey_len
Private key byte length
httpd_ssl_transport_mode_t transport_mode
Transport Mode (default secure)
uint16_t port_secure
Port used when transport mode is secure (default 443)
uint16_t port_insecure
Port used when transport mode is insecure (default 80)
bool session_tickets
Enable tls session tickets
bool use_secure_element
Enable secure element for server session
esp_https_server_user_cb *user_cb
User callback for esp_https_server
Macros
HTTPD_SSL_CONFIG_DEFAULT()
Default config struct init
(http_server default config had to be copied for customization)
Notes:
• port is set when starting the server, according to ‘transport_mode’
• one socket uses ~ 40kB RAM with SSL, we reduce the default socket count to 4
• SSL sockets are usually long-lived, closing LRU prevents pool exhaustion DOS
• Stack size may need adjustments depending on the user application
Type Definitions
Enumerations
enum httpd_ssl_transport_mode_t
Values:
enumerator HTTPD_SSL_TRANSPORT_SECURE
enumerator HTTPD_SSL_TRANSPORT_INSECURE
enum httpd_ssl_user_cb_state_t
Indicates the state at which the user callback is executed, i.e at session creation or session close.
Values:
enumerator HTTPD_SSL_USER_CB_SESS_CREATE
enumerator HTTPD_SSL_USER_CB_SESS_CLOSE
Overview
ICMP (Internet Control Message Protocol) is used for diagnostic or control purposes or generated in response to
errors in IP operations. The common network util ping is implemented based on the ICMP packets with the type
field value of 0, also called Echo Reply.
During a ping session, the source host firstly sends out an ICMP echo request packet and wait for an ICMP echo reply
with specific times. In this way, it also measures the round-trip time for the messages. After receiving a valid ICMP
echo reply, the source host will generate statistics about the IP link layer (e.g. packet loss, elapsed time, etc).
It is common that IoT device needs to check whether a remote server is alive or not. The device should show the
warnings to users when it got offline. It can be achieved by creating a ping session and sending/parsing ICMP echo
packets periodically.
To make this internal procedure much easier for users, ESP-IDF provides some out-of-box APIs.
Create a new ping session To create a ping session, you need to fill in the esp_ping_config_t configuration
structure firstly, specifying target IP address, interval times, and etc. Optionally, you can also register some callback
functions with the esp_ping_callbacks_t` structure.
Example method to create a new ping session and register callbacks:
static void test_on_ping_success(esp_ping_handle_t hdl, void *args)
{
// optionally, get callback arguments
// const char* str = (const char*) args;
// printf("%s\r\n", str); // "foo"
uint8_t ttl;
uint16_t seqno;
uint32_t elapsed_time, recv_len;
ip_addr_t target_addr;
esp_ping_get_profile(hdl, ESP_PING_PROF_SEQNO, &seqno, sizeof(seqno));
esp_ping_get_profile(hdl, ESP_PING_PROF_TTL, &ttl, sizeof(ttl));
esp_ping_get_profile(hdl, ESP_PING_PROF_IPADDR, &target_addr, sizeof(target_
,→addr));
void initialize_ping()
{
/* convert URL to IP address */
ip_addr_t target_addr;
struct addrinfo hint;
struct addrinfo *res = NULL;
memset(&hint, 0, sizeof(hint));
memset(&target_addr, 0, sizeof(target_addr));
getaddrinfo("www.espressif.com", NULL, &hint, &res);
struct in_addr addr4 = ((struct sockaddr_in *) (res->ai_addr))->sin_addr;
inet_addr_to_ip4addr(ip_2_ip4(&target_addr), &addr4);
freeaddrinfo(res);
cbs.cb_args = eth_event_group;
esp_ping_handle_t ping;
esp_ping_new_session(&ping_config, &cbs, &ping);
}
Start and Stop ping session You can start and stop ping session with the handle returned by
esp_ping_new_session. Note that, the ping session won’t start automatically after creation. If the ping
session is stopped, and restart again, the sequence number in ICMP packets will recount from zero again.
Delete a ping session If a ping session won’t be used any more, you can delete it with
esp_ping_delete_session. Please make sure the ping session is in stop state (i.e. you have called
esp_ping_stop before or the ping session has finished all the procedures) when you call this function.
Get runtime statistics As the example code above, you can call esp_ping_get_profile to get different
runtime statistics of ping session in the callback function.
Application Example
API Reference
Header File
• components/lwip/include/apps/ping/ping_sock.h
Functions
esp_err_t esp_ping_new_session(const esp_ping_config_t *config, const esp_ping_callbacks_t *cbs,
esp_ping_handle_t *hdl_out)
Create a ping session.
Parameters
• config –ping configuration
• cbs –a bunch of callback functions invoked by internal ping task
• hdl_out –handle of ping session
Returns
• ESP_ERR_INVALID_ARG: invalid parameters (e.g. configuration is null, etc)
• ESP_ERR_NO_MEM: out of memory
• ESP_FAIL: other internal error (e.g. socket error)
• ESP_OK: create ping session successfully, user can take the ping handle to do follow-on
jobs
esp_err_t esp_ping_delete_session(esp_ping_handle_t hdl)
Delete a ping session.
Parameters hdl –handle of ping session
Returns
• ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc)
• ESP_OK: delete ping session successfully
esp_err_t esp_ping_start(esp_ping_handle_t hdl)
Start the ping session.
Parameters hdl –handle of ping session
Returns
• ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc)
• ESP_OK: start ping session successfully
esp_err_t esp_ping_stop(esp_ping_handle_t hdl)
Stop the ping session.
Parameters hdl –handle of ping session
Returns
• ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc)
• ESP_OK: stop ping session successfully
esp_err_t esp_ping_get_profile(esp_ping_handle_t hdl, esp_ping_profile_t profile, void *data, uint32_t
size)
Get runtime profile of ping session.
Parameters
• hdl –handle of ping session
• profile –type of profile
• data –profile data
• size –profile data size
Returns
• ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc)
• ESP_ERR_INVALID_SIZE: the actual profile data size doesn’t match the “size”pa-
rameter
• ESP_OK: get profile successfully
Structures
struct esp_ping_callbacks_t
Type of “ping”callback functions.
Public Members
void *cb_args
arguments for callback functions
struct esp_ping_config_t
Type of “ping”configuration.
Public Members
uint32_t count
A “ping”session contains count procedures
uint32_t interval_ms
Milliseconds between each ping procedure
uint32_t timeout_ms
Timeout value (in milliseconds) of each ping procedure
uint32_t data_size
Size of the data next to ICMP packet header
int tos
Type of Service, a field specified in the IP header
int ttl
Time to Live,a field specified in the IP header
ip_addr_t target_addr
Target IP address, either IPv4 or IPv6
uint32_t task_stack_size
Stack size of internal ping task
uint32_t task_prio
Priority of internal ping task
uint32_t interface
Netif index, interface=0 means NETIF_NO_INDEX
Macros
ESP_PING_DEFAULT_CONFIG()
Default ping configuration.
ESP_PING_COUNT_INFINITE
Set ping count to zero will ping target infinitely
Type Definitions
Enumerations
enum esp_ping_profile_t
Profile of ping session.
Values:
enumerator ESP_PING_PROF_SEQNO
Sequence number of a ping procedure
enumerator ESP_PING_PROF_TOS
Type of service of a ping procedure
enumerator ESP_PING_PROF_TTL
Time to live of a ping procedure
enumerator ESP_PING_PROF_REQUEST
Number of request packets sent out
enumerator ESP_PING_PROF_REPLY
Number of reply packets received
enumerator ESP_PING_PROF_IPADDR
IP address of replied target
enumerator ESP_PING_PROF_SIZE
Size of received packet
enumerator ESP_PING_PROF_TIMEGAP
Elapsed time between request and reply packet
enumerator ESP_PING_PROF_DURATION
Elapsed time of the whole ping session
mDNS is a multicast UDP service that is used to provide local network service and host discovery.
The ESP-IDF component mDNS has been moved from ESP-IDF since version v5.0 to a separate repository:
Hosted Documentation
Mbed TLS is a C library that implements cryptographic primitives, X.509 certificate manipulation and the SSL/TLS
and DTLS protocols. Its small code footprint makes it suitable for embedded systems.
Note: ESP-IDF uses a fork of Mbed TLS which includes a few patches (related to hardware routines of certain
modules like bignum (MPI) and ECC) over vanilla Mbed TLS.
Mbed TLS supports SSL 3.0 up to TLS 1.3 and DTLS 1.0 to 1.2 communication by providing the following:
• TCP/IP communication functions: listen, connect, accept, read/write.
• SSL/TLS communication functions: init, handshake, read/write.
• X.509 functions: CRT, CRL and key handling
• Random number generation
• Hashing
• Encryption/decryption
Note: Mbed TLS is in the process of migrating all the documentation to a single place. In the meantime, users can
find the documentation at the old Mbed TLS site .
Please find the information about the Mbed TLS versions present in different branches of ESP-IDF here.
Note: Please refer the ESP-IDF Migration Guide to migrate from Mbed TLS version 2.x to version 3.0 or greater.
Application Examples
Examples in ESP-IDF use ESP-TLS which provides a simplified API interface for accessing the commonly used TLS
functionality.
Refer to the examples protocols/https_server/simple (Simple HTTPS server) and protocols/https_request (Make
HTTPS requests) for more information.
If the Mbed TLS API is to be used directly, refer to the example protocols/https_mbedtls.
Alternatives
ESP-TLS acts as an abstraction layer over the underlying SSL/TLS library and thus has an option to use Mbed TLS
or wolfSSL as the underlying library. By default, only Mbed TLS is available and used in ESP-IDF whereas wolfSSL
is available publicly at https://github.com/espressif/esp-wolfSSL with the upstream submodule pointer.
Please refer to ESP-TLS: Underlying SSL/TLS Library Options docs for more information on this and comparison of
Mbed TLS and wolfSSL.
Following is a brief list of important config options accessible at Component Config -> mbedTLS. The full
list of config options can be found here.
Note: Mbed TLS v3.0.0 and later support only TLS 1.2 and TLS 1.3 (SSL 3.0, TLS 1.0, TLS 1.1 and DTLS 1.0 are
not supported). The support for TLS 1.3 is experimental and only supports the client-side. More information about
this can be found out here.
Reducing Heap Usage The following table shows typical memory usage with different configs when the proto-
cols/https_request example (with Server Validation enabled) was run with Mbed TLS as the SSL/TLS library.
Note: These values are subject to change with change in configuration options and versions of Mbed TLS.
Reducing Binary Size Under Component Config -> mbedTLS, there are multiple Mbed TLS features
which are enabled by default but can be disabled if not needed to save code size. More information can be about this
can be found in Minimizing Binary Size docs.
Code examples for this API section are provided in the protocols directory of ESP-IDF examples.
Documentation for IP Network Layer protocols (below the Application Protocol layer) are provided in Networking
APIs.
2.3.1 BT COMMON
BT GENERIC DEFINES
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_bt_defs.h
Structures
struct esp_bt_uuid_t
UUID type.
Public Members
uint16_t len
UUID length, 16bit, 32bit or 128bit
uint16_t uuid16
16bit UUID
uint32_t uuid32
32bit UUID
uint8_t uuid128[ESP_UUID_LEN_128]
128bit UUID
Macros
ESP_BLUEDROID_STATUS_CHECK(status)
ESP_BT_OCTET16_LEN
ESP_BT_OCTET8_LEN
ESP_DEFAULT_GATT_IF
Default GATT interface id.
ESP_BLE_PRIM_ADV_INT_MIN
Minimum advertising interval for undirected and low duty cycle directed advertising
ESP_BLE_PRIM_ADV_INT_MAX
Maximum advertising interval for undirected and low duty cycle directed advertising
ESP_BLE_CONN_INT_MIN
relate to BTM_BLE_CONN_INT_MIN in stack/btm_ble_api.h
ESP_BLE_CONN_INT_MAX
relate to BTM_BLE_CONN_INT_MAX in stack/btm_ble_api.h
ESP_BLE_CONN_LATENCY_MAX
relate to ESP_BLE_CONN_LATENCY_MAX in stack/btm_ble_api.h
ESP_BLE_CONN_SUP_TOUT_MIN
relate to BTM_BLE_CONN_SUP_TOUT_MIN in stack/btm_ble_api.h
ESP_BLE_CONN_SUP_TOUT_MAX
relate to ESP_BLE_CONN_SUP_TOUT_MAX in stack/btm_ble_api.h
ESP_BLE_CONN_PARAM_UNDEF
ESP_BLE_SCAN_PARAM_UNDEF
ESP_UUID_LEN_16
ESP_UUID_LEN_32
ESP_UUID_LEN_128
ESP_BD_ADDR_LEN
Bluetooth address length.
ESP_BLE_ENC_KEY_MASK
Used to exchange the encryption key in the init key & response key.
ESP_BLE_ID_KEY_MASK
Used to exchange the IRK key in the init key & response key.
ESP_BLE_CSR_KEY_MASK
Used to exchange the CSRK key in the init key & response key.
ESP_BLE_LINK_KEY_MASK
Used to exchange the link key(this key just used in the BLE & BR/EDR coexist mode) in the init key &
response key.
ESP_APP_ID_MIN
Minimum of the application id.
ESP_APP_ID_MAX
Maximum of the application id.
ESP_BD_ADDR_STR
ESP_BD_ADDR_HEX(addr)
Type Definitions
Enumerations
enum esp_bt_status_t
Status Return Value.
Values:
enumerator ESP_BT_STATUS_SUCCESS
enumerator ESP_BT_STATUS_FAIL
enumerator ESP_BT_STATUS_NOT_READY
enumerator ESP_BT_STATUS_NOMEM
enumerator ESP_BT_STATUS_BUSY
enumerator ESP_BT_STATUS_DONE
enumerator ESP_BT_STATUS_UNSUPPORTED
enumerator ESP_BT_STATUS_PARM_INVALID
enumerator ESP_BT_STATUS_UNHANDLED
enumerator ESP_BT_STATUS_AUTH_FAILURE
enumerator ESP_BT_STATUS_RMT_DEV_DOWN
enumerator ESP_BT_STATUS_AUTH_REJECTED
enumerator ESP_BT_STATUS_INVALID_STATIC_RAND_ADDR
enumerator ESP_BT_STATUS_PENDING
enumerator ESP_BT_STATUS_UNACCEPT_CONN_INTERVAL
enumerator ESP_BT_STATUS_PARAM_OUT_OF_RANGE
enumerator ESP_BT_STATUS_TIMEOUT
enumerator ESP_BT_STATUS_PEER_LE_DATA_LEN_UNSUPPORTED
enumerator ESP_BT_STATUS_CONTROL_LE_DATA_LEN_UNSUPPORTED
enumerator ESP_BT_STATUS_ERR_ILLEGAL_PARAMETER_FMT
enumerator ESP_BT_STATUS_MEMORY_FULL
enumerator ESP_BT_STATUS_EIR_TOO_LARGE
enum esp_bt_dev_type_t
Bluetooth device type.
Values:
enumerator ESP_BT_DEVICE_TYPE_BREDR
enumerator ESP_BT_DEVICE_TYPE_BLE
enumerator ESP_BT_DEVICE_TYPE_DUMO
enum esp_ble_addr_type_t
BLE device address type.
Values:
enumerator BLE_ADDR_TYPE_PUBLIC
enumerator BLE_ADDR_TYPE_RANDOM
enumerator BLE_ADDR_TYPE_RPA_PUBLIC
enumerator BLE_ADDR_TYPE_RPA_RANDOM
enum esp_ble_wl_addr_type_t
white list address type
Values:
enumerator BLE_WL_ADDR_TYPE_PUBLIC
enumerator BLE_WL_ADDR_TYPE_RANDOM
BT MAIN API
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_bt_main.h
Functions
esp_bluedroid_status_t esp_bluedroid_get_status(void)
Get bluetooth stack status.
Returns Bluetooth stack status
esp_err_t esp_bluedroid_enable(void)
Enable bluetooth, must after esp_bluedroid_init().
Returns
• ESP_OK : Succeed
• Other : Failed
esp_err_t esp_bluedroid_disable(void)
Disable bluetooth, must prior to esp_bluedroid_deinit().
Returns
• ESP_OK : Succeed
• Other : Failed
esp_err_t esp_bluedroid_init(void)
Init and alloc the resource for bluetooth, must be prior to every bluetooth stuff.
Returns
• ESP_OK : Succeed
• Other : Failed
esp_err_t esp_bluedroid_deinit(void)
Deinit and free the resource for bluetooth, must be after every bluetooth stuff.
Returns
• ESP_OK : Succeed
• Other : Failed
Enumerations
enum esp_bluedroid_status_t
Bluetooth stack status type, to indicate whether the bluetooth stack is ready.
Values:
enumerator ESP_BLUEDROID_STATUS_UNINITIALIZED
Bluetooth not initialized
enumerator ESP_BLUEDROID_STATUS_INITIALIZED
Bluetooth initialized but not enabled
enumerator ESP_BLUEDROID_STATUS_ENABLED
Bluetooth initialized and enabled
BT DEVICE APIs
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_bt_device.h
Functions
const uint8_t *esp_bt_dev_get_address(void)
Get bluetooth device address. Must use after “esp_bluedroid_enable”.
Returns bluetooth device address (six bytes), or NULL if bluetooth stack is not enabled
esp_err_t esp_bt_dev_set_device_name(const char *name)
Set bluetooth device name. This function should be called after esp_bluedroid_enable() completes successfully.
A BR/EDR/LE device type shall have a single Bluetooth device name which shall be identical irrespective of
the physical channel used to perform the name discovery procedure.
Parameters name –[in] : device name to be set
Returns
• ESP_OK : Succeed
• ESP_ERR_INVALID_ARG : if name is NULL pointer or empty, or string length out of
limit
• ESP_ERR_INVALID_STATE : if bluetooth stack is not yet enabled
• ESP_FAIL : others
2.3.2 BT LE
GAP API
Application Example Check bluetooth/bluedroid/ble folder in ESP-IDF examples, which contains the following
demos and their tutorials:
• This is a SMP security client demo and its tutorial. This demo initiates its security parameters and acts as a
GATT client, which can send a security request to the peer device and then complete the encryption procedure.
– bluetooth/bluedroid/ble/gatt_security_client
– GATT Security Client Example Walkthrough
• This is a SMP security server demo and its tutorial. This demo initiates its security parameters and acts as a
GATT server, which can send a pair request to the peer device and then complete the encryption procedure.
– bluetooth/bluedroid/ble/gatt_security_server
– GATT Security Server Example Walkthrough
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_gap_ble_api.h
Functions
esp_err_t esp_ble_gap_register_callback(esp_gap_ble_cb_t callback)
This function is called to occur gap event, such as scan result.
Parameters callback –[in] callback function
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_config_adv_data(esp_ble_adv_data_t *adv_data)
This function is called to override the BTA default ADV parameters.
Parameters adv_data –[in] Pointer to User defined ADV data structure. This memory space
can not be freed until callback of config_adv_data is received.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_set_scan_params(esp_ble_scan_params_t *scan_params)
This function is called to set scan parameters.
Parameters scan_params –[in] Pointer to User defined scan_params data structure. This
memory space can not be freed until callback of set_scan_params
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_start_scanning(uint32_t duration)
This procedure keep the device scanning the peer device which advertising on the air.
Parameters duration –[in] Keeping the scanning time, the unit is second.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_stop_scanning(void)
This function call to stop the device scanning the peer device which advertising on the air.
Returns
• ESP_OK : success
– other : failed
esp_err_t esp_ble_gap_start_advertising(esp_ble_adv_params_t *adv_params)
This function is called to start advertising.
Parameters adv_params –[in] pointer to User defined adv_params data structure.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_stop_advertising(void)
This function is called to stop advertising.
Returns
• ESP_OK : success
• other : failed
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_get_whitelist_size(uint16_t *length)
Get the whitelist size in the controller.
Parameters length –[out] the white list length.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_set_prefer_conn_params(esp_bd_addr_t bd_addr, uint16_t min_conn_int,
uint16_t max_conn_int, uint16_t slave_latency,
uint16_t supervision_tout)
This function is called to set the preferred connection parameters when default connection parameter is not
desired before connecting. This API can only be used in the master role.
Parameters
• bd_addr –[in] BD address of the peripheral
• min_conn_int –[in] minimum preferred connection interval
• max_conn_int –[in] maximum preferred connection interval
• slave_latency –[in] preferred slave latency
• supervision_tout –[in] preferred supervision timeout
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_set_device_name(const char *name)
Set device name to the local device.
Parameters name –[in] - device name.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_get_local_used_addr(esp_bd_addr_t local_used_addr, uint8_t *addr_type)
This function is called to get local used address and address type. uint8_t *esp_bt_dev_get_address(void) get
the public address.
Parameters
• local_used_addr –[in] - current local used ble address (six bytes)
• addr_type –[in] - ble address type
Returns - ESP_OK : success
• other : failed
uint8_t *esp_ble_resolve_adv_data(uint8_t *adv_data, uint8_t type, uint8_t *length)
This function is called to get ADV data for a specific type.
Parameters
• adv_data –[in] - pointer of ADV data which to be resolved
• type –[in] - finding ADV data type
• length –[out] - return the length of ADV data not including type
Returns pointer of ADV data
esp_err_t esp_ble_gap_config_adv_data_raw(uint8_t *raw_data, uint32_t raw_data_len)
This function is called to set raw advertising data. User need to fill ADV data by self.
Parameters
• raw_data –[in] : raw advertising data
• raw_data_len –[in] : raw advertising data length , less than 31 bytes
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_config_scan_rsp_data_raw(uint8_t *raw_data, uint32_t raw_data_len)
This function is called to set raw scan response data. User need to fill scan response data by self.
Parameters
• raw_data –[in] : raw scan response data
• raw_data_len –[in] : raw scan response data length , less than 31 bytes
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_read_rssi(esp_bd_addr_t remote_addr)
This function is called to read the RSSI of remote device. The address of link policy results are returned in the
gap callback function with ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT event.
Parameters remote_addr –[in] : The remote connection device address.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_add_duplicate_scan_exceptional_device(esp_ble_duplicate_exceptional_info_type_t
type, esp_duplicate_info_t
device_info)
This function is called to add a device info into the duplicate scan exceptional list.
Parameters
• type –[in] device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t
when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or
MESH_PROXY_SRV_ADV , device_info is invalid.
• device_info –[in] the device information.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_remove_duplicate_scan_exceptional_device(esp_ble_duplicate_exceptional_info_type_t
type,
esp_duplicate_info_t
device_info)
This function is called to remove a device info from the duplicate scan exceptional list.
Parameters
• type –[in] device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t
when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or
MESH_PROXY_SRV_ADV , device_info is invalid.
• device_info –[in] the device information.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_clean_duplicate_scan_exceptional_list(esp_duplicate_scan_exceptional_list_type_t
list_type)
This function is called to clean the duplicate scan exceptional list. This API will delete all device information
in the duplicate scan exceptional list.
Parameters list_type –[in] duplicate scan exceptional list type, the value can be one or more
of esp_duplicate_scan_exceptional_list_type_t.
Returns
• ESP_OK : success
• other : failed
Parameters
• param_type –[in] : the type of the param which to be set
• value –[in] : the param value
• len –[in] : the length of the param value
Returns - ESP_OK : success
• other : failed
Parameters
• instance –[in] : Used to identify an advertising set
• rand_addr –[in] : Random Device Address
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_ext_adv_set_params(uint8_t instance, const esp_ble_gap_ext_adv_params_t
*params)
This function is used by the Host to set the advertising parameters.
Parameters
• instance –[in] : identifies the advertising set whose parameters are being configured.
• params –[in] : advertising parameters
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_config_ext_adv_data_raw(uint8_t instance, uint16_t length, const uint8_t
*data)
This function is used to set the data used in advertising PDUs that have a data field.
Parameters
• instance –[in] : identifies the advertising set whose data are being configured
• length –[in] : data length
• data –[in] : data information
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_config_ext_scan_rsp_data_raw(uint8_t instance, uint16_t length, const
uint8_t *scan_rsp_data)
This function is used to provide scan response data used in scanning response PDUs.
Parameters
• instance –[in] : identifies the advertising set whose response data are being configured.
• length –[in] : responsedata length
• scan_rsp_data –[in] : response data information
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_ext_adv_start(uint8_t num_adv, const esp_ble_gap_ext_adv_t *ext_adv)
This function is used to request the Controller to enable one or more advertising sets using the advertising sets
identified by the instance parameter.
Parameters
• num_adv –[in] : Number of advertising sets to enable or disable
• ext_adv –[in] : adv parameters
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_ext_adv_stop(uint8_t num_adv, const uint8_t *ext_adv_inst)
This function is used to request the Controller to disable one or more advertising sets using the advertising sets
identified by the instance parameter.
Parameters
• num_adv –[in] : Number of advertising sets to enable or disable
• ext_adv_inst –[in] : ext adv instance
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_ext_adv_set_remove(uint8_t instance)
This function is used to remove an advertising set from the Controller.
Parameters instance –[in] : Used to identify an advertising set
esp_err_t esp_ble_gap_stop_ext_scan(void)
This function is used to disable scanning.
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_create_sync(const esp_ble_gap_periodic_adv_sync_params_t
*params)
This function is used to synchronize with periodic advertising from an advertiser and begin receiving periodic
advertising packets.
Parameters params –[in] : sync parameters
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_sync_cancel(void)
This function is used to cancel the LE_Periodic_Advertising_Create_Sync command while it is pending.
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_sync_terminate(uint16_t sync_handle)
This function is used to stop reception of the periodic advertising identified by the Sync Handle parameter.
Parameters sync_handle –[in] : identify the periodic advertiser
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_add_dev_to_list(esp_ble_addr_type_t addr_type,
esp_bd_addr_t addr, uint8_t sid)
This function is used to add a single device to the Periodic Advertiser list stored in the Controller.
Parameters
• addr_type –[in] : address type
• addr –[in] : Device Address
• sid –[in] : Advertising SID subfield in the ADI field used to identify the Periodic Ad-
vertising
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_remove_dev_from_list(esp_ble_addr_type_t addr_type,
esp_bd_addr_t addr, uint8_t sid)
This function is used to remove one device from the list of Periodic Advertisers stored in the Controller.
Removals from the Periodic Advertisers List take effect immediately.
Parameters
• addr_type –[in] : address type
• addr –[in] : Device Address
• sid –[in] : Advertising SID subfield in the ADI field used to identify the Periodic Ad-
vertising
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_clear_dev(void)
This function is used to remove all devices from the list of Periodic Advertisers in the Controller.
Returns - ESP_OK : success
• other : failed
Unions
union esp_ble_key_value_t
#include <esp_gap_ble_api.h> union type of the security key value
Public Members
esp_ble_penc_keys_t penc_key
received peer encryption key
esp_ble_pcsrk_keys_t pcsrk_key
received peer device SRK
esp_ble_pid_keys_t pid_key
peer device ID key
esp_ble_lenc_keys_t lenc_key
local encryption reproduction keys LTK = = d1(ER,DIV,0)
esp_ble_lcsrk_keys lcsrk_key
local device CSRK = d1(ER,DIV,1)
union esp_ble_sec_t
#include <esp_gap_ble_api.h> union associated with ble security
Public Members
esp_ble_sec_key_notif_t key_notif
passkey notification
esp_ble_sec_req_t ble_req
BLE SMP related request
esp_ble_key_t ble_key
BLE SMP keys used when pairing
esp_ble_local_id_keys_t ble_id_keys
BLE IR event
esp_ble_auth_cmpl_t auth_cmpl
Authentication complete indication.
union esp_ble_gap_cb_param_t
#include <esp_gap_ble_api.h> Gap callback parameters union.
Public Members
esp_ble_sec_t ble_security
ble gap security union type
struct esp_ble_gap_cb_param_t::ble_update_duplicate_exceptional_list_cmpl_evt_param
update_duplicate_exceptional_list_cmpl
Event parameter of ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT
struct esp_ble_gap_cb_param_t::ble_ext_adv_set_rand_addr_cmpl_evt_param
ext_adv_set_rand_addr
Event parameter of ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT
struct ble_adv_data_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate the set advertising data operation success status
struct ble_adv_data_raw_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate the set raw advertising data operation success status
struct ble_adv_start_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_START_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate advertising start operation success status
struct ble_adv_stop_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate adv stop operation success status
struct ble_adv_terminate_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_TERMINATED_EVT.
Public Members
uint8_t status
Indicate adv terminate status
uint8_t adv_instance
extend advertising handle
uint16_t conn_idx
connection index
uint8_t completed_event
the number of completed extend advertising events
struct ble_channel_sel_alg_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT.
Public Members
uint16_t conn_handle
connection handle
uint8_t channel_sel_alg
channel selection algorithm
struct ble_clear_bond_dev_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate the clear bond device operation success status
struct ble_ext_adv_data_set_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate extend advertising data set status
struct ble_ext_adv_report_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_REPORT_EVT.
Public Members
esp_ble_gap_ext_adv_reprot_t params
extend advertising report parameters
struct ble_ext_adv_scan_rsp_set_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate extend advertising scan response data set status
struct ble_ext_adv_set_clear_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate advertising stop operation success status
struct ble_ext_adv_set_params_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate extend advertising parameters set status
struct ble_ext_adv_set_rand_addr_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate extend advertising random address set status
struct ble_ext_adv_set_remove_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate advertising stop operation success status
struct ble_ext_adv_start_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate advertising start operation success status
struct ble_ext_adv_stop_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate advertising stop operation success status
struct ble_ext_conn_params_set_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate extend connection parameters set status
struct ble_ext_scan_start_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate extend advertising start status
struct ble_ext_scan_stop_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate extend advertising stop status
struct ble_get_bond_dev_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate the get bond device operation success status
uint8_t dev_num
Indicate the get number device in the bond list
esp_ble_bond_dev_t *bond_dev
the pointer to the bond device Structure
struct ble_local_privacy_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate the set local privacy operation success status
struct ble_period_adv_add_dev_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate periodic advertising device list add status
struct ble_period_adv_clear_dev_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate periodic advertising device list clean status
struct ble_period_adv_create_sync_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate periodic advertising create sync status
struct ble_period_adv_remove_dev_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate periodic advertising device list remove status
struct ble_period_adv_sync_cancel_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate periodic advertising sync cancel status
struct ble_period_adv_sync_terminate_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate periodic advertising sync terminate status
struct ble_periodic_adv_data_set_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate periodic advertising data set status
struct ble_periodic_adv_report_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT.
Public Members
esp_ble_gap_periodic_adv_report_t params
periodic advertising report parameters
struct ble_periodic_adv_set_params_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate periodic advertisingparameters set status
struct ble_periodic_adv_start_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate periodic advertising start status
struct ble_periodic_adv_stop_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate periodic advertising stop status
struct ble_periodic_adv_sync_estab_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT.
Public Members
uint8_t status
periodic advertising sync status
uint16_t sync_handle
periodic advertising sync handle
uint8_t sid
periodic advertising sid
esp_ble_addr_type_t adv_addr_type
periodic advertising address type
esp_bd_addr_t adv_addr
periodic advertising address
esp_ble_gap_phy_t adv_phy
periodic advertising phy type
uint16_t period_adv_interval
periodic advertising interval
uint8_t adv_clk_accuracy
periodic advertising clock accuracy
struct ble_periodic_adv_sync_lost_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT.
Public Members
uint16_t sync_handle
sync handle
struct ble_phy_update_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT.
Public Members
esp_bt_status_t status
phy update status
esp_bd_addr_t bda
address
esp_ble_gap_phy_t tx_phy
tx phy type
esp_ble_gap_phy_t rx_phy
rx phy type
struct ble_pkt_data_length_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate the set pkt data length operation success status
esp_ble_pkt_data_length_params_t params
pkt data length value
struct ble_read_phy_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_READ_PHY_COMPLETE_EVT.
Public Members
esp_bt_status_t status
read phy complete status
esp_bd_addr_t bda
read phy address
esp_ble_gap_phy_t tx_phy
tx phy type
esp_ble_gap_phy_t rx_phy
rx phy type
struct ble_read_rssi_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate the read adv tx power operation success status
int8_t rssi
The ble remote device rssi value, the range is from -127 to 20, the unit is dbm, if the RSSI cannot
be read, the RSSI metric shall be set to 127.
esp_bd_addr_t remote_addr
The remote device address
struct ble_remove_bond_dev_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate the remove bond device operation success status
esp_bd_addr_t bd_addr
The device address which has been remove from the bond list
struct ble_scan_param_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate the set scan param operation success status
struct ble_scan_req_received_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT.
Public Members
uint8_t adv_instance
extend advertising handle
esp_ble_addr_type_t scan_addr_type
scanner address type
esp_bd_addr_t scan_addr
scanner address
struct ble_scan_result_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RESULT_EVT.
Public Members
esp_gap_search_evt_t search_evt
Search event type
esp_bd_addr_t bda
Bluetooth device address which has been searched
esp_bt_dev_type_t dev_type
Device type
esp_ble_addr_type_t ble_addr_type
Ble device address type
esp_ble_evt_type_t ble_evt_type
Ble scan result event type
int rssi
Searched device’s RSSI
uint8_t ble_adv[ESP_BLE_ADV_DATA_LEN_MAX +
ESP_BLE_SCAN_RSP_DATA_LEN_MAX]
Received EIR
int flag
Advertising data flag bit
int num_resps
Scan result number
uint8_t adv_data_len
Adv data length
uint8_t scan_rsp_len
Scan response length
uint32_t num_dis
The number of discard packets
struct ble_scan_rsp_data_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate the set scan response data operation success status
struct ble_scan_rsp_data_raw_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate the set raw advertising data operation success status
struct ble_scan_start_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_START_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate scan start operation success status
struct ble_scan_stop_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate scan stop operation success status
struct ble_set_channels_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_CHANNELS_EVT.
Public Members
esp_bt_status_t stat
BLE set channel status
struct ble_set_ext_scan_params_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate extend advertising parameters set status
struct ble_set_perf_def_phy_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PREFERRED_DEFAULT_PHY_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate perf default phy set status
struct ble_set_perf_phy_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PREFERRED_PHY_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate perf phy set status
struct ble_set_rand_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT.
Public Members
esp_bt_status_t status
Indicate set static rand address operation success status
struct ble_update_conn_params_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT.
Public Members
esp_bt_status_t status
Indicate update connection parameters success status
esp_bd_addr_t bda
Bluetooth device address
uint16_t min_int
Min connection interval
uint16_t max_int
Max connection interval
uint16_t latency
Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3
uint16_t conn_int
Current connection interval
uint16_t timeout
Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to
0x0C80 Time = N * 10 msec
struct ble_update_duplicate_exceptional_list_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate update duplicate scan exceptional list operation success status
uint8_t subcode
Define in esp_bt_duplicate_exceptional_subcode_type_t
uint16_t length
The length of device_info
esp_duplicate_info_t device_info
device information, when subcode is ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_CLEAN,
the value is invalid
struct ble_update_whitelist_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT.
Public Members
esp_bt_status_t status
Indicate the add or remove whitelist operation success status
esp_ble_wl_operation_t wl_operation
The value is ESP_BLE_WHITELIST_ADD if add address to whitelist operation success,
ESP_BLE_WHITELIST_REMOVE if remove address from the whitelist operation success
Structures
struct esp_ble_adv_params_t
Advertising parameters.
Public Members
uint16_t adv_int_min
Minimum advertising interval for undirected and low duty cycle directed advertising. Range: 0x0020 to
0x4000 Default: N = 0x0800 (1.28 second) Time = N * 0.625 msec Time Range: 20 ms to 10.24 sec
uint16_t adv_int_max
Maximum advertising interval for undirected and low duty cycle directed advertising. Range: 0x0020 to
0x4000 Default: N = 0x0800 (1.28 second) Time = N * 0.625 msec Time Range: 20 ms to 10.24 sec
Advertising max interval
esp_ble_adv_type_t adv_type
Advertising type
esp_ble_addr_type_t own_addr_type
Owner bluetooth device address type
esp_bd_addr_t peer_addr
Peer device bluetooth device address
esp_ble_addr_type_t peer_addr_type
Peer device bluetooth device address type, only support public address type and random address type
esp_ble_adv_channel_t channel_map
Advertising channel map
esp_ble_adv_filter_t adv_filter_policy
Advertising filter policy
struct esp_ble_adv_data_t
Advertising data content, according to “Supplement to the Bluetooth Core Specification”.
Public Members
bool set_scan_rsp
Set this advertising data as scan response or not
bool include_name
Advertising data include device name or not
bool include_txpower
Advertising data include TX power
int min_interval
Advertising data show slave preferred connection min interval. The connection interval in the following
manner: connIntervalmin = Conn_Interval_Min * 1.25 ms Conn_Interval_Min range: 0x0006 to 0x0C80
Value of 0xFFFF indicates no specific minimum. Values not defined above are reserved for future use.
int max_interval
Advertising data show slave preferred connection max interval. The connection interval in the follow-
ing manner: connIntervalmax = Conn_Interval_Max * 1.25 ms Conn_Interval_Max range: 0x0006 to
0x0C80 Conn_Interval_Max shall be equal to or greater than the Conn_Interval_Min. Value of 0xFFFF
indicates no specific maximum. Values not defined above are reserved for future use.
int appearance
External appearance of device
uint16_t manufacturer_len
Manufacturer data length
uint8_t *p_manufacturer_data
Manufacturer data point
uint16_t service_data_len
Service data length
uint8_t *p_service_data
Service data point
uint16_t service_uuid_len
Service uuid length
uint8_t *p_service_uuid
Service uuid array point
uint8_t flag
Advertising flag of discovery mode, see BLE_ADV_DATA_FLAG detail
struct esp_ble_scan_params_t
Ble scan parameters.
Public Members
esp_ble_scan_type_t scan_type
Scan type
esp_ble_addr_type_t own_addr_type
Owner address type
esp_ble_scan_filter_t scan_filter_policy
Scan filter policy
uint16_t scan_interval
Scan interval. This is defined as the time interval from when the Controller started its last LE scan until
it begins the subsequent LE scan. Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms) Time = N * 0.625
msec Time Range: 2.5 msec to 10.24 seconds
uint16_t scan_window
Scan window. The duration of the LE scan. LE_Scan_Window shall be less than or equal to
LE_Scan_Interval Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms) Time = N * 0.625 msec Time
Range: 2.5 msec to 10240 msec
esp_ble_scan_duplicate_t scan_duplicate
The Scan_Duplicates parameter controls whether the Link Layer should filter out duplicate advertising
reports (BLE_SCAN_DUPLICATE_ENABLE) to the Host, or if the Link Layer should generate ad-
vertising reports for each packet received
struct esp_gap_conn_params_t
connection parameters information
Public Members
uint16_t interval
connection interval
uint16_t latency
Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3
uint16_t timeout
Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80
Time = N * 10 msec Time Range: 100 msec to 32 seconds
struct esp_ble_conn_update_params_t
Connection update parameters.
Public Members
esp_bd_addr_t bda
Bluetooth device address
uint16_t min_int
Min connection interval
uint16_t max_int
Max connection interval
uint16_t latency
Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3
uint16_t timeout
Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80
Time = N * 10 msec Time Range: 100 msec to 32 seconds
struct esp_ble_pkt_data_length_params_t
BLE pkt date length keys.
Public Members
uint16_t rx_len
pkt rx data length value
uint16_t tx_len
pkt tx data length value
struct esp_ble_penc_keys_t
BLE encryption keys.
Public Members
esp_bt_octet16_t ltk
The long term key
esp_bt_octet8_t rand
The random number
uint16_t ediv
The ediv value
uint8_t sec_level
The security level of the security link
uint8_t key_size
The key size(7~16) of the security link
struct esp_ble_pcsrk_keys_t
BLE CSRK keys.
Public Members
uint32_t counter
The counter
esp_bt_octet16_t csrk
The csrk key
uint8_t sec_level
The security level
struct esp_ble_pid_keys_t
BLE pid keys.
Public Members
esp_bt_octet16_t irk
The irk value
esp_ble_addr_type_t addr_type
The address type
esp_bd_addr_t static_addr
The static address
struct esp_ble_lenc_keys_t
BLE Encryption reproduction keys.
Public Members
esp_bt_octet16_t ltk
The long term key
uint16_t div
The div value
uint8_t key_size
The key size of the security link
uint8_t sec_level
The security level of the security link
struct esp_ble_lcsrk_keys
BLE SRK keys.
Public Members
uint32_t counter
The counter value
uint16_t div
The div value
uint8_t sec_level
The security level of the security link
esp_bt_octet16_t csrk
The csrk key value
struct esp_ble_sec_key_notif_t
Structure associated with ESP_KEY_NOTIF_EVT.
Public Members
esp_bd_addr_t bd_addr
peer address
uint32_t passkey
the numeric value for comparison. If just_works, do not show this number to UI
struct esp_ble_sec_req_t
Structure of the security request.
Public Members
esp_bd_addr_t bd_addr
peer address
struct esp_ble_bond_key_info_t
struct type of the bond key information value
Public Members
esp_ble_key_mask_t key_mask
the key mask to indicate witch key is present
esp_ble_penc_keys_t penc_key
received peer encryption key
esp_ble_pcsrk_keys_t pcsrk_key
received peer device SRK
esp_ble_pid_keys_t pid_key
peer device ID key
struct esp_ble_bond_dev_t
struct type of the bond device value
Public Members
esp_bd_addr_t bd_addr
peer address
esp_ble_bond_key_info_t bond_key
the bond key information
struct esp_ble_key_t
union type of the security key value
Public Members
esp_bd_addr_t bd_addr
peer address
esp_ble_key_type_t key_type
key type of the security link
esp_ble_key_value_t p_key_value
the pointer to the key value
struct esp_ble_local_id_keys_t
structure type of the ble local id keys value
Public Members
esp_bt_octet16_t ir
the 16 bits of the ir value
esp_bt_octet16_t irk
the 16 bits of the ir key value
esp_bt_octet16_t dhk
the 16 bits of the dh key value
struct esp_ble_auth_cmpl_t
Structure associated with ESP_AUTH_CMPL_EVT.
Public Members
esp_bd_addr_t bd_addr
BD address peer device.
bool key_present
Valid link key value in key element
esp_link_key key
Link key associated with peer device.
uint8_t key_type
The type of Link Key
bool success
TRUE of authentication succeeded, FALSE if failed.
uint8_t fail_reason
The HCI reason/error code for when success=FALSE
esp_ble_addr_type_t addr_type
Peer device address type
esp_bt_dev_type_t dev_type
Device type
esp_ble_auth_req_t auth_mode
authentication mode
struct esp_ble_gap_ext_adv_params_t
ext adv parameters
Public Members
esp_ble_ext_adv_type_mask_t type
ext adv type
uint32_t interval_min
ext adv minimum interval
uint32_t interval_max
ext adv maximum interval
esp_ble_adv_channel_t channel_map
ext adv channel map
esp_ble_addr_type_t own_addr_type
ext adv own address type
esp_ble_addr_type_t peer_addr_type
ext adv peer address type
esp_bd_addr_t peer_addr
ext adv peer address
esp_ble_adv_filter_t filter_policy
ext adv filter policy
int8_t tx_power
ext adv tx power
esp_ble_gap_pri_phy_t primary_phy
ext adv primary phy
uint8_t max_skip
ext adv maximum skip
esp_ble_gap_phy_t secondary_phy
ext adv secondary phy
uint8_t sid
ext adv sid
bool scan_req_notif
ext adv scan request event notify
struct esp_ble_ext_scan_cfg_t
ext scan config
Public Members
esp_ble_scan_type_t scan_type
ext scan type
uint16_t scan_interval
ext scan interval
uint16_t scan_window
ext scan window
struct esp_ble_ext_scan_params_t
ext scan parameters
Public Members
esp_ble_addr_type_t own_addr_type
ext scan own address type
esp_ble_scan_filter_t filter_policy
ext scan filter policy
esp_ble_scan_duplicate_t scan_duplicate
ext scan duplicate scan
esp_ble_ext_scan_cfg_mask_t cfg_mask
ext scan config mask
esp_ble_ext_scan_cfg_t uncoded_cfg
ext scan uncoded config parameters
esp_ble_ext_scan_cfg_t coded_cfg
ext scan coded config parameters
struct esp_ble_gap_conn_params_t
create extend connection parameters
Public Members
uint16_t scan_interval
init scan interval
uint16_t scan_window
init scan window
uint16_t interval_min
minimum interval
uint16_t interval_max
maximum interval
uint16_t latency
ext scan type
uint16_t supervision_timeout
connection supervision timeout
uint16_t min_ce_len
minimum ce length
uint16_t max_ce_len
maximum ce length
struct esp_ble_gap_ext_adv_t
extend adv enable parameters
Public Members
uint8_t instance
advertising handle
int duration
advertising duration
int max_events
maximum number of extended advertising events
struct esp_ble_gap_periodic_adv_params_t
periodic adv parameters
Public Members
uint16_t interval_min
periodic advertising minimum interval
uint16_t interval_max
periodic advertising maximum interval
uint8_t properties
periodic advertising properties
struct esp_ble_gap_periodic_adv_sync_params_t
periodic adv sync parameters
Public Members
esp_ble_gap_sync_t filter_policy
periodic advertising sync filter policy
uint8_t sid
periodic advertising sid
esp_ble_addr_type_t addr_type
periodic advertising address type
esp_bd_addr_t addr
periodic advertising address
uint16_t skip
the maximum number of periodic advertising events that can be skipped
uint16_t sync_timeout
synchronization timeout
struct esp_ble_gap_ext_adv_reprot_t
extend adv report parameters
Public Members
esp_ble_gap_adv_type_t event_type
extend advertising type
uint8_t addr_type
extend advertising address type
esp_bd_addr_t addr
extend advertising address
esp_ble_gap_pri_phy_t primary_phy
extend advertising primary phy
esp_ble_gap_phy_t secondly_phy
extend advertising secondary phy
uint8_t sid
extend advertising sid
uint8_t tx_power
extend advertising tx power
int8_t rssi
extend advertising rssi
uint16_t per_adv_interval
periodic advertising interval
uint8_t dir_addr_type
direct address type
esp_bd_addr_t dir_addr
direct address
esp_ble_gap_ext_adv_data_status_t data_status
data type
uint8_t adv_data_len
extend advertising data length
uint8_t adv_data[251]
extend advertising data
struct esp_ble_gap_periodic_adv_report_t
periodic adv report parameters
Public Members
uint16_t sync_handle
periodic advertising train handle
uint8_t tx_power
periodic advertising tx power
int8_t rssi
periodic advertising rssi
esp_ble_gap_ext_adv_data_status_t data_status
periodic advertising data type
uint8_t data_length
periodic advertising data length
uint8_t data[251]
periodic advertising data
struct esp_ble_gap_periodic_adv_sync_estab_t
perodic adv sync establish parameters
Public Members
uint8_t status
periodic advertising sync status
uint16_t sync_handle
periodic advertising train handle
uint8_t sid
periodic advertising sid
esp_ble_addr_type_t addr_type
periodic advertising address type
esp_bd_addr_t adv_addr
periodic advertising address
esp_ble_gap_phy_t adv_phy
periodic advertising adv phy type
uint16_t period_adv_interval
periodic advertising interval
uint8_t adv_clk_accuracy
periodic advertising clock accuracy
Macros
ESP_BLE_ADV_FLAG_LIMIT_DISC
BLE_ADV_DATA_FLAG data flag bit definition used for advertising data flag
ESP_BLE_ADV_FLAG_GEN_DISC
ESP_BLE_ADV_FLAG_BREDR_NOT_SPT
ESP_BLE_ADV_FLAG_DMT_CONTROLLER_SPT
ESP_BLE_ADV_FLAG_DMT_HOST_SPT
ESP_BLE_ADV_FLAG_NON_LIMIT_DISC
ESP_LE_KEY_NONE
ESP_LE_KEY_PENC
ESP_LE_KEY_PID
ESP_LE_KEY_PCSRK
ESP_LE_KEY_PLK
ESP_LE_KEY_LLK
ESP_LE_KEY_LENC
ESP_LE_KEY_LID
ESP_LE_KEY_LCSRK
ESP_LE_AUTH_NO_BOND
ESP_LE_AUTH_BOND
ESP_LE_AUTH_REQ_MITM
ESP_LE_AUTH_REQ_BOND_MITM
0101
ESP_LE_AUTH_REQ_SC_ONLY
ESP_LE_AUTH_REQ_SC_BOND
ESP_LE_AUTH_REQ_SC_MITM
ESP_LE_AUTH_REQ_SC_MITM_BOND
ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_DISABLE
ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_ENABLE
ESP_BLE_OOB_DISABLE
ESP_BLE_OOB_ENABLE
ESP_IO_CAP_OUT
ESP_IO_CAP_IO
ESP_IO_CAP_IN
ESP_IO_CAP_NONE
ESP_IO_CAP_KBDISP
ESP_BLE_APPEARANCE_UNKNOWN
ESP_BLE_APPEARANCE_GENERIC_PHONE
ESP_BLE_APPEARANCE_GENERIC_COMPUTER
ESP_BLE_APPEARANCE_GENERIC_WATCH
ESP_BLE_APPEARANCE_SPORTS_WATCH
ESP_BLE_APPEARANCE_GENERIC_CLOCK
ESP_BLE_APPEARANCE_GENERIC_DISPLAY
ESP_BLE_APPEARANCE_GENERIC_REMOTE
ESP_BLE_APPEARANCE_GENERIC_EYEGLASSES
ESP_BLE_APPEARANCE_GENERIC_TAG
ESP_BLE_APPEARANCE_GENERIC_KEYRING
ESP_BLE_APPEARANCE_GENERIC_MEDIA_PLAYER
ESP_BLE_APPEARANCE_GENERIC_BARCODE_SCANNER
ESP_BLE_APPEARANCE_GENERIC_THERMOMETER
ESP_BLE_APPEARANCE_THERMOMETER_EAR
ESP_BLE_APPEARANCE_GENERIC_HEART_RATE
ESP_BLE_APPEARANCE_HEART_RATE_BELT
ESP_BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE
ESP_BLE_APPEARANCE_BLOOD_PRESSURE_ARM
ESP_BLE_APPEARANCE_BLOOD_PRESSURE_WRIST
ESP_BLE_APPEARANCE_GENERIC_HID
ESP_BLE_APPEARANCE_HID_KEYBOARD
ESP_BLE_APPEARANCE_HID_MOUSE
ESP_BLE_APPEARANCE_HID_JOYSTICK
ESP_BLE_APPEARANCE_HID_GAMEPAD
ESP_BLE_APPEARANCE_HID_DIGITIZER_TABLET
ESP_BLE_APPEARANCE_HID_CARD_READER
ESP_BLE_APPEARANCE_HID_DIGITAL_PEN
ESP_BLE_APPEARANCE_HID_BARCODE_SCANNER
ESP_BLE_APPEARANCE_GENERIC_GLUCOSE
ESP_BLE_APPEARANCE_GENERIC_WALKING
ESP_BLE_APPEARANCE_WALKING_IN_SHOE
ESP_BLE_APPEARANCE_WALKING_ON_SHOE
ESP_BLE_APPEARANCE_WALKING_ON_HIP
ESP_BLE_APPEARANCE_GENERIC_CYCLING
ESP_BLE_APPEARANCE_CYCLING_COMPUTER
ESP_BLE_APPEARANCE_CYCLING_SPEED
ESP_BLE_APPEARANCE_CYCLING_CADENCE
ESP_BLE_APPEARANCE_CYCLING_POWER
ESP_BLE_APPEARANCE_CYCLING_SPEED_CADENCE
ESP_BLE_APPEARANCE_GENERIC_PULSE_OXIMETER
ESP_BLE_APPEARANCE_PULSE_OXIMETER_FINGERTIP
ESP_BLE_APPEARANCE_PULSE_OXIMETER_WRIST
ESP_BLE_APPEARANCE_GENERIC_WEIGHT
ESP_BLE_APPEARANCE_GENERIC_PERSONAL_MOBILITY_DEVICE
ESP_BLE_APPEARANCE_POWERED_WHEELCHAIR
ESP_BLE_APPEARANCE_MOBILITY_SCOOTER
ESP_BLE_APPEARANCE_GENERIC_CONTINUOUS_GLUCOSE_MONITOR
ESP_BLE_APPEARANCE_GENERIC_INSULIN_PUMP
ESP_BLE_APPEARANCE_INSULIN_PUMP_DURABLE_PUMP
ESP_BLE_APPEARANCE_INSULIN_PUMP_PATCH_PUMP
ESP_BLE_APPEARANCE_INSULIN_PEN
ESP_BLE_APPEARANCE_GENERIC_MEDICATION_DELIVERY
ESP_BLE_APPEARANCE_GENERIC_OUTDOOR_SPORTS
ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION
ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_AND_NAV
ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD
ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD_AND_NAV
ESP_GAP_BLE_CHANNELS_LEN
ESP_GAP_BLE_ADD_WHITELIST_COMPLETE_EVT
This is the old name, just for backwards compatibility.
ESP_BLE_ADV_DATA_LEN_MAX
Advertising data maximum length.
ESP_BLE_SCAN_RSP_DATA_LEN_MAX
Scan response data maximum length.
BLE_BIT(n)
ESP_BLE_GAP_SET_EXT_ADV_PROP_NONCONN_NONSCANNABLE_UNDIRECTED
ESP_BLE_GAP_SET_EXT_ADV_PROP_CONNECTABLE
ESP_BLE_GAP_SET_EXT_ADV_PROP_SCANNABLE
ESP_BLE_GAP_SET_EXT_ADV_PROP_DIRECTED
ESP_BLE_GAP_SET_EXT_ADV_PROP_HD_DIRECTED
ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY
ESP_BLE_GAP_SET_EXT_ADV_PROP_ANON_ADV
ESP_BLE_GAP_SET_EXT_ADV_PROP_INCLUDE_TX_PWR
ESP_BLE_GAP_SET_EXT_ADV_PROP_MASK
ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_IND
ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_LD_DIR
ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_HD_DIR
ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_SCAN
ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_NONCONN
ESP_BLE_GAP_PHY_1M
ESP_BLE_GAP_PHY_2M
ESP_BLE_GAP_PHY_CODED
ESP_BLE_GAP_NO_PREFER_TRANSMIT_PHY
ESP_BLE_GAP_NO_PREFER_RECEIVE_PHY
ESP_BLE_GAP_PRI_PHY_1M
ESP_BLE_GAP_PRI_PHY_CODED
ESP_BLE_GAP_PHY_1M_PREF_MASK
ESP_BLE_GAP_PHY_2M_PREF_MASK
ESP_BLE_GAP_PHY_CODED_PREF_MASK
ESP_BLE_GAP_PHY_OPTIONS_NO_PREF
ESP_BLE_GAP_PHY_OPTIONS_PREF_S2_CODING
ESP_BLE_GAP_PHY_OPTIONS_PREF_S8_CODING
ESP_BLE_GAP_EXT_SCAN_CFG_UNCODE_MASK
ESP_BLE_GAP_EXT_SCAN_CFG_CODE_MASK
ESP_BLE_GAP_EXT_ADV_DATA_COMPLETE
ESP_BLE_GAP_EXT_ADV_DATA_INCOMPLETE
ESP_BLE_GAP_EXT_ADV_DATA_TRUNCATED
ESP_BLE_GAP_SYNC_POLICY_BY_ADV_INFO
ESP_BLE_GAP_SYNC_POLICY_BY_PERIODIC_LIST
ESP_BLE_ADV_REPORT_EXT_ADV_IND
ESP_BLE_ADV_REPORT_EXT_SCAN_IND
ESP_BLE_ADV_REPORT_EXT_DIRECT_ADV
ESP_BLE_ADV_REPORT_EXT_SCAN_RSP
ESP_BLE_LEGACY_ADV_TYPE_IND
ESP_BLE_LEGACY_ADV_TYPE_DIRECT_IND
ESP_BLE_LEGACY_ADV_TYPE_SCAN_IND
ESP_BLE_LEGACY_ADV_TYPE_NONCON_IND
ESP_BLE_LEGACY_ADV_TYPE_SCAN_RSP_TO_ADV_IND
ESP_BLE_LEGACY_ADV_TYPE_SCAN_RSP_TO_ADV_SCAN_IND
Type Definitions
Enumerations
enum esp_gap_ble_cb_event_t
GAP BLE callback event type.
Values:
enumerator ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT
When advertising data set complete, the event comes
enumerator ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT
When scan response data set complete, the event comes
enumerator ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT
When scan parameters set complete, the event comes
enumerator ESP_GAP_BLE_SCAN_RESULT_EVT
When one scan result ready, the event comes each time
enumerator ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT
When raw advertising data set complete, the event comes
enumerator ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT
When raw advertising data set complete, the event comes
enumerator ESP_GAP_BLE_ADV_START_COMPLETE_EVT
When start advertising complete, the event comes
enumerator ESP_GAP_BLE_SCAN_START_COMPLETE_EVT
When start scan complete, the event comes
enumerator ESP_GAP_BLE_AUTH_CMPL_EVT
enumerator ESP_GAP_BLE_KEY_EVT
enumerator ESP_GAP_BLE_SEC_REQ_EVT
enumerator ESP_GAP_BLE_PASSKEY_NOTIF_EVT
enumerator ESP_GAP_BLE_PASSKEY_REQ_EVT
enumerator ESP_GAP_BLE_OOB_REQ_EVT
enumerator ESP_GAP_BLE_LOCAL_IR_EVT
enumerator ESP_GAP_BLE_LOCAL_ER_EVT
enumerator ESP_GAP_BLE_NC_REQ_EVT
enumerator ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT
When stop adv complete, the event comes
enumerator ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT
When stop scan complete, the event comes
enumerator ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT
When set the static rand address complete, the event comes
enumerator ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT
When update connection parameters complete, the event comes
enumerator ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT
When set pkt length complete, the event comes
enumerator ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT
When Enable/disable privacy on the local device complete, the event comes
enumerator ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT
When remove the bond device complete, the event comes
enumerator ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT
When clear the bond device clear complete, the event comes
enumerator ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT
When get the bond device list complete, the event comes
enumerator ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT
When read the rssi complete, the event comes
enumerator ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT
When add or remove whitelist complete, the event comes
enumerator ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT
When update duplicate exceptional list complete, the event comes
enumerator ESP_GAP_BLE_SET_CHANNELS_EVT
When setting BLE channels complete, the event comes
enumerator ESP_GAP_BLE_READ_PHY_COMPLETE_EVT
enumerator ESP_GAP_BLE_SET_PREFERRED_DEFAULT_PHY_COMPLETE_EVT
enumerator ESP_GAP_BLE_SET_PREFERRED_PHY_COMPLETE_EVT
enumerator ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT
enumerator ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT
enumerator ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT
enumerator ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT
enumerator ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT
enumerator ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT
enumerator ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT
enumerator ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT
enumerator ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT
enumerator ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT
enumerator ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT
enumerator ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT
enumerator ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT
enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT
enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT
enumerator ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT
enumerator ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT
enumerator ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT
enumerator ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT
enumerator ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT
enumerator ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT
enumerator ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT
enumerator ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT
enumerator ESP_GAP_BLE_EXT_ADV_REPORT_EVT
enumerator ESP_GAP_BLE_SCAN_TIMEOUT_EVT
enumerator ESP_GAP_BLE_ADV_TERMINATED_EVT
enumerator ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT
enumerator ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT
enumerator ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT
enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT
enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT
enumerator ESP_GAP_BLE_EVT_MAX
enum esp_ble_adv_data_type
The type of advertising data(not adv_type)
Values:
enumerator ESP_BLE_AD_TYPE_FLAG
enumerator ESP_BLE_AD_TYPE_16SRV_PART
enumerator ESP_BLE_AD_TYPE_16SRV_CMPL
enumerator ESP_BLE_AD_TYPE_32SRV_PART
enumerator ESP_BLE_AD_TYPE_32SRV_CMPL
enumerator ESP_BLE_AD_TYPE_128SRV_PART
enumerator ESP_BLE_AD_TYPE_128SRV_CMPL
enumerator ESP_BLE_AD_TYPE_NAME_SHORT
enumerator ESP_BLE_AD_TYPE_NAME_CMPL
enumerator ESP_BLE_AD_TYPE_TX_PWR
enumerator ESP_BLE_AD_TYPE_DEV_CLASS
enumerator ESP_BLE_AD_TYPE_SM_TK
enumerator ESP_BLE_AD_TYPE_SM_OOB_FLAG
enumerator ESP_BLE_AD_TYPE_INT_RANGE
enumerator ESP_BLE_AD_TYPE_SOL_SRV_UUID
enumerator ESP_BLE_AD_TYPE_128SOL_SRV_UUID
enumerator ESP_BLE_AD_TYPE_SERVICE_DATA
enumerator ESP_BLE_AD_TYPE_PUBLIC_TARGET
enumerator ESP_BLE_AD_TYPE_RANDOM_TARGET
enumerator ESP_BLE_AD_TYPE_APPEARANCE
enumerator ESP_BLE_AD_TYPE_ADV_INT
enumerator ESP_BLE_AD_TYPE_LE_DEV_ADDR
enumerator ESP_BLE_AD_TYPE_LE_ROLE
enumerator ESP_BLE_AD_TYPE_SPAIR_C256
enumerator ESP_BLE_AD_TYPE_SPAIR_R256
enumerator ESP_BLE_AD_TYPE_32SOL_SRV_UUID
enumerator ESP_BLE_AD_TYPE_32SERVICE_DATA
enumerator ESP_BLE_AD_TYPE_128SERVICE_DATA
enumerator ESP_BLE_AD_TYPE_LE_SECURE_CONFIRM
enumerator ESP_BLE_AD_TYPE_LE_SECURE_RANDOM
enumerator ESP_BLE_AD_TYPE_URI
enumerator ESP_BLE_AD_TYPE_INDOOR_POSITION
enumerator ESP_BLE_AD_TYPE_TRANS_DISC_DATA
enumerator ESP_BLE_AD_TYPE_LE_SUPPORT_FEATURE
enumerator ESP_BLE_AD_TYPE_CHAN_MAP_UPDATE
enumerator ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE
enum esp_ble_adv_type_t
Advertising mode.
Values:
enumerator ADV_TYPE_IND
enumerator ADV_TYPE_DIRECT_IND_HIGH
enumerator ADV_TYPE_SCAN_IND
enumerator ADV_TYPE_NONCONN_IND
enumerator ADV_TYPE_DIRECT_IND_LOW
enum esp_ble_adv_channel_t
Advertising channel mask.
Values:
enumerator ADV_CHNL_37
enumerator ADV_CHNL_38
enumerator ADV_CHNL_39
enumerator ADV_CHNL_ALL
enum esp_ble_adv_filter_t
Values:
enumerator ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY
Allow both scan and connection requests from anyone.
enumerator ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY
Allow both scan req from White List devices only and connection req from anyone.
enumerator ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST
Allow both scan req from anyone and connection req from White List devices only.
enumerator ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST
Allow scan and connection requests from White List devices only.
enum esp_ble_sec_act_t
Values:
enumerator ESP_BLE_SEC_ENCRYPT
enumerator ESP_BLE_SEC_ENCRYPT_NO_MITM
enumerator ESP_BLE_SEC_ENCRYPT_MITM
enum esp_ble_sm_param_t
Values:
enumerator ESP_BLE_SM_PASSKEY
enumerator ESP_BLE_SM_AUTHEN_REQ_MODE
enumerator ESP_BLE_SM_IOCAP_MODE
enumerator ESP_BLE_SM_SET_INIT_KEY
enumerator ESP_BLE_SM_SET_RSP_KEY
enumerator ESP_BLE_SM_MAX_KEY_SIZE
enumerator ESP_BLE_SM_MIN_KEY_SIZE
enumerator ESP_BLE_SM_SET_STATIC_PASSKEY
enumerator ESP_BLE_SM_CLEAR_STATIC_PASSKEY
enumerator ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH
enumerator ESP_BLE_SM_OOB_SUPPORT
enumerator ESP_BLE_APP_ENC_KEY_SIZE
enumerator ESP_BLE_SM_MAX_PARAM
enum esp_ble_scan_type_t
Ble scan type.
Values:
enumerator BLE_SCAN_TYPE_PASSIVE
Passive scan
enumerator BLE_SCAN_TYPE_ACTIVE
Active scan
enum esp_ble_scan_filter_t
Ble scan filter type.
Values:
enumerator BLE_SCAN_FILTER_ALLOW_ALL
Accept all :
i. advertisement packets except directed advertising packets not addressed to this device (default).
enumerator BLE_SCAN_FILTER_ALLOW_ONLY_WLST
Accept only :
i. advertisement packets from devices where the advertiser’s address is in the White list.
ii. Directed advertising packets which are not addressed for this device shall be ignored.
enumerator BLE_SCAN_FILTER_ALLOW_UND_RPA_DIR
Accept all :
i. undirected advertisement packets, and
ii. directed advertising packets where the initiator address is a resolvable private address, and
iii. directed advertising packets addressed to this device.
enumerator BLE_SCAN_FILTER_ALLOW_WLIST_RPA_DIR
Accept all :
i. advertisement packets from devices where the advertiser’s address is in the White list, and
ii. directed advertising packets where the initiator address is a resolvable private address, and
iii. directed advertising packets addressed to this device.
enum esp_ble_scan_duplicate_t
Ble scan duplicate type.
Values:
enumerator BLE_SCAN_DUPLICATE_DISABLE
the Link Layer should generate advertising reports to the host for each packet received
enumerator BLE_SCAN_DUPLICATE_ENABLE
the Link Layer should filter out duplicate advertising reports to the Host
enumerator BLE_SCAN_DUPLICATE_MAX
0x02 –0xFF, Reserved for future use
enum esp_gap_search_evt_t
Sub Event of ESP_GAP_BLE_SCAN_RESULT_EVT.
Values:
enumerator ESP_GAP_SEARCH_INQ_RES_EVT
Inquiry result for a peer device.
enumerator ESP_GAP_SEARCH_INQ_CMPL_EVT
Inquiry complete.
enumerator ESP_GAP_SEARCH_DISC_RES_EVT
Discovery result for a peer device.
enumerator ESP_GAP_SEARCH_DISC_BLE_RES_EVT
Discovery result for BLE GATT based service on a peer device.
enumerator ESP_GAP_SEARCH_DISC_CMPL_EVT
Discovery complete.
enumerator ESP_GAP_SEARCH_DI_DISC_CMPL_EVT
Discovery complete.
enumerator ESP_GAP_SEARCH_SEARCH_CANCEL_CMPL_EVT
Search cancelled
enumerator ESP_GAP_SEARCH_INQ_DISCARD_NUM_EVT
The number of pkt discarded by flow control
enum esp_ble_evt_type_t
Ble scan result event type, to indicate the result is scan response or advertising data or other.
Values:
enumerator ESP_BLE_EVT_CONN_ADV
Connectable undirected advertising (ADV_IND)
enumerator ESP_BLE_EVT_CONN_DIR_ADV
Connectable directed advertising (ADV_DIRECT_IND)
enumerator ESP_BLE_EVT_DISC_ADV
Scannable undirected advertising (ADV_SCAN_IND)
enumerator ESP_BLE_EVT_NON_CONN_ADV
Non connectable undirected advertising (ADV_NONCONN_IND)
enumerator ESP_BLE_EVT_SCAN_RSP
Scan Response (SCAN_RSP)
enum esp_ble_wl_operation_t
Values:
enumerator ESP_BLE_WHITELIST_REMOVE
remove mac from whitelist
enumerator ESP_BLE_WHITELIST_ADD
add address to whitelist
enum esp_bt_duplicate_exceptional_subcode_type_t
Values:
enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_ADD
Add device info into duplicate scan exceptional list
enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_REMOVE
Remove device info from duplicate scan exceptional list
enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_CLEAN
Clean duplicate scan exceptional list
enum esp_ble_duplicate_exceptional_info_type_t
Values:
enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_ADV_ADDR
BLE advertising address , device info will be added into ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ADDR_LIST
enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_LINK_ID
BLE mesh link ID, it is for BLE mesh, device info will be added into
ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_LINK_ID_LIST
enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_BEACON_TYPE
BLE mesh beacon AD type, the format is | Len | 0x2B | Beacon Type | Beacon Data |
enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROV_SRV_ADV
BLE mesh provisioning service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1827 | …. |`
enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROXY_SRV_ADV
BLE mesh adv with proxy service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1828 | …. |`
enum esp_duplicate_scan_exceptional_list_type_t
Values:
enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ADDR_LIST
duplicate scan exceptional addr list
enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_LINK_ID_LIST
duplicate scan exceptional mesh link ID list
enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_BEACON_TYPE_LIST
duplicate scan exceptional mesh beacon type list
enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROV_SRV_ADV_LIST
duplicate scan exceptional mesh adv with provisioning service uuid
enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROXY_SRV_ADV_LIST
duplicate scan exceptional mesh adv with provisioning service uuid
enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ALL_LIST
duplicate scan exceptional all list
GATT DEFINES
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_gatt_defs.h
Unions
union esp_gatt_rsp_t
#include <esp_gatt_defs.h> GATT remote read request response type.
Public Members
esp_gatt_value_t attr_value
Gatt attribute structure
uint16_t handle
Gatt attribute handle
Structures
struct esp_gatt_id_t
Gatt id, include uuid and instance id.
Public Members
esp_bt_uuid_t uuid
UUID
uint8_t inst_id
Instance id
struct esp_gatt_srvc_id_t
Gatt service id, include id (uuid and instance id) and primary flag.
Public Members
esp_gatt_id_t id
Gatt id, include uuid and instance
bool is_primary
This service is primary or not
struct esp_attr_desc_t
Attribute description (used to create database)
Public Members
uint16_t uuid_length
UUID length
uint8_t *uuid_p
UUID value
uint16_t perm
Attribute permission
uint16_t max_length
Maximum length of the element
uint16_t length
Current length of the element
uint8_t *value
Element value array
struct esp_attr_control_t
attribute auto response flag
Public Members
uint8_t auto_rsp
if auto_rsp set to ESP_GATT_RSP_BY_APP, means the response of Write/Read operation will by
replied by application. if auto_rsp set to ESP_GATT_AUTO_RSP, means the response of Write/Read
operation will be replied by GATT stack automatically.
struct esp_gatts_attr_db_t
attribute type added to the gatt server database
Public Members
esp_attr_control_t attr_control
The attribute control type
esp_attr_desc_t att_desc
The attribute type
struct esp_attr_value_t
set the attribute value type
Public Members
uint16_t attr_max_len
attribute max value length
uint16_t attr_len
attribute current value length
uint8_t *attr_value
the pointer to attribute value
struct esp_gatts_incl_svc_desc_t
Gatt include service entry element.
Public Members
uint16_t start_hdl
Gatt start handle value of included service
uint16_t end_hdl
Gatt end handle value of included service
uint16_t uuid
Gatt attribute value UUID of included service
struct esp_gatts_incl128_svc_desc_t
Gatt include 128 bit service entry element.
Public Members
uint16_t start_hdl
Gatt start handle value of included 128 bit service
uint16_t end_hdl
Gatt end handle value of included 128 bit service
struct esp_gatt_value_t
Gatt attribute value.
Public Members
uint8_t value[ESP_GATT_MAX_ATTR_LEN]
Gatt attribute value
uint16_t handle
Gatt attribute handle
uint16_t offset
Gatt attribute value offset
uint16_t len
Gatt attribute value length
uint8_t auth_req
Gatt authentication request
struct esp_gatt_conn_params_t
Connection parameters information.
Public Members
uint16_t interval
connection interval
uint16_t latency
Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3
uint16_t timeout
Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80
Time = N * 10 msec Time Range: 100 msec to 32 seconds
struct esp_gattc_multi_t
read multiple attribute
Public Members
uint8_t num_attr
The number of the attribute
uint16_t handles[ESP_GATT_MAX_READ_MULTI_HANDLES]
The handles list
struct esp_gattc_db_elem_t
data base attribute element
Public Members
esp_gatt_db_attr_type_t type
The attribute type
uint16_t attribute_handle
The attribute handle, it’s valid for all of the type
uint16_t start_handle
The service start handle, it’s valid only when the type = ESP_GATT_DB_PRIMARY_SERVICE or
ESP_GATT_DB_SECONDARY_SERVICE
uint16_t end_handle
The service end handle, it’s valid only when the type = ESP_GATT_DB_PRIMARY_SERVICE or
ESP_GATT_DB_SECONDARY_SERVICE
esp_gatt_char_prop_t properties
The characteristic properties, it’s valid only when the type = ESP_GATT_DB_CHARACTERISTIC
esp_bt_uuid_t uuid
The attribute uuid, it’s valid for all of the type
struct esp_gattc_service_elem_t
service element
Public Members
bool is_primary
The service flag, true if the service is primary service, else is secondary service
uint16_t start_handle
The start handle of the service
uint16_t end_handle
The end handle of the service
esp_bt_uuid_t uuid
The uuid of the service
struct esp_gattc_char_elem_t
characteristic element
Public Members
uint16_t char_handle
The characteristic handle
esp_gatt_char_prop_t properties
The characteristic properties
esp_bt_uuid_t uuid
The characteristic uuid
struct esp_gattc_descr_elem_t
descriptor element
Public Members
uint16_t handle
The characteristic descriptor handle
esp_bt_uuid_t uuid
The characteristic descriptor uuid
struct esp_gattc_incl_svc_elem_t
include service element
Public Members
uint16_t handle
The include service current attribute handle
uint16_t incl_srvc_s_handle
The start handle of the service which has been included
uint16_t incl_srvc_e_handle
The end handle of the service which has been included
esp_bt_uuid_t uuid
The include service uuid
Macros
ESP_GATT_UUID_IMMEDIATE_ALERT_SVC
All “ESP_GATT_UUID_xxx”is attribute types
ESP_GATT_UUID_LINK_LOSS_SVC
ESP_GATT_UUID_TX_POWER_SVC
ESP_GATT_UUID_CURRENT_TIME_SVC
ESP_GATT_UUID_REF_TIME_UPDATE_SVC
ESP_GATT_UUID_NEXT_DST_CHANGE_SVC
ESP_GATT_UUID_GLUCOSE_SVC
ESP_GATT_UUID_HEALTH_THERMOM_SVC
ESP_GATT_UUID_DEVICE_INFO_SVC
ESP_GATT_UUID_HEART_RATE_SVC
ESP_GATT_UUID_PHONE_ALERT_STATUS_SVC
ESP_GATT_UUID_BATTERY_SERVICE_SVC
ESP_GATT_UUID_BLOOD_PRESSURE_SVC
ESP_GATT_UUID_ALERT_NTF_SVC
ESP_GATT_UUID_HID_SVC
ESP_GATT_UUID_SCAN_PARAMETERS_SVC
ESP_GATT_UUID_RUNNING_SPEED_CADENCE_SVC
ESP_GATT_UUID_Automation_IO_SVC
ESP_GATT_UUID_CYCLING_SPEED_CADENCE_SVC
ESP_GATT_UUID_CYCLING_POWER_SVC
ESP_GATT_UUID_LOCATION_AND_NAVIGATION_SVC
ESP_GATT_UUID_ENVIRONMENTAL_SENSING_SVC
ESP_GATT_UUID_BODY_COMPOSITION
ESP_GATT_UUID_USER_DATA_SVC
ESP_GATT_UUID_WEIGHT_SCALE_SVC
ESP_GATT_UUID_BOND_MANAGEMENT_SVC
ESP_GATT_UUID_CONT_GLUCOSE_MONITOR_SVC
ESP_GATT_UUID_PRI_SERVICE
ESP_GATT_UUID_SEC_SERVICE
ESP_GATT_UUID_INCLUDE_SERVICE
ESP_GATT_UUID_CHAR_DECLARE
ESP_GATT_UUID_CHAR_EXT_PROP
ESP_GATT_UUID_CHAR_DESCRIPTION
ESP_GATT_UUID_CHAR_CLIENT_CONFIG
ESP_GATT_UUID_CHAR_SRVR_CONFIG
ESP_GATT_UUID_CHAR_PRESENT_FORMAT
ESP_GATT_UUID_CHAR_AGG_FORMAT
ESP_GATT_UUID_CHAR_VALID_RANGE
ESP_GATT_UUID_EXT_RPT_REF_DESCR
ESP_GATT_UUID_RPT_REF_DESCR
ESP_GATT_UUID_NUM_DIGITALS_DESCR
ESP_GATT_UUID_VALUE_TRIGGER_DESCR
ESP_GATT_UUID_ENV_SENSING_CONFIG_DESCR
ESP_GATT_UUID_ENV_SENSING_MEASUREMENT_DESCR
ESP_GATT_UUID_ENV_SENSING_TRIGGER_DESCR
ESP_GATT_UUID_TIME_TRIGGER_DESCR
ESP_GATT_UUID_GAP_DEVICE_NAME
ESP_GATT_UUID_GAP_ICON
ESP_GATT_UUID_GAP_PREF_CONN_PARAM
ESP_GATT_UUID_GAP_CENTRAL_ADDR_RESOL
ESP_GATT_UUID_GATT_SRV_CHGD
ESP_GATT_UUID_ALERT_LEVEL
ESP_GATT_UUID_TX_POWER_LEVEL
ESP_GATT_UUID_CURRENT_TIME
ESP_GATT_UUID_LOCAL_TIME_INFO
ESP_GATT_UUID_REF_TIME_INFO
ESP_GATT_UUID_NW_STATUS
ESP_GATT_UUID_NW_TRIGGER
ESP_GATT_UUID_ALERT_STATUS
ESP_GATT_UUID_RINGER_CP
ESP_GATT_UUID_RINGER_SETTING
ESP_GATT_UUID_GM_MEASUREMENT
ESP_GATT_UUID_GM_CONTEXT
ESP_GATT_UUID_GM_CONTROL_POINT
ESP_GATT_UUID_GM_FEATURE
ESP_GATT_UUID_SYSTEM_ID
ESP_GATT_UUID_MODEL_NUMBER_STR
ESP_GATT_UUID_SERIAL_NUMBER_STR
ESP_GATT_UUID_FW_VERSION_STR
ESP_GATT_UUID_HW_VERSION_STR
ESP_GATT_UUID_SW_VERSION_STR
ESP_GATT_UUID_MANU_NAME
ESP_GATT_UUID_IEEE_DATA
ESP_GATT_UUID_PNP_ID
ESP_GATT_UUID_HID_INFORMATION
ESP_GATT_UUID_HID_REPORT_MAP
ESP_GATT_UUID_HID_CONTROL_POINT
ESP_GATT_UUID_HID_REPORT
ESP_GATT_UUID_HID_PROTO_MODE
ESP_GATT_UUID_HID_BT_KB_INPUT
ESP_GATT_UUID_HID_BT_KB_OUTPUT
ESP_GATT_UUID_HID_BT_MOUSE_INPUT
ESP_GATT_HEART_RATE_MEAS
Heart Rate Measurement.
ESP_GATT_BODY_SENSOR_LOCATION
Body Sensor Location.
ESP_GATT_HEART_RATE_CNTL_POINT
Heart Rate Control Point.
ESP_GATT_UUID_BATTERY_LEVEL
ESP_GATT_UUID_SC_CONTROL_POINT
ESP_GATT_UUID_SENSOR_LOCATION
ESP_GATT_UUID_RSC_MEASUREMENT
ESP_GATT_UUID_RSC_FEATURE
ESP_GATT_UUID_CSC_MEASUREMENT
ESP_GATT_UUID_CSC_FEATURE
ESP_GATT_UUID_SCAN_INT_WINDOW
ESP_GATT_UUID_SCAN_REFRESH
ESP_GATT_ILLEGAL_UUID
GATT INVALID UUID.
ESP_GATT_ILLEGAL_HANDLE
GATT INVALID HANDLE.
ESP_GATT_ATTR_HANDLE_MAX
GATT attribute max handle.
ESP_GATT_MAX_READ_MULTI_HANDLES
ESP_GATT_PERM_READ
Attribute permissions.
ESP_GATT_PERM_READ_ENCRYPTED
ESP_GATT_PERM_READ_ENC_MITM
ESP_GATT_PERM_WRITE
ESP_GATT_PERM_WRITE_ENCRYPTED
ESP_GATT_PERM_WRITE_ENC_MITM
ESP_GATT_PERM_WRITE_SIGNED
ESP_GATT_PERM_WRITE_SIGNED_MITM
ESP_GATT_PERM_READ_AUTHORIZATION
ESP_GATT_PERM_WRITE_AUTHORIZATION
ESP_GATT_CHAR_PROP_BIT_BROADCAST
ESP_GATT_CHAR_PROP_BIT_READ
ESP_GATT_CHAR_PROP_BIT_WRITE_NR
ESP_GATT_CHAR_PROP_BIT_WRITE
ESP_GATT_CHAR_PROP_BIT_NOTIFY
ESP_GATT_CHAR_PROP_BIT_INDICATE
ESP_GATT_CHAR_PROP_BIT_AUTH
ESP_GATT_CHAR_PROP_BIT_EXT_PROP
ESP_GATT_MAX_ATTR_LEN
GATT maximum attribute length.
ESP_GATT_RSP_BY_APP
ESP_GATT_AUTO_RSP
ESP_GATT_IF_NONE
If callback report gattc_if/gatts_if as this macro, means this event is not correspond to any app
Type Definitions
Enumerations
enum esp_gatt_prep_write_type
Attribute write data type from the client.
Values:
enumerator ESP_GATT_PREP_WRITE_CANCEL
Prepare write cancel
enumerator ESP_GATT_PREP_WRITE_EXEC
Prepare write execute
enum esp_gatt_status_t
GATT success code and error codes.
Values:
enumerator ESP_GATT_OK
enumerator ESP_GATT_INVALID_HANDLE
enumerator ESP_GATT_READ_NOT_PERMIT
enumerator ESP_GATT_WRITE_NOT_PERMIT
enumerator ESP_GATT_INVALID_PDU
enumerator ESP_GATT_INSUF_AUTHENTICATION
enumerator ESP_GATT_REQ_NOT_SUPPORTED
enumerator ESP_GATT_INVALID_OFFSET
enumerator ESP_GATT_INSUF_AUTHORIZATION
enumerator ESP_GATT_PREPARE_Q_FULL
enumerator ESP_GATT_NOT_FOUND
enumerator ESP_GATT_NOT_LONG
enumerator ESP_GATT_INSUF_KEY_SIZE
enumerator ESP_GATT_INVALID_ATTR_LEN
enumerator ESP_GATT_ERR_UNLIKELY
enumerator ESP_GATT_INSUF_ENCRYPTION
enumerator ESP_GATT_UNSUPPORT_GRP_TYPE
enumerator ESP_GATT_INSUF_RESOURCE
enumerator ESP_GATT_NO_RESOURCES
enumerator ESP_GATT_INTERNAL_ERROR
enumerator ESP_GATT_WRONG_STATE
enumerator ESP_GATT_DB_FULL
enumerator ESP_GATT_BUSY
enumerator ESP_GATT_ERROR
enumerator ESP_GATT_CMD_STARTED
enumerator ESP_GATT_ILLEGAL_PARAMETER
enumerator ESP_GATT_PENDING
enumerator ESP_GATT_AUTH_FAIL
enumerator ESP_GATT_MORE
enumerator ESP_GATT_INVALID_CFG
enumerator ESP_GATT_SERVICE_STARTED
enumerator ESP_GATT_ENCRYPTED_MITM
enumerator ESP_GATT_ENCRYPTED_NO_MITM
enumerator ESP_GATT_NOT_ENCRYPTED
enumerator ESP_GATT_CONGESTED
enumerator ESP_GATT_DUP_REG
enumerator ESP_GATT_ALREADY_OPEN
enumerator ESP_GATT_CANCEL
enumerator ESP_GATT_STACK_RSP
enumerator ESP_GATT_APP_RSP
enumerator ESP_GATT_UNKNOWN_ERROR
enumerator ESP_GATT_CCC_CFG_ERR
enumerator ESP_GATT_PRC_IN_PROGRESS
enumerator ESP_GATT_OUT_OF_RANGE
enum esp_gatt_conn_reason_t
Gatt Connection reason enum.
Values:
enumerator ESP_GATT_CONN_UNKNOWN
Gatt connection unknown
enumerator ESP_GATT_CONN_L2C_FAILURE
General L2cap failure
enumerator ESP_GATT_CONN_TIMEOUT
Connection timeout
enumerator ESP_GATT_CONN_TERMINATE_PEER_USER
Connection terminate by peer user
enumerator ESP_GATT_CONN_TERMINATE_LOCAL_HOST
Connection terminated by local host
enumerator ESP_GATT_CONN_FAIL_ESTABLISH
Connection fail to establish
enumerator ESP_GATT_CONN_LMP_TIMEOUT
Connection fail for LMP response tout
enumerator ESP_GATT_CONN_CONN_CANCEL
L2CAP connection cancelled
enumerator ESP_GATT_CONN_NONE
No connection to cancel
enum esp_gatt_auth_req_t
Gatt authentication request type.
Values:
enumerator ESP_GATT_AUTH_REQ_NONE
enumerator ESP_GATT_AUTH_REQ_NO_MITM
enumerator ESP_GATT_AUTH_REQ_MITM
enumerator ESP_GATT_AUTH_REQ_SIGNED_NO_MITM
enumerator ESP_GATT_AUTH_REQ_SIGNED_MITM
enum esp_service_source_t
Values:
enumerator ESP_GATT_SERVICE_FROM_REMOTE_DEVICE
enumerator ESP_GATT_SERVICE_FROM_NVS_FLASH
enumerator ESP_GATT_SERVICE_FROM_UNKNOWN
enum esp_gatt_write_type_t
Gatt write type.
Values:
enumerator ESP_GATT_WRITE_TYPE_NO_RSP
Gatt write attribute need no response
enumerator ESP_GATT_WRITE_TYPE_RSP
Gatt write attribute need remote response
enum esp_gatt_db_attr_type_t
the type of attribute element
Values:
enumerator ESP_GATT_DB_PRIMARY_SERVICE
Gattc primary service attribute type in the cache
enumerator ESP_GATT_DB_SECONDARY_SERVICE
Gattc secondary service attribute type in the cache
enumerator ESP_GATT_DB_CHARACTERISTIC
Gattc characteristic attribute type in the cache
enumerator ESP_GATT_DB_DESCRIPTOR
Gattc characteristic descriptor attribute type in the cache
enumerator ESP_GATT_DB_INCLUDED_SERVICE
Gattc include service attribute type in the cache
enumerator ESP_GATT_DB_ALL
Gattc all the attribute (primary service & secondary service & include service & char & descriptor) type
in the cache
Application Example Check bluetooth/bluedroid/ble folder in ESP-IDF examples, which contains the following
demos and their tutorials:
• This is a GATT sever demo and its tutorial. This demo creates a GATT service with an attribute table, which
releases the user from adding attributes one by one. This is the recommended method of adding attributes.
– bluetooth/bluedroid/ble/gatt_server_service_table
– GATT Server Service Table Example Walkthrough
• This is a GATT server demo and its tutorial. This demo creates a GATT service by adding attributes one by
one as defined by Bluedroid. The recommended method of adding attributes is presented in example above.
– bluetooth/bluedroid/ble/gatt_server
– GATT Server Example Walkthrough
• This is a BLE SPP-Like demo. This demo, which acts as a GATT server, can receive data from UART and
then send the data to the peer device automatically.
– bluetooth/bluedroid/ble/ble_spp_server
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_gatts_api.h
Functions
esp_err_t esp_ble_gatts_register_callback(esp_gatts_cb_t callback)
This function is called to register application callbacks with BTA GATTS module.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_app_register(uint16_t app_id)
This function is called to register application identifier.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_app_unregister(esp_gatt_if_t gatts_if)
unregister with GATT Server.
Parameters gatts_if –[in] GATT server access interface
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_create_service(esp_gatt_if_t gatts_if, esp_gatt_srvc_id_t *service_id,
uint16_t num_handle)
Create a service. When service creation is done, a callback event ESP_GATTS_CREATE_EVT is called to
report status and service ID to the profile. The service ID obtained in the callback function needs to be used
when adding included service and characteristics/descriptors into the service.
Parameters
• gatts_if –[in] GATT server access interface
• service_id –[in] service ID.
• num_handle –[in] number of handle requested for this service.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_create_attr_tab(const esp_gatts_attr_db_t *gatts_attr_db, esp_gatt_if_t
gatts_if, uint8_t max_nb_attr, uint8_t srvc_inst_id)
Create a service attribute tab.
Parameters
• gatts_attr_db –[in] the pointer to the service attr tab
• gatts_if –[in] GATT server access interface
• max_nb_attr –[in] the number of attribute to be added to the service database.
• srvc_inst_id –[in] the instance id of the service
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_add_included_service(uint16_t service_handle, uint16_t
included_service_handle)
This function is called to add an included service. This function have to be called between
‘esp_ble_gatts_create_service’and‘esp_ble_gatts_add_char’. After included service is included, a callback
event ESP_GATTS_ADD_INCL_SRVC_EVT is reported the included service ID.
Parameters
• service_handle –[in] service handle to which this included service is to be added.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_close(esp_gatt_if_t gatts_if, uint16_t conn_id)
Close a connection a remote device.
Parameters
• gatts_if –[in] GATT server access interface
• conn_id –[in] connection ID to be closed.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_send_service_change_indication(esp_gatt_if_t gatts_if,
esp_bd_addr_t remote_bda)
Send service change indication.
Parameters
• gatts_if –[in] GATT server access interface
• remote_bda –[in] remote device bluetooth device address. If remote_bda is NULL
then it will send service change indication to all the connected devices and if not then to a
specific device
Returns
• ESP_OK : success
• other : failed
Unions
union esp_ble_gatts_cb_param_t
#include <esp_gatts_api.h> Gatt server callback parameters union.
Public Members
struct gatts_add_attr_tab_evt_param
#include <esp_gatts_api.h> ESP_GATTS_CREAT_ATTR_TAB_EVT.
Public Members
esp_gatt_status_t status
Operation status
esp_bt_uuid_t svc_uuid
Service uuid type
uint8_t svc_inst_id
Service id
uint16_t num_handle
The number of the attribute handle to be added to the gatts database
uint16_t *handles
The number to the handles
struct gatts_add_char_descr_evt_param
#include <esp_gatts_api.h> ESP_GATTS_ADD_CHAR_DESCR_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t attr_handle
Descriptor attribute handle
uint16_t service_handle
Service attribute handle
esp_bt_uuid_t descr_uuid
Characteristic descriptor uuid
struct gatts_add_char_evt_param
#include <esp_gatts_api.h> ESP_GATTS_ADD_CHAR_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t attr_handle
Characteristic attribute handle
uint16_t service_handle
Service attribute handle
esp_bt_uuid_t char_uuid
Characteristic uuid
struct gatts_add_incl_srvc_evt_param
#include <esp_gatts_api.h> ESP_GATTS_ADD_INCL_SRVC_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t attr_handle
Included service attribute handle
uint16_t service_handle
Service attribute handle
struct gatts_cancel_open_evt_param
#include <esp_gatts_api.h> ESP_GATTS_CANCEL_OPEN_EVT.
Public Members
esp_gatt_status_t status
Operation status
struct gatts_close_evt_param
#include <esp_gatts_api.h> ESP_GATTS_CLOSE_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t conn_id
Connection id
struct gatts_conf_evt_param
#include <esp_gatts_api.h> ESP_GATTS_CONF_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t conn_id
Connection id
uint16_t handle
attribute handle
uint16_t len
The indication or notification value length, len is valid when send notification or indication failed
uint8_t *value
The indication or notification value , value is valid when send notification or indication failed
struct gatts_congest_evt_param
#include <esp_gatts_api.h> ESP_GATTS_LISTEN_EVT.
ESP_GATTS_CONGEST_EVT
Public Members
uint16_t conn_id
Connection id
bool congested
Congested or not
struct gatts_connect_evt_param
#include <esp_gatts_api.h> ESP_GATTS_CONNECT_EVT.
Public Members
uint16_t conn_id
Connection id
uint8_t link_role
Link role : master role = 0 ; slave role = 1
esp_bd_addr_t remote_bda
Remote bluetooth device address
esp_gatt_conn_params_t conn_params
current Connection parameters
struct gatts_create_evt_param
#include <esp_gatts_api.h> ESP_GATTS_UNREG_EVT.
ESP_GATTS_CREATE_EVT
Public Members
esp_gatt_status_t status
Operation status
uint16_t service_handle
Service attribute handle
esp_gatt_srvc_id_t service_id
Service id, include service uuid and other information
struct gatts_delete_evt_param
#include <esp_gatts_api.h> ESP_GATTS_DELETE_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t service_handle
Service attribute handle
struct gatts_disconnect_evt_param
#include <esp_gatts_api.h> ESP_GATTS_DISCONNECT_EVT.
Public Members
uint16_t conn_id
Connection id
esp_bd_addr_t remote_bda
Remote bluetooth device address
esp_gatt_conn_reason_t reason
Indicate the reason of disconnection
struct gatts_exec_write_evt_param
#include <esp_gatts_api.h> ESP_GATTS_EXEC_WRITE_EVT.
Public Members
uint16_t conn_id
Connection id
uint32_t trans_id
Transfer id
esp_bd_addr_t bda
The bluetooth device address which been written
uint8_t exec_write_flag
Execute write flag
struct gatts_mtu_evt_param
#include <esp_gatts_api.h> ESP_GATTS_MTU_EVT.
Public Members
uint16_t conn_id
Connection id
uint16_t mtu
MTU size
struct gatts_open_evt_param
#include <esp_gatts_api.h> ESP_GATTS_OPEN_EVT.
Public Members
esp_gatt_status_t status
Operation status
struct gatts_read_evt_param
#include <esp_gatts_api.h> ESP_GATTS_READ_EVT.
Public Members
uint16_t conn_id
Connection id
uint32_t trans_id
Transfer id
esp_bd_addr_t bda
The bluetooth device address which been read
uint16_t handle
The attribute handle
uint16_t offset
Offset of the value, if the value is too long
bool is_long
The value is too long or not
bool need_rsp
The read operation need to do response
struct gatts_reg_evt_param
#include <esp_gatts_api.h> ESP_GATTS_REG_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t app_id
Application id which input in register API
struct gatts_rsp_evt_param
#include <esp_gatts_api.h> ESP_GATTS_RESPONSE_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t handle
Attribute handle which send response
struct gatts_send_service_change_evt_param
#include <esp_gatts_api.h> ESP_GATTS_SEND_SERVICE_CHANGE_EVT.
Public Members
esp_gatt_status_t status
Operation status
struct gatts_set_attr_val_evt_param
#include <esp_gatts_api.h> ESP_GATTS_SET_ATTR_VAL_EVT.
Public Members
uint16_t srvc_handle
The service handle
uint16_t attr_handle
The attribute handle
esp_gatt_status_t status
Operation status
struct gatts_start_evt_param
#include <esp_gatts_api.h> ESP_GATTS_START_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t service_handle
Service attribute handle
struct gatts_stop_evt_param
#include <esp_gatts_api.h> ESP_GATTS_STOP_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t service_handle
Service attribute handle
struct gatts_write_evt_param
#include <esp_gatts_api.h> ESP_GATTS_WRITE_EVT.
Public Members
uint16_t conn_id
Connection id
uint32_t trans_id
Transfer id
esp_bd_addr_t bda
The bluetooth device address which been written
uint16_t handle
The attribute handle
uint16_t offset
Offset of the value, if the value is too long
bool need_rsp
The write operation need to do response
bool is_prep
This write operation is prepare write
uint16_t len
The write attribute value length
uint8_t *value
The write attribute value
Macros
ESP_GATT_PREP_WRITE_CANCEL
Prepare write flag to indicate cancel prepare write
ESP_GATT_PREP_WRITE_EXEC
Prepare write flag to indicate execute prepare write
Type Definitions
typedef void (*esp_gatts_cb_t)(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t
*param)
GATT Server callback function type.
Param event : Event type
Param gatts_if : GATT server access interface, normally different gatts_if correspond to different
profile
Param param : Point to callback parameter, currently is union type
Enumerations
enum esp_gatts_cb_event_t
GATT Server callback function events.
Values:
enumerator ESP_GATTS_REG_EVT
When register application id, the event comes
enumerator ESP_GATTS_READ_EVT
When gatt client request read operation, the event comes
enumerator ESP_GATTS_WRITE_EVT
When gatt client request write operation, the event comes
enumerator ESP_GATTS_EXEC_WRITE_EVT
When gatt client request execute write, the event comes
enumerator ESP_GATTS_MTU_EVT
When set mtu complete, the event comes
enumerator ESP_GATTS_CONF_EVT
When receive confirm, the event comes
enumerator ESP_GATTS_UNREG_EVT
When unregister application id, the event comes
enumerator ESP_GATTS_CREATE_EVT
When create service complete, the event comes
enumerator ESP_GATTS_ADD_INCL_SRVC_EVT
When add included service complete, the event comes
enumerator ESP_GATTS_ADD_CHAR_EVT
When add characteristic complete, the event comes
enumerator ESP_GATTS_ADD_CHAR_DESCR_EVT
When add descriptor complete, the event comes
enumerator ESP_GATTS_DELETE_EVT
When delete service complete, the event comes
enumerator ESP_GATTS_START_EVT
When start service complete, the event comes
enumerator ESP_GATTS_STOP_EVT
When stop service complete, the event comes
enumerator ESP_GATTS_CONNECT_EVT
When gatt client connect, the event comes
enumerator ESP_GATTS_DISCONNECT_EVT
When gatt client disconnect, the event comes
enumerator ESP_GATTS_OPEN_EVT
When connect to peer, the event comes
enumerator ESP_GATTS_CANCEL_OPEN_EVT
When disconnect from peer, the event comes
enumerator ESP_GATTS_CLOSE_EVT
When gatt server close, the event comes
enumerator ESP_GATTS_LISTEN_EVT
When gatt listen to be connected the event comes
enumerator ESP_GATTS_CONGEST_EVT
When congest happen, the event comes
enumerator ESP_GATTS_RESPONSE_EVT
When gatt send response complete, the event comes
enumerator ESP_GATTS_CREAT_ATTR_TAB_EVT
When gatt create table complete, the event comes
enumerator ESP_GATTS_SET_ATTR_VAL_EVT
When gatt set attr value complete, the event comes
enumerator ESP_GATTS_SEND_SERVICE_CHANGE_EVT
When gatt send service change indication complete, the event comes
Application Example Check bluetooth/bluedroid/ble folder in ESP-IDF examples, which contains the following
demos and their tutorials:
• This is a GATT client demo and its tutorial. This demo can scan for devices, connect to the GATT server and
discover its services.
– bluetooth/bluedroid/ble/gatt_client
– GATT Client Example Walkthrough
• This is a multiple connection demo and its tutorial. This demo can connect to multiple GATT server devices
and discover their services.
– bluetooth/bluedroid/ble/gattc_multi_connect
– GATT Client Multi-connection Example Walkthrough
• This is a BLE SPP-Like demo. This demo, which acts as a GATT client, can receive data from UART and
then send the data to the peer device automatically.
– bluetooth/bluedroid/ble/ble_spp_client
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_gattc_api.h
Functions
esp_err_t esp_ble_gattc_register_callback(esp_gattc_cb_t callback)
This function is called to register application callbacks with GATTC module.
Parameters callback –[in] : pointer to the application callback function.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_app_register(uint16_t app_id)
This function is called to register application callbacks with GATTC module.
Parameters app_id –[in] : Application Identify (UUID), for different application
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_app_unregister(esp_gatt_if_t gattc_if)
This function is called to unregister an application from GATTC module.
Parameters gattc_if –[in] Gatt client access interface.
Returns
• ESP_OK: success
• other: failed
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] connection ID which identify the server.
• svc_uuid –[in] the pointer to the service uuid.
• result –[out] The pointer to the service which has been found in the gattc cache.
• count –[inout] input the number of service want to find, it will output the number of
service has been found in the gattc cache with the given service uuid.
• offset –[in] Offset of the service position to get.
Returns
• ESP_OK: success
• other: failed
esp_gatt_status_t esp_ble_gattc_get_all_char(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t
start_handle, uint16_t end_handle,
esp_gattc_char_elem_t *result, uint16_t *count, uint16_t
offset)
Find all the characteristic with the given service in the gattc cache Note: It just get characteristic from local
cache, won’t get from remote devices.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] connection ID which identify the server.
• start_handle –[in] the attribute start handle.
• end_handle –[in] the attribute end handle
• result –[out] The pointer to the characteristic in the service.
• count –[inout] input the number of characteristic want to find, it will output the number
of characteristic has been found in the gattc cache with the given service.
• offset –[in] Offset of the characteristic position to get.
Returns
• ESP_OK: success
• other: failed
esp_gatt_status_t esp_ble_gattc_get_all_descr(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t
char_handle, esp_gattc_descr_elem_t *result, uint16_t
*count, uint16_t offset)
Find all the descriptor with the given characteristic in the gattc cache Note: It just get descriptor from local
cache, won’t get from remote devices.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] connection ID which identify the server.
• char_handle –[in] the given characteristic handle
• result –[out] The pointer to the descriptor in the characteristic.
• count –[inout] input the number of descriptor want to find, it will output the number of
descriptor has been found in the gattc cache with the given characteristic.
• offset –[in] Offset of the descriptor position to get.
Returns
• ESP_OK: success
• other: failed
esp_gatt_status_t esp_ble_gattc_get_char_by_uuid(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t
start_handle, uint16_t end_handle, esp_bt_uuid_t
char_uuid, esp_gattc_char_elem_t *result,
uint16_t *count)
Find the characteristic with the given characteristic uuid in the gattc cache Note: It just get characteristic from
local cache, won’t get from remote devices.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] connection ID which identify the server.
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_write_char_descr(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle,
uint16_t value_len, uint8_t *value, esp_gatt_write_type_t
write_type, esp_gatt_auth_req_t auth_req)
This function is called to write characteristic descriptor value.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] : connection ID
• handle –[in] : descriptor handle to write.
• value_len –[in] length of the value to be written.
• value –[in] : the value to be written.
• write_type –[in] : the type of attribute write operation.
• auth_req –[in] : authentication request.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_prepare_write(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle,
uint16_t offset, uint16_t value_len, uint8_t *value,
esp_gatt_auth_req_t auth_req)
This function is called to prepare write a characteristic value.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] : connection ID.
• handle –[in] : characteristic handle to prepare write.
• offset –[in] : offset of the write value.
• value_len –[in] length of the value to be written.
• value –[in] : the value to be written.
• auth_req –[in] : authentication request.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_prepare_write_char_descr(esp_gatt_if_t gattc_if, uint16_t conn_id,
uint16_t handle, uint16_t offset, uint16_t
value_len, uint8_t *value,
esp_gatt_auth_req_t auth_req)
This function is called to prepare write a characteristic descriptor value.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] : connection ID.
• handle –[in] : characteristic descriptor handle to prepare write.
• offset –[in] : offset of the write value.
• value_len –[in] length of the value to be written.
• value –[in] : the value to be written.
• auth_req –[in] : authentication request.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_execute_write(esp_gatt_if_t gattc_if, uint16_t conn_id, bool is_execute)
This function is called to execute write a prepare write sequence.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] : connection ID.
Unions
union esp_ble_gattc_cb_param_t
#include <esp_gattc_api.h> Gatt client callback parameters union.
Public Members
struct gattc_cfg_mtu_evt_param
#include <esp_gattc_api.h> ESP_GATTC_CFG_MTU_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t conn_id
Connection id
uint16_t mtu
MTU size
struct gattc_close_evt_param
#include <esp_gattc_api.h> ESP_GATTC_CLOSE_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t conn_id
Connection id
esp_bd_addr_t remote_bda
Remote bluetooth device address
esp_gatt_conn_reason_t reason
The reason of gatt connection close
struct gattc_congest_evt_param
#include <esp_gattc_api.h> ESP_GATTC_CONGEST_EVT.
Public Members
uint16_t conn_id
Connection id
bool congested
Congested or not
struct gattc_connect_evt_param
#include <esp_gattc_api.h> ESP_GATTC_CONNECT_EVT.
Public Members
uint16_t conn_id
Connection id
uint8_t link_role
Link role : master role = 0 ; slave role = 1
esp_bd_addr_t remote_bda
Remote bluetooth device address
esp_gatt_conn_params_t conn_params
current connection parameters
struct gattc_dis_srvc_cmpl_evt_param
#include <esp_gattc_api.h> ESP_GATTC_DIS_SRVC_CMPL_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t conn_id
Connection id
struct gattc_disconnect_evt_param
#include <esp_gattc_api.h> ESP_GATTC_DISCONNECT_EVT.
Public Members
esp_gatt_conn_reason_t reason
disconnection reason
uint16_t conn_id
Connection id
esp_bd_addr_t remote_bda
Remote bluetooth device address
struct gattc_exec_cmpl_evt_param
#include <esp_gattc_api.h> ESP_GATTC_EXEC_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t conn_id
Connection id
struct gattc_get_addr_list_evt_param
#include <esp_gattc_api.h> ESP_GATTC_GET_ADDR_LIST_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint8_t num_addr
The number of address in the gattc cache address list
esp_bd_addr_t *addr_list
The pointer to the address list which has been get from the gattc cache
struct gattc_notify_evt_param
#include <esp_gattc_api.h> ESP_GATTC_NOTIFY_EVT.
Public Members
uint16_t conn_id
Connection id
esp_bd_addr_t remote_bda
Remote bluetooth device address
uint16_t handle
The Characteristic or descriptor handle
uint16_t value_len
Notify attribute value
uint8_t *value
Notify attribute value
bool is_notify
True means notify, false means indicate
struct gattc_open_evt_param
#include <esp_gattc_api.h> ESP_GATTC_OPEN_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t conn_id
Connection id
esp_bd_addr_t remote_bda
Remote bluetooth device address
uint16_t mtu
MTU size
struct gattc_queue_full_evt_param
#include <esp_gattc_api.h> ESP_GATTC_QUEUE_FULL_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t conn_id
Connection id
bool is_full
The gattc command queue is full or not
struct gattc_read_char_evt_param
#include <esp_gattc_api.h> ESP_GATTC_READ_CHAR_EVT, ESP_GATTC_READ_DESCR_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t conn_id
Connection id
uint16_t handle
Characteristic handle
uint8_t *value
Characteristic value
uint16_t value_len
Characteristic value length
struct gattc_reg_evt_param
#include <esp_gattc_api.h> ESP_GATTC_REG_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t app_id
Application id which input in register API
struct gattc_reg_for_notify_evt_param
#include <esp_gattc_api.h> ESP_GATTC_REG_FOR_NOTIFY_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t handle
The characteristic or descriptor handle
struct gattc_search_cmpl_evt_param
#include <esp_gattc_api.h> ESP_GATTC_SEARCH_CMPL_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t conn_id
Connection id
esp_service_source_t searched_service_source
The source of the service information
struct gattc_search_res_evt_param
#include <esp_gattc_api.h> ESP_GATTC_SEARCH_RES_EVT.
Public Members
uint16_t conn_id
Connection id
uint16_t start_handle
Service start handle
uint16_t end_handle
Service end handle
esp_gatt_id_t srvc_id
Service id, include service uuid and other information
bool is_primary
True if this is the primary service
struct gattc_set_assoc_addr_cmp_evt_param
#include <esp_gattc_api.h> ESP_GATTC_SET_ASSOC_EVT.
Public Members
esp_gatt_status_t status
Operation status
struct gattc_srvc_chg_evt_param
#include <esp_gattc_api.h> ESP_GATTC_SRVC_CHG_EVT.
Public Members
esp_bd_addr_t remote_bda
Remote bluetooth device address
struct gattc_unreg_for_notify_evt_param
#include <esp_gattc_api.h> ESP_GATTC_UNREG_FOR_NOTIFY_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t handle
The characteristic or descriptor handle
struct gattc_write_evt_param
#include <esp_gattc_api.h> ESP_GATTC_WRITE_CHAR_EVT, ESP_GATTC_PREP_WRITE_EVT,
ESP_GATTC_WRITE_DESCR_EVT.
Public Members
esp_gatt_status_t status
Operation status
uint16_t conn_id
Connection id
uint16_t handle
The Characteristic or descriptor handle
uint16_t offset
The prepare write offset, this value is valid only when prepare write
Type Definitions
typedef void (*esp_gattc_cb_t)(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t
*param)
GATT Client callback function type.
Param event : Event type
Param gattc_if : GATT client access interface, normally different gattc_if correspond to different
profile
Param param : Point to callback parameter, currently is union type
Enumerations
enum esp_gattc_cb_event_t
GATT Client callback function events.
Values:
enumerator ESP_GATTC_REG_EVT
When GATT client is registered, the event comes
enumerator ESP_GATTC_UNREG_EVT
When GATT client is unregistered, the event comes
enumerator ESP_GATTC_OPEN_EVT
When GATT virtual connection is set up, the event comes
enumerator ESP_GATTC_READ_CHAR_EVT
When GATT characteristic is read, the event comes
enumerator ESP_GATTC_WRITE_CHAR_EVT
When GATT characteristic write operation completes, the event comes
enumerator ESP_GATTC_CLOSE_EVT
When GATT virtual connection is closed, the event comes
enumerator ESP_GATTC_SEARCH_CMPL_EVT
When GATT service discovery is completed, the event comes
enumerator ESP_GATTC_SEARCH_RES_EVT
When GATT service discovery result is got, the event comes
enumerator ESP_GATTC_READ_DESCR_EVT
When GATT characteristic descriptor read completes, the event comes
enumerator ESP_GATTC_WRITE_DESCR_EVT
When GATT characteristic descriptor write completes, the event comes
enumerator ESP_GATTC_NOTIFY_EVT
When GATT notification or indication arrives, the event comes
enumerator ESP_GATTC_PREP_WRITE_EVT
When GATT prepare-write operation completes, the event comes
enumerator ESP_GATTC_EXEC_EVT
When write execution completes, the event comes
enumerator ESP_GATTC_ACL_EVT
When ACL connection is up, the event comes
enumerator ESP_GATTC_CANCEL_OPEN_EVT
When GATT client ongoing connection is cancelled, the event comes
enumerator ESP_GATTC_SRVC_CHG_EVT
When “service changed”occurs, the event comes
enumerator ESP_GATTC_ENC_CMPL_CB_EVT
When encryption procedure completes, the event comes
enumerator ESP_GATTC_CFG_MTU_EVT
When configuration of MTU completes, the event comes
enumerator ESP_GATTC_ADV_DATA_EVT
When advertising of data, the event comes
enumerator ESP_GATTC_MULT_ADV_ENB_EVT
When multi-advertising is enabled, the event comes
enumerator ESP_GATTC_MULT_ADV_UPD_EVT
When multi-advertising parameters are updated, the event comes
enumerator ESP_GATTC_MULT_ADV_DATA_EVT
When multi-advertising data arrives, the event comes
enumerator ESP_GATTC_MULT_ADV_DIS_EVT
When multi-advertising is disabled, the event comes
enumerator ESP_GATTC_CONGEST_EVT
When GATT connection congestion comes, the event comes
enumerator ESP_GATTC_BTH_SCAN_ENB_EVT
When batch scan is enabled, the event comes
enumerator ESP_GATTC_BTH_SCAN_CFG_EVT
When batch scan storage is configured, the event comes
enumerator ESP_GATTC_BTH_SCAN_RD_EVT
When Batch scan read event is reported, the event comes
enumerator ESP_GATTC_BTH_SCAN_THR_EVT
When Batch scan threshold is set, the event comes
enumerator ESP_GATTC_BTH_SCAN_PARAM_EVT
When Batch scan parameters are set, the event comes
enumerator ESP_GATTC_BTH_SCAN_DIS_EVT
When Batch scan is disabled, the event comes
enumerator ESP_GATTC_SCAN_FLT_CFG_EVT
When Scan filter configuration completes, the event comes
enumerator ESP_GATTC_SCAN_FLT_PARAM_EVT
When Scan filter parameters are set, the event comes
enumerator ESP_GATTC_SCAN_FLT_STATUS_EVT
When Scan filter status is reported, the event comes
enumerator ESP_GATTC_ADV_VSC_EVT
When advertising vendor spec content event is reported, the event comes
enumerator ESP_GATTC_REG_FOR_NOTIFY_EVT
When register for notification of a service completes, the event comes
enumerator ESP_GATTC_UNREG_FOR_NOTIFY_EVT
When unregister for notification of a service completes, the event comes
enumerator ESP_GATTC_CONNECT_EVT
When the ble physical connection is set up, the event comes
enumerator ESP_GATTC_DISCONNECT_EVT
When the ble physical connection disconnected, the event comes
enumerator ESP_GATTC_READ_MULTIPLE_EVT
When the ble characteristic or descriptor multiple complete, the event comes
enumerator ESP_GATTC_QUEUE_FULL_EVT
When the gattc command queue full, the event comes
enumerator ESP_GATTC_SET_ASSOC_EVT
When the ble gattc set the associated address complete, the event comes
enumerator ESP_GATTC_GET_ADDR_LIST_EVT
When the ble get gattc address list in cache finish, the event comes
enumerator ESP_GATTC_DIS_SRVC_CMPL_EVT
When the ble discover service complete, the event comes
BLUFI API
Overview BLUFI is a profile based GATT to config ESP32 WIFI to connect/disconnect AP or setup a softap and
etc. Use should concern these things:
1. The event sent from profile. Then you need to do something as the event indicate.
2. Security reference. You can write your own Security functions such as symmetrical encryption/decryption and
checksum functions. Even you can define the “Key Exchange/Negotiation”procedure.
Application Example Check bluetooth folder in ESP-IDF examples, which contains the following application:
• This is the BLUFI demo. This demo can set ESP32’s wifi to softap/station/softap&station mode and config
wifi connections - bluetooth/blufi
API Reference
Header File
• components/bt/common/api/include/api/esp_blufi_api.h
Functions
esp_err_t esp_blufi_register_callbacks(esp_blufi_callbacks_t *callbacks)
This function is called to receive blufi callback event.
Parameters callbacks –[in] callback functions
Returns ESP_OK - success, other - failed
esp_err_t esp_blufi_profile_init(void)
This function is called to initialize blufi_profile.
Returns ESP_OK - success, other - failed
esp_err_t esp_blufi_profile_deinit(void)
This function is called to de-initialize blufi_profile.
Returns ESP_OK - success, other - failed
esp_err_t esp_blufi_send_wifi_conn_report(wifi_mode_t opmode, esp_blufi_sta_conn_state_t
sta_conn_state, uint8_t softap_conn_num,
esp_blufi_extra_info_t *extra_info)
This function is called to send wifi connection report.
Parameters
• opmode –: wifi opmode
• sta_conn_state –: station is already in connection or not
• softap_conn_num –: softap connection number
• extra_info –: extra information, such as sta_ssid, softap_ssid and etc.
Returns ESP_OK - success, other - failed
esp_err_t esp_blufi_send_wifi_list(uint16_t apCount, esp_blufi_ap_record_t *list)
This function is called to send wifi list.
Parameters
• apCount –: wifi list count
• list –: wifi list
Returns ESP_OK - success, other - failed
uint16_t esp_blufi_get_version(void)
Get BLUFI profile version.
Returns Most 8bit significant is Great version, Least 8bit is Sub version
esp_err_t esp_blufi_send_error_info(esp_blufi_error_state_t state)
This function is called to send blufi error information.
Parameters state –: error state
Returns ESP_OK - success, other - failed
esp_err_t esp_blufi_send_custom_data(uint8_t *data, uint32_t data_len)
This function is called to custom data.
Parameters
Unions
union esp_blufi_cb_param_t
#include <esp_blufi_api.h> BLUFI callback parameters union.
Public Members
struct esp_blufi_cb_param_t::blufi_recv_ca_evt_param ca
Blufi callback param of ESP_BLUFI_EVENT_RECV_CA_CERT
struct blufi_connect_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_CONNECT.
Public Members
esp_blufi_bd_addr_t remote_bda
Blufi Remote bluetooth device address
uint8_t server_if
server interface
uint16_t conn_id
Connection id
struct blufi_deinit_finish_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_DEINIT_FINISH.
Public Members
esp_blufi_deinit_state_t state
De-initial status
struct blufi_disconnect_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_DISCONNECT.
Public Members
esp_blufi_bd_addr_t remote_bda
Blufi Remote bluetooth device address
struct blufi_get_error_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_REPORT_ERROR.
Public Members
esp_blufi_error_state_t state
Blufi error state
struct blufi_init_finish_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_INIT_FINISH.
Public Members
esp_blufi_init_state_t state
Initial status
struct blufi_recv_ca_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CA_CERT.
Public Members
uint8_t *cert
CA certificate point
int cert_len
CA certificate length
struct blufi_recv_client_cert_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CLIENT_CERT
Public Members
uint8_t *cert
Client certificate point
int cert_len
Client certificate length
struct blufi_recv_client_pkey_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY
Public Members
uint8_t *pkey
Client Private Key point, if Client certificate not contain Key
int pkey_len
Client Private key length
struct blufi_recv_custom_data_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CUSTOM_DATA.
Public Members
uint8_t *data
Custom data
uint32_t data_len
Custom data Length
struct blufi_recv_server_cert_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SERVER_CERT
Public Members
uint8_t *cert
Client certificate point
int cert_len
Client certificate length
struct blufi_recv_server_pkey_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY
Public Members
uint8_t *pkey
Client Private Key point, if Client certificate not contain Key
int pkey_len
Client Private key length
struct blufi_recv_softap_auth_mode_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE.
Public Members
wifi_auth_mode_t auth_mode
Authentication mode
struct blufi_recv_softap_channel_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL.
Public Members
uint8_t channel
Authentication mode
struct blufi_recv_softap_max_conn_num_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM.
Public Members
int max_conn_num
SSID
struct blufi_recv_softap_passwd_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD.
Public Members
uint8_t *passwd
Password
int passwd_len
Password Length
struct blufi_recv_softap_ssid_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_SSID.
Public Members
uint8_t *ssid
SSID
int ssid_len
SSID length
struct blufi_recv_sta_bssid_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_BSSID.
Public Members
uint8_t bssid[6]
BSSID
struct blufi_recv_sta_passwd_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_PASSWD.
Public Members
uint8_t *passwd
Password
int passwd_len
Password Length
struct blufi_recv_sta_ssid_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_SSID.
Public Members
uint8_t *ssid
SSID
int ssid_len
SSID length
struct blufi_recv_username_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_USERNAME.
Public Members
uint8_t *name
Username point
int name_len
Username length
struct blufi_set_wifi_mode_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_SET_WIFI_MODE.
Public Members
wifi_mode_t op_mode
Wifi operation mode
Structures
struct esp_blufi_extra_info_t
BLUFI extra information structure.
Public Members
uint8_t sta_bssid[6]
BSSID of station interface
bool sta_bssid_set
is BSSID of station interface set
uint8_t *sta_ssid
SSID of station interface
int sta_ssid_len
length of SSID of station interface
uint8_t *sta_passwd
password of station interface
int sta_passwd_len
length of password of station interface
uint8_t *softap_ssid
SSID of softap interface
int softap_ssid_len
length of SSID of softap interface
uint8_t *softap_passwd
password of station interface
int softap_passwd_len
length of password of station interface
uint8_t softap_authmode
authentication mode of softap interface
bool softap_authmode_set
is authentication mode of softap interface set
uint8_t softap_max_conn_num
max connection number of softap interface
bool softap_max_conn_num_set
is max connection number of softap interface set
uint8_t softap_channel
channel of softap interface
bool softap_channel_set
is channel of softap interface set
struct esp_blufi_ap_record_t
Description of an WiFi AP.
Public Members
uint8_t ssid[33]
SSID of AP
int8_t rssi
signal strength of AP
struct esp_blufi_callbacks_t
BLUFI callback functions type.
Public Members
esp_blufi_event_cb_t event_cb
BLUFI event callback
esp_blufi_negotiate_data_handler_t negotiate_data_handler
BLUFI negotiate data function for negotiate share key
esp_blufi_encrypt_func_t encrypt_func
BLUFI encrypt data function with share key generated by negotiate_data_handler
esp_blufi_decrypt_func_t decrypt_func
BLUFI decrypt data function with share key generated by negotiate_data_handler
esp_blufi_checksum_func_t checksum_func
BLUFI check sum function (FCS)
Macros
ESP_BLUFI_BD_ADDR_LEN
Bluetooth address length.
Type Definitions
Enumerations
enum esp_blufi_cb_event_t
Values:
enumerator ESP_BLUFI_EVENT_INIT_FINISH
enumerator ESP_BLUFI_EVENT_DEINIT_FINISH
enumerator ESP_BLUFI_EVENT_SET_WIFI_OPMODE
enumerator ESP_BLUFI_EVENT_BLE_CONNECT
enumerator ESP_BLUFI_EVENT_BLE_DISCONNECT
enumerator ESP_BLUFI_EVENT_REQ_CONNECT_TO_AP
enumerator ESP_BLUFI_EVENT_REQ_DISCONNECT_FROM_AP
enumerator ESP_BLUFI_EVENT_GET_WIFI_STATUS
enumerator ESP_BLUFI_EVENT_DEAUTHENTICATE_STA
enumerator ESP_BLUFI_EVENT_RECV_STA_BSSID
enumerator ESP_BLUFI_EVENT_RECV_STA_SSID
enumerator ESP_BLUFI_EVENT_RECV_STA_PASSWD
enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_SSID
enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD
enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM
enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE
enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL
enumerator ESP_BLUFI_EVENT_RECV_USERNAME
enumerator ESP_BLUFI_EVENT_RECV_CA_CERT
enumerator ESP_BLUFI_EVENT_RECV_CLIENT_CERT
enumerator ESP_BLUFI_EVENT_RECV_SERVER_CERT
enumerator ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY
enumerator ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY
enumerator ESP_BLUFI_EVENT_RECV_SLAVE_DISCONNECT_BLE
enumerator ESP_BLUFI_EVENT_GET_WIFI_LIST
enumerator ESP_BLUFI_EVENT_REPORT_ERROR
enumerator ESP_BLUFI_EVENT_RECV_CUSTOM_DATA
enum esp_blufi_sta_conn_state_t
BLUFI config status.
Values:
enumerator ESP_BLUFI_STA_CONN_SUCCESS
enumerator ESP_BLUFI_STA_CONN_FAIL
enum esp_blufi_init_state_t
BLUFI init status.
Values:
enumerator ESP_BLUFI_INIT_OK
enumerator ESP_BLUFI_INIT_FAILED
enum esp_blufi_deinit_state_t
BLUFI deinit status.
Values:
enumerator ESP_BLUFI_DEINIT_OK
enumerator ESP_BLUFI_DEINIT_FAILED
enum esp_blufi_error_state_t
Values:
enumerator ESP_BLUFI_SEQUENCE_ERROR
enumerator ESP_BLUFI_CHECKSUM_ERROR
enumerator ESP_BLUFI_DECRYPT_ERROR
enumerator ESP_BLUFI_ENCRYPT_ERROR
enumerator ESP_BLUFI_INIT_SECURITY_ERROR
enumerator ESP_BLUFI_DH_MALLOC_ERROR
enumerator ESP_BLUFI_DH_PARAM_ERROR
enumerator ESP_BLUFI_READ_PARAM_ERROR
enumerator ESP_BLUFI_MAKE_PUBLIC_ERROR
enumerator ESP_BLUFI_DATA_FORMAT_ERROR
enumerator ESP_BLUFI_CALC_MD5_ERROR
2.3.3 CLASSIC BT
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_gap_bt_api.h
Functions
static inline uint32_t esp_bt_gap_get_cod_srvc(uint32_t cod)
get major service field of COD
Parameters cod –[in] Class of Device
Returns major service bits
static inline uint32_t esp_bt_gap_get_cod_major_dev(uint32_t cod)
get major device field of COD
Parameters cod –[in] Class of Device
Returns major device bits
static inline uint32_t esp_bt_gap_get_cod_minor_dev(uint32_t cod)
get minor service field of COD
Parameters cod –[in] Class of Device
Returns minor service bits
static inline uint32_t esp_bt_gap_get_cod_format_type(uint32_t cod)
get format type of COD
Parameters cod –[in] Class of Device
Returns format type
static inline bool esp_bt_gap_is_valid_cod(uint32_t cod)
decide the integrity of COD
Parameters cod –[in] Class of Device
Returns
• true if cod is valid
• false otherise
esp_err_t esp_bt_gap_register_callback(esp_bt_gap_cb_t callback)
register callback function. This function should be called after esp_bluedroid_enable() completes successfully
Returns
• ESP_OK : Succeed
• ESP_FAIL: others
esp_err_t esp_bt_gap_set_scan_mode(esp_bt_connection_mode_t c_mode, esp_bt_discovery_mode_t
d_mode)
Set discoverability and connectability mode for legacy bluetooth. This function should be called after
esp_bluedroid_enable() completes successfully.
Parameters
int esp_bt_gap_get_bond_device_num(void)
Get the device number from the security database list of peer device. It will return the device bonded number
immediately.
Returns - >= 0 : bonded devices number
• ESP_FAIL : failed
esp_err_t esp_bt_gap_get_bond_device_list(int *dev_num, esp_bd_addr_t *dev_list)
Get the device from the security database list of peer device. It will return the device bonded information
immediately.
Parameters
• dev_num –[inout] Indicate the dev_list array(buffer) size as input. If dev_num is large
enough, it means the actual number as output. Suggest that dev_num value equal to
esp_ble_get_bond_device_num().
• dev_list –[out] an array(buffer) of esp_bd_addr_t type. Use for storing the
bonded devices address. The dev_list should be allocated by who call this API.
Returns
• ESP_OK : Succeed
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_bt_gap_set_pin(esp_bt_pin_type_t pin_type, uint8_t pin_code_len, esp_bt_pin_code_t
pin_code)
Set pin type and default pin code for legacy pairing.
Parameters
• pin_type –[in] Use variable or fixed pin. If pin_type is
ESP_BT_PIN_TYPE_VARIABLE, pin_code and pin_code_len will be ignored,
and ESP_BT_GAP_PIN_REQ_EVT will come when control requests for pin code. Else,
will use fixed pin code and not callback to users.
• pin_code_len –[in] Length of pin_code
• pin_code –[in] Pin_code
Returns - ESP_OK : success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• other : failed
esp_err_t esp_bt_gap_pin_reply(esp_bd_addr_t bd_addr, bool accept, uint8_t pin_code_len,
esp_bt_pin_code_t pin_code)
Reply the pin_code to the peer device for legacy pairing when ESP_BT_GAP_PIN_REQ_EVT is coming.
Parameters
• bd_addr –[in] BD address of the peer
• accept –[in] Pin_code reply successful or declined.
• pin_code_len –[in] Length of pin_code
• pin_code –[in] Pin_code
Returns - ESP_OK : success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• other : failed
esp_err_t esp_bt_gap_set_security_param(esp_bt_sp_param_t param_type, void *value, uint8_t len)
Set a GAP security parameter value. Overrides the default value.
Parameters
• param_type –[in] : the type of the param which is to be set
• value –[in] : the param value
• len –[in] : the length of the param value
Returns - ESP_OK : success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• other : failed
Unions
union esp_bt_gap_cb_param_t
#include <esp_gap_bt_api.h> GAP state callback parameters.
Public Members
struct auth_cmpl_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_AUTH_CMPL_EVT.
Public Members
esp_bd_addr_t bda
remote bluetooth device address
esp_bt_status_t stat
authentication complete status
uint8_t device_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1]
device name
struct bt_remove_bond_dev_cmpl_evt_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT.
Public Members
esp_bd_addr_t bda
remote bluetooth device address
esp_bt_status_t status
Indicate the remove bond device operation success status
struct cfm_req_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_CFM_REQ_EVT.
Public Members
esp_bd_addr_t bda
remote bluetooth device address
uint32_t num_val
the numeric value for comparison.
struct config_eir_data_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_CONFIG_EIR_DATA_EVT *.
Public Members
esp_bt_status_t stat
config EIR status: ESP_BT_STATUS_SUCCESS: config success
ESP_BT_STATUS_EIR_TOO_LARGE: the EIR data is more than 240B. The EIR may not
contain the whole data. others: failed
uint8_t eir_type_num
the number of EIR types in EIR type
esp_bt_eir_type_t eir_type[ESP_BT_EIR_TYPE_MAX_NUM]
EIR types in EIR type
struct disc_res_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_DISC_RES_EVT.
Public Members
esp_bd_addr_t bda
remote bluetooth device address
int num_prop
number of properties got
esp_bt_gap_dev_prop_t *prop
properties discovered from the new device
struct disc_state_changed_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_DISC_STATE_CHANGED_EVT.
Public Members
esp_bt_gap_discovery_state_t state
discovery state
struct key_notif_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_KEY_NOTIF_EVT.
Public Members
esp_bd_addr_t bda
remote bluetooth device address
uint32_t passkey
the numeric value for passkey entry.
struct key_req_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_KEY_REQ_EVT.
Public Members
esp_bd_addr_t bda
remote bluetooth device address
struct mode_chg_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_MODE_CHG_EVT.
Public Members
esp_bd_addr_t bda
remote bluetooth device address
esp_bt_pm_mode_t mode
PM mode
struct pin_req_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_PIN_REQ_EVT.
Public Members
esp_bd_addr_t bda
remote bluetooth device address
bool min_16_digit
TRUE if the pin returned must be at least 16 digits
struct qos_cmpl_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_QOS_CMPL_EVT.
Public Members
esp_bt_status_t stat
QoS status
esp_bd_addr_t bda
remote bluetooth device address
uint32_t t_poll
poll interval, the maximum time between transmissions which from the master to a particular slave
on the ACL logical transport. unit is 0.625ms.
struct read_rmt_name_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_READ_REMOTE_NAME_EVT.
Public Members
esp_bd_addr_t bda
remote bluetooth device address
esp_bt_status_t stat
read Remote Name status
uint8_t rmt_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1]
Remote device name
struct read_rssi_delta_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_READ_RSSI_DELTA_EVT *.
Public Members
esp_bd_addr_t bda
remote bluetooth device address
esp_bt_status_t stat
read rssi status
int8_t rssi_delta
rssi delta value range -128 ~127, The value zero indicates that the RSSI is inside the Golden Receive
Power Range, the Golden Receive Power Range is from ESP_BT_GAP_RSSI_LOW_THRLD to
ESP_BT_GAP_RSSI_HIGH_THRLD
struct rmt_srvc_rec_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_RMT_SRVC_REC_EVT.
Public Members
esp_bd_addr_t bda
remote bluetooth device address
esp_bt_status_t stat
service search status
struct rmt_srvcs_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_RMT_SRVCS_EVT.
Public Members
esp_bd_addr_t bda
remote bluetooth device address
esp_bt_status_t stat
service search status
int num_uuids
number of UUID in uuid_list
esp_bt_uuid_t *uuid_list
list of service UUIDs of remote device
struct set_afh_channels_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_SET_AFH_CHANNELS_EVT.
Public Members
esp_bt_status_t stat
set AFH channel status
Structures
struct esp_bt_cod_t
Class of device.
Public Members
uint32_t reserved_2
undefined
uint32_t minor
minor class
uint32_t major
major class
uint32_t service
service class
uint32_t reserved_8
undefined
struct esp_bt_gap_dev_prop_t
Bluetooth Device Property Descriptor.
Public Members
esp_bt_gap_dev_prop_type_t type
Device property type
int len
Device property value length
void *val
Device property value
struct esp_bt_eir_data_t
EIR data content, according to “Supplement to the Bluetooth Core Specification”.
Public Members
bool fec_required
FEC is required or not, true by default
bool include_txpower
EIR data include TX power, false by default
bool include_uuid
EIR data include UUID, false by default
uint8_t flag
EIR flags, see ESP_BT_EIR_FLAG for details, EIR will not include flag if it is 0, 0 by default
uint16_t manufacturer_len
Manufacturer data length, 0 by default
uint8_t *p_manufacturer_data
Manufacturer data point
uint16_t url_len
URL length, 0 by default
uint8_t *p_url
URL point
Macros
ESP_BT_GAP_RSSI_HIGH_THRLD
RSSI threshold.
High RSSI threshold
ESP_BT_GAP_RSSI_LOW_THRLD
Low RSSI threshold
ESP_BT_GAP_AFH_CHANNELS_LEN
ESP_BT_GAP_MAX_BDNAME_LEN
Maximum bytes of Bluetooth device name.
ESP_BT_GAP_EIR_DATA_LEN
Maximum size of EIR Significant part.
ESP_BT_EIR_TYPE_FLAGS
Extended Inquiry Response data type.
Flag with information such as BR/EDR and LE support
ESP_BT_EIR_TYPE_INCMPL_16BITS_UUID
Incomplete list of 16-bit service UUIDs
ESP_BT_EIR_TYPE_CMPL_16BITS_UUID
Complete list of 16-bit service UUIDs
ESP_BT_EIR_TYPE_INCMPL_32BITS_UUID
Incomplete list of 32-bit service UUIDs
ESP_BT_EIR_TYPE_CMPL_32BITS_UUID
Complete list of 32-bit service UUIDs
ESP_BT_EIR_TYPE_INCMPL_128BITS_UUID
Incomplete list of 128-bit service UUIDs
ESP_BT_EIR_TYPE_CMPL_128BITS_UUID
Complete list of 128-bit service UUIDs
ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME
Shortened Local Name
ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME
Complete Local Name
ESP_BT_EIR_TYPE_TX_POWER_LEVEL
Tx power level, value is 1 octet ranging from -127 to 127, unit is dBm
ESP_BT_EIR_TYPE_URL
Uniform resource identifier
ESP_BT_EIR_TYPE_MANU_SPECIFIC
Manufacturer specific data
ESP_BT_EIR_TYPE_MAX_NUM
MAX number of EIR type
ESP_BT_EIR_FLAG_LIMIT_DISC
ESP_BT_EIR_FLAG_GEN_DISC
ESP_BT_EIR_FLAG_BREDR_NOT_SPT
ESP_BT_EIR_FLAG_DMT_CONTROLLER_SPT
ESP_BT_EIR_FLAG_DMT_HOST_SPT
ESP_BT_EIR_MAX_LEN
ESP_BT_PIN_CODE_LEN
Max pin code length
ESP_BT_IO_CAP_OUT
ESP_BT_IO_CAP_IO
ESP_BT_IO_CAP_IN
ESP_BT_IO_CAP_NONE
ESP_BT_PM_MD_ACTIVE
Active mode
ESP_BT_PM_MD_HOLD
Hold mode
ESP_BT_PM_MD_SNIFF
Sniff mode
ESP_BT_PM_MD_PARK
Park state
ESP_BT_COD_SRVC_BIT_MASK
Bits of major service class field.
Major service bit mask
ESP_BT_COD_SRVC_BIT_OFFSET
Major service bit offset
ESP_BT_COD_MAJOR_DEV_BIT_MASK
Bits of major device class field.
Major device bit mask
ESP_BT_COD_MAJOR_DEV_BIT_OFFSET
Major device bit offset
ESP_BT_COD_MINOR_DEV_BIT_MASK
Bits of minor device class field.
Minor device bit mask
ESP_BT_COD_MINOR_DEV_BIT_OFFSET
Minor device bit offset
ESP_BT_COD_FORMAT_TYPE_BIT_MASK
Bits of format type.
Format type bit mask
ESP_BT_COD_FORMAT_TYPE_BIT_OFFSET
Format type bit offset
ESP_BT_COD_FORMAT_TYPE_1
Class of device format type 1.
ESP_BT_GAP_MIN_INQ_LEN
Minimum and Maximum inquiry length Minimum inquiry duration, unit is 1.28s
ESP_BT_GAP_MAX_INQ_LEN
Maximum inquiry duration, unit is 1.28s
Type Definitions
Enumerations
enum esp_bt_cod_mode_t
class of device settings
Values:
enumerator ESP_BT_SET_COD_MAJOR_MINOR
overwrite major, minor class
enumerator ESP_BT_SET_COD_SERVICE_CLASS
set the bits in the input, the current bit will remain
enumerator ESP_BT_CLR_COD_SERVICE_CLASS
clear the bits in the input, others will remain
enumerator ESP_BT_SET_COD_ALL
overwrite major, minor, set the bits in service class
enumerator ESP_BT_INIT_COD
overwrite major, minor, and service class
enum esp_bt_connection_mode_t
Discoverability and Connectability mode.
Values:
enumerator ESP_BT_NON_CONNECTABLE
Non-connectable
enumerator ESP_BT_CONNECTABLE
Connectable
enum esp_bt_discovery_mode_t
Values:
enumerator ESP_BT_NON_DISCOVERABLE
Non-discoverable
enumerator ESP_BT_LIMITED_DISCOVERABLE
Limited Discoverable
enumerator ESP_BT_GENERAL_DISCOVERABLE
General Discoverable
enum esp_bt_gap_dev_prop_type_t
Bluetooth Device Property type.
Values:
enumerator ESP_BT_GAP_DEV_PROP_BDNAME
Bluetooth device name, value type is int8_t []
enumerator ESP_BT_GAP_DEV_PROP_COD
Class of Device, value type is uint32_t
enumerator ESP_BT_GAP_DEV_PROP_RSSI
Received Signal strength Indication, value type is int8_t, ranging from -128 to 127
enumerator ESP_BT_GAP_DEV_PROP_EIR
Extended Inquiry Response, value type is uint8_t []
enum esp_bt_cod_srvc_t
Major service class field of Class of Device, mutiple bits can be set.
Values:
enumerator ESP_BT_COD_SRVC_NONE
None indicates an invalid value
enumerator ESP_BT_COD_SRVC_LMTD_DISCOVER
Limited Discoverable Mode
enumerator ESP_BT_COD_SRVC_POSITIONING
Positioning (Location identification)
enumerator ESP_BT_COD_SRVC_NETWORKING
Networking, e.g. LAN, Ad hoc
enumerator ESP_BT_COD_SRVC_RENDERING
Rendering, e.g. Printing, Speakers
enumerator ESP_BT_COD_SRVC_CAPTURING
Capturing, e.g. Scanner, Microphone
enumerator ESP_BT_COD_SRVC_OBJ_TRANSFER
Object Transfer, e.g. v-Inbox, v-Folder
enumerator ESP_BT_COD_SRVC_AUDIO
Audio, e.g. Speaker, Microphone, Headset service
enumerator ESP_BT_COD_SRVC_TELEPHONY
Telephony, e.g. Cordless telephony, Modem, Headset service
enumerator ESP_BT_COD_SRVC_INFORMATION
Information, e.g., WEB-server, WAP-server
enum esp_bt_pin_type_t
Values:
enumerator ESP_BT_PIN_TYPE_VARIABLE
Refer to BTM_PIN_TYPE_VARIABLE
enumerator ESP_BT_PIN_TYPE_FIXED
Refer to BTM_PIN_TYPE_FIXED
enum esp_bt_sp_param_t
Values:
enumerator ESP_BT_SP_IOCAP_MODE
Set IO mode
enum esp_bt_cod_major_dev_t
Major device class field of Class of Device.
Values:
enumerator ESP_BT_COD_MAJOR_DEV_MISC
Miscellaneous
enumerator ESP_BT_COD_MAJOR_DEV_COMPUTER
Computer
enumerator ESP_BT_COD_MAJOR_DEV_PHONE
Phone(cellular, cordless, pay phone, modem
enumerator ESP_BT_COD_MAJOR_DEV_LAN_NAP
LAN, Network Access Point
enumerator ESP_BT_COD_MAJOR_DEV_AV
Audio/Video(headset, speaker, stereo, video display, VCR
enumerator ESP_BT_COD_MAJOR_DEV_PERIPHERAL
Peripheral(mouse, joystick, keyboard)
enumerator ESP_BT_COD_MAJOR_DEV_IMAGING
Imaging(printer, scanner, camera, display
enumerator ESP_BT_COD_MAJOR_DEV_WEARABLE
Wearable
enumerator ESP_BT_COD_MAJOR_DEV_TOY
Toy
enumerator ESP_BT_COD_MAJOR_DEV_HEALTH
Health
enumerator ESP_BT_COD_MAJOR_DEV_UNCATEGORIZED
Uncategorized: device not specified
enum esp_bt_gap_discovery_state_t
Bluetooth Device Discovery state
Values:
enumerator ESP_BT_GAP_DISCOVERY_STOPPED
Device discovery stopped
enumerator ESP_BT_GAP_DISCOVERY_STARTED
Device discovery started
enum esp_bt_gap_cb_event_t
BT GAP callback events.
Values:
enumerator ESP_BT_GAP_DISC_RES_EVT
Device discovery result event
enumerator ESP_BT_GAP_DISC_STATE_CHANGED_EVT
Discovery state changed event
enumerator ESP_BT_GAP_RMT_SRVCS_EVT
Get remote services event
enumerator ESP_BT_GAP_RMT_SRVC_REC_EVT
Get remote service record event
enumerator ESP_BT_GAP_AUTH_CMPL_EVT
Authentication complete event
enumerator ESP_BT_GAP_PIN_REQ_EVT
Legacy Pairing Pin code request
enumerator ESP_BT_GAP_CFM_REQ_EVT
Security Simple Pairing User Confirmation request.
enumerator ESP_BT_GAP_KEY_NOTIF_EVT
Security Simple Pairing Passkey Notification
enumerator ESP_BT_GAP_KEY_REQ_EVT
Security Simple Pairing Passkey request
enumerator ESP_BT_GAP_READ_RSSI_DELTA_EVT
Read rssi event
enumerator ESP_BT_GAP_CONFIG_EIR_DATA_EVT
Config EIR data event
enumerator ESP_BT_GAP_SET_AFH_CHANNELS_EVT
Set AFH channels event
enumerator ESP_BT_GAP_READ_REMOTE_NAME_EVT
Read Remote Name event
enumerator ESP_BT_GAP_MODE_CHG_EVT
enumerator ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT
remove bond device complete event
enumerator ESP_BT_GAP_QOS_CMPL_EVT
QOS complete event
enumerator ESP_BT_GAP_EVT_MAX
enum esp_bt_inq_mode_t
Inquiry Mode
Values:
enumerator ESP_BT_INQ_MODE_GENERAL_INQUIRY
General inquiry mode
enumerator ESP_BT_INQ_MODE_LIMITED_INQUIRY
Limited inquiry mode
Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the fol-
lowing application:
• This is a A2DP sink client demo. This demo can be discovered and connected by A2DP source device and
receive the audio stream from remote device - bluetooth/bluedroid/classic_bt/a2dp_sink
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_a2dp_api.h
Functions
esp_err_t esp_a2d_register_callback(esp_a2d_cb_t callback)
Register application callback function to A2DP module. This function should be called only after
esp_bluedroid_enable() completes successfully, used by both A2DP source and sink.
Parameters callback –[in] A2DP event callback function
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: if callback is a NULL function pointer
esp_err_t esp_a2d_sink_register_data_callback(esp_a2d_sink_data_cb_t callback)
Register A2DP sink data output function; For now the output is PCM data stream decoded from SBC format.
This function should be called only after esp_bluedroid_enable() completes successfully, used only by A2DP
sink. The callback is invoked in the context of A2DP sink task whose stack size is configurable through
menuconfig.
Parameters callback –[in] A2DP sink data callback function
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: if callback is a NULL function pointer
esp_err_t esp_a2d_sink_init(void)
Initialize the bluetooth A2DP sink module. This function should be called after esp_bluedroid_enable() com-
pletes successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_INIT_SUCCESS will reported to
the APP layer. Note: A2DP can work independently. If you want to use AVRC together, you should initiate
AVRC first. This function should be called after esp_bluedroid_enable() completes successfully.
Returns
• ESP_OK: if the initialization request is sent successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_sink_deinit(void)
De-initialize for A2DP sink module. This function should be called only after esp_bluedroid_enable() com-
pletes successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_DEINIT_SUCCESS will reported
to APP layer.
Returns
• ESP_OK: if the deinitialization request is sent successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_sink_connect(esp_bd_addr_t remote_bda)
Connect to remote bluetooth A2DP source device. This API must be called after esp_a2d_sink_init() and
before esp_a2d_sink_deinit().
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: connect request is sent to lower layer successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_sink_disconnect(esp_bd_addr_t remote_bda)
Disconnect from the remote A2DP source device. This API must be called after esp_a2d_sink_init() and
before esp_a2d_sink_deinit().
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: disconnect request is sent to lower layer successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_sink_set_delay_value(uint16_t delay_value)
Set delay reporting value. The delay value of sink is caused by buffering (including protocol stack and appli-
cation layer), decoding and rendering. The default delay value is 120ms, if the set value is less than 120ms,
the setting will fail. This API must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit().
Parameters delay_value –[in] reporting value is in 1/10 millisecond
Returns
• ESP_OK: delay value is sent to lower layer successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_sink_get_delay_value(void)
Get delay reporting value. This API must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit().
Returns
• ESP_OK: if the request is sent successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_media_ctrl(esp_a2d_media_ctrl_t ctrl)
Media control commands. This API can be used for both A2DP sink and source and must be called after
esp_a2d_sink_init() and before esp_a2d_sink_deinit().
Parameters ctrl –[in] control commands for A2DP data channel
Returns
• ESP_OK: control command is sent to lower layer successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_source_init(void)
Initialize the bluetooth A2DP source module. A2DP can work independently. If you want to use AVRC
together, you should initiate AVRC first. This function should be called after esp_bluedroid_enable() completes
successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_INIT_SUCCESS will reported to the APP
layer. Note: A2DP can work independently. If you want to use AVRC together, you should initiate AVRC
first.
Returns
• ESP_OK: if the initialization request is sent to lower layer successfully
Unions
union esp_a2d_cb_param_t
#include <esp_a2dp_api.h> A2DP state callback parameters.
Public Members
struct a2d_audio_cfg_param
#include <esp_a2dp_api.h> ESP_A2D_AUDIO_CFG_EVT.
Public Members
esp_bd_addr_t remote_bda
remote bluetooth device address
esp_a2d_mcc_t mcc
A2DP media codec capability information
struct a2d_audio_stat_param
#include <esp_a2dp_api.h> ESP_A2D_AUDIO_STATE_EVT.
Public Members
esp_a2d_audio_state_t state
one of the values from esp_a2d_audio_state_t
esp_bd_addr_t remote_bda
remote bluetooth device address
struct a2d_conn_stat_param
#include <esp_a2dp_api.h> ESP_A2D_CONNECTION_STATE_EVT.
Public Members
esp_a2d_connection_state_t state
one of values from esp_a2d_connection_state_t
esp_bd_addr_t remote_bda
remote bluetooth device address
esp_a2d_disc_rsn_t disc_rsn
reason of disconnection for “DISCONNECTED”
struct a2d_get_stat_param
#include <esp_a2dp_api.h> ESP_A2D_SNK_GET_DELAY_VALUE_EVT.
Public Members
uint16_t delay_value
delay report value
struct a2d_prof_stat_param
#include <esp_a2dp_api.h> ESP_A2D_PROF_STATE_EVT.
Public Members
esp_a2d_init_state_t init_state
a2dp profile state param
struct a2d_psc_cfg_param
#include <esp_a2dp_api.h> ESP_A2D_SNK_PSC_CFG_EVT.
Public Members
esp_a2d_psc_t psc_mask
protocol service capabilities configured
struct a2d_report_delay_stat_param
#include <esp_a2dp_api.h> ESP_A2D_REPORT_SNK_DELAY_VALUE_EVT.
Public Members
uint16_t delay_value
delay report value
struct a2d_set_stat_param
#include <esp_a2dp_api.h> ESP_A2D_SNK_SET_DELAY_VALUE_EVT.
Public Members
esp_a2d_set_delay_value_state_t set_state
a2dp profile state param
uint16_t delay_value
delay report value
struct media_ctrl_stat_param
#include <esp_a2dp_api.h> ESP_A2D_MEDIA_CTRL_ACK_EVT.
Public Members
esp_a2d_media_ctrl_t cmd
media control commands to acknowledge
esp_a2d_media_ctrl_ack_t status
acknowledgement to media control commands
Structures
struct esp_a2d_mcc_t
A2DP media codec capabilities union.
Public Members
esp_a2d_mct_t type
A2DP media codec type
uint8_t sbc[ESP_A2D_CIE_LEN_SBC]
SBC codec capabilities
uint8_t m12[ESP_A2D_CIE_LEN_M12]
MPEG-1,2 audio codec capabilities
uint8_t m24[ESP_A2D_CIE_LEN_M24]
MPEG-2, 4 AAC audio codec capabilities
uint8_t atrac[ESP_A2D_CIE_LEN_ATRAC]
ATRAC family codec capabilities
Macros
ESP_A2D_MCT_SBC
Media codec types supported by A2DP.
SBC
ESP_A2D_MCT_M12
MPEG-1, 2 Audio
ESP_A2D_MCT_M24
MPEG-2, 4 AAC
ESP_A2D_MCT_ATRAC
ATRAC family
ESP_A2D_MCT_NON_A2DP
NON-A2DP
ESP_A2D_PSC_DELAY_RPT
Protocol service capabilities. This value is a mask.
Delay Report
ESP_A2D_CIE_LEN_SBC
ESP_A2D_CIE_LEN_M12
ESP_A2D_CIE_LEN_M24
ESP_A2D_CIE_LEN_ATRAC
Type Definitions
Enumerations
enum esp_a2d_connection_state_t
Bluetooth A2DP connection states.
Values:
enumerator ESP_A2D_CONNECTION_STATE_DISCONNECTED
connection released
enumerator ESP_A2D_CONNECTION_STATE_CONNECTING
connecting remote device
enumerator ESP_A2D_CONNECTION_STATE_CONNECTED
connection established
enumerator ESP_A2D_CONNECTION_STATE_DISCONNECTING
disconnecting remote device
enum esp_a2d_disc_rsn_t
Bluetooth A2DP disconnection reason.
Values:
enumerator ESP_A2D_DISC_RSN_NORMAL
Finished disconnection that is initiated by local or remote device
enumerator ESP_A2D_DISC_RSN_ABNORMAL
Abnormal disconnection caused by signal loss
enum esp_a2d_audio_state_t
Bluetooth A2DP datapath states.
Values:
enumerator ESP_A2D_AUDIO_STATE_REMOTE_SUSPEND
audio stream datapath suspended by remote device
enumerator ESP_A2D_AUDIO_STATE_STOPPED
audio stream datapath stopped
enumerator ESP_A2D_AUDIO_STATE_STARTED
audio stream datapath started
enum esp_a2d_media_ctrl_ack_t
A2DP media control command acknowledgement code.
Values:
enumerator ESP_A2D_MEDIA_CTRL_ACK_SUCCESS
media control command is acknowledged with success
enumerator ESP_A2D_MEDIA_CTRL_ACK_FAILURE
media control command is acknowledged with failure
enumerator ESP_A2D_MEDIA_CTRL_ACK_BUSY
media control command is rejected, as previous command is not yet acknowledged
enum esp_a2d_media_ctrl_t
A2DP media control commands.
Values:
enumerator ESP_A2D_MEDIA_CTRL_NONE
Not for application use, use inside stack only.
enumerator ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY
check whether AVDTP is connected, only used in A2DP source
enumerator ESP_A2D_MEDIA_CTRL_START
command to set up media transmission channel
enumerator ESP_A2D_MEDIA_CTRL_STOP
command to stop media transmission
enumerator ESP_A2D_MEDIA_CTRL_SUSPEND
command to suspend media transmission
enum esp_a2d_init_state_t
Bluetooth A2DP Initiation states.
Values:
enumerator ESP_A2D_DEINIT_SUCCESS
A2DP profile deinit successful event
enumerator ESP_A2D_INIT_SUCCESS
A2DP profile deinit successful event
enum esp_a2d_set_delay_value_state_t
Bluetooth A2DP set delay report value states.
Values:
enumerator ESP_A2D_SET_SUCCESS
A2DP profile set delay report value successful
enumerator ESP_A2D_SET_INVALID_PARAMS
A2DP profile set delay report value is invalid parameter
enum esp_a2d_cb_event_t
A2DP callback events.
Values:
enumerator ESP_A2D_CONNECTION_STATE_EVT
connection state changed event
enumerator ESP_A2D_AUDIO_STATE_EVT
audio stream transmission state changed event
enumerator ESP_A2D_AUDIO_CFG_EVT
audio codec is configured, only used for A2DP SINK
enumerator ESP_A2D_MEDIA_CTRL_ACK_EVT
acknowledge event in response to media control commands
enumerator ESP_A2D_PROF_STATE_EVT
indicate a2dp init&deinit complete
enumerator ESP_A2D_SNK_PSC_CFG_EVT
protocol service capabilities configured,only used for A2DP SINK
enumerator ESP_A2D_SNK_SET_DELAY_VALUE_EVT
indicate a2dp sink set delay report value complete, only used for A2DP SINK
enumerator ESP_A2D_SNK_GET_DELAY_VALUE_EVT
indicate a2dp sink get delay report value complete, only used for A2DP SINK
enumerator ESP_A2D_REPORT_SNK_DELAY_VALUE_EVT
report delay value, only used for A2DP SRC
BT AVRCP APIs
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_avrc_api.h
Functions
esp_err_t esp_avrc_ct_register_callback(esp_avrc_ct_cb_t callback)
Register application callbacks to AVRCP module. This function should be called after esp_bluedroid_enable()
completes successfully.
• ESP_FAIL: others
esp_err_t esp_avrc_tg_init(void)
Initialize the bluetooth AVRCP target module, This function should be called after esp_bluedroid_enable()
completes successfully. Note: AVRC cannot work independently, AVRC should be used along with A2DP
and AVRC should be initialized before A2DP.
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_avrc_tg_deinit(void)
De-initialize AVRCP target module. This function should be called after after esp_bluedroid_enable() com-
pletes successfully. Note: AVRC cannot work independently, AVRC should be used along with A2DP and
AVRC should be deinitialized before A2DP.
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_avrc_tg_get_psth_cmd_filter(esp_avrc_psth_filter_t filter, esp_avrc_psth_bit_mask_t
*cmd_set)
Get the current filter of remote passthrough commands on AVRC target. Filter is given by filter type
and bit mask for the passthrough commands. This function should be called after esp_avrc_tg_init().
For filter type ESP_AVRC_PSTH_FILTER_ALLOWED_CMD, the retrieved command set is constant
and it covers all of the passthrough commands that can possibly be supported. For filter type
ESP_AVRC_PSTH_FILTER_SUPPORT_COMMANDS, the retrieved command set covers the passthrough
commands selected to be supported according to current configuration. The configuration can be changed
using esp_avrc_tg_set_psth_cmd_filter().
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not ini-
tialized
• ESP_ERR_INVALID_ARG: if filter type is invalid or cmd_set is NULL
• ESP_FAIL: otherwise
esp_err_t esp_avrc_tg_set_psth_cmd_filter(esp_avrc_psth_filter_t filter, const
esp_avrc_psth_bit_mask_t *cmd_set)
Set the filter of remote passthrough commands on AVRC target. Filter is given by filter type and bit mask for
the passthrough commands. This function should be called after esp_avrc_tg_init().
If filter type is ESP_AVRC_PSTH_FILTER_SUPPORT_CMD, the passthrough commands which are
set “1”as given in cmd_set will generate ESP_AVRC_CT_PASSTHROUGH_RSP_EVT callback event
and are auto-accepted in the protocol stack, other commands are replied with response type “NOT
IMPLEMENTED”(8). The set of supported commands should be a subset of allowed command
set. The allowed command set can be retrieved using esp_avrc_tg_get_psth_cmd_filter() with filter type
“ESP_AVRC_PSTH_FILTER_ALLOWED_CMD”.
Filter type “ESP_AVRC_PSTH_FILTER_ALLOWED_CMD”does not apply to this function.
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled
• ESP_ERR_INVALID_ARG: if filter type is invalid or cmd_set is NULL
• ESP_ERR_NOT_SUPPORTED:: if filter type is
ESP_AVRC_PSTH_FILTER_ALLOWED_CMD, or cmd_set includes commands
that are not allowed
bool esp_avrc_psth_bit_mask_operation(esp_avrc_bit_mask_op_t op, esp_avrc_psth_bit_mask_t
*psth, esp_avrc_pt_cmd_t cmd)
For operation ESP_AVRC_BIT_MASK_OP_TEST, return true if the corresponding bit is set, otherwise false.
Parameters
• op –[in] operation requested on the bit mask field
• events –[in] pointer to event notification capability bit mask structure
• event_id –[in] notification event code
Returns For operation ESP_AVRC_BIT_MASK_OP_SET or
ESP_AVRC_BIT_MASK_OP_CLEAR, return true for a successful operation, other-
wise return false.
esp_err_t esp_avrc_tg_send_rn_rsp(esp_avrc_rn_event_ids_t event_id, esp_avrc_rn_rsp_t rsp,
esp_avrc_rn_param_t *param)
Send RegisterNotification Response to remote AVRCP controller. Local event notification capability can be
set using esp_avrc_tg_set_rn_evt_cap(), in a bit mask representation in evt_set. This function should be called
after esp_avrc_tg_init().
Parameters
• event_id –[in] notification event ID that remote AVRCP CT registers
• rsp –[in] notification response code
• param –[in] parameters included in the specific notification
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not ini-
tialized
• ESP_ERR_INVALID_ARG: if evt_set is NULL
Unions
union esp_avrc_rn_param_t
#include <esp_avrc_api.h> AVRCP notification parameters.
Public Members
uint8_t volume
response data for ESP_AVRC_RN_VOLUME_CHANGE, ranges 0..127
esp_avrc_playback_stat_t playback
response data for ESP_AVRC_RN_PLAY_STATUS_CHANGE
uint8_t elm_id[8]
response data for ESP_AVRC_RN_TRACK_CHANGE
uint32_t play_pos
response data for ESP_AVRC_RN_PLAY_POS_CHANGED, in millisecond
esp_avrc_batt_stat_t batt
response data for ESP_AVRC_RN_BATTERY_STATUS_CHANGE
union esp_avrc_ct_cb_param_t
#include <esp_avrc_api.h> AVRC controller callback parameters.
Public Members
struct avrc_ct_change_notify_param
#include <esp_avrc_api.h> ESP_AVRC_CT_CHANGE_NOTIFY_EVT.
Public Members
uint8_t event_id
id of AVRC event notification
esp_avrc_rn_param_t event_parameter
event notification parameter
struct avrc_ct_conn_stat_param
#include <esp_avrc_api.h> ESP_AVRC_CT_CONNECTION_STATE_EVT.
Public Members
bool connected
whether AVRC connection is set up
esp_bd_addr_t remote_bda
remote bluetooth device address
struct avrc_ct_get_rn_caps_rsp_param
#include <esp_avrc_api.h> ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT.
Public Members
uint8_t cap_count
number of items provided in event or company_id according to cap_id used
esp_avrc_rn_evt_cap_mask_t evt_set
supported event_ids represented in bit-mask
struct avrc_ct_meta_rsp_param
#include <esp_avrc_api.h> ESP_AVRC_CT_METADATA_RSP_EVT.
Public Members
uint8_t attr_id
id of metadata attribute
uint8_t *attr_text
attribute itself
int attr_length
attribute character length
struct avrc_ct_psth_rsp_param
#include <esp_avrc_api.h> ESP_AVRC_CT_PASSTHROUGH_RSP_EVT.
Public Members
uint8_t tl
transaction label, 0 to 15
uint8_t key_code
passthrough command code
uint8_t key_state
0 for PRESSED, 1 for RELEASED
struct avrc_ct_rmt_feats_param
#include <esp_avrc_api.h> ESP_AVRC_CT_REMOTE_FEATURES_EVT.
Public Members
uint32_t feat_mask
AVRC feature mask of remote device
uint16_t tg_feat_flag
feature flag of remote device as TG
esp_bd_addr_t remote_bda
remote bluetooth device address
struct avrc_ct_set_volume_rsp_param
#include <esp_avrc_api.h> ESP_AVRC_CT_SET_ABSOLUTE_VOLUME_RSP_EVT.
Public Members
uint8_t volume
the volume which has actually been set, range is 0 to 0x7f, means 0% to 100%
union esp_avrc_tg_cb_param_t
#include <esp_avrc_api.h> AVRC target callback parameters.
Public Members
struct avrc_tg_conn_stat_param
#include <esp_avrc_api.h> ESP_AVRC_TG_CONNECTION_STATE_EVT.
Public Members
bool connected
whether AVRC connection is set up
esp_bd_addr_t remote_bda
remote bluetooth device address
struct avrc_tg_psth_cmd_param
#include <esp_avrc_api.h> ESP_AVRC_TG_PASSTHROUGH_CMD_EVT.
Public Members
uint8_t key_code
passthrough command code
uint8_t key_state
0 for PRESSED, 1 for RELEASED
struct avrc_tg_reg_ntf_param
#include <esp_avrc_api.h> ESP_AVRC_TG_REGISTER_NOTIFICATION_EVT.
Public Members
uint8_t event_id
event id of AVRC RegisterNotification
uint32_t event_parameter
event notification parameter
struct avrc_tg_rmt_feats_param
#include <esp_avrc_api.h> ESP_AVRC_TG_REMOTE_FEATURES_EVT.
Public Members
uint32_t feat_mask
AVRC feature mask of remote device
uint16_t ct_feat_flag
feature flag of remote device as CT
esp_bd_addr_t remote_bda
remote bluetooth device address
struct avrc_tg_set_abs_vol_param
#include <esp_avrc_api.h> ESP_AVRC_TG_SET_ABSOLUTE_VOLUME_CMD_EVT.
Public Members
uint8_t volume
volume ranges from 0 to 127
struct avrc_tg_set_app_value_param
#include <esp_avrc_api.h> ESP_AVRC_TG_SET_PLAYER_APP_VALUE_EVT.
Public Members
uint8_t num_val
attribute num
esp_avrc_set_app_value_param_t *p_vals
point to the id and value of player application attribute
Structures
struct esp_avrc_psth_bit_mask_t
AVRC passthrough command bit mask.
Public Members
uint16_t bits[8]
bit mask representation of PASSTHROUGH commands
struct esp_avrc_rn_evt_cap_mask_t
AVRC target notification event capability bit mask.
Public Members
uint16_t bits
bit mask representation of PASSTHROUGH commands
struct esp_avrc_set_app_value_param_t
AVRCP set app value parameters.
Public Members
uint8_t attr_id
player application attribute id
uint8_t attr_val
player application attribute value
Macros
ESP_AVRC_TRANS_LABEL_MAX
max transaction label
Type Definitions
Enumerations
enum esp_avrc_features_t
AVRC feature bit mask.
Values:
enumerator ESP_AVRC_FEAT_RCTG
remote control target
enumerator ESP_AVRC_FEAT_RCCT
remote control controller
enumerator ESP_AVRC_FEAT_VENDOR
remote control vendor dependent commands
enumerator ESP_AVRC_FEAT_BROWSE
use browsing channel
enumerator ESP_AVRC_FEAT_META_DATA
remote control metadata transfer command/response
enumerator ESP_AVRC_FEAT_ADV_CTRL
remote control advanced control command/response
enum esp_avrc_feature_flag_t
AVRC supported features flag retrieved in SDP record.
Values:
enumerator ESP_AVRC_FEAT_FLAG_CAT1
category 1
enumerator ESP_AVRC_FEAT_FLAG_CAT2
category 2
enumerator ESP_AVRC_FEAT_FLAG_CAT3
category 3
enumerator ESP_AVRC_FEAT_FLAG_CAT4
category 4
enumerator ESP_AVRC_FEAT_FLAG_BROWSING
browsing
enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_IMAGE_PROP
Cover Art GetImageProperties
enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_IMAGE
Cover Art GetImage
enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_LINKED_THUMBNAIL
Cover Art GetLinkedThumbnail
enum esp_avrc_pt_cmd_t
AVRC passthrough command code.
Values:
enumerator ESP_AVRC_PT_CMD_SELECT
select
enumerator ESP_AVRC_PT_CMD_UP
up
enumerator ESP_AVRC_PT_CMD_DOWN
down
enumerator ESP_AVRC_PT_CMD_LEFT
left
enumerator ESP_AVRC_PT_CMD_RIGHT
right
enumerator ESP_AVRC_PT_CMD_RIGHT_UP
right-up
enumerator ESP_AVRC_PT_CMD_RIGHT_DOWN
right-down
enumerator ESP_AVRC_PT_CMD_LEFT_UP
left-up
enumerator ESP_AVRC_PT_CMD_LEFT_DOWN
left-down
enumerator ESP_AVRC_PT_CMD_ROOT_MENU
root menu
enumerator ESP_AVRC_PT_CMD_SETUP_MENU
setup menu
enumerator ESP_AVRC_PT_CMD_CONT_MENU
contents menu
enumerator ESP_AVRC_PT_CMD_FAV_MENU
favorite menu
enumerator ESP_AVRC_PT_CMD_EXIT
exit
enumerator ESP_AVRC_PT_CMD_0
0
enumerator ESP_AVRC_PT_CMD_1
1
enumerator ESP_AVRC_PT_CMD_2
2
enumerator ESP_AVRC_PT_CMD_3
3
enumerator ESP_AVRC_PT_CMD_4
4
enumerator ESP_AVRC_PT_CMD_5
5
enumerator ESP_AVRC_PT_CMD_6
6
enumerator ESP_AVRC_PT_CMD_7
7
enumerator ESP_AVRC_PT_CMD_8
8
enumerator ESP_AVRC_PT_CMD_9
9
enumerator ESP_AVRC_PT_CMD_DOT
dot
enumerator ESP_AVRC_PT_CMD_ENTER
enter
enumerator ESP_AVRC_PT_CMD_CLEAR
clear
enumerator ESP_AVRC_PT_CMD_CHAN_UP
channel up
enumerator ESP_AVRC_PT_CMD_CHAN_DOWN
channel down
enumerator ESP_AVRC_PT_CMD_PREV_CHAN
previous channel
enumerator ESP_AVRC_PT_CMD_SOUND_SEL
sound select
enumerator ESP_AVRC_PT_CMD_INPUT_SEL
input select
enumerator ESP_AVRC_PT_CMD_DISP_INFO
display information
enumerator ESP_AVRC_PT_CMD_HELP
help
enumerator ESP_AVRC_PT_CMD_PAGE_UP
page up
enumerator ESP_AVRC_PT_CMD_PAGE_DOWN
page down
enumerator ESP_AVRC_PT_CMD_POWER
power
enumerator ESP_AVRC_PT_CMD_VOL_UP
volume up
enumerator ESP_AVRC_PT_CMD_VOL_DOWN
volume down
enumerator ESP_AVRC_PT_CMD_MUTE
mute
enumerator ESP_AVRC_PT_CMD_PLAY
play
enumerator ESP_AVRC_PT_CMD_STOP
stop
enumerator ESP_AVRC_PT_CMD_PAUSE
pause
enumerator ESP_AVRC_PT_CMD_RECORD
record
enumerator ESP_AVRC_PT_CMD_REWIND
rewind
enumerator ESP_AVRC_PT_CMD_FAST_FORWARD
fast forward
enumerator ESP_AVRC_PT_CMD_EJECT
eject
enumerator ESP_AVRC_PT_CMD_FORWARD
forward
enumerator ESP_AVRC_PT_CMD_BACKWARD
backward
enumerator ESP_AVRC_PT_CMD_ANGLE
angle
enumerator ESP_AVRC_PT_CMD_SUBPICT
subpicture
enumerator ESP_AVRC_PT_CMD_F1
F1
enumerator ESP_AVRC_PT_CMD_F2
F2
enumerator ESP_AVRC_PT_CMD_F3
F3
enumerator ESP_AVRC_PT_CMD_F4
F4
enumerator ESP_AVRC_PT_CMD_F5
F5
enumerator ESP_AVRC_PT_CMD_VENDOR
vendor unique
enum esp_avrc_psth_filter_t
AVRC passthrough command filter.
Values:
enumerator ESP_AVRC_PSTH_FILTER_ALLOWED_CMD
all of the PASSTHROUGH commands that can possibly be used, immutable
enumerator ESP_AVRC_PSTH_FILTER_SUPPORTED_CMD
PASSTHROUGH commands selectively supported according to the current configuration
enumerator ESP_AVRC_PSTH_FILTER_SUPPORT_MAX
enum esp_avrc_bit_mask_op_t
Values:
enumerator ESP_AVRC_BIT_MASK_OP_TEST
operation code to test a specific bit
enumerator ESP_AVRC_BIT_MASK_OP_SET
operation code to set a specific bit
enumerator ESP_AVRC_BIT_MASK_OP_CLEAR
operation code to clear a specific bit
enum esp_avrc_pt_cmd_state_t
AVRC passthrough command state.
Values:
enumerator ESP_AVRC_PT_CMD_STATE_PRESSED
key pressed
enumerator ESP_AVRC_PT_CMD_STATE_RELEASED
key released
enum esp_avrc_ct_cb_event_t
AVRC Controller callback events.
Values:
enumerator ESP_AVRC_CT_CONNECTION_STATE_EVT
connection state changed event
enumerator ESP_AVRC_CT_PASSTHROUGH_RSP_EVT
passthrough response event
enumerator ESP_AVRC_CT_METADATA_RSP_EVT
metadata response event
enumerator ESP_AVRC_CT_PLAY_STATUS_RSP_EVT
play status response event
enumerator ESP_AVRC_CT_CHANGE_NOTIFY_EVT
notification event
enumerator ESP_AVRC_CT_REMOTE_FEATURES_EVT
feature of remote device indication event
enumerator ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT
supported notification events capability of peer device
enumerator ESP_AVRC_CT_SET_ABSOLUTE_VOLUME_RSP_EVT
set absolute volume response event
enum esp_avrc_tg_cb_event_t
AVRC Target callback events.
Values:
enumerator ESP_AVRC_TG_CONNECTION_STATE_EVT
connection state changed event
enumerator ESP_AVRC_TG_REMOTE_FEATURES_EVT
feature of remote device indication event
enumerator ESP_AVRC_TG_PASSTHROUGH_CMD_EVT
passthrough command event
enumerator ESP_AVRC_TG_SET_ABSOLUTE_VOLUME_CMD_EVT
set absolute volume command from remote device
enumerator ESP_AVRC_TG_REGISTER_NOTIFICATION_EVT
register notification event
enumerator ESP_AVRC_TG_SET_PLAYER_APP_VALUE_EVT
set application attribute value, attribute refer to esp_avrc_ps_attr_ids_t
enum esp_avrc_md_attr_mask_t
AVRC metadata attribute mask.
Values:
enumerator ESP_AVRC_MD_ATTR_TITLE
title of the playing track
enumerator ESP_AVRC_MD_ATTR_ARTIST
track artist
enumerator ESP_AVRC_MD_ATTR_ALBUM
album name
enumerator ESP_AVRC_MD_ATTR_TRACK_NUM
track position on the album
enumerator ESP_AVRC_MD_ATTR_NUM_TRACKS
number of tracks on the album
enumerator ESP_AVRC_MD_ATTR_GENRE
track genre
enumerator ESP_AVRC_MD_ATTR_PLAYING_TIME
total album playing time in miliseconds
enum esp_avrc_rn_event_ids_t
AVRC event notification ids.
Values:
enumerator ESP_AVRC_RN_PLAY_STATUS_CHANGE
track status change, eg. from playing to paused
enumerator ESP_AVRC_RN_TRACK_CHANGE
new track is loaded
enumerator ESP_AVRC_RN_TRACK_REACHED_END
current track reached end
enumerator ESP_AVRC_RN_TRACK_REACHED_START
current track reached start position
enumerator ESP_AVRC_RN_PLAY_POS_CHANGED
track playing position changed
enumerator ESP_AVRC_RN_BATTERY_STATUS_CHANGE
battery status changed
enumerator ESP_AVRC_RN_SYSTEM_STATUS_CHANGE
system status changed
enumerator ESP_AVRC_RN_APP_SETTING_CHANGE
application settings changed
enumerator ESP_AVRC_RN_NOW_PLAYING_CHANGE
now playing content changed
enumerator ESP_AVRC_RN_AVAILABLE_PLAYERS_CHANGE
available players changed
enumerator ESP_AVRC_RN_ADDRESSED_PLAYER_CHANGE
the addressed player changed
enumerator ESP_AVRC_RN_UIDS_CHANGE
UIDs changed
enumerator ESP_AVRC_RN_VOLUME_CHANGE
volume changed locally on TG
enumerator ESP_AVRC_RN_MAX_EVT
enum esp_avrc_rn_evt_cap_t
AVRC target notification event notification capability.
Values:
enumerator ESP_AVRC_RN_CAP_ALLOWED_EVT
all of the notification events that can possibly be supported, immutable
enumerator ESP_AVRC_RN_CAP_SUPPORTED_EVT
notification events selectively supported according to the current configuration
enumerator ESP_AVRC_RN_CAP_MAX
enum esp_avrc_rn_rsp_t
AVRC notification response type.
Values:
enumerator ESP_AVRC_RN_RSP_INTERIM
initial response to RegisterNotification, should be sent T_mtp(1000ms) from receiving the command
enumerator ESP_AVRC_RN_RSP_CHANGED
final response to RegisterNotification command
enum esp_avrc_ps_attr_ids_t
AVRC player setting ids.
Values:
enumerator ESP_AVRC_PS_EQUALIZER
equalizer, on or off
enumerator ESP_AVRC_PS_REPEAT_MODE
repeat mode
enumerator ESP_AVRC_PS_SHUFFLE_MODE
shuffle mode
enumerator ESP_AVRC_PS_SCAN_MODE
scan mode on or off
enumerator ESP_AVRC_PS_MAX_ATTR
enum esp_avrc_ps_eq_value_ids_t
AVRC equalizer modes.
Values:
enumerator ESP_AVRC_PS_EQUALIZER_OFF
equalizer OFF
enumerator ESP_AVRC_PS_EQUALIZER_ON
equalizer ON
enum esp_avrc_ps_rpt_value_ids_t
AVRC repeat modes.
Values:
enumerator ESP_AVRC_PS_REPEAT_OFF
repeat mode off
enumerator ESP_AVRC_PS_REPEAT_SINGLE
single track repeat
enumerator ESP_AVRC_PS_REPEAT_GROUP
group repeat
enum esp_avrc_ps_shf_value_ids_t
AVRC shuffle modes.
Values:
enumerator ESP_AVRC_PS_SHUFFLE_OFF
enumerator ESP_AVRC_PS_SHUFFLE_ALL
enumerator ESP_AVRC_PS_SHUFFLE_GROUP
enum esp_avrc_ps_scn_value_ids_t
AVRC scan modes.
Values:
enumerator ESP_AVRC_PS_SCAN_OFF
scan off
enumerator ESP_AVRC_PS_SCAN_ALL
all tracks scan
enumerator ESP_AVRC_PS_SCAN_GROUP
group scan
enum esp_avrc_rsp_t
AVCTP response codes.
Values:
enumerator ESP_AVRC_RSP_NOT_IMPL
not implemented
enumerator ESP_AVRC_RSP_ACCEPT
accept
enumerator ESP_AVRC_RSP_REJECT
reject
enumerator ESP_AVRC_RSP_IN_TRANS
in transition
enumerator ESP_AVRC_RSP_IMPL_STBL
implemented/stable
enumerator ESP_AVRC_RSP_CHANGED
changed
enumerator ESP_AVRC_RSP_INTERIM
interim
enum esp_avrc_batt_stat_t
AVRCP battery status.
Values:
enumerator ESP_AVRC_BATT_NORMAL
normal state
enumerator ESP_AVRC_BATT_WARNING
unable to operate soon
enumerator ESP_AVRC_BATT_CRITICAL
cannot operate any more
enumerator ESP_AVRC_BATT_EXTERNAL
plugged to external power supply
enumerator ESP_AVRC_BATT_FULL_CHARGE
when completely charged from external power supply
enum esp_avrc_playback_stat_t
AVRCP current status of playback.
Values:
enumerator ESP_AVRC_PLAYBACK_STOPPED
stopped
enumerator ESP_AVRC_PLAYBACK_PLAYING
playing
enumerator ESP_AVRC_PLAYBACK_PAUSED
paused
enumerator ESP_AVRC_PLAYBACK_FWD_SEEK
forward seek
enumerator ESP_AVRC_PLAYBACK_REV_SEEK
reverse seek
enumerator ESP_AVRC_PLAYBACK_ERROR
error
SPP API
Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the fol-
lowing application:
• This is a SPP demo. This demo can discover the service, connect, send and recive SPP data blue-
tooth/bluedroid/classic_bt/bt_spp_acceptor, bluetooth/bluedroid/classic_bt/bt_spp_initiator
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_spp_api.h
Functions
esp_err_t esp_spp_register_callback(esp_spp_cb_t callback)
This function is called to init callbacks with SPP module.
Parameters callback –[in] pointer to the init callback function.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_init(esp_spp_mode_t mode)
This function is called to init SPP module. When the operation is completed, the callback function will be called
with ESP_SPP_INIT_EVT. This function should be called after esp_bluedroid_enable() completes success-
fully.
Parameters mode –[in] Choose the mode of SPP, ESP_SPP_MODE_CB or
ESP_SPP_MODE_VFS.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_deinit(void)
This function is called to uninit SPP module. The operation will close all active SPP connection first, then the
callback function will be called with ESP_SPP_CLOSE_EVT, and the number of ESP_SPP_CLOSE_EVT
is equal to the number of connection. When the operation is completed, the callback function will be called
with ESP_SPP_UNINIT_EVT. This function should be called after esp_spp_init() completes successfully.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_start_discovery(esp_bd_addr_t bd_addr)
This function is called to performs service discovery for the services provided by the given peer device. When
the operation is completed, the callback function will be called with ESP_SPP_DISCOVERY_COMP_EVT.
This function must be called after esp_spp_init() successful and before esp_spp_deinit().
Parameters bd_addr –[in] Remote device bluetooth device address.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_connect(esp_spp_sec_t sec_mask, esp_spp_role_t role, uint8_t remote_scn,
esp_bd_addr_t peer_bd_addr)
This function makes an SPP connection to a remote BD Address. When the connection is initiated or failed to
initiate, the callback is called with ESP_SPP_CL_INIT_EVT. When the connection is established or failed,
the callback is called with ESP_SPP_OPEN_EVT. This function must be called after esp_spp_init() successful
and before esp_spp_deinit().
Parameters
• sec_mask –[in] Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE,
ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only.
• role –[in] Master or slave.
• remote_scn –[in] Remote device bluetooth device SCN.
• peer_bd_addr –[in] Remote device bluetooth device address.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_disconnect(uint32_t handle)
This function closes an SPP connection. When the operation is completed, the callback function will be
called with ESP_SPP_CLOSE_EVT. This function must be called after esp_spp_init() successful and before
esp_spp_deinit().
Parameters handle –[in] The connection handle.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_start_srv(esp_spp_sec_t sec_mask, esp_spp_role_t role, uint8_t local_scn, const char
*name)
This function create a SPP server and starts listening for an SPP connection request from a remote Bluetooth
device. When the server is started successfully, the callback is called with ESP_SPP_START_EVT. When
the connection is established, the callback is called with ESP_SPP_SRV_OPEN_EVT. This function must be
called after esp_spp_init() successful and before esp_spp_deinit().
Parameters
• sec_mask –[in] Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE,
ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only.
• role –[in] Master or slave.
• local_scn –[in] The specific channel you want to get. If channel is 0, means get any
channel.
• name –[in] Server’s name.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_stop_srv(void)
This function stops all SPP servers. The operation will close all active SPP connection first, then the call-
back function will be called with ESP_SPP_CLOSE_EVT, and the number of ESP_SPP_CLOSE_EVT
is equal to the number of connection. When the operation is completed, the callback is called with
ESP_SPP_SRV_STOP_EVT. This function must be called after esp_spp_init() successful and before
esp_spp_deinit().
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_stop_srv_scn(uint8_t scn)
This function stops a specific SPP server. The operation will close all active SPP connection first on the
specific SPP server, then the callback function will be called with ESP_SPP_CLOSE_EVT, and the number of
ESP_SPP_CLOSE_EVT is equal to the number of connection. When the operation is completed, the callback
is called with ESP_SPP_SRV_STOP_EVT. This function must be called after esp_spp_init() successful and
before esp_spp_deinit().
Parameters scn –[in] Server channel number.
Returns
• ESP_OK: success
• other: failed
Unions
union esp_spp_cb_param_t
#include <esp_spp_api.h> SPP callback parameters union.
Public Members
struct spp_cl_init_evt_param
#include <esp_spp_api.h> ESP_SPP_CL_INIT_EVT.
Public Members
esp_spp_status_t status
status
uint32_t handle
The connection handle
uint8_t sec_id
security ID used by this server
bool use_co
TRUE to use co_rfc_data
struct spp_close_evt_param
#include <esp_spp_api.h> ESP_SPP_CLOSE_EVT.
Public Members
esp_spp_status_t status
status
uint32_t port_status
PORT status
uint32_t handle
The connection handle
bool async
FALSE, if local initiates disconnect
struct spp_cong_evt_param
#include <esp_spp_api.h> ESP_SPP_CONG_EVT.
Public Members
esp_spp_status_t status
status
uint32_t handle
The connection handle
bool cong
TRUE, congested. FALSE, uncongested
struct spp_data_ind_evt_param
#include <esp_spp_api.h> ESP_SPP_DATA_IND_EVT.
Public Members
esp_spp_status_t status
status
uint32_t handle
The connection handle
uint16_t len
The length of data
uint8_t *data
The data received
struct spp_discovery_comp_evt_param
#include <esp_spp_api.h> SPP_DISCOVERY_COMP_EVT.
Public Members
esp_spp_status_t status
status
uint8_t scn_num
The num of scn_num
uint8_t scn[ESP_SPP_MAX_SCN]
channel #
struct spp_init_evt_param
#include <esp_spp_api.h> SPP_INIT_EVT.
Public Members
esp_spp_status_t status
status
struct spp_open_evt_param
#include <esp_spp_api.h> ESP_SPP_OPEN_EVT.
Public Members
esp_spp_status_t status
status
uint32_t handle
The connection handle
int fd
The file descriptor only for ESP_SPP_MODE_VFS
esp_bd_addr_t rem_bda
The peer address
struct spp_srv_open_evt_param
#include <esp_spp_api.h> ESP_SPP_SRV_OPEN_EVT.
Public Members
esp_spp_status_t status
status
uint32_t handle
The connection handle
uint32_t new_listen_handle
The new listen handle
int fd
The file descriptor only for ESP_SPP_MODE_VFS
esp_bd_addr_t rem_bda
The peer address
struct spp_srv_stop_evt_param
#include <esp_spp_api.h> ESP_SPP_SRV_STOP_EVT.
Public Members
esp_spp_status_t status
status
uint8_t scn
Server channel number
struct spp_start_evt_param
#include <esp_spp_api.h> ESP_SPP_START_EVT.
Public Members
esp_spp_status_t status
status
uint32_t handle
The connection handle
uint8_t sec_id
security ID used by this server
uint8_t scn
Server channel number
bool use_co
TRUE to use co_rfc_data
struct spp_uninit_evt_param
#include <esp_spp_api.h> SPP_UNINIT_EVT.
Public Members
esp_spp_status_t status
status
struct spp_write_evt_param
#include <esp_spp_api.h> ESP_SPP_WRITE_EVT.
Public Members
esp_spp_status_t status
status
uint32_t handle
The connection handle
int len
The length of the data written.
bool cong
congestion status
Macros
ESP_SPP_SEC_NONE
No security. relate to BTA_SEC_NONE in bta/bta_api.h
ESP_SPP_SEC_AUTHORIZE
Authorization required (only needed for out going connection ) relate to BTA_SEC_AUTHORIZE in
bta/bta_api.h
ESP_SPP_SEC_AUTHENTICATE
Authentication required. relate to BTA_SEC_AUTHENTICATE in bta/bta_api.h
ESP_SPP_SEC_ENCRYPT
Encryption required. relate to BTA_SEC_ENCRYPT in bta/bta_api.h
ESP_SPP_SEC_MODE4_LEVEL4
Mode 4 level 4 service, i.e. incoming/outgoing MITM and P-256 encryption relate to
BTA_SEC_MODE4_LEVEL4 in bta/bta_api.h
ESP_SPP_SEC_MITM
Man-In-The_Middle protection relate to BTA_SEC_MITM in bta/bta_api.h
ESP_SPP_SEC_IN_16_DIGITS
Min 16 digit for pin code relate to BTA_SEC_IN_16_DIGITS in bta/bta_api.h
ESP_SPP_MAX_MTU
SPP max MTU
ESP_SPP_MAX_SCN
SPP max SCN
Type Definitions
Enumerations
enum esp_spp_status_t
Values:
enumerator ESP_SPP_SUCCESS
Successful operation.
enumerator ESP_SPP_FAILURE
Generic failure.
enumerator ESP_SPP_BUSY
Temporarily can not handle this request.
enumerator ESP_SPP_NO_DATA
No data
enumerator ESP_SPP_NO_RESOURCE
No more resource
enumerator ESP_SPP_NEED_INIT
SPP module shall init first
enumerator ESP_SPP_NEED_DEINIT
SPP module shall deinit first
enumerator ESP_SPP_NO_CONNECTION
Connection may have been closed
enumerator ESP_SPP_NO_SERVER
No SPP server
enum esp_spp_role_t
Values:
enumerator ESP_SPP_ROLE_MASTER
Role: master
enumerator ESP_SPP_ROLE_SLAVE
Role: slave
enum esp_spp_mode_t
Values:
enumerator ESP_SPP_MODE_CB
When data is coming, a callback will come with data
enumerator ESP_SPP_MODE_VFS
Use VFS to write/read data
enum esp_spp_cb_event_t
SPP callback function events.
Values:
enumerator ESP_SPP_INIT_EVT
When SPP is initialized, the event comes
enumerator ESP_SPP_UNINIT_EVT
When SPP is deinitialized, the event comes
enumerator ESP_SPP_DISCOVERY_COMP_EVT
When SDP discovery complete, the event comes
enumerator ESP_SPP_OPEN_EVT
When SPP Client connection open, the event comes
enumerator ESP_SPP_CLOSE_EVT
When SPP connection closed, the event comes
enumerator ESP_SPP_START_EVT
When SPP server started, the event comes
enumerator ESP_SPP_CL_INIT_EVT
When SPP client initiated a connection, the event comes
enumerator ESP_SPP_DATA_IND_EVT
When SPP connection received data, the event comes, only for ESP_SPP_MODE_CB
enumerator ESP_SPP_CONG_EVT
When SPP connection congestion status changed, the event comes, only for ESP_SPP_MODE_CB
enumerator ESP_SPP_WRITE_EVT
When SPP write operation completes, the event comes, only for ESP_SPP_MODE_CB
enumerator ESP_SPP_SRV_OPEN_EVT
When SPP Server connection open, the event comes
enumerator ESP_SPP_SRV_STOP_EVT
When SPP server stopped, the event comes
HFP DEFINES
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_hf_defs.h
Macros
ESP_BT_HF_NUMBER_LEN
ESP_BT_HF_OPERATOR_NAME_LEN
BTC_HSAG_SERVICE_NAME
BTC_HFAG_SERVICE_NAME
BTC_HF_SERVICES
BTC_HF_SERVICE_NAMES
BTC_HF_SECURITY
BTC_HF_CALL_END_TIMEOUT
BTC_HF_INVALID_IDX
Type Definitions
typedef void (*esp_hf_connection_state_callback)(esp_hf_connection_state_t state, esp_bd_addr_t
*bd_addr)
Callback for connection state change. state will have one of the values from BtHfConnectionState
Enumerations
enum esp_hf_in_band_ring_state_t
in-band ring tone state
Values:
enumerator ESP_HF_IN_BAND_RINGTONE_NOT_PROVIDED
enumerator ESP_HF_IN_BAND_RINGTONE_PROVIDED
enum esp_hf_vr_state_t
voice recognition state
Values:
enumerator ESP_HF_VR_STATE_DISABLED
voice recognition disabled
enumerator ESP_HF_VR_STATE_ENABLED
voice recognition enabled
enum esp_hf_volume_control_target_t
Bluetooth HFP audio volume control target.
Values:
enumerator ESP_HF_VOLUME_CONTROL_TARGET_SPK
speaker
enumerator ESP_HF_VOLUME_CONTROL_TARGET_MIC
microphone
enum esp_hf_audio_state_t
Bluetooth HFP audio connection status.
Values:
enumerator ESP_HF_AUDIO_STATE_DISCONNECTED
audio connection released
enumerator ESP_HF_AUDIO_STATE_CONNECTING
audio connection has been initiated
enumerator ESP_HF_AUDIO_STATE_CONNECTED
audio connection is established
enumerator ESP_HF_AUDIO_STATE_CONNECTED_MSBC
mSBC audio connection is established
enum esp_hf_volume_type_t
Values:
enumerator ESP_HF_VOLUME_TYPE_SPK
enumerator ESP_HF_VOLUME_TYPE_MIC
enum esp_hf_network_state_t
+CIND network service availability status
Values:
enumerator ESP_HF_NETWORK_STATE_NOT_AVAILABLE
enumerator ESP_HF_NETWORK_STATE_AVAILABLE
enum esp_hf_service_type_t
+CIEV Service type
Values:
enumerator ESP_HF_SERVICE_TYPE_HOME
enumerator ESP_HF_SERVICE_TYPE_ROAMING
enum esp_hf_call_status_t
+CIND call status indicator values
Values:
enumerator ESP_HF_CALL_STATUS_NO_CALLS
no call in progress
enumerator ESP_HF_CALL_STATUS_CALL_IN_PROGRESS
call is present(active or held)
enum esp_hf_call_setup_status_t
+CIND call setup status indicator values
Values:
enumerator ESP_HF_CALL_SETUP_STATUS_IDLE
no call setup in progress
enumerator ESP_HF_CALL_SETUP_STATUS_INCOMING
incoming call setup in progress
enumerator ESP_HF_CALL_SETUP_STATUS_OUTGOING_DIALING
outgoing call setup in dialing state
enumerator ESP_HF_CALL_SETUP_STATUS_OUTGOING_ALERTING
outgoing call setup in alerting state
enum esp_hf_roaming_status_t
+CIND roaming status indicator values
Values:
enumerator ESP_HF_ROAMING_STATUS_INACTIVE
roaming is not active
enumerator ESP_HF_ROAMING_STATUS_ACTIVE
a roaming is active
enum esp_hf_call_held_status_t
+CIND call held indicator values
Values:
enumerator ESP_HF_CALL_HELD_STATUS_NONE
no calls held
enumerator ESP_HF_CALL_HELD_STATUS_HELD_AND_ACTIVE
both active and held call
enumerator ESP_HF_CALL_HELD_STATUS_HELD
call on hold, no active call
enum esp_hf_current_call_status_t
+CLCC status of the call
Values:
enumerator ESP_HF_CURRENT_CALL_STATUS_ACTIVE
active
enumerator ESP_HF_CURRENT_CALL_STATUS_HELD
held
enumerator ESP_HF_CURRENT_CALL_STATUS_DIALING
dialing (outgoing calls only)
enumerator ESP_HF_CURRENT_CALL_STATUS_ALERTING
alerting (outgoing calls only)
enumerator ESP_HF_CURRENT_CALL_STATUS_INCOMING
incoming (incoming calls only)
enumerator ESP_HF_CURRENT_CALL_STATUS_WAITING
waiting (incoming calls only)
enumerator ESP_HF_CURRENT_CALL_STATUS_HELD_BY_RESP_HOLD
call held by response and hold
enum esp_hf_current_call_direction_t
+CLCC direction of the call
Values:
enumerator ESP_HF_CURRENT_CALL_DIRECTION_OUTGOING
outgoing
enumerator ESP_HF_CURRENT_CALL_DIRECTION_INCOMING
incoming
enum esp_hf_current_call_mpty_type_t
+CLCC multi-party call flag
Values:
enumerator ESP_HF_CURRENT_CALL_MPTY_TYPE_SINGLE
not a member of a multi-party call
enumerator ESP_HF_CURRENT_CALL_MPTY_TYPE_MULTI
member of a multi-party call
enum esp_hf_current_call_mode_t
+CLCC call mode
Values:
enumerator ESP_HF_CURRENT_CALL_MODE_VOICE
enumerator ESP_HF_CURRENT_CALL_MODE_DATA
enumerator ESP_HF_CURRENT_CALL_MODE_FAX
enum esp_hf_call_addr_type_t
+CLCC address type
Values:
enumerator ESP_HF_CALL_ADDR_TYPE_UNKNOWN
unkown address type
enumerator ESP_HF_CALL_ADDR_TYPE_INTERNATIONAL
international address
enum esp_hf_subscriber_service_type_t
+CNUM service type of the phone number
Values:
enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_UNKNOWN
unknown
enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_VOICE
voice service
enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_FAX
fax service
enum esp_hf_btrh_status_t
+BTRH response and hold result code
Values:
enumerator ESP_HF_BTRH_STATUS_HELD
incoming call is put on held in AG
enumerator ESP_HF_BTRH_STATUS_ACCEPTED
held incoming call is accepted in AG
enumerator ESP_HF_BTRH_STATUS_REJECTED
held incoming call is rejected in AG
enum esp_hf_btrh_cmd_t
AT+BTRH response and hold action code.
Values:
enumerator ESP_HF_BTRH_CMD_HOLD
put the incoming call on hold
enumerator ESP_HF_BTRH_CMD_ACCEPT
accept a held incoming call
enumerator ESP_HF_BTRH_CMD_REJECT
reject a held incoming call
enum esp_hf_nrec_t
Values:
enumerator ESP_HF_NREC_STOP
enumerator ESP_HF_NREC_START
enum esp_hf_call_waiting_status_t
+CCWA resposne status
Values:
enumerator ESP_HF_CALL_WAITING_INACTIVE
enumerator ESP_HF_CALL_WAITING_ACTIVE
enum esp_hf_wbs_config_t
Values:
enumerator ESP_HF_WBS_NONE
enumerator ESP_HF_WBS_NO
enumerator ESP_HF_WBS_YES
enum esp_hf_connection_state_t
Bluetooth HFP RFCOMM connection and service level connection status.
Values:
enumerator ESP_HF_CONNECTION_STATE_DISCONNECTED
RFCOMM data link channel released
enumerator ESP_HF_CONNECTION_STATE_CONNECTING
connecting remote device on the RFCOMM data link
enumerator ESP_HF_CONNECTION_STATE_CONNECTED
RFCOMM connection established
enumerator ESP_HF_CONNECTION_STATE_SLC_CONNECTED
service level connection established
enumerator ESP_HF_CONNECTION_STATE_DISCONNECTING
disconnecting with remote device on the RFCOMM data link
enum esp_hf_chld_type_t
AT+CHLD command values.
Values:
enumerator ESP_HF_CHLD_TYPE_REL
<0>, Terminate all held or set UDUB(“busy”) to a waiting call
enumerator ESP_HF_CHLD_TYPE_REL_ACC
<1>, Terminate all active calls and accepts a waiting/held call
enumerator ESP_HF_CHLD_TYPE_HOLD_ACC
<2>, Hold all active calls and accepts a waiting/held call
enumerator ESP_HF_CHLD_TYPE_MERGE
<3>, Add all held calls to a conference
enumerator ESP_HF_CHLD_TYPE_MERGE_DETACH
<4>, connect the two calls and disconnects the subscriber from both calls
enumerator ESP_HF_CHLD_TYPE_REL_X
<1x>, releases specified calls only
enumerator ESP_HF_CHLD_TYPE_PRIV_X
<2x>, request private consultation mode with specified call
enum esp_hf_at_response_code_t
Values:
enumerator ESP_HF_AT_RESPONSE_CODE_OK
acknowledges execution of a command line
enumerator ESP_HF_AT_RESPONSE_CODE_ERR
command not accepted
enumerator ESP_HF_AT_RESPONSE_CODE_NO_CARRIER
connection terminated
enumerator ESP_HF_AT_RESPONSE_CODE_BUSY
busy signal detected
enumerator ESP_HF_AT_RESPONSE_CODE_NO_ANSWER
connection completion timeout
enumerator ESP_HF_AT_RESPONSE_CODE_DELAYED
delayed
enumerator ESP_HF_AT_RESPONSE_CODE_BLACKLISTED
blacklisted
enumerator ESP_HF_AT_RESPONSE_CODE_CME
CME error
enum esp_hf_at_response_t
Values:
enumerator ESP_HF_AT_RESPONSE_ERROR
enumerator ESP_HF_AT_RESPONSE_OK
enum esp_hf_cme_err_t
Extended Audio Gateway Error Result Code Response.
Values:
enumerator ESP_HF_CME_AG_FAILURE
ag failure
enumerator ESP_HF_CME_NO_CONNECTION_TO_PHONE
no connection to phone
enumerator ESP_HF_CME_OPERATION_NOT_ALLOWED
operation not allowed
enumerator ESP_HF_CME_OPERATION_NOT_SUPPORTED
operation not supported
enumerator ESP_HF_CME_PH_SIM_PIN_REQUIRED
PH-SIM PIN Required
enumerator ESP_HF_CME_SIM_NOT_INSERTED
SIM not inserted
enumerator ESP_HF_CME_SIM_PIN_REQUIRED
SIM PIN required
enumerator ESP_HF_CME_SIM_PUK_REQUIRED
SIM PUK required
enumerator ESP_HF_CME_SIM_FAILURE
SIM failure
enumerator ESP_HF_CME_SIM_BUSY
SIM busy
enumerator ESP_HF_CME_INCORRECT_PASSWORD
incorrect password
enumerator ESP_HF_CME_SIM_PIN2_REQUIRED
SIM PIN2 required
enumerator ESP_HF_CME_SIM_PUK2_REQUIRED
SIM PUK2 required
enumerator ESP_HF_CME_MEMORY_FULL
memory full
enumerator ESP_HF_CME_INVALID_INDEX
invalid index
enumerator ESP_HF_CME_MEMORY_FAILURE
memory failure
enumerator ESP_HF_CME_TEXT_STRING_TOO_LONG
test string too long
enumerator ESP_HF_CME_INVALID_CHARACTERS_IN_TEXT_STRING
invalid characters in text string
enumerator ESP_HF_CME_DIAL_STRING_TOO_LONG
dial string too long
enumerator ESP_HF_CME_INVALID_CHARACTERS_IN_DIAL_STRING
invalid characters in dial string
enumerator ESP_HF_CME_NO_NETWORK_SERVICE
no network service
enumerator ESP_HF_CME_NETWORK_TIMEOUT
network timeout
enumerator ESP_HF_CME_NETWORK_NOT_ALLOWED
network not allowed —emergency calls only
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_hf_client_api.h
Functions
esp_err_t esp_hf_client_register_callback(esp_hf_client_cb_t callback)
Register application callback function to HFP client module. This function should be called only after
esp_bluedroid_enable() completes successfully.
Parameters callback –[in] HFP client event callback function
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: if callback is a NULL function pointer
esp_err_t esp_hf_client_init(void)
Initialize the bluetooth HFP client module. This function should be called after esp_bluedroid_enable() com-
pletes successfully.
Returns
• ESP_OK: if the initialization request is sent successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_deinit(void)
De-initialize for HFP client module. This function should be called only after esp_bluedroid_enable() com-
pletes successfully.
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_connect(esp_bd_addr_t remote_bda)
Establish a Service Level Connection to remote bluetooth HFP audio gateway(AG) device. This function must
be called after esp_hf_client_init() and before esp_hf_client_deinit().
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: connect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_disconnect(esp_bd_addr_t remote_bda)
Disconnect from the remote HFP audio gateway. This function must be called after esp_hf_client_init() and
before esp_hf_client_deinit().
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_connect_audio(esp_bd_addr_t remote_bda)
Create audio connection with remote HFP AG. As a precondition to use this API, Service Level Connection
shall exist with AG.
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_disconnect_audio(esp_bd_addr_t remote_bda)
Release the established audio connection with remote HFP AG. As a precondition to use this API, Service
Level Connection shall exist with AG.
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_start_voice_recognition(void)
Enable voice recognition in the AG. As a precondition to use this API, Service Level Connection shall exist
with AG.
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_stop_voice_recognition(void)
Disable voice recognition in the AG. As a precondition to use this API, Service Level Connection shall exist
with AG.
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_volume_update(esp_hf_volume_control_target_t type, int volume)
Volume synchronization with AG. As a precondition to use this API, Service Level Connection shall exist with
AG.
Parameters
• type –[in] volume control target, speaker or microphone
• volume –[in] gain of the speaker of microphone, ranges 0 to 15
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_dial(const char *number)
Place a call with a specified number, if number is NULL, last called number is called. As a precondition to
use this API, Service Level Connection shall exist with AG.
Parameters number –[in] number string of the call. If NULL, the last number is called(aka
re-dial)
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_dial_memory(int location)
Place a call with number specified by location(speed dial). As a precondition to use this API, Service Level
Connection shall exist with AG.
Parameters location –[in] location of the number in the memory
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_send_chld_cmd(esp_hf_chld_type_t chld, int idx)
Send call hold and multiparty commands, or enhanced call control commands(Use AT+CHLD). As a precon-
dition to use this API, Service Level Connection shall exist with AG.
Parameters
• chld –[in] AT+CHLD call hold and multiparty handling AT command.
Unions
union esp_hf_client_cb_param_t
#include <esp_hf_client_api.h> HFP client callback parameters.
Public Members
struct hf_client_at_response_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_AT_RESPONSE_EVT.
Public Members
esp_hf_at_response_code_t code
AT response code
esp_hf_cme_err_t cme
Extended Audio Gateway Error Result Code
struct hf_client_audio_stat_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_AUDIO_STATE_EVT.
Public Members
esp_hf_client_audio_state_t state
audio connection state
esp_bd_addr_t remote_bda
remote bluetooth device address
struct hf_client_battery_level_ind_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT.
Public Members
int value
battery charge value, ranges from 0 to 5
struct hf_client_binp_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_BINP_EVT.
Public Members
struct hf_client_bsirparam
#include <esp_hf_client_api.h> ESP_HF_CLIENT_BSIR_EVT.
Public Members
esp_hf_client_in_band_ring_state_t state
setting state of in-band ring tone
struct hf_client_btrh_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_BTRH_EVT.
Public Members
esp_hf_btrh_status_t status
call hold and response status result code
struct hf_client_bvra_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_BVRA_EVT.
Public Members
esp_hf_vr_state_t value
voice recognition state
struct hf_client_call_held_ind_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_HELD_EVT.
Public Members
esp_hf_call_held_status_t status
bluetooth proprietary call hold status indicator
struct hf_client_call_ind_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_EVT.
Public Members
esp_hf_call_status_t status
call status indicator
struct hf_client_call_setup_ind_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_SETUP_EVT.
Public Members
esp_hf_call_setup_status_t status
call setup status indicator
struct hf_client_ccwa_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CCWA_EVT.
Public Members
struct hf_client_clcc_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CLCC_EVT.
Public Members
int idx
numbering(starting with 1) of the call
esp_hf_current_call_direction_t dir
direction of the call
esp_hf_current_call_status_t status
status of the call
esp_hf_current_call_mpty_type_t mpty
multi-party flag
char *number
phone number(optional)
struct hf_client_clip_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CLIP_EVT.
Public Members
struct hf_client_cnum_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CNUM_EVT.
Public Members
esp_hf_subscriber_service_type_t type
service type that the phone number relates to
struct hf_client_conn_stat_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CONNECTION_STATE_EVT.
Public Members
esp_hf_client_connection_state_t state
HF connection state
uint32_t peer_feat
AG supported features
uint32_t chld_feat
AG supported features on call hold and multiparty services
esp_bd_addr_t remote_bda
remote bluetooth device address
struct hf_client_current_operator_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT.
Public Members
struct hf_client_network_roaming_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT.
Public Members
esp_hf_roaming_status_t status
roaming status
struct hf_client_service_availability_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT.
Public Members
esp_hf_network_state_t status
service availability status
struct hf_client_signal_strength_ind_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT.
Public Members
int value
signal strength value, ranges from 0 to 5
struct hf_client_volume_control_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_VOLUME_CONTROL_EVT.
Public Members
esp_hf_volume_control_target_t type
volume control target, speaker or microphone
int volume
gain, ranges from 0 to 15
Macros
ESP_BT_HF_CLIENT_NUMBER_LEN
ESP_BT_HF_CLIENT_OPERATOR_NAME_LEN
ESP_BT_HF_AT_SEND_XAPL_LEN
ESP_HF_CLIENT_PEER_FEAT_3WAY
ESP_HF_CLIENT_PEER_FEAT_ECNR
ESP_HF_CLIENT_PEER_FEAT_VREC
ESP_HF_CLIENT_PEER_FEAT_INBAND
ESP_HF_CLIENT_PEER_FEAT_VTAG
ESP_HF_CLIENT_PEER_FEAT_REJECT
ESP_HF_CLIENT_PEER_FEAT_ECS
ESP_HF_CLIENT_PEER_FEAT_ECC
ESP_HF_CLIENT_PEER_FEAT_EXTERR
ESP_HF_CLIENT_PEER_FEAT_CODEC
ESP_HF_CLIENT_PEER_FEAT_HF_IND
ESP_HF_CLIENT_PEER_FEAT_ESCO_S4
ESP_HF_CLIENT_CHLD_FEAT_REL
ESP_HF_CLIENT_CHLD_FEAT_REL_ACC
ESP_HF_CLIENT_CHLD_FEAT_REL_X
ESP_HF_CLIENT_CHLD_FEAT_HOLD_ACC
ESP_HF_CLIENT_CHLD_FEAT_PRIV_X
ESP_HF_CLIENT_CHLD_FEAT_MERGE
ESP_HF_CLIENT_CHLD_FEAT_MERGE_DETACH
ESP_HF_CLIENT_XAPL_FEAT_RESERVED
ESP_HF_CLIENT_XAPL_FEAT_BATTERY_REPORT
ESP_HF_CLIENT_XAPL_FEAT_DOCKED
ESP_HF_CLIENT_XAPL_FEAT_SIRI_STATUS_REPORT
ESP_HF_CLIENT_XAPL_NR_STATUS_REPORT
Type Definitions
Enumerations
enum esp_hf_client_connection_state_t
Bluetooth HFP RFCOMM connection and service level connection status.
Values:
enumerator ESP_HF_CLIENT_CONNECTION_STATE_DISCONNECTED
RFCOMM data link channel released
enumerator ESP_HF_CLIENT_CONNECTION_STATE_CONNECTING
connecting remote device on the RFCOMM data link
enumerator ESP_HF_CLIENT_CONNECTION_STATE_CONNECTED
RFCOMM connection established
enumerator ESP_HF_CLIENT_CONNECTION_STATE_SLC_CONNECTED
service level connection established
enumerator ESP_HF_CLIENT_CONNECTION_STATE_DISCONNECTING
disconnecting with remote device on the RFCOMM dat link
enum esp_hf_client_audio_state_t
Bluetooth HFP audio connection status.
Values:
enumerator ESP_HF_CLIENT_AUDIO_STATE_DISCONNECTED
audio connection released
enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTING
audio connection has been initiated
enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTED
audio connection is established
enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTED_MSBC
mSBC audio connection is established
enum esp_hf_client_in_band_ring_state_t
in-band ring tone state
Values:
enumerator ESP_HF_CLIENT_IN_BAND_RINGTONE_NOT_PROVIDED
enumerator ESP_HF_CLIENT_IN_BAND_RINGTONE_PROVIDED
enum esp_hf_client_cb_event_t
HF CLIENT callback events.
Values:
enumerator ESP_HF_CLIENT_CONNECTION_STATE_EVT
connection state changed event
enumerator ESP_HF_CLIENT_AUDIO_STATE_EVT
audio connection state change event
enumerator ESP_HF_CLIENT_BVRA_EVT
voice recognition state change event
enumerator ESP_HF_CLIENT_CIND_CALL_EVT
call indication
enumerator ESP_HF_CLIENT_CIND_CALL_SETUP_EVT
call setup indication
enumerator ESP_HF_CLIENT_CIND_CALL_HELD_EVT
call held indication
enumerator ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT
network service availability indication
enumerator ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT
signal strength indication
enumerator ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT
roaming status indication
enumerator ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT
battery level indication
enumerator ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT
current operator information
enumerator ESP_HF_CLIENT_BTRH_EVT
call response and hold event
enumerator ESP_HF_CLIENT_CLIP_EVT
Calling Line Identification notification
enumerator ESP_HF_CLIENT_CCWA_EVT
call waiting notification
enumerator ESP_HF_CLIENT_CLCC_EVT
list of current calls notification
enumerator ESP_HF_CLIENT_VOLUME_CONTROL_EVT
audio volume control command from AG, provided by +VGM or +VGS message
enumerator ESP_HF_CLIENT_AT_RESPONSE_EVT
AT command response event
enumerator ESP_HF_CLIENT_CNUM_EVT
subscriber information response from AG
enumerator ESP_HF_CLIENT_BSIR_EVT
setting of in-band ring tone
enumerator ESP_HF_CLIENT_BINP_EVT
requested number of last voice tag from AG
enumerator ESP_HF_CLIENT_RING_IND_EVT
ring indication event
HFP AG API
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_hf_ag_api.h
Functions
esp_err_t esp_bt_hf_register_callback(esp_hf_cb_t callback)
Register application callback function to HFP AG module. This function should be called only after
esp_bluedroid_enable() completes successfully.
Parameters callback –[in] HFP AG event callback function
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: if callback is a NULL function pointer
esp_err_t esp_bt_hf_init(esp_bd_addr_t remote_addr)
Initialize the bluetooth HF AG module. This function should be called after esp_bluedroid_enable() completes
successfully.
Parameters remote_addr –[in] remote bluetooth device address
Returns
• ESP_OK: if the initialization request is sent successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_bt_hf_deinit(esp_bd_addr_t remote_addr)
De-initialize for HF AG module. This function should be called only after esp_bluedroid_enable() completes
successfully.
Parameters remote_addr –[in] remote bluetooth device address
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_bt_hf_connect(esp_bd_addr_t remote_bda)
To establish a Service Level Connection to remote bluetooth HFP client device. This function must be called
after esp_bt_hf_init() and before esp_bt_hf_deinit().
Parameters remote_bda –[in] remote bluetooth HFP client device address
Returns
• ESP_OK: connect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
Reponse for AT+COPS command from HF Client. As a precondition to use this API, Service Level Connection
shall exist with HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• name –[in] current operator name
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_bt_hf_clcc_response(esp_bd_addr_t remote_addr, int index,
esp_hf_current_call_direction_t dir, esp_hf_current_call_status_t
current_call_state, esp_hf_current_call_mode_t mode,
esp_hf_current_call_mpty_type_t mpty, char *number,
esp_hf_call_addr_type_t type)
Response to AT+CLCC command from HFP Client. As a precondition to use this API, Service Level Con-
nection shall exist with HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• index –[in] the index of current call
• dir –[in] call direction (incoming/outgoing)
• current_call_state –[in] current call state
• mode –[in] current call mode (voice/data/fax)
• mpty –[in] single or multi type
• number –[in] current call number
• type –[in] international type or unknow
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_bt_hf_cnum_response(esp_bd_addr_t remote_addr, char *number,
esp_hf_subscriber_service_type_t type)
Response for AT+CNUM command from HF Client. As a precondition to use this API, Service Level Con-
nection shall exist with HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• number –[in] registration number
• type –[in] service type (unknown/voice/fax)
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_bt_hf_bsir(esp_bd_addr_t remote_addr, esp_hf_in_band_ring_state_t state)
Inform HF Client that AG Provided in-band ring tone or not. As a precondition to use this API, Service Level
Connection shall exist with HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• state –[in] in-band ring tone state
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
End an ongoing call. As a precondition to use this API, Service Level Connection shall exist with HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• num_active –[in] the number of active call
• num_held –[in] the number of held call
• call_state –[in] call state
• call_setup_state –[in] call setup state
• number –[in] number of the call
• call_addr_type –[in] call address type
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_bt_hf_register_data_callback(esp_hf_incoming_data_cb_t recv,
esp_hf_outgoing_data_cb_t send)
Register AG data output function. The callback is only used in the case that Voice Over HCI is enabled.
Parameters
• recv –[in] HFP client incoming data callback function
• send –[in] HFP client outgoing data callback function
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: if callback is a NULL function pointer
void esp_hf_outgoing_data_ready(void)
Trigger the lower-layer to fetch and send audio data.
This function is only used in the case that Voice Over HCI is␣
,→ enabled.
As a precondition to use this API, Service Level Connection shall␣
,→exist with HFP client.
After this function is called, lower layer will invoke esp_hf_
,→client_outgoing_data_cb_t to fetch data
Unions
union esp_hf_cb_param_t
#include <esp_hf_ag_api.h> HFP AG callback parameters.
Public Members
struct hf_audio_stat_param
#include <esp_hf_ag_api.h> ESP_HF_AUDIO_STATE_EVT.
Public Members
esp_bd_addr_t remote_addr
Remote bluetooth device address
esp_hf_audio_state_t state
Audio connection state
struct hf_bcs_rep_param
#include <esp_hf_ag_api.h> ESP_HF_BCS_RESPONSE_EVT.
Public Members
esp_hf_wbs_config_t mode
codec mode CVSD or mSBC
struct hf_cind_param
#include <esp_hf_ag_api.h> ESP_HF_CIND_RESPONSE_EVT.
Public Members
esp_hf_call_status_t call_status
call status indicator
esp_hf_call_setup_status_t call_setup_status
call setup status indicator
esp_hf_network_state_t svc
bluetooth proprietary call hold status indicator
int signal_strength
bluetooth proprietary call hold status indicator
esp_hf_roaming_status_t roam
bluetooth proprietary call hold status indicator
int battery_level
battery charge value, ranges from 0 to 5
esp_hf_call_held_status_t call_held_status
bluetooth proprietary call hold status indicator
struct hf_conn_stat_param
#include <esp_hf_ag_api.h> ESP_HS_CONNECTION_STATE_EVT.
Public Members
esp_bd_addr_t remote_bda
Remote bluetooth device address
esp_hf_connection_state_t state
Connection state
uint32_t peer_feat
HF supported features
uint32_t chld_feat
AG supported features on call hold and multiparty services
struct hf_nrec_param
#include <esp_hf_ag_api.h> ESP_HF_NREC_RESPONSE_EVT.
Public Members
esp_hf_nrec_t state
NREC enabled or disabled
struct hf_out_call_param
#include <esp_hf_ag_api.h> ESP_HF_DIAL_EVT.
Public Members
esp_bd_addr_t remote_addr
remote bluetooth device address
char *num_or_loc
location in phone memory
struct hf_unat_rep_param
#include <esp_hf_ag_api.h> ESP_HF_UNAT_RESPONSE_EVT.
Public Members
char *unat
Unknown AT command string
struct hf_volume_control_param
#include <esp_hf_ag_api.h> ESP_HF_VOLUME_CONTROL_EVT.
Public Members
esp_hf_volume_type_t type
Volume control target, speaker or microphone
int volume
Gain, ranges from 0 to 15
struct hf_vra_rep_param
#include <esp_hf_ag_api.h> ESP_HF_BVRA_RESPONSE_EVT.
Public Members
esp_bd_addr_t remote_addr
Remote bluetooth device address
esp_hf_vr_state_t value
Voice recognition state
struct hf_vts_rep_param
#include <esp_hf_ag_api.h> ESP_HF_VTS_RESPONSE_EVT.
Public Members
char *code
MTF code from HF Client
struct hf_wbs_rep_param
#include <esp_hf_ag_api.h> ESP_HF_WBS_RESPONSE_EVT.
Public Members
esp_hf_wbs_config_t codec
codec mode CVSD or mSBC
Macros
ESP_HF_PEER_FEAT_3WAY
ESP_HF_PEER_FEAT_ECNR
ESP_HF_PEER_FEAT_VREC
ESP_HF_PEER_FEAT_INBAND
ESP_HF_PEER_FEAT_VTAG
ESP_HF_PEER_FEAT_REJECT
ESP_HF_PEER_FEAT_ECS
ESP_HF_PEER_FEAT_ECC
ESP_HF_PEER_FEAT_EXTERR
ESP_HF_PEER_FEAT_CODEC
ESP_HF_PEER_FEAT_HF_IND
ESP_HF_PEER_FEAT_ESCO_S4
ESP_HF_CHLD_FEAT_REL
ESP_HF_CHLD_FEAT_REL_ACC
ESP_HF_CHLD_FEAT_REL_X
ESP_HF_CHLD_FEAT_HOLD_ACC
ESP_HF_CHLD_FEAT_PRIV_X
ESP_HF_CHLD_FEAT_MERGE
ESP_HF_CHLD_FEAT_MERGE_DETACH
Type Definitions
Enumerations
enum esp_hf_cb_event_t
HF callback events.
Values:
enumerator ESP_HF_CONNECTION_STATE_EVT
Connection state changed event
enumerator ESP_HF_AUDIO_STATE_EVT
Audio connection state change event
enumerator ESP_HF_BVRA_RESPONSE_EVT
Voice recognition state change event
enumerator ESP_HF_VOLUME_CONTROL_EVT
Audio volume control command from HF Client, provided by +VGM or +VGS message
enumerator ESP_HF_UNAT_RESPONSE_EVT
Unknown AT cmd Response
enumerator ESP_HF_IND_UPDATE_EVT
Indicator Update Event
enumerator ESP_HF_CIND_RESPONSE_EVT
Call And Device Indicator Response
enumerator ESP_HF_COPS_RESPONSE_EVT
Current operator information
enumerator ESP_HF_CLCC_RESPONSE_EVT
List of current calls notification
enumerator ESP_HF_CNUM_RESPONSE_EVT
Subscriber information response from HF Client
enumerator ESP_HF_VTS_RESPONSE_EVT
Enable or not DTMF
enumerator ESP_HF_NREC_RESPONSE_EVT
Enable or not NREC
enumerator ESP_HF_ATA_RESPONSE_EVT
Answer an Incoming Call
enumerator ESP_HF_CHUP_RESPONSE_EVT
Reject an Incoming Call
enumerator ESP_HF_DIAL_EVT
Origin an outgoing call with specific number or the dial the last number
enumerator ESP_HF_WBS_RESPONSE_EVT
Codec Status
enumerator ESP_HF_BCS_RESPONSE_EVT
Final Codec Choice
Overview A Bluetooth HID device is a device providing the service of human or other data input and output to and
from a Bluetooth HID Host. Users can use the Bluetooth HID Device APIs to make devices like keyboards, mice,
joysticks and so on.
Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the fol-
lowing application:
• This is an example of Bluetooth HID mouse device. The device running this example can be discovered and
connected by a Bluetooth HID Host device such as a PC, and the pointer will move left and right after HID
connection is established - bluetooth/bluedroid/classic_bt/bt_hid_mouse_device
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_hidd_api.h
Functions
esp_err_t esp_bt_hid_device_register_callback(esp_hd_cb_t callback)
This function is called to init callbacks with HID device module.
Parameters callback –[in] pointer to the init callback function.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_init(void)
This function initializes HIDD. This function should be called after esp_bluedroid_enable and
esp_bluedroid_init success, and should be called after esp_bt_hid_device_register_callback. When the op-
eration is complete the callback function will be called with ESP_HIDD_INIT_EVT.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_deinit(void)
This function de-initializes HIDD interface. This function should be called after esp_bluedroid_enable() and
esp_bluedroid_init() success, and should be called after esp_bt_hid_device_init(). When the operation is com-
plete the callback function will be called with ESP_HIDD_DEINIT_EVT.
Returns - ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_register_app(esp_hidd_app_param_t *app_param,
esp_hidd_qos_param_t *in_qos, esp_hidd_qos_param_t
*out_qos)
Registers HIDD parameters with SDP and sets l2cap Quality of Service. This function should be called after
esp_bluedroid_enable and esp_bluedroid_init success, and must be done after esp_bt_hid_device_init. When
the operation is complete the callback function will be called with ESP_HIDD_REGISTER_APP_EVT.
Parameters
• app_param –[in] HIDD parameters
• in_qos –[in] incoming QoS parameters
• out_qos –[in] outgoing QoS parameters
Returns - ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_unregister_app(void)
Removes HIDD parameters from SDP and resets l2cap Quality of Service. This function should
be called after esp_bluedroid_enable and esp_bluedroid_init success, and should be called after
esp_bt_hid_device_init. When the operation is complete the callback function will be called with
ESP_HIDD_UNREGISTER_APP_EVT.
Returns - ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_connect(esp_bd_addr_t bd_addr)
This function connects HIDD interface to connected bluetooth device, if not done already. When the operation
is complete the callback function will be called with ESP_HIDD_OPEN_EVT.
Parameters bd_addr –[in] Remote host bluetooth device address.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_disconnect(void)
This function disconnects HIDD interface. When the operation is complete the callback function will be called
with ESP_HIDD_CLOSE_EVT.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_send_report(esp_hidd_report_type_t type, uint8_t id, uint16_t len,
uint8_t *data)
Send HIDD report. When the operation is complete the callback function will be called with
ESP_HIDD_SEND_REPORT_EVT.
Parameters
• type –[in] type of report
• id –[in] report id as defined by descriptor
• len –[in] length of report
• data –[in] report data
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_report_error(esp_hidd_handshake_error_t error)
Sends HIDD handshake with error info for invalid set_report. When the operation is complete the callback
function will be called with ESP_HIDD_REPORT_ERR_EVT.
Parameters error –[in] type of error
Returns - ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_virtual_cable_unplug(void)
Unplug virtual cable of HIDD. When the operation is complete the callback function will be called with
ESP_HIDD_VC_UNPLUG_EVT.
Returns - ESP_OK: success
• other: failed
Unions
union esp_hidd_cb_param_t
#include <esp_hidd_api.h> HID device callback parameters union.
Public Members
struct hidd_close_evt_param
#include <esp_hidd_api.h> ESP_HIDD_CLOSE_EVT.
Public Members
esp_hidd_status_t status
operation status
esp_hidd_connection_state_t conn_status
connection status
struct hidd_deinit_evt_param
#include <esp_hidd_api.h> ESP_HIDD_DEINIT_EVT.
Public Members
esp_hidd_status_t status
operation status
struct hidd_get_report_evt_param
#include <esp_hidd_api.h> ESP_HIDD_GET_REPORT_EVT.
Public Members
esp_hidd_report_type_t report_type
report type
uint8_t report_id
report id
uint16_t buffer_size
buffer size
struct hidd_init_evt_param
#include <esp_hidd_api.h> ESP_HIDD_INIT_EVT.
Public Members
esp_hidd_status_t status
operation status
struct hidd_intr_data_evt_param
#include <esp_hidd_api.h> ESP_HIDD_INTR_DATA_EVT.
Public Members
uint8_t report_id
interrupt channel report id
uint16_t len
interrupt channel report data length
uint8_t *data
interrupt channel report data pointer
struct hidd_open_evt_param
#include <esp_hidd_api.h> ESP_HIDD_OPEN_EVT.
Public Members
esp_hidd_status_t status
operation status
esp_hidd_connection_state_t conn_status
connection status
esp_bd_addr_t bd_addr
host address
struct hidd_register_app_evt_param
#include <esp_hidd_api.h> ESP_HIDD_REGISTER_APP_EVT.
Public Members
esp_hidd_status_t status
operation status
bool in_use
indicate whether use virtual cable plug host address
esp_bd_addr_t bd_addr
host address
struct hidd_report_err_evt_param
#include <esp_hidd_api.h> ESP_HIDD_REPORT_ERR_EVT.
Public Members
esp_hidd_status_t status
operation status
uint8_t reason
lower layer failed reason(ref hiddefs.h)
struct hidd_send_report_evt_param
#include <esp_hidd_api.h> ESP_HIDD_SEND_REPORT_EVT.
Public Members
esp_hidd_status_t status
operation status
uint8_t reason
lower layer failed reason(ref hiddefs.h)
esp_hidd_report_type_t report_type
report type
uint8_t report_id
report id
struct hidd_set_protocol_evt_param
#include <esp_hidd_api.h> ESP_HIDD_SET_PROTOCOL_EVT.
Public Members
esp_hidd_protocol_mode_t protocol_mode
protocol mode
struct hidd_set_report_evt_param
#include <esp_hidd_api.h> ESP_HIDD_SET_REPORT_EVT.
Public Members
esp_hidd_report_type_t report_type
report type
uint8_t report_id
report id
uint16_t len
set_report data length
uint8_t *data
set_report data pointer
struct hidd_unregister_app_evt_param
#include <esp_hidd_api.h> ESP_HIDD_UNREGISTER_APP_EVT.
Public Members
esp_hidd_status_t status
operation status
struct hidd_vc_unplug_param
#include <esp_hidd_api.h> ESP_HIDD_VC_UNPLUG_EVT.
Public Members
esp_hidd_status_t status
operation status
esp_hidd_connection_state_t conn_status
connection status
Structures
struct esp_hidd_app_param_t
HID device characteristics for SDP server.
Public Members
uint8_t subclass
HID device subclass
uint8_t *desc_list
HID descriptor list
int desc_list_len
size in bytes of HID descriptor list
struct esp_hidd_qos_param_t
HIDD Quality of Service parameters negotiated over L2CAP.
Public Members
uint8_t service_type
the level of service, 0 indicates no traffic
uint32_t token_rate
token rate in bytes per second, 0 indicates “don’t care”
uint32_t token_bucket_size
limit on the burstness of the application data
uint32_t peak_bandwidth
bytes per second, value 0 indicates “don’t care”
uint32_t access_latency
maximum acceptable delay in microseconds
uint32_t delay_variation
the difference in microseconds between the max and min delay
Macros
ESP_HID_CLASS_UNKNOWN
subclass of hid device
unknown HID device subclass
ESP_HID_CLASS_JOS
joystick
ESP_HID_CLASS_GPD
game pad
ESP_HID_CLASS_RMC
remote control
ESP_HID_CLASS_SED
sensing device
ESP_HID_CLASS_DGT
digitizer tablet
ESP_HID_CLASS_CDR
card reader
ESP_HID_CLASS_KBD
keyboard
ESP_HID_CLASS_MIC
pointing device
ESP_HID_CLASS_COM
combo keyboard/pointing
Type Definitions
Enumerations
enum esp_hidd_handshake_error_t
HIDD handshake result code.
Values:
enumerator ESP_HID_PAR_HANDSHAKE_RSP_SUCCESS
successful
enumerator ESP_HID_PAR_HANDSHAKE_RSP_NOT_READY
not ready, device is too busy to accept data
enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_INVALID_REP_ID
invalid report ID
enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_UNSUPPORTED_REQ
device does not support the request
enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_INVALID_PARAM
parameter value is out of range or inappropriate
enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_UNKNOWN
device could not identify the error condition
enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_FATAL
restart is essential to resume functionality
enum esp_hidd_report_type_t
HIDD report types.
Values:
enumerator ESP_HIDD_REPORT_TYPE_OTHER
unknown report type
enumerator ESP_HIDD_REPORT_TYPE_INPUT
input report
enumerator ESP_HIDD_REPORT_TYPE_OUTPUT
output report
enumerator ESP_HIDD_REPORT_TYPE_FEATURE
feature report
enumerator ESP_HIDD_REPORT_TYPE_INTRDATA
special value for reports to be sent on interrupt channel, INPUT is assumed
enum esp_hidd_connection_state_t
HIDD connection state.
Values:
enumerator ESP_HIDD_CONN_STATE_CONNECTED
HID connection established
enumerator ESP_HIDD_CONN_STATE_CONNECTING
connection to remote Bluetooth device
enumerator ESP_HIDD_CONN_STATE_DISCONNECTED
connection released
enumerator ESP_HIDD_CONN_STATE_DISCONNECTING
disconnecting to remote Bluetooth device
enumerator ESP_HIDD_CONN_STATE_UNKNOWN
unknown connection state
enum esp_hidd_protocol_mode_t
HID device protocol modes.
Values:
enumerator ESP_HIDD_REPORT_MODE
Report Protocol Mode
enumerator ESP_HIDD_BOOT_MODE
Boot Protocol Mode
enumerator ESP_HIDD_UNSUPPORTED_MODE
unsupported
enum esp_hidd_boot_report_id_t
HID Boot Protocol report IDs.
Values:
enumerator ESP_HIDD_BOOT_REPORT_ID_KEYBOARD
report ID of Boot Protocol keyboard report
enumerator ESP_HIDD_BOOT_REPORT_ID_MOUSE
report ID of Boot Protocol mouse report
enum [anonymous]
HID Boot Protocol report size including report ID.
Values:
enumerator ESP_HIDD_BOOT_REPORT_SIZE_KEYBOARD
report size of Boot Protocol keyboard report
enumerator ESP_HIDD_BOOT_REPORT_SIZE_MOUSE
report size of Boot Protocol mouse report
enum esp_hidd_cb_event_t
HID device callback function events.
Values:
enumerator ESP_HIDD_INIT_EVT
When HID device is initialized, the event comes
enumerator ESP_HIDD_DEINIT_EVT
When HID device is deinitialized, the event comes
enumerator ESP_HIDD_REGISTER_APP_EVT
When HID device application registered, the event comes
enumerator ESP_HIDD_UNREGISTER_APP_EVT
When HID device application unregistered, the event comes
enumerator ESP_HIDD_OPEN_EVT
When HID device connection to host opened, the event comes
enumerator ESP_HIDD_CLOSE_EVT
When HID device connection to host closed, the event comes
enumerator ESP_HIDD_SEND_REPORT_EVT
When HID device send report to lower layer, the event comes
enumerator ESP_HIDD_REPORT_ERR_EVT
When HID device report handshanke error to lower layer, the event comes
enumerator ESP_HIDD_GET_REPORT_EVT
When HID device receives GET_REPORT request from host, the event comes
enumerator ESP_HIDD_SET_REPORT_EVT
When HID device receives SET_REPORT request from host, the event comes
enumerator ESP_HIDD_SET_PROTOCOL_EVT
When HID device receives SET_PROTOCOL request from host, the event comes
enumerator ESP_HIDD_INTR_DATA_EVT
When HID device receives DATA from host on intr, the event comes
enumerator ESP_HIDD_VC_UNPLUG_EVT
When HID device initiates Virtual Cable Unplug, the event comes
enumerator ESP_HIDD_API_ERR_EVT
When HID device has API error, the event comes
enum esp_hidd_status_t
Values:
enumerator ESP_HIDD_SUCCESS
enumerator ESP_HIDD_ERROR
general ESP HD error
enumerator ESP_HIDD_NO_RES
out of system resources
enumerator ESP_HIDD_BUSY
Temporarily can not handle this request.
enumerator ESP_HIDD_NO_DATA
No data.
enumerator ESP_HIDD_NEED_INIT
HIDD module shall init first
enumerator ESP_HIDD_NEED_DEINIT
HIDD module shall deinit first
enumerator ESP_HIDD_NEED_REG
HIDD module shall register first
enumerator ESP_HIDD_NEED_DEREG
HIDD module shall deregister first
enumerator ESP_HIDD_NO_CONNECTION
connection may have been closed
Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the fol-
lowing application:
• This is a BT_L2CAP demo. This demo can connect, send and receive L2CAP data blue-
tooth/bluedroid/classic_bt/bt_l2cap_client, bluetooth/bluedroid/classic_bt/bt_l2cap_server
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_l2cap_bt_api.h
Functions
esp_err_t esp_bt_l2cap_register_callback(esp_bt_l2cap_cb_t callback)
This function is called to init callbacks with L2CAP module.
Parameters callback –[in] pointer to the init callback function.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_l2cap_init(void)
This function is called to init L2CAP module. When the operation is completed, the callback function will be
called with ESP_BT_L2CAP_INIT_EVT. This function should be called after esp_bluedroid_enable() com-
pletes successfully.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_l2cap_deinit(void)
This function is called to uninit l2cap module. The operation will close all active L2CAP connection
first, then the callback function will be called with ESP_BT_L2CAP_CLOSE_EVT, and the number of
ESP_BT_L2CAP_CLOSE_EVT is equal to the number of connection. When the operation is completed,
the callback function will be called with ESP_BT_L2CAP_UNINIT_EVT. This function should be called
after esp_bt_l2cap_init() completes successfully.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_l2cap_vfs_unregister(void)
This function is used to unregister VFS. This function must be called after esp_bt_l2cap_init() successful and
before esp_bt_l2cap_deinit().
Returns
• ESP_OK: success
• other: failed
Unions
union esp_bt_l2cap_cb_param_t
#include <esp_l2cap_bt_api.h> L2CAP callback parameters union.
Public Members
struct l2cap_cl_init_evt_param
#include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_CL_INIT_EVT.
Public Members
esp_bt_l2cap_status_t status
status
uint32_t handle
The connection handle
uint8_t sec_id
security ID used by this server
struct l2cap_close_evt_param
#include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_CLOSE_EVT.
Public Members
esp_bt_l2cap_status_t status
status
uint32_t handle
The connection handle
bool async
FALSE, if local initiates disconnect
struct l2cap_init_evt_param
#include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_INIT_EVT.
Public Members
esp_bt_l2cap_status_t status
status
struct l2cap_open_evt_param
#include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_OPEN_EVT.
Public Members
esp_bt_l2cap_status_t status
status
uint32_t handle
The connection handle
int fd
File descriptor
esp_bd_addr_t rem_bda
The peer address
int32_t tx_mtu
The transmit MTU
struct l2cap_srv_stop_evt_param
#include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_SRV_STOP_EVT.
Public Members
esp_bt_l2cap_status_t status
status
uint8_t psm
local psm
struct l2cap_start_evt_param
#include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_START_EVT.
Public Members
esp_bt_l2cap_status_t status
status
uint32_t handle
The connection handle
uint8_t sec_id
security ID used by this server
struct l2cap_uninit_evt_param
#include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_UNINIT_EVT.
Public Members
esp_bt_l2cap_status_t status
status
Macros
ESP_BT_L2CAP_SEC_NONE
Security Setting Mask. Use these three mask mode:
a. ESP_BT_L2CAP_SEC_NONE
b. ESP_BT_L2CAP_SEC_AUTHENTICATE
c. (ESP_BT_L2CAP_SEC_ENCRYPT|ESP_BT_L2CAP_SEC_AUTHENTICATE) No security
ESP_BT_L2CAP_SEC_AUTHORIZE
Authorization required
ESP_BT_L2CAP_SEC_AUTHENTICATE
Authentication required
ESP_BT_L2CAP_SEC_ENCRYPT
Encryption required
Type Definitions
Enumerations
enum esp_bt_l2cap_status_t
L2CAP operation success and failure codes.
Values:
enumerator ESP_BT_L2CAP_SUCCESS
Successful operation.
enumerator ESP_BT_L2CAP_FAILURE
Generic failure.
enumerator ESP_BT_L2CAP_BUSY
Temporarily can not handle this request.
enumerator ESP_BT_L2CAP_NO_RESOURCE
No more resource
enumerator ESP_BT_L2CAP_NEED_INIT
L2CAP module shall init first
enumerator ESP_BT_L2CAP_NEED_DEINIT
L2CAP module shall deinit first
enumerator ESP_BT_L2CAP_NO_CONNECTION
Connection may have been closed
enumerator ESP_BT_L2CAP_NO_SERVER
No server
enum esp_bt_l2cap_cb_event_t
L2CAP callback function events.
Values:
enumerator ESP_BT_L2CAP_INIT_EVT
When L2CAP is initialized, the event comes
enumerator ESP_BT_L2CAP_UNINIT_EVT
When L2CAP is deinitialized, the event comes
enumerator ESP_BT_L2CAP_OPEN_EVT
When L2CAP Client connection open, the event comes
enumerator ESP_BT_L2CAP_CLOSE_EVT
When L2CAP connection closed, the event comes
enumerator ESP_BT_L2CAP_START_EVT
When L2CAP server started, the event comes
enumerator ESP_BT_L2CAP_CL_INIT_EVT
When L2CAP client initiated a connection, the event comes
enumerator ESP_BT_L2CAP_SRV_STOP_EVT
When L2CAP server stopped, the event comes
BT SDP APIs
API Reference
Header File
• components/bt/host/bluedroid/api/include/api/esp_sdp_api.h
Functions
esp_err_t esp_sdp_register_callback(esp_sdp_cb_t callback)
This function is called to init callbacks with SDP module.
Parameters callback –[in] pointer to the init callback function.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_sdp_init(void)
This function is called to init SDP module. When the operation is completed, the callback function will be
called with ESP_SDP_INIT_EVT. This function should be called after esp_bluedroid_enable() completes suc-
cessfully.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_sdp_deinit(void)
This function is called to de-initialize SDP module. The operation will remove all SDP records, then the
callback function will be called with ESP_SDP_REMOVE_RECORD_COMP_EVT, and the number of
ESP_SDP_REMOVE_RECORD_COMP_EVT is equal to the number of SDP records.When the operation is
completed, the callback function will be called with ESP_SDP_DEINIT_EVT. This function should be called
after esp_sdp_init() completes successfully.
Returns
• ESP_OK: success
• other: failed
Unions
union esp_bluetooth_sdp_record_t
#include <esp_sdp_api.h> SDP record parameters union.
Public Members
esp_bluetooth_sdp_hdr_overlay_t hdr
General info
esp_bluetooth_sdp_mas_record_t mas
Message Access Profile - Server
esp_bluetooth_sdp_mns_record_t mns
Message Access Profile - Client (Notification Server)
esp_bluetooth_sdp_pse_record_t pse
Phone Book Profile - Server
esp_bluetooth_sdp_pce_record_t pce
Phone Book Profile - Client
esp_bluetooth_sdp_ops_record_t ops
Object Push Profile
esp_bluetooth_sdp_sap_record_t sap
SIM Access Profile
union esp_sdp_cb_param_t
#include <esp_sdp_api.h> SDP callback parameters union.
Public Members
struct sdp_crate_record_evt_param
#include <esp_sdp_api.h> ESP_SDP_CREATE_RECORD_COMP_EVT.
Public Members
esp_sdp_status_t status
status
int record_handle
SDP record handle
struct sdp_deinit_evt_param
#include <esp_sdp_api.h> ESP_SDP_DEINIT_EVT.
Public Members
esp_sdp_status_t status
status
struct sdp_init_evt_param
#include <esp_sdp_api.h> ESP_SDP_INIT_EVT.
Public Members
esp_sdp_status_t status
status
struct sdp_remove_record_evt_param
#include <esp_sdp_api.h> ESP_SDP_REMOVE_RECORD_COMP_EVT.
Public Members
esp_sdp_status_t status
status
struct sdp_search_evt_param
#include <esp_sdp_api.h> ESP_SDP_SEARCH_COMP_EVT.
Public Members
esp_sdp_status_t status
status
esp_bd_addr_t remote_addr
remote device address
esp_bt_uuid_t sdp_uuid
service uuid
int record_count
Number of SDP records
esp_bluetooth_sdp_record_t *records
SDP records
Structures
struct bluetooth_sdp_hdr_overlay
Some signals need additional pointers, hence we introduce a generic way to handle these pointers.
Public Members
esp_bluetooth_sdp_types_t type
SDP type
esp_bt_uuid_t uuid
UUID type,include uuid and uuid length
uint32_t service_name_length
Service name length
char *service_name
service name
int32_t rfcomm_channel_number
rfcomm channel number, if not used set to -1
int32_t l2cap_psm
l2cap psm, if not used set to -1
int32_t profile_version
profile version
int user1_ptr_len
see esp_bluetooth_sdp_ops_record_t
uint8_t *user1_ptr
see esp_bluetooth_sdp_ops_record_t
int user2_ptr_len
see esp_bluetooth_sdp_ops_record_t
uint8_t *user2_ptr
see esp_bluetooth_sdp_ops_record_t
struct bluetooth_sdp_mas_record
Message Access Profile - Server parameters.
Public Members
esp_bluetooth_sdp_hdr_overlay_t hdr
General info
uint32_t mas_instance_id
MAS Instance ID
uint32_t supported_features
Map supported features
uint32_t supported_message_types
Supported message types
struct bluetooth_sdp_mns_record
Message Access Profile - Client (Notification Server) parameters.
Public Members
esp_bluetooth_sdp_hdr_overlay_t hdr
General info
uint32_t supported_features
Supported features
struct bluetooth_sdp_pse_record
Phone Book Profile - Server parameters.
Public Members
esp_bluetooth_sdp_hdr_overlay_t hdr
General info
uint32_t supported_features
Pbap Supported Features
uint32_t supported_repositories
Supported Repositories
struct bluetooth_sdp_pce_record
Phone Book Profile - Client parameters.
Public Members
esp_bluetooth_sdp_hdr_overlay_t hdr
General info
struct bluetooth_sdp_ops_record
Object Push Profile parameters.
Public Members
esp_bluetooth_sdp_hdr_overlay_t hdr
General info
int supported_formats_list_len
Supported formats list length
uint8_t supported_formats_list[SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH]
Supported formats list
struct bluetooth_sdp_sap_record
SIM Access Profile parameters.
Public Members
esp_bluetooth_sdp_hdr_overlay_t hdr
General info
Macros
ESP_SDP_SERVER_NAME_MAX
Service name max length
SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH
OPP supported format list maximum length
Type Definitions
Enumerations
enum esp_sdp_status_t
Values:
enumerator ESP_SDP_SUCCESS
Successful operation.
enumerator ESP_SDP_FAILURE
Generic failure.
enumerator ESP_SDP_NO_RESOURCE
No more resource
enumerator ESP_SDP_NEED_INIT
SDP module shall init first
enumerator ESP_SDP_NEED_DEINIT
SDP module shall deinit first
enumerator ESP_SDP_NO_CREATE_RECORD
No record created
enum esp_sdp_cb_event_t
SDP callback function events.
Values:
enumerator ESP_SDP_INIT_EVT
When SDP is initialized, the event comes
enumerator ESP_SDP_DEINIT_EVT
When SDP is deinitialized, the event comes
enumerator ESP_SDP_SEARCH_COMP_EVT
When SDP search complete, the event comes
enumerator ESP_SDP_CREATE_RECORD_COMP_EVT
When create SDP records complete, the event comes
enumerator ESP_SDP_REMOVE_RECORD_COMP_EVT
When remove a SDP record complete, the event comes
enum esp_bluetooth_sdp_types_t
SDP record type.
Values:
enumerator ESP_SDP_TYPE_RAW
Used to carry raw SDP search data for unknown UUIDs
enumerator ESP_SDP_TYPE_MAP_MAS
Message Access Profile - Server
enumerator ESP_SDP_TYPE_MAP_MNS
Message Access Profile - Client (Notification Server)
enumerator ESP_SDP_TYPE_PBAP_PSE
Phone Book Profile - Server
enumerator ESP_SDP_TYPE_PBAP_PCE
Phone Book Profile - Client
enumerator ESP_SDP_TYPE_OPP_SERVER
Object Push Profile
enumerator ESP_SDP_TYPE_SAP_SERVER
SIM Access Profile
Application Example
Check bluetooth/hci folder in ESP-IDF examples, which contains the following application:
• This is a BLE advertising demo with virtual HCI interface. Send Re-
set/ADV_PARAM/ADV_DATA/ADV_ENABLE HCI command for BLE advertising - blue-
tooth/hci/controller_vhci_ble_adv.
API Reference
Header File
• components/bt/include/esp32/include/esp_bt.h
Functions
esp_err_t esp_ble_tx_power_set(esp_ble_power_type_t power_type, esp_power_level_t power_level)
Set BLE TX power Connection Tx power should only be set after connection created.
Parameters
• power_type –: The type of which tx power, could set Advertising/Connection/Default
and etc
• power_level –Power level(index) corresponding to absolute value(dbm)
Returns ESP_OK - success, other - failed
esp_power_level_t esp_ble_tx_power_get(esp_ble_power_type_t power_type)
Get BLE TX power Connection Tx power should only be get after connection created.
Parameters power_type –: The type of which tx power, could set Advertis-
ing/Connection/Default and etc
Returns >= 0 - Power level, < 0 - Invalid
esp_err_t esp_bredr_tx_power_set(esp_power_level_t min_power_level, esp_power_level_t
max_power_level)
Set BR/EDR TX power BR/EDR power control will use the power in range of minimum value and maximum
value. The power level will effect the global BR/EDR TX power, such inquire, page, connection and so on.
Please call the function after esp_bt_controller_enable and before any function which cause RF do TX. So you
can call the function before doing discovery, profile init and so on. For example, if you want BR/EDR use the
new TX power to do inquire, you should call this function before inquire. Another word, If call this function
when BR/EDR is in inquire(ING), please do inquire again after call this function. Default minimum power
level is ESP_PWR_LVL_N0, and maximum power level is ESP_PWR_LVL_P3.
Parameters
• min_power_level –The minimum power level
• max_power_level –The maximum power level
Returns ESP_OK - success, other - failed
esp_bluedroid_disable();
esp_bluedroid_deinit();
esp_bt_controller_disable();
esp_bt_controller_deinit();
esp_bt_mem_release(ESP_BT_MODE_BTDM);
Note: In case of NimBLE host, to release BSS and data memory to heap, the mode needs to be set to
ESP_BT_MODE_BTDM as controller is dual mode.
esp_err_t esp_bt_sleep_enable(void)
enable bluetooth to enter modem sleep
Note that this function shall not be invoked before esp_bt_controller_enable()
There are currently two options for bluetooth modem sleep, one is ORIG mode, and another is EVED Mode.
EVED Mode is intended for BLE only.
For ORIG mode: Bluetooth modem sleep is enabled in controller start up by default if CON-
FIG_CTRL_BTDM_MODEM_SLEEP is set and “ORIG mode”is selected. In ORIG modem sleep mode,
bluetooth controller will switch off some components and pause to work every now and then, if there is no
event to process; and wakeup according to the scheduled interval and resume the work. It can also wakeup
earlier upon external request using function “esp_bt_controller_wakeup_request”.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_bt_sleep_disable(void)
disable bluetooth modem sleep
Note that this function shall not be invoked before esp_bt_controller_enable()
If esp_bt_sleep_disable() is called, bluetooth controller will not be allowed to enter modem sleep;
If ORIG modem sleep mode is in use, if this function is called, bluetooth controller may not immediately wake
up if it is dormant then. In this case, esp_bt_controller_wakeup_request() can be used to shorten the time for
wakeup.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_scan_dupilcate_list_flush(void)
Manually clear scan duplicate list.
Note that scan duplicate list will be automatically cleared when the maximum amount of device in the filter is
reached the amount of device in the filter can be configured in menuconfig.
Note: This function name is incorrectly spelled, it will be fixed in release 5.x version.
Returns
• ESP_OK : success
• other : failed
void esp_wifi_bt_power_domain_on(void)
bt Wi-Fi power domain power on
void esp_wifi_bt_power_domain_off(void)
bt Wi-Fi power domain power off
Structures
struct esp_bt_controller_config_t
Controller config options, depend on config mask. Config mask indicate which functions enabled, this means
some options or parameters of some functions enabled by config mask.
Public Members
uint16_t controller_task_stack_size
Bluetooth controller task stack size
uint8_t controller_task_prio
Bluetooth controller task priority
uint8_t hci_uart_no
If use UART1/2 as HCI IO interface, indicate UART number
uint32_t hci_uart_baudrate
If use UART1/2 as HCI IO interface, indicate UART baudrate
uint8_t scan_duplicate_mode
scan duplicate mode
uint8_t scan_duplicate_type
scan duplicate type
uint16_t normal_adv_size
Normal adv size for scan duplicate
uint16_t mesh_adv_size
Mesh adv size for scan duplicate
uint16_t send_adv_reserved_size
Controller minimum memory value
uint32_t controller_debug_flag
Controller debug log flag
uint8_t mode
Controller mode: BR/EDR, BLE or Dual Mode
uint8_t ble_max_conn
BLE maximum connection numbers
uint8_t bt_max_acl_conn
BR/EDR maximum ACL connection numbers
uint8_t bt_sco_datapath
SCO data path, i.e. HCI or PCM module
bool auto_latency
BLE auto latency, used to enhance classic BT performance
bool bt_legacy_auth_vs_evt
BR/EDR Legacy auth complete event required to protect from BIAS attack
uint8_t bt_max_sync_conn
BR/EDR maximum ACL connection numbers. Effective in menuconfig
uint8_t ble_sca
BLE low power crystal accuracy index
uint8_t pcm_role
PCM role (master & slave)
uint8_t pcm_polar
PCM polar trig (falling clk edge & rising clk edge)
bool hli
Using high level interrupt or not
uint32_t magic
Magic number
struct esp_vhci_host_callback
esp_vhci_host_callback used for vhci call host function to notify what host need to do
Public Members
void (*notify_host_send_available)(void)
callback used to notify that the host can send packet to controller
Macros
ESP_BT_CONTROLLER_CONFIG_MAGIC_VAL
BT_CONTROLLER_INIT_CONFIG_DEFAULT()
Type Definitions
Enumerations
enum esp_bt_mode_t
Bluetooth mode for controller enable/disable.
Values:
enumerator ESP_BT_MODE_IDLE
Bluetooth is not running
enumerator ESP_BT_MODE_BLE
Run BLE mode
enumerator ESP_BT_MODE_CLASSIC_BT
Run Classic BT mode
enumerator ESP_BT_MODE_BTDM
Run dual mode
enum [anonymous]
BLE sleep clock accuracy(SCA), values for ble_sca field in esp_bt_controller_config_t, currently only
ESP_BLE_SCA_500PPM and ESP_BLE_SCA_250PPM are supported.
Values:
enumerator ESP_BLE_SCA_500PPM
BLE SCA at 500ppm
enumerator ESP_BLE_SCA_250PPM
BLE SCA at 250ppm
enumerator ESP_BLE_SCA_150PPM
BLE SCA at 150ppm
enumerator ESP_BLE_SCA_100PPM
BLE SCA at 100ppm
enumerator ESP_BLE_SCA_75PPM
BLE SCA at 75ppm
enumerator ESP_BLE_SCA_50PPM
BLE SCA at 50ppm
enumerator ESP_BLE_SCA_30PPM
BLE SCA at 30ppm
enumerator ESP_BLE_SCA_20PPM
BLE SCA at 20ppm
enum esp_bt_controller_status_t
Bluetooth controller enable/disable/initialised/de-initialised status.
Values:
enumerator ESP_BT_CONTROLLER_STATUS_IDLE
enumerator ESP_BT_CONTROLLER_STATUS_INITED
enumerator ESP_BT_CONTROLLER_STATUS_ENABLED
enumerator ESP_BT_CONTROLLER_STATUS_NUM
enum esp_ble_power_type_t
BLE tx power type ESP_BLE_PWR_TYPE_CONN_HDL0-8: for each connection, and only be
set after connection completed. when disconnect, the correspond TX power is not effected.
ESP_BLE_PWR_TYPE_ADV : for advertising/scan response. ESP_BLE_PWR_TYPE_SCAN : for scan.
ESP_BLE_PWR_TYPE_DEFAULT : if each connection’s TX power is not set, it will use this default value.
if neither in scan mode nor in adv mode, it will use this default value. If none of power type is set, system will
use ESP_PWR_LVL_P3 as default for ADV/SCAN/CONN0-9.
Values:
enumerator ESP_BLE_PWR_TYPE_CONN_HDL0
For connection handle 0
enumerator ESP_BLE_PWR_TYPE_CONN_HDL1
For connection handle 1
enumerator ESP_BLE_PWR_TYPE_CONN_HDL2
For connection handle 2
enumerator ESP_BLE_PWR_TYPE_CONN_HDL3
For connection handle 3
enumerator ESP_BLE_PWR_TYPE_CONN_HDL4
For connection handle 4
enumerator ESP_BLE_PWR_TYPE_CONN_HDL5
For connection handle 5
enumerator ESP_BLE_PWR_TYPE_CONN_HDL6
For connection handle 6
enumerator ESP_BLE_PWR_TYPE_CONN_HDL7
For connection handle 7
enumerator ESP_BLE_PWR_TYPE_CONN_HDL8
For connection handle 8
enumerator ESP_BLE_PWR_TYPE_ADV
For advertising
enumerator ESP_BLE_PWR_TYPE_SCAN
For scan
enumerator ESP_BLE_PWR_TYPE_DEFAULT
For default, if not set other, it will use default value
enumerator ESP_BLE_PWR_TYPE_NUM
TYPE numbers
enum esp_power_level_t
Bluetooth TX power level(index), it’s just a index corresponding to power(dbm).
Values:
enumerator ESP_PWR_LVL_N12
Corresponding to -12dbm
enumerator ESP_PWR_LVL_N9
Corresponding to -9dbm
enumerator ESP_PWR_LVL_N6
Corresponding to -6dbm
enumerator ESP_PWR_LVL_N3
Corresponding to -3dbm
enumerator ESP_PWR_LVL_N0
Corresponding to 0dbm
enumerator ESP_PWR_LVL_P3
Corresponding to +3dbm
enumerator ESP_PWR_LVL_P6
Corresponding to +6dbm
enumerator ESP_PWR_LVL_P9
Corresponding to +9dbm
enumerator ESP_PWR_LVL_N14
Backward compatibility! Setting to -14dbm will actually result to -12dbm
enumerator ESP_PWR_LVL_N11
Backward compatibility! Setting to -11dbm will actually result to -9dbm
enumerator ESP_PWR_LVL_N8
Backward compatibility! Setting to -8dbm will actually result to -6dbm
enumerator ESP_PWR_LVL_N5
Backward compatibility! Setting to -5dbm will actually result to -3dbm
enumerator ESP_PWR_LVL_N2
Backward compatibility! Setting to -2dbm will actually result to 0dbm
enumerator ESP_PWR_LVL_P1
Backward compatibility! Setting to +1dbm will actually result to +3dbm
enumerator ESP_PWR_LVL_P4
Backward compatibility! Setting to +4dbm will actually result to +6dbm
enumerator ESP_PWR_LVL_P7
Backward compatibility! Setting to +7dbm will actually result to +9dbm
enum esp_sco_data_path_t
Bluetooth audio data transport path.
Values:
enumerator ESP_SCO_DATA_PATH_HCI
data over HCI transport
enumerator ESP_SCO_DATA_PATH_PCM
data over PCM interface
2.3.5 ESP-BLE-MESH
With various features of ESP-BLE-MESH, users can create a managed flooding mesh network for several scenarios,
such as lighting, sensor and etc.
For an ESP32 to join and work on a ESP-BLE-MESH network, it must be provisioned firstly. By provisioning, the
ESP32, as an unprovisioned device, will join the ESP-BLE-MESH network and become a ESP-BLE-MESH node,
communicating with other nodes within or beyond the radio range.
Apart from ESP-BLE-MESH nodes, inside ESP-BLE-MESH network, there is also ESP32 that works as ESP-BLE-
MESH Provisioner, which could provision unprovisioned devices into ESP-BLE-MESH nodes and configure the
nodes with various features.
For information how to start using ESP32 and ESP-BLE-MESH, please see the Section Getting Started with ESP-
BLE-MESH. If you are interested in information on ESP-BLE-MESH architecture, including some details of software
implementation, please see Section ESP-BLE-MESH Architecture.
API Reference
ESP-BLE-MESH Definitions
This section contains only one header file, which lists the following items of ESP-BLE-MESH.
• ID of all the models and related message opcodes
Header File
• components/bt/esp_ble_mesh/api/esp_ble_mesh_defs.h
Unions
union esp_ble_mesh_prov_cb_param_t
#include <esp_ble_mesh_defs.h> BLE Mesh Node/Provisioner callback parameters union.
Public Members
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_unprov_dev_name_comp_param
node_set_unprov_dev_name_comp
Event parameter of ESP_BLE_MESH_NODE_SET_UNPROV_DEV_NAME_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_prov_enable_comp_param
node_prov_enable_comp
Event parameter of ESP_BLE_MESH_NODE_PROV_ENABLE_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_prov_disable_comp_param
node_prov_disable_comp
Event parameter of ESP_BLE_MESH_NODE_PROV_DISABLE_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_oob_pub_key_comp_param
node_prov_set_oob_pub_key_comp
Event parameter of ESP_BLE_MESH_NODE_PROV_SET_OOB_PUB_KEY_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_input_number_comp_param
node_prov_input_num_comp
Event parameter of ESP_BLE_MESH_NODE_PROV_INPUT_NUM_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_input_string_comp_param
node_prov_input_str_comp
Event parameter of ESP_BLE_MESH_NODE_PROV_INPUT_STR_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_identity_enable_comp_param
node_proxy_identity_enable_comp
Event parameter of ESP_BLE_MESH_NODE_PROXY_IDENTITY_ENABLE_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_gatt_enable_comp_param
node_proxy_gatt_enable_comp
Event parameter of ESP_BLE_MESH_NODE_PROXY_GATT_ENABLE_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_gatt_disable_comp_param
node_proxy_gatt_disable_comp
Event parameter of ESP_BLE_MESH_NODE_PROXY_GATT_DISABLE_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_node_add_local_net_key_comp_param
node_add_net_key_comp
Event parameter of ESP_BLE_MESH_NODE_ADD_LOCAL_NET_KEY_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_node_add_local_app_key_comp_param
node_add_app_key_comp
Event parameter of ESP_BLE_MESH_NODE_ADD_LOCAL_APP_KEY_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_node_bind_local_mod_app_comp_param
node_bind_app_key_to_model_comp
Event parameter of ESP_BLE_MESH_NODE_BIND_APP_KEY_TO_MODEL_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_recv_unprov_adv_pkt_param
provisioner_recv_unprov_adv_pkt
Event parameter of ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_enable_comp_param
provisioner_prov_enable_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_ENABLE_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_disable_comp_param
provisioner_prov_disable_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_DISABLE_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_link_open_evt_param
provisioner_prov_link_open
Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_LINK_OPEN_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_read_oob_pub_key_evt_param
provisioner_prov_read_oob_pub_key
Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_input_evt_param
provisioner_prov_input
Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_INPUT_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_output_evt_param
provisioner_prov_output
Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_OUTPUT_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_link_close_evt_param
provisioner_prov_link_close
Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_LINK_CLOSE_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_comp_param
provisioner_prov_complete
Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_add_unprov_dev_comp_param
provisioner_add_unprov_dev_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_ADD_UNPROV_DEV_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_dev_with_addr_comp_param
provisioner_prov_dev_with_addr_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_DEV_WITH_ADDR_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_delete_dev_comp_param
provisioner_delete_dev_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_DEV_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_dev_uuid_match_comp_param
provisioner_set_dev_uuid_match_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_SET_DEV_UUID_MATCH_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_prov_data_info_comp_param
provisioner_set_prov_data_info_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_SET_PROV_DATA_INFO_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_static_oob_val_comp_param
provisioner_set_static_oob_val_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_SET_STATIC_OOB_VALUE_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_primary_elem_addr_comp_param
provisioner_set_primary_elem_addr_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_SET_PRIMARY_ELEM_ADDR_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_read_oob_pub_key_comp_param
provisioner_prov_read_oob_pub_key_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_input_num_comp_param
provisioner_prov_input_num_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_INPUT_NUMBER_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_input_str_comp_param
provisioner_prov_input_str_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_PROV_INPUT_STRING_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_set_node_name_comp_param
provisioner_set_node_name_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_SET_NODE_NAME_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_add_local_app_key_comp_param
provisioner_add_app_key_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_APP_KEY_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_update_local_app_key_comp_param
provisioner_update_app_key_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_APP_KEY_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_bind_local_mod_app_comp_param
provisioner_bind_app_key_to_model_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_BIND_APP_KEY_TO_MODEL_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_add_local_net_key_comp_param
provisioner_add_net_key_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_NET_KEY_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_update_local_net_key_comp_param
provisioner_update_net_key_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_NET_KEY_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_store_node_comp_data_comp_param
provisioner_store_node_comp_data_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_STORE_NODE_COMP_DATA_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_delete_node_with_uuid_comp_param
provisioner_delete_node_with_uuid_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_UUID_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_delete_node_with_addr_comp_param
provisioner_delete_node_with_addr_comp
Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_ADDR_COMP_EVT
int err_code
Indicate the result of enabling/disabling to receive heartbeat messages by the Provisioner
Indicate the result of setting the heartbeat filter type by the Provisioner
Indicate the result of setting the heartbeat filter address by the Provisioner
bool enable
Indicate enabling or disabling receiving heartbeat messages
struct esp_ble_mesh_prov_cb_param_t::[anonymous]
provisioner_enable_heartbeat_recv_comp
ESP_BLE_MESH_PROVISIONER_ENABLE_HEARTBEAT_RECV_COMP_EVT.
Event parameters of ESP_BLE_MESH_PROVISIONER_ENABLE_HEARTBEAT_RECV_COMP_EVT
uint8_t type
Type of the filter used for receiving heartbeat messages
struct esp_ble_mesh_prov_cb_param_t::[anonymous]
provisioner_set_heartbeat_filter_type_comp
ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_TYPE_COMP_EVT.
Event parameters of ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_TYPE_COMP_EVT
uint8_t op
Operation (add, remove, clean)
uint16_t hb_src
Heartbeat source address
uint16_t hb_dst
Heartbeat destination address
struct esp_ble_mesh_prov_cb_param_t::[anonymous]
provisioner_set_heartbeat_filter_info_comp
ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_INFO_COMP_EVT.
Event parameters of ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_INFO_COMP_EVT
uint8_t init_ttl
Heartbeat InitTTL
uint8_t rx_ttl
Heartbeat RxTTL
uint8_t hops
Heartbeat hops (InitTTL - RxTTL + 1)
uint16_t feature
Bit field of currently active features of the node
int8_t rssi
RSSI of the heartbeat message
struct esp_ble_mesh_prov_cb_param_t::[anonymous]
provisioner_direct_erase_settings_comp
ESP_BLE_MESH_PROVISIONER_DRIECT_ERASE_SETTINGS_COMP_EVT.
Event parameters of ESP_BLE_MESH_PROVISIONER_DRIECT_ERASE_SETTINGS_COMP_EVT
uint8_t index
Index of Provisioner settings
struct esp_ble_mesh_prov_cb_param_t::[anonymous]
provisioner_open_settings_with_index_comp
ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_INDEX_COMP_EVT.
Event parameter of ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_INDEX_COMP_EVT
char uid[ESP_BLE_MESH_SETTINGS_UID_SIZE + 1]
Provisioner settings user id
struct esp_ble_mesh_prov_cb_param_t::[anonymous]
provisioner_open_settings_with_uid_comp
ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_UID_COMP_EVT.
Event parameters of ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_UID_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::[anonymous]
provisioner_close_settings_with_index_comp
ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_INDEX_COMP_EVT.
Event parameter of ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_INDEX_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::[anonymous]
provisioner_close_settings_with_uid_comp
ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_UID_COMP_EVT.
Event parameters of ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_UID_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::[anonymous]
provisioner_delete_settings_with_index_comp
ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_INDEX_COMP_EVT.
Event parameter of ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_INDEX_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::[anonymous]
provisioner_delete_settings_with_uid_comp
ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_UID_COMP_EVT.
Event parameters of ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_UID_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_fast_prov_info_comp_param
set_fast_prov_info_comp
Event parameter of ESP_BLE_MESH_SET_FAST_PROV_INFO_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_set_fast_prov_action_comp_param
set_fast_prov_action_comp
Event parameter of ESP_BLE_MESH_SET_FAST_PROV_ACTION_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_friendship_establish_param
lpn_friendship_establish
Event parameter of ESP_BLE_MESH_LPN_FRIENDSHIP_ESTABLISH_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_lpn_friendship_terminate_param
lpn_friendship_terminate
Event parameter of ESP_BLE_MESH_LPN_FRIENDSHIP_TERMINATE_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_friend_friendship_establish_param
frnd_friendship_establish
Event parameter of ESP_BLE_MESH_FRIEND_FRIENDSHIP_ESTABLISH_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_friend_friendship_terminate_param
frnd_friendship_terminate
Event parameter of ESP_BLE_MESH_FRIEND_FRIENDSHIP_TERMINATE_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_recv_adv_pkt_param
proxy_client_recv_adv_pkt
Event parameter of ESP_BLE_MESH_PROXY_CLIENT_RECV_ADV_PKT_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_connected_param
proxy_client_connected
Event parameter of ESP_BLE_MESH_PROXY_CLIENT_CONNECTED_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_disconnected_param
proxy_client_disconnected
Event parameter of ESP_BLE_MESH_PROXY_CLIENT_DISCONNECTED_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_recv_filter_status_param
proxy_client_recv_filter_status
Event parameter of ESP_BLE_MESH_PROXY_CLIENT_RECV_FILTER_STATUS_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_connect_comp_param
proxy_client_connect_comp
Event parameter of ESP_BLE_MESH_PROXY_CLIENT_CONNECT_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_disconnect_comp_param
proxy_client_disconnect_comp
Event parameter of ESP_BLE_MESH_PROXY_CLIENT_DISCONNECT_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_set_filter_type_comp_param
proxy_client_set_filter_type_comp
Event parameter of ESP_BLE_MESH_PROXY_CLIENT_SET_FILTER_TYPE_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_add_filter_addr_comp_param
proxy_client_add_filter_addr_comp
Event parameter of ESP_BLE_MESH_PROXY_CLIENT_ADD_FILTER_ADDR_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_client_remove_filter_addr_comp_param
proxy_client_remove_filter_addr_comp
Event parameter of ESP_BLE_MESH_PROXY_CLIENT_REMOVE_FILTER_ADDR_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_server_connected_param
proxy_server_connected
Event parameter of ESP_BLE_MESH_PROXY_SERVER_CONNECTED_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_proxy_server_disconnected_param
proxy_server_disconnected
Event parameter of ESP_BLE_MESH_PROXY_SERVER_DISCONNECTED_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_model_sub_group_addr_comp_param
model_sub_group_addr_comp
Event parameters of ESP_BLE_MESH_MODEL_SUBSCRIBE_GROUP_ADDR_COMP_EVT
struct esp_ble_mesh_prov_cb_param_t::ble_mesh_model_unsub_group_addr_comp_param
model_unsub_group_addr_comp
Event parameters of ESP_BLE_MESH_MODEL_UNSUBSCRIBE_GROUP_ADDR_COMP_EVT
struct ble_mesh_deinit_mesh_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_DEINIT_MESH_COMP_EVT.
Public Members
int err_code
Indicate the result of BLE Mesh deinitialization
struct ble_mesh_friend_friendship_establish_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_FRIEND_FRIENDSHIP_ESTABLISH_EVT.
Public Members
uint16_t lpn_addr
Low Power Node unicast address
struct ble_mesh_friend_friendship_terminate_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_FRIEND_FRIENDSHIP_TERMINATE_EVT.
Public Types
enum [anonymous]
This enum value is the reason of friendship termination on the friend node side
Values:
enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_ESTABLISH_FAIL
Friend Offer has been sent, but Friend Offer is not received within 1 second, friendship fails to
be established
enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_POLL_TIMEOUT
Friendship is established, PollTimeout timer expires and no Friend Poll/Sub Add/Sub Remove
is received
enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_RECV_FRND_REQ
Receive Friend Request from existing Low Power Node
enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_RECV_FRND_CLEAR
Receive Friend Clear from other friend node
enumerator ESP_BLE_MESH_FRND_FRIENDSHIP_TERMINATE_DISABLE
Friend feature disabled or corresponding NetKey is deleted
Public Members
uint16_t lpn_addr
Low Power Node unicast address
enum esp_ble_mesh_prov_cb_param_t::ble_mesh_friend_friendship_terminate_param::[anonymous]
reason
This enum value is the reason of friendship termination on the friend node side Friendship terminated
reason
struct ble_mesh_heartbeat_msg_recv_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_HEARTBEAT_MESSAGE_RECV_EVT.
Public Members
uint8_t hops
Heartbeat hops (InitTTL - RxTTL + 1)
uint16_t feature
Bit field of currently active features of the node
struct ble_mesh_input_evt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_INPUT_EVT.
Public Members
esp_ble_mesh_input_action_t action
Action of Input OOB Authentication
uint8_t size
Size of Input OOB Authentication
struct ble_mesh_input_number_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_INPUT_NUM_COMP_EVT.
Public Members
int err_code
Indicate the result of inputting number
struct ble_mesh_input_string_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_INPUT_STR_COMP_EVT.
Public Members
int err_code
Indicate the result of inputting string
struct ble_mesh_link_close_evt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_LINK_CLOSE_EVT.
Public Members
esp_ble_mesh_prov_bearer_t bearer
Type of the bearer used when device link is closed
struct ble_mesh_link_open_evt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_LINK_OPEN_EVT.
Public Members
esp_ble_mesh_prov_bearer_t bearer
Type of the bearer used when device link is open
struct ble_mesh_lpn_disable_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_DISABLE_COMP_EVT.
Public Members
int err_code
Indicate the result of disabling LPN functionality
struct ble_mesh_lpn_enable_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_ENABLE_COMP_EVT.
Public Members
int err_code
Indicate the result of enabling LPN functionality
struct ble_mesh_lpn_friendship_establish_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_FRIENDSHIP_ESTABLISH_EVT.
Public Members
uint16_t friend_addr
Friend Node unicast address
struct ble_mesh_lpn_friendship_terminate_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_FRIENDSHIP_TERMINATE_EVT.
Public Members
uint16_t friend_addr
Friend Node unicast address
struct ble_mesh_lpn_poll_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_LPN_POLL_COMP_EVT.
Public Members
int err_code
Indicate the result of sending Friend Poll
struct ble_mesh_model_sub_group_addr_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_SUBSCRIBE_GROUP_ADDR_COMP_EVT.
Public Members
int err_code
Indicate the result of local model subscribing group address
uint16_t element_addr
Element address
uint16_t company_id
Company ID
uint16_t model_id
Model ID
uint16_t group_addr
Group Address
struct ble_mesh_model_unsub_group_addr_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_UNSUBSCRIBE_GROUP_ADDR_COMP_EVT.
Public Members
int err_code
Indicate the result of local model unsubscribing group address
uint16_t element_addr
Element address
uint16_t company_id
Company ID
uint16_t model_id
Model ID
uint16_t group_addr
Group Address
struct ble_mesh_node_add_local_app_key_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_ADD_LOCAL_APP_KEY_COMP_EVT.
Public Members
int err_code
Indicate the result of adding local AppKey by the node
uint16_t net_idx
NetKey Index
uint16_t app_idx
AppKey Index
struct ble_mesh_node_add_local_net_key_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_ADD_LOCAL_NET_KEY_COMP_EVT.
Public Members
int err_code
Indicate the result of adding local NetKey by the node
uint16_t net_idx
NetKey Index
struct ble_mesh_node_bind_local_mod_app_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_BIND_APP_KEY_TO_MODEL_COMP_EVT.
Public Members
int err_code
Indicate the result of binding AppKey with model by the node
uint16_t element_addr
Element address
uint16_t app_idx
AppKey Index
uint16_t company_id
Company ID
uint16_t model_id
Model ID
struct ble_mesh_output_num_evt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_OUTPUT_NUMBER_EVT.
Public Members
esp_ble_mesh_output_action_t action
Action of Output OOB Authentication
uint32_t number
Number of Output OOB Authentication
struct ble_mesh_output_str_evt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_OUTPUT_STRING_EVT.
Public Members
char string[8]
String of Output OOB Authentication
struct ble_mesh_prov_disable_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_DISABLE_COMP_EVT.
Public Members
int err_code
Indicate the result of disabling BLE Mesh device
struct ble_mesh_prov_enable_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_ENABLE_COMP_EVT.
Public Members
int err_code
Indicate the result of enabling BLE Mesh device
struct ble_mesh_prov_register_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROV_REGISTER_COMP_EVT.
Public Members
int err_code
Indicate the result of BLE Mesh initialization
struct ble_mesh_provision_complete_evt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_COMPLETE_EVT.
Public Members
uint16_t net_idx
NetKey Index
uint8_t net_key[16]
NetKey
uint16_t addr
Primary address
uint8_t flags
Flags
uint32_t iv_index
IV Index
struct ble_mesh_provision_reset_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_RESET_EVT.
struct ble_mesh_provisioner_add_local_app_key_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_APP_KEY_COMP_EVT.
Public Members
int err_code
Indicate the result of adding local AppKey by the Provisioner
uint16_t net_idx
NetKey Index
uint16_t app_idx
AppKey Index
struct ble_mesh_provisioner_add_local_net_key_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_NET_KEY_COMP_EVT.
Public Members
int err_code
Indicate the result of adding local NetKey by the Provisioner
uint16_t net_idx
NetKey Index
struct ble_mesh_provisioner_add_unprov_dev_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_ADD_UNPROV_DEV_COMP_EVT.
Public Members
int err_code
Indicate the result of adding device into queue by the Provisioner
struct ble_mesh_provisioner_bind_local_mod_app_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_BIND_APP_KEY_TO_MODEL_COMP_EVT.
Public Members
int err_code
Indicate the result of binding AppKey with model by the Provisioner
uint16_t element_addr
Element address
uint16_t app_idx
AppKey Index
uint16_t company_id
Company ID
uint16_t model_id
Model ID
struct ble_mesh_provisioner_delete_dev_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_DELETE_DEV_COMP_EVT.
Public Members
int err_code
Indicate the result of deleting device by the Provisioner
struct ble_mesh_provisioner_delete_node_with_addr_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_ADDR_COMP_EVT.
Public Members
int err_code
Indicate the result of deleting node with unicast address by the Provisioner
uint16_t unicast_addr
Node unicast address
struct ble_mesh_provisioner_delete_node_with_uuid_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_UUID_COMP_EVT.
Public Members
int err_code
Indicate the result of deleting node with uuid by the Provisioner
uint8_t uuid[16]
Node device uuid
struct ble_mesh_provisioner_link_close_evt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_LINK_CLOSE_EVT.
Public Members
esp_ble_mesh_prov_bearer_t bearer
Type of the bearer used when Provisioner link is closed
uint8_t reason
Reason of the closed provisioning link
struct ble_mesh_provisioner_link_open_evt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_LINK_OPEN_EVT.
Public Members
esp_ble_mesh_prov_bearer_t bearer
Type of the bearer used when Provisioner link is opened
struct ble_mesh_provisioner_prov_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT.
Public Members
uint16_t node_idx
Index of the provisioned device
esp_ble_mesh_octet16_t device_uuid
Device UUID of the provisioned device
uint16_t unicast_addr
Primary address of the provisioned device
uint8_t element_num
Element count of the provisioned device
uint16_t netkey_idx
NetKey Index of the provisioned device
struct ble_mesh_provisioner_prov_dev_with_addr_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_DEV_WITH_ADDR_COMP_EVT.
Public Members
int err_code
Indicate the result of Provisioner starting to provision a device
struct ble_mesh_provisioner_prov_disable_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_DISABLE_COMP_EVT.
Public Members
int err_code
Indicate the result of disabling BLE Mesh Provisioner
struct ble_mesh_provisioner_prov_enable_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_ENABLE_COMP_EVT.
Public Members
int err_code
Indicate the result of enabling BLE Mesh Provisioner
struct ble_mesh_provisioner_prov_input_evt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_INPUT_EVT.
Public Members
esp_ble_mesh_oob_method_t method
Method of device Output OOB Authentication
esp_ble_mesh_output_action_t action
Action of device Output OOB Authentication
uint8_t size
Size of device Output OOB Authentication
uint8_t link_idx
Index of the provisioning link
struct ble_mesh_provisioner_prov_input_num_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_INPUT_NUMBER_COMP_EVT.
Public Members
int err_code
Indicate the result of inputting number by the Provisioner
struct ble_mesh_provisioner_prov_input_str_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_INPUT_STRING_COMP_EVT.
Public Members
int err_code
Indicate the result of inputting string by the Provisioner
struct ble_mesh_provisioner_prov_output_evt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_OUTPUT_EVT.
Public Members
esp_ble_mesh_oob_method_t method
Method of device Input OOB Authentication
esp_ble_mesh_input_action_t action
Action of device Input OOB Authentication
uint8_t size
Size of device Input OOB Authentication
uint8_t link_idx
Index of the provisioning link
char string[8]
String output by the Provisioner
uint32_t number
Number output by the Provisioner
union esp_ble_mesh_prov_cb_param_t::ble_mesh_provisioner_prov_output_evt_param::[anonymous]
[anonymous]
struct ble_mesh_provisioner_prov_read_oob_pub_key_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_COMP_EVT.
Public Members
int err_code
Indicate the result of setting OOB Public Key by the Provisioner
struct ble_mesh_provisioner_prov_read_oob_pub_key_evt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_EVT.
Public Members
uint8_t link_idx
Index of the provisioning link
struct ble_mesh_provisioner_recv_unprov_adv_pkt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT.
Public Members
uint8_t dev_uuid[16]
Device UUID of the unprovisioned device
esp_ble_mesh_bd_addr_t addr
Device address of the unprovisioned device
esp_ble_mesh_addr_type_t addr_type
Device address type
uint16_t oob_info
OOB Info of the unprovisioned device
uint8_t adv_type
Avertising type of the unprovisioned device
esp_ble_mesh_prov_bearer_t bearer
Bearer of the unprovisioned device
int8_t rssi
RSSI of the received advertising packet
struct ble_mesh_provisioner_set_dev_uuid_match_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_DEV_UUID_MATCH_COMP_EVT.
Public Members
int err_code
Indicate the result of setting Device UUID match value by the Provisioner
struct ble_mesh_provisioner_set_node_name_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_NODE_NAME_COMP_EVT.
Public Members
int err_code
Indicate the result of setting provisioned device name by the Provisioner
uint16_t node_index
Index of the provisioned device
struct ble_mesh_provisioner_set_primary_elem_addr_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_PRIMARY_ELEM_ADDR_COMP_EVT.
Public Members
int err_code
Indicate the result of setting unicast address of primary element by the Provisioner
struct ble_mesh_provisioner_set_prov_data_info_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_PROV_DATA_INFO_COMP_EVT.
Public Members
int err_code
Indicate the result of setting provisioning info by the Provisioner
struct ble_mesh_provisioner_set_static_oob_val_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_SET_STATIC_OOB_VALUE_COMP_EVT.
Public Members
int err_code
Indicate the result of setting static oob value by the Provisioner
struct ble_mesh_provisioner_store_node_comp_data_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_STORE_NODE_COMP_DATA_COMP_EVT.
Public Members
int err_code
Indicate the result of storing node composition data by the Provisioner
uint16_t addr
Node element address
struct ble_mesh_provisioner_update_local_app_key_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_APP_KEY_COMP_EVT.
Public Members
int err_code
Indicate the result of updating local AppKey by the Provisioner
uint16_t net_idx
NetKey Index
uint16_t app_idx
AppKey Index
struct ble_mesh_provisioner_update_local_net_key_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_NET_KEY_COMP_EVT.
Public Members
int err_code
Indicate the result of updating local NetKey by the Provisioner
uint16_t net_idx
NetKey Index
struct ble_mesh_proxy_client_add_filter_addr_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_ADD_FILTER_ADDR_COMP_EVT.
Public Members
int err_code
Indicate the result of Proxy Client add filter address
uint8_t conn_handle
Proxy connection handle
uint16_t net_idx
Corresponding NetKey Index
struct ble_mesh_proxy_client_connect_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_CONNECT_COMP_EVT.
Public Members
int err_code
Indicate the result of Proxy Client connect
esp_ble_mesh_bd_addr_t addr
Device address of the Proxy Server
esp_ble_mesh_addr_type_t addr_type
Device address type
uint16_t net_idx
Corresponding NetKey Index
struct ble_mesh_proxy_client_connected_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_CONNECTED_EVT.
Public Members
esp_ble_mesh_bd_addr_t addr
Device address of the Proxy Server
esp_ble_mesh_addr_type_t addr_type
Device address type
uint8_t conn_handle
Proxy connection handle
uint16_t net_idx
Corresponding NetKey Index
struct ble_mesh_proxy_client_disconnect_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_DISCONNECT_COMP_EVT.
Public Members
int err_code
Indicate the result of Proxy Client disconnect
uint8_t conn_handle
Proxy connection handle
struct ble_mesh_proxy_client_disconnected_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_DISCONNECTED_EVT.
Public Members
esp_ble_mesh_bd_addr_t addr
Device address of the Proxy Server
esp_ble_mesh_addr_type_t addr_type
Device address type
uint8_t conn_handle
Proxy connection handle
uint16_t net_idx
Corresponding NetKey Index
uint8_t reason
Proxy disconnect reason
struct ble_mesh_proxy_client_recv_adv_pkt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_RECV_ADV_PKT_EVT.
Public Members
esp_ble_mesh_bd_addr_t addr
Device address
esp_ble_mesh_addr_type_t addr_type
Device address type
uint16_t net_idx
Network ID related NetKey Index
uint8_t net_id[8]
Network ID contained in the advertising packet
int8_t rssi
RSSI of the received advertising packet
struct ble_mesh_proxy_client_recv_filter_status_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_RECV_FILTER_STATUS_EVT.
Public Members
uint8_t conn_handle
Proxy connection handle
uint16_t server_addr
Proxy Server primary element address
uint16_t net_idx
Corresponding NetKey Index
uint8_t filter_type
Proxy Server filter type(whitelist or blacklist)
uint16_t list_size
Number of addresses in the Proxy Server filter list
struct ble_mesh_proxy_client_remove_filter_addr_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_REMOVE_FILTER_ADDR_COMP_EVT.
Public Members
int err_code
Indicate the result of Proxy Client remove filter address
uint8_t conn_handle
Proxy connection handle
uint16_t net_idx
Corresponding NetKey Index
struct ble_mesh_proxy_client_set_filter_type_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_CLIENT_SET_FILTER_TYPE_COMP_EVT.
Public Members
int err_code
Indicate the result of Proxy Client set filter type
uint8_t conn_handle
Proxy connection handle
uint16_t net_idx
Corresponding NetKey Index
struct ble_mesh_proxy_gatt_disable_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROXY_GATT_DISABLE_COMP_EVT.
Public Members
int err_code
Indicate the result of disabling Mesh Proxy Service
struct ble_mesh_proxy_gatt_enable_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROXY_GATT_ENABLE_COMP_EVT.
Public Members
int err_code
Indicate the result of enabling Mesh Proxy Service
struct ble_mesh_proxy_identity_enable_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROXY_IDENTITY_ENABLE_COMP_EVT.
Public Members
int err_code
Indicate the result of enabling Mesh Proxy advertising
struct ble_mesh_proxy_server_connected_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_SERVER_CONNECTED_EVT.
Public Members
uint8_t conn_handle
Proxy connection handle
struct ble_mesh_proxy_server_disconnected_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_PROXY_SERVER_DISCONNECTED_EVT.
Public Members
uint8_t conn_handle
Proxy connection handle
uint8_t reason
Proxy disconnect reason
struct ble_mesh_set_fast_prov_action_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_SET_FAST_PROV_ACTION_COMP_EVT.
Public Members
uint8_t status_action
Indicate the result of setting action of fast provisioning
struct ble_mesh_set_fast_prov_info_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_SET_FAST_PROV_INFO_COMP_EVT.
Public Members
uint8_t status_unicast
Indicate the result of setting unicast address range of fast provisioning
uint8_t status_net_idx
Indicate the result of setting NetKey Index of fast provisioning
uint8_t status_match
Indicate the result of setting matching Device UUID of fast provisioning
struct ble_mesh_set_oob_pub_key_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_PROV_SET_OOB_PUB_KEY_COMP_EVT.
Public Members
int err_code
Indicate the result of setting OOB Public Key
struct ble_mesh_set_unprov_dev_name_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_NODE_SET_UNPROV_DEV_NAME_COMP_EVT.
Public Members
int err_code
Indicate the result of setting BLE Mesh device name
union esp_ble_mesh_server_state_value_t
#include <esp_ble_mesh_defs.h> Server model state value union.
Public Members
uint8_t onoff
The value of the Generic OnOff state
The value of the Light LC Light OnOff state
int16_t level
The value of the Generic Level state
uint8_t onpowerup
The value of the Generic OnPowerUp state
uint16_t power
The value of the Generic Power Actual state
uint16_t lightness
The value of the Light Lightness Actual state
The value of the Light Lightness Linear state
The value of the Light CTL Lightness state
The value of the Light HSL Lightness state
The value of the Light xyL Lightness state
uint16_t temperature
The value of the Light CTL Temperature state
int16_t delta_uv
The value of the Light CTL Delta UV state
uint16_t hue
The value of the Light HSL Hue state
uint16_t saturation
The value of the Light HSL Saturation state
union esp_ble_mesh_model_cb_param_t
#include <esp_ble_mesh_defs.h> BLE Mesh model callback parameters union.
Public Members
struct esp_ble_mesh_model_cb_param_t::ble_mesh_mod_recv_publish_msg_param
client_recv_publish_msg
Event parameter of ESP_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT
struct esp_ble_mesh_model_cb_param_t::ble_mesh_client_model_send_timeout_param
client_send_timeout
Event parameter of ESP_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT
struct esp_ble_mesh_model_cb_param_t::ble_mesh_model_publish_update_evt_param
model_publish_update
Event parameter of ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT
struct esp_ble_mesh_model_cb_param_t::ble_mesh_server_model_update_state_comp_param
server_model_update_state
Event parameter of ESP_BLE_MESH_SERVER_MODEL_UPDATE_STATE_COMP_EVT
struct ble_mesh_client_model_send_timeout_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT.
Public Members
uint32_t opcode
Opcode of the previously sent message
esp_ble_mesh_model_t *model
Pointer to the model which sends the previous message
esp_ble_mesh_msg_ctx_t *ctx
Pointer to the context of the previous message
struct ble_mesh_mod_recv_publish_msg_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT.
Public Members
uint32_t opcode
Opcode of the unsolicited received message
esp_ble_mesh_model_t *model
Pointer to the model which receives the message
esp_ble_mesh_msg_ctx_t *ctx
Pointer to the context of the message
uint16_t length
Length of the received message
uint8_t *msg
Value of the received message
struct ble_mesh_model_operation_evt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_OPERATION_EVT.
Public Members
uint32_t opcode
Opcode of the received message
esp_ble_mesh_model_t *model
Pointer to the model which receives the message
esp_ble_mesh_msg_ctx_t *ctx
Pointer to the context of the received message
uint16_t length
Length of the received message
uint8_t *msg
Value of the received message
struct ble_mesh_model_publish_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_PUBLISH_COMP_EVT.
Public Members
int err_code
Indicate the result of publishing a message
esp_ble_mesh_model_t *model
Pointer to the model which publishes the message
struct ble_mesh_model_publish_update_evt_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT.
Public Members
esp_ble_mesh_model_t *model
Pointer to the model which is going to update its publish message
struct ble_mesh_model_send_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_MODEL_SEND_COMP_EVT.
Public Members
int err_code
Indicate the result of sending a message
uint32_t opcode
Opcode of the message
esp_ble_mesh_model_t *model
Pointer to the model which sends the message
esp_ble_mesh_msg_ctx_t *ctx
Context of the message
struct ble_mesh_server_model_update_state_comp_param
#include <esp_ble_mesh_defs.h> ESP_BLE_MESH_SERVER_MODEL_UPDATE_STATE_COMP_EVT.
Public Members
int err_code
Indicate the result of updating server model state
esp_ble_mesh_model_t *model
Pointer to the server model which state value is updated
esp_ble_mesh_server_state_type_t type
Type of the updated server state
Structures
struct esp_ble_mesh_deinit_param_t
BLE Mesh deinit parameters
Public Members
bool erase_flash
Indicate if erasing flash when deinit mesh stack
struct esp_ble_mesh_elem_t
Abstraction that describes a BLE Mesh Element. This structure is associated with struct bt_mesh_elem in
mesh_access.h
Public Members
uint16_t element_addr
Element Address, assigned during provisioning.
esp_ble_mesh_model_t *sig_models
SIG Models
esp_ble_mesh_model_t *vnd_models
Vendor Models
struct esp_ble_mesh_model_pub_t
Abstraction that describes a model publication context. This structure is associated with struct
bt_mesh_model_pub in mesh_access.h
Public Members
esp_ble_mesh_model_t *model
Pointer to the model to which the context belongs. Initialized by the stack.
uint16_t publish_addr
Publish Address.
uint16_t app_idx
Publish AppKey Index.
uint16_t cred
Friendship Credentials Flag.
uint16_t send_rel
Force reliable sending (segment acks)
uint8_t ttl
Publish Time to Live.
uint8_t retransmit
Retransmit Count & Interval Steps.
uint8_t period
Publish Period.
uint8_t period_div
Divisor for the Period.
uint8_t fast_period
Use FastPeriodDivisor
uint8_t count
Retransmissions left.
uint32_t period_start
Start of the current period.
esp_ble_mesh_cb_t update
Callback used to update publish message. Initialized by the stack.
uint8_t dev_role
Role of the device that is going to publish messages
struct esp_ble_mesh_model_op_t
Abstraction that describes a model operation context. This structure is associated with struct
bt_mesh_model_op in mesh_access.h
Public Members
esp_ble_mesh_cb_t param_cb
Callback used to handle message. Initialized by the stack.
struct esp_ble_mesh_model_cbs_t
Abstraction that describes a model callback structure. This structure is associated with struct
bt_mesh_model_cb in mesh_access.h.
Public Members
esp_ble_mesh_cb_t init_cb
Callback used during model initialization. Initialized by the stack.
struct esp_ble_mesh_model
Abstraction that describes a Mesh Model instance. This structure is associated with struct bt_mesh_model in
mesh_access.h
Public Members
uint16_t company_id
16-bit company identifier
uint16_t model_id
16-bit model identifier
uint8_t element_idx
Internal information, mainly for persistent storage Belongs to Nth element
uint8_t model_idx
Is the Nth model in the element
uint16_t flags
Information about what has changed
esp_ble_mesh_elem_t *element
The Element to which this Model belongs
uint16_t keys[CONFIG_BLE_MESH_MODEL_KEY_COUNT]
AppKey List
uint16_t groups[CONFIG_BLE_MESH_MODEL_GROUP_COUNT]
Subscription List (group or virtual addresses)
esp_ble_mesh_model_op_t *op
Model operation context
esp_ble_mesh_model_cbs_t *cb
Model callback structure
void *user_data
Model-specific user data
struct esp_ble_mesh_msg_ctx_t
Message sending context. This structure is associated with struct bt_mesh_msg_ctx in mesh_access.h
Public Members
uint16_t net_idx
NetKey Index of the subnet through which to send the message.
uint16_t app_idx
AppKey Index for message encryption.
uint16_t addr
Remote address.
uint16_t recv_dst
Destination address of a received message. Not used for sending.
int8_t recv_rssi
RSSI of received packet. Not used for sending.
uint8_t recv_ttl
Received TTL value. Not used for sending.
uint8_t send_rel
Force sending reliably by using segment acknowledgement
uint8_t send_ttl
TTL, or ESP_BLE_MESH_TTL_DEFAULT for default TTL.
uint32_t recv_op
Opcode of a received message. Not used for sending message.
esp_ble_mesh_model_t *model
Model corresponding to the message, no need to be initialized before sending message
bool srv_send
Indicate if the message is sent by a node server model, no need to be initialized before sending message
struct esp_ble_mesh_prov_t
Provisioning properties & capabilities. This structure is associated with struct bt_mesh_prov in mesh_access.h
struct esp_ble_mesh_comp_t
Node Composition data context. This structure is associated with struct bt_mesh_comp in mesh_access.h
Public Members
uint16_t cid
16-bit SIG-assigned company identifier
uint16_t pid
16-bit vendor-assigned product identifier
uint16_t vid
16-bit vendor-assigned product version identifier
size_t element_count
Element count
esp_ble_mesh_elem_t *elements
A sequence of elements
struct esp_ble_mesh_unprov_dev_add_t
Information of the device which is going to be added for provisioning.
Public Members
esp_ble_mesh_bd_addr_t addr
Device address
esp_ble_mesh_addr_type_t addr_type
Device address type
uint8_t uuid[16]
Device UUID
uint16_t oob_info
Device OOB Info ADD_DEV_START_PROV_NOW_FLAG shall not be set if the bearer has both
PB-ADV and PB-GATT enabled
esp_ble_mesh_prov_bearer_t bearer
Provisioning Bearer
struct esp_ble_mesh_device_delete_t
Information of the device which is going to be deleted.
Public Members
esp_ble_mesh_bd_addr_t addr
Device address
esp_ble_mesh_addr_type_t addr_type
Device address type
uint8_t uuid[16]
Device UUID
uint8_t flag
BIT0: device address; BIT1: device UUID
struct esp_ble_mesh_prov_data_info_t
Information of the provisioner which is going to be updated.
Public Members
uint16_t net_idx
NetKey Index
uint8_t flags
Flags
uint32_t iv_index
IV Index
uint8_t flag
BIT0: net_idx; BIT1: flags; BIT2: iv_index
struct esp_ble_mesh_node_t
Information of the provisioned node
Public Members
esp_ble_mesh_bd_addr_t addr
Node device address
esp_ble_mesh_addr_type_t addr_type
Node device address type
uint8_t dev_uuid[16]
Device UUID
uint16_t oob_info
Node OOB information
uint16_t unicast_addr
Node unicast address
uint8_t element_num
Node element number
uint16_t net_idx
Node NetKey Index
uint8_t flags
Node key refresh flag and iv update flag
uint32_t iv_index
Node IV Index
uint8_t dev_key[16]
Node device key
char name[ESP_BLE_MESH_NODE_NAME_MAX_LEN + 1]
Node name
uint16_t comp_length
Length of Composition Data
uint8_t *comp_data
Value of Composition Data
struct esp_ble_mesh_fast_prov_info_t
Context of fast provisioning which need to be set.
Public Members
uint16_t unicast_min
Minimum unicast address used for fast provisioning
uint16_t unicast_max
Maximum unicast address used for fast provisioning
uint16_t net_idx
Netkey index used for fast provisioning
uint8_t flags
Flags used for fast provisioning
uint32_t iv_index
IV Index used for fast provisioning
uint8_t offset
Offset of the UUID to be compared
uint8_t match_len
Length of the UUID to be compared
uint8_t match_val[16]
Value of UUID to be compared
struct esp_ble_mesh_heartbeat_filter_info_t
Context of Provisioner heartbeat filter information to be set
Public Members
uint16_t hb_src
Heartbeat source address (unicast address)
uint16_t hb_dst
Heartbeat destination address (unicast address or group address)
struct esp_ble_mesh_client_op_pair_t
BLE Mesh client models related definitions.
Client model Get/Set message opcode and corresponding Status message opcode
Public Members
uint32_t cli_op
The client message opcode
uint32_t status_op
The server status opcode corresponding to the client message opcode
struct esp_ble_mesh_client_t
Client Model user data context.
Public Members
esp_ble_mesh_model_t *model
Pointer to the client model. Initialized by the stack.
int op_pair_size
Size of the op_pair
uint32_t publish_status
Callback used to handle the received unsolicited message. Initialized by the stack.
void *internal_data
Pointer to the internal data of client model
uint8_t msg_role
Role of the device (Node/Provisioner) that is going to send messages
struct esp_ble_mesh_client_common_param_t
Common parameters of the messages sent by Client Model.
Public Members
esp_ble_mesh_opcode_t opcode
Message opcode
esp_ble_mesh_model_t *model
Pointer to the client model structure
esp_ble_mesh_msg_ctx_t ctx
The context used to send message
int32_t msg_timeout
Timeout value (ms) to get response to the sent message Note: if using default timeout value in menuconfig,
make sure to set this value to 0
uint8_t msg_role
Role of the device - Node/Provisioner
struct esp_ble_mesh_state_transition_t
Parameters of the server model state transition
Public Functions
BLE_MESH_ATOMIC_DEFINE(flag, ESP_BLE_MESH_SERVER_FLAG_MAX)
Flag used to indicate if the transition timer has been started internally.
If the model which contains esp_ble_mesh_state_transition_t sets “set_auto_rsp”to
ESP_BLE_MESH_SERVER_RSP_BY_APP, the handler of the timer shall be initialized by the
users.
And users can use this flag to indicate whether the timer is started or not.
Public Members
bool just_started
Indicate if the state transition has just started
uint8_t trans_time
State transition time
uint8_t remain_time
Remaining time of state transition
uint8_t delay
Delay before starting state transition
uint32_t quo_tt
Duration of each divided transition step
uint32_t counter
Number of steps which the transition duration is divided
uint32_t total_duration
State transition total duration
int64_t start_timestamp
Time when the state transition is started
struct esp_ble_mesh_last_msg_info_t
Parameters of the server model received last same set message.
Public Members
uint8_t tid
Transaction number of the last message
uint16_t src
Source address of the last message
uint16_t dst
Destination address of the last message
int64_t timestamp
Time when the last message is received
struct esp_ble_mesh_server_rsp_ctrl_t
Parameters of the Server Model response control
Public Members
uint8_t get_auto_rsp
BLE Mesh Server Response Option.
uint8_t set_auto_rsp
Response control for Client Set messages
uint8_t status_auto_rsp
Response control for Server Status messages
Macros
ESP_BLE_MESH_SDU_MAX_LEN
< The maximum length of a BLE Mesh message, including Opcode, Payload and TransMIC Length of a short
Mesh MIC.
ESP_BLE_MESH_MIC_SHORT
Length of a long Mesh MIC.
ESP_BLE_MESH_MIC_LONG
The maximum length of a BLE Mesh provisioned node name
ESP_BLE_MESH_NODE_NAME_MAX_LEN
The maximum length of a BLE Mesh unprovisioned device name
ESP_BLE_MESH_DEVICE_NAME_MAX_LEN
The maximum length of settings user id
ESP_BLE_MESH_SETTINGS_UID_SIZE
Invalid settings index
ESP_BLE_MESH_INVALID_SETTINGS_IDX
Define the BLE Mesh octet 16 bytes size
ESP_BLE_MESH_OCTET16_LEN
ESP_BLE_MESH_OCTET8_LEN
ESP_BLE_MESH_CID_NVAL
Special TTL value to request using configured default TTL
ESP_BLE_MESH_TTL_DEFAULT
Maximum allowed TTL value
ESP_BLE_MESH_TTL_MAX
ESP_BLE_MESH_ADDR_UNASSIGNED
ESP_BLE_MESH_ADDR_ALL_NODES
ESP_BLE_MESH_ADDR_PROXIES
ESP_BLE_MESH_ADDR_FRIENDS
ESP_BLE_MESH_ADDR_RELAYS
ESP_BLE_MESH_KEY_UNUSED
ESP_BLE_MESH_KEY_DEV
ESP_BLE_MESH_KEY_PRIMARY
ESP_BLE_MESH_KEY_ANY
Primary Network Key index
ESP_BLE_MESH_NET_PRIMARY
Relay state value
ESP_BLE_MESH_RELAY_DISABLED
ESP_BLE_MESH_RELAY_ENABLED
ESP_BLE_MESH_RELAY_NOT_SUPPORTED
Beacon state value
ESP_BLE_MESH_BEACON_DISABLED
ESP_BLE_MESH_BEACON_ENABLED
GATT Proxy state value
ESP_BLE_MESH_GATT_PROXY_DISABLED
ESP_BLE_MESH_GATT_PROXY_ENABLED
ESP_BLE_MESH_GATT_PROXY_NOT_SUPPORTED
Friend state value
ESP_BLE_MESH_FRIEND_DISABLED
ESP_BLE_MESH_FRIEND_ENABLED
ESP_BLE_MESH_FRIEND_NOT_SUPPORTED
Node identity state value
ESP_BLE_MESH_NODE_IDENTITY_STOPPED
ESP_BLE_MESH_NODE_IDENTITY_RUNNING
ESP_BLE_MESH_NODE_IDENTITY_NOT_SUPPORTED
Supported features
ESP_BLE_MESH_FEATURE_RELAY
ESP_BLE_MESH_FEATURE_PROXY
ESP_BLE_MESH_FEATURE_FRIEND
ESP_BLE_MESH_FEATURE_LOW_POWER
ESP_BLE_MESH_FEATURE_ALL_SUPPORTED
ESP_BLE_MESH_ADDR_IS_UNICAST(addr)
ESP_BLE_MESH_ADDR_IS_GROUP(addr)
ESP_BLE_MESH_ADDR_IS_VIRTUAL(addr)
ESP_BLE_MESH_ADDR_IS_RFU(addr)
ESP_BLE_MESH_INVALID_NODE_INDEX
ESP_BLE_MESH_TRANSMIT(count, int_ms)
Encode transmission count & interval steps.
Note: For example, ESP_BLE_MESH_TRANSMIT(2, 20) means that the message will be sent about
90ms(count is 3, step is 1, interval is 30 ms which includes 10ms of advertising interval random delay).
Parameters
• count –Number of retransmissions (first transmission is excluded).
• int_ms –Interval steps in milliseconds. Must be greater than 0 and a multiple of 10.
Returns BLE Mesh transmit value that can be used e.g. for the default values of the Configuration
Model data.
ESP_BLE_MESH_GET_TRANSMIT_COUNT(transmit)
Decode transmit count from a transmit value.
Parameters
• transmit –Encoded transmit count & interval value.
Returns Transmission count (actual transmissions equal to N + 1).
ESP_BLE_MESH_GET_TRANSMIT_INTERVAL(transmit)
Decode transmit interval from a transmit value.
Parameters
• transmit –Encoded transmit count & interval value.
Returns Transmission interval in milliseconds.
ESP_BLE_MESH_PUBLISH_TRANSMIT(count, int_ms)
Encode Publish Retransmit count & interval steps.
Parameters
• count –Number of retransmissions (first transmission is excluded).
• int_ms –Interval steps in milliseconds. Must be greater than 0 and a multiple of 50.
Returns BLE Mesh transmit value that can be used e.g. for the default values of the Configuration
Model data.
ESP_BLE_MESH_GET_PUBLISH_TRANSMIT_COUNT(transmit)
Decode Publish Retransmit count from a given value.
Parameters
• transmit –Encoded Publish Retransmit count & interval value.
Returns Retransmission count (actual transmissions equal to N + 1).
ESP_BLE_MESH_GET_PUBLISH_TRANSMIT_INTERVAL(transmit)
Decode Publish Retransmit interval from a given value.
Callbacks which are not needed to be initialized by users (set with 0 and will be initialized internally)
Parameters
• transmit –Encoded Publish Retransmit count & interval value.
Returns Transmission interval in milliseconds.
ESP_BLE_MESH_PROV_STATIC_OOB_MAX_LEN
Maximum length of string used by Output OOB authentication
ESP_BLE_MESH_PROV_OUTPUT_OOB_MAX_LEN
Maximum length of string used by Output OOB authentication
ESP_BLE_MESH_PROV_INPUT_OOB_MAX_LEN
Macros used to define message opcode
ESP_BLE_MESH_MODEL_OP_1(b0)
ESP_BLE_MESH_MODEL_OP_2(b0, b1)
ESP_BLE_MESH_MODEL_OP_3(b0, cid)
This macro is associated with BLE_MESH_MODEL_CB in mesh_access.h
ESP_BLE_MESH_SIG_MODEL(_id, _op, _pub, _user_data)
This macro is associated with BLE_MESH_MODEL_VND_CB in mesh_access.h
ESP_BLE_MESH_VENDOR_MODEL(_company, _id, _op, _pub, _user_data)
Parameters
• _loc –Location Descriptor.
• _mods –Array of SIG models.
• _vnd_mods –Array of vendor models.
BT_OCTET32_LEN
BD_ADDR_LEN
ESP_BLE_MESH_ADDR_TYPE_PUBLIC
ESP_BLE_MESH_ADDR_TYPE_RANDOM
ESP_BLE_MESH_ADDR_TYPE_RPA_PUBLIC
ESP_BLE_MESH_ADDR_TYPE_RPA_RANDOM
ESP_BLE_MESH_MODEL_OP_END
Define the terminator for the model operation table. Each model operation struct array must use this terminator
as the end tag of the operation unit.
ESP_BLE_MESH_MODEL_NONE
Helper to define an empty model array. This structure is associated with BLE_MESH_MODEL_NONE in
mesh_access.h
ADD_DEV_RM_AFTER_PROV_FLAG
Device will be removed from queue after provisioned successfully
ADD_DEV_START_PROV_NOW_FLAG
Start provisioning device immediately
ADD_DEV_FLUSHABLE_DEV_FLAG
Device can be remove when queue is full and new device is going to added
DEL_DEV_ADDR_FLAG
DEL_DEV_UUID_FLAG
PROV_DATA_NET_IDX_FLAG
PROV_DATA_FLAGS_FLAG
PROV_DATA_IV_INDEX_FLAG
ESP_BLE_MESH_HEARTBEAT_FILTER_ACCEPTLIST
ESP_BLE_MESH_HEARTBEAT_FILTER_REJECTLIST
Provisioner heartbeat filter operation
ESP_BLE_MESH_HEARTBEAT_FILTER_ADD
ESP_BLE_MESH_HEARTBEAT_FILTER_REMOVE
ESP_BLE_MESH_MODEL_ID_CONFIG_SRV
BLE Mesh models related Model ID and Opcode definitions.
< Foundation Models
ESP_BLE_MESH_MODEL_ID_CONFIG_CLI
ESP_BLE_MESH_MODEL_ID_HEALTH_SRV
ESP_BLE_MESH_MODEL_ID_HEALTH_CLI
Models from the Mesh Model Specification
ESP_BLE_MESH_MODEL_ID_GEN_ONOFF_SRV
ESP_BLE_MESH_MODEL_ID_GEN_ONOFF_CLI
ESP_BLE_MESH_MODEL_ID_GEN_LEVEL_SRV
ESP_BLE_MESH_MODEL_ID_GEN_LEVEL_CLI
ESP_BLE_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_SRV
ESP_BLE_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_CLI
ESP_BLE_MESH_MODEL_ID_GEN_POWER_ONOFF_SRV
ESP_BLE_MESH_MODEL_ID_GEN_POWER_ONOFF_SETUP_SRV
ESP_BLE_MESH_MODEL_ID_GEN_POWER_ONOFF_CLI
ESP_BLE_MESH_MODEL_ID_GEN_POWER_LEVEL_SRV
ESP_BLE_MESH_MODEL_ID_GEN_POWER_LEVEL_SETUP_SRV
ESP_BLE_MESH_MODEL_ID_GEN_POWER_LEVEL_CLI
ESP_BLE_MESH_MODEL_ID_GEN_BATTERY_SRV
ESP_BLE_MESH_MODEL_ID_GEN_BATTERY_CLI
ESP_BLE_MESH_MODEL_ID_GEN_LOCATION_SRV
ESP_BLE_MESH_MODEL_ID_GEN_LOCATION_SETUP_SRV
ESP_BLE_MESH_MODEL_ID_GEN_LOCATION_CLI
ESP_BLE_MESH_MODEL_ID_GEN_ADMIN_PROP_SRV
ESP_BLE_MESH_MODEL_ID_GEN_MANUFACTURER_PROP_SRV
ESP_BLE_MESH_MODEL_ID_GEN_USER_PROP_SRV
ESP_BLE_MESH_MODEL_ID_GEN_CLIENT_PROP_SRV
ESP_BLE_MESH_MODEL_ID_GEN_PROP_CLI
ESP_BLE_MESH_MODEL_ID_SENSOR_SRV
ESP_BLE_MESH_MODEL_ID_SENSOR_SETUP_SRV
ESP_BLE_MESH_MODEL_ID_SENSOR_CLI
ESP_BLE_MESH_MODEL_ID_TIME_SRV
ESP_BLE_MESH_MODEL_ID_TIME_SETUP_SRV
ESP_BLE_MESH_MODEL_ID_TIME_CLI
ESP_BLE_MESH_MODEL_ID_SCENE_SRV
ESP_BLE_MESH_MODEL_ID_SCENE_SETUP_SRV
ESP_BLE_MESH_MODEL_ID_SCENE_CLI
ESP_BLE_MESH_MODEL_ID_SCHEDULER_SRV
ESP_BLE_MESH_MODEL_ID_SCHEDULER_SETUP_SRV
ESP_BLE_MESH_MODEL_ID_SCHEDULER_CLI
ESP_BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_SRV
ESP_BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_SETUP_SRV
ESP_BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_CLI
ESP_BLE_MESH_MODEL_ID_LIGHT_CTL_SRV
ESP_BLE_MESH_MODEL_ID_LIGHT_CTL_SETUP_SRV
ESP_BLE_MESH_MODEL_ID_LIGHT_CTL_CLI
ESP_BLE_MESH_MODEL_ID_LIGHT_CTL_TEMP_SRV
ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_SRV
ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_SETUP_SRV
ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_CLI
ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_HUE_SRV
ESP_BLE_MESH_MODEL_ID_LIGHT_HSL_SAT_SRV
ESP_BLE_MESH_MODEL_ID_LIGHT_XYL_SRV
ESP_BLE_MESH_MODEL_ID_LIGHT_XYL_SETUP_SRV
ESP_BLE_MESH_MODEL_ID_LIGHT_XYL_CLI
ESP_BLE_MESH_MODEL_ID_LIGHT_LC_SRV
ESP_BLE_MESH_MODEL_ID_LIGHT_LC_SETUP_SRV
ESP_BLE_MESH_MODEL_ID_LIGHT_LC_CLI
ESP_BLE_MESH_MODEL_OP_BEACON_GET
Config Beacon Get
ESP_BLE_MESH_MODEL_OP_COMPOSITION_DATA_GET
Config Composition Data Get
ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_GET
Config Default TTL Get
ESP_BLE_MESH_MODEL_OP_GATT_PROXY_GET
Config GATT Proxy Get
ESP_BLE_MESH_MODEL_OP_RELAY_GET
Config Relay Get
ESP_BLE_MESH_MODEL_OP_MODEL_PUB_GET
Config Model Publication Get
ESP_BLE_MESH_MODEL_OP_FRIEND_GET
Config Friend Get
ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_GET
Config Heartbeat Publication Get
ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_GET
Config Heartbeat Subscription Get
ESP_BLE_MESH_MODEL_OP_NET_KEY_GET
Config NetKey Get
ESP_BLE_MESH_MODEL_OP_APP_KEY_GET
Config AppKey Get
ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_GET
Config Node Identity Get
ESP_BLE_MESH_MODEL_OP_SIG_MODEL_SUB_GET
Config SIG Model Subscription Get
ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_SUB_GET
Config Vendor Model Subscription Get
ESP_BLE_MESH_MODEL_OP_SIG_MODEL_APP_GET
Config SIG Model App Get
ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_APP_GET
Config Vendor Model App Get
ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_GET
Config Key Refresh Phase Get
ESP_BLE_MESH_MODEL_OP_LPN_POLLTIMEOUT_GET
Config Low Power Node PollTimeout Get
ESP_BLE_MESH_MODEL_OP_NETWORK_TRANSMIT_GET
Config Network Transmit Get
ESP_BLE_MESH_MODEL_OP_BEACON_SET
Config Beacon Set
ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_SET
Config Default TTL Set
ESP_BLE_MESH_MODEL_OP_GATT_PROXY_SET
Config GATT Proxy Set
ESP_BLE_MESH_MODEL_OP_RELAY_SET
Config Relay Set
ESP_BLE_MESH_MODEL_OP_MODEL_PUB_SET
Config Model Publication Set
ESP_BLE_MESH_MODEL_OP_MODEL_SUB_ADD
Config Model Subscription Add
ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_ADD
Config Model Subscription Virtual Address Add
ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE
Config Model Subscription Delete
ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_DELETE
Config Model Subscription Virtual Address Delete
ESP_BLE_MESH_MODEL_OP_MODEL_SUB_OVERWRITE
Config Model Subscription Overwrite
ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_OVERWRITE
Config Model Subscription Virtual Address Overwrite
ESP_BLE_MESH_MODEL_OP_NET_KEY_ADD
Config NetKey Add
ESP_BLE_MESH_MODEL_OP_APP_KEY_ADD
Config AppKey Add
ESP_BLE_MESH_MODEL_OP_MODEL_APP_BIND
Config Model App Bind
ESP_BLE_MESH_MODEL_OP_NODE_RESET
Config Node Reset
ESP_BLE_MESH_MODEL_OP_FRIEND_SET
Config Friend Set
ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_SET
Config Heartbeat Publication Set
ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_SET
Config Heartbeat Subscription Set
ESP_BLE_MESH_MODEL_OP_NET_KEY_UPDATE
Config NetKey Update
ESP_BLE_MESH_MODEL_OP_NET_KEY_DELETE
Config NetKey Delete
ESP_BLE_MESH_MODEL_OP_APP_KEY_UPDATE
Config AppKey Update
ESP_BLE_MESH_MODEL_OP_APP_KEY_DELETE
Config AppKey Delete
ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_SET
Config Node Identity Set
ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_SET
Config Key Refresh Phase Set
ESP_BLE_MESH_MODEL_OP_MODEL_PUB_VIRTUAL_ADDR_SET
Config Model Publication Virtual Address Set
ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE_ALL
Config Model Subscription Delete All
ESP_BLE_MESH_MODEL_OP_MODEL_APP_UNBIND
Config Model App Unbind
ESP_BLE_MESH_MODEL_OP_NETWORK_TRANSMIT_SET
Config Network Transmit Set
ESP_BLE_MESH_MODEL_OP_BEACON_STATUS
ESP_BLE_MESH_MODEL_OP_COMPOSITION_DATA_STATUS
ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_STATUS
ESP_BLE_MESH_MODEL_OP_GATT_PROXY_STATUS
ESP_BLE_MESH_MODEL_OP_RELAY_STATUS
ESP_BLE_MESH_MODEL_OP_MODEL_PUB_STATUS
ESP_BLE_MESH_MODEL_OP_MODEL_SUB_STATUS
ESP_BLE_MESH_MODEL_OP_SIG_MODEL_SUB_LIST
ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_SUB_LIST
ESP_BLE_MESH_MODEL_OP_NET_KEY_STATUS
ESP_BLE_MESH_MODEL_OP_NET_KEY_LIST
ESP_BLE_MESH_MODEL_OP_APP_KEY_STATUS
ESP_BLE_MESH_MODEL_OP_APP_KEY_LIST
ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_STATUS
ESP_BLE_MESH_MODEL_OP_MODEL_APP_STATUS
ESP_BLE_MESH_MODEL_OP_SIG_MODEL_APP_LIST
ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_APP_LIST
ESP_BLE_MESH_MODEL_OP_NODE_RESET_STATUS
ESP_BLE_MESH_MODEL_OP_FRIEND_STATUS
ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_STATUS
ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_STATUS
ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_STATUS
ESP_BLE_MESH_MODEL_OP_LPN_POLLTIMEOUT_STATUS
ESP_BLE_MESH_MODEL_OP_NETWORK_TRANSMIT_STATUS
ESP_BLE_MESH_CFG_STATUS_SUCCESS
ESP_BLE_MESH_CFG_STATUS_INVALID_ADDRESS
ESP_BLE_MESH_CFG_STATUS_INVALID_MODEL
ESP_BLE_MESH_CFG_STATUS_INVALID_APPKEY
ESP_BLE_MESH_CFG_STATUS_INVALID_NETKEY
ESP_BLE_MESH_CFG_STATUS_INSUFFICIENT_RESOURCES
ESP_BLE_MESH_CFG_STATUS_KEY_INDEX_ALREADY_STORED
ESP_BLE_MESH_CFG_STATUS_INVALID_PUBLISH_PARAMETERS
ESP_BLE_MESH_CFG_STATUS_NOT_A_SUBSCRIBE_MODEL
ESP_BLE_MESH_CFG_STATUS_STORAGE_FAILURE
ESP_BLE_MESH_CFG_STATUS_FEATURE_NOT_SUPPORTED
ESP_BLE_MESH_CFG_STATUS_CANNOT_UPDATE
ESP_BLE_MESH_CFG_STATUS_CANNOT_REMOVE
ESP_BLE_MESH_CFG_STATUS_CANNOT_BIND
ESP_BLE_MESH_CFG_STATUS_TEMP_UNABLE_TO_CHANGE_STATE
ESP_BLE_MESH_CFG_STATUS_CANNOT_SET
ESP_BLE_MESH_CFG_STATUS_UNSPECIFIED_ERROR
ESP_BLE_MESH_CFG_STATUS_INVALID_BINDING
ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_GET
Health Fault Get
ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_GET
Health Period Get
ESP_BLE_MESH_MODEL_OP_ATTENTION_GET
Health Attention Get
ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR
Health Fault Clear
ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR_UNACK
Health Fault Clear Unacknowledged
ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST
Health Fault Test
ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST_UNACK
Health Fault Test Unacknowledged
ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET
Health Period Set
ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET_UNACK
Health Period Set Unacknowledged
ESP_BLE_MESH_MODEL_OP_ATTENTION_SET
Health Attention Set
ESP_BLE_MESH_MODEL_OP_ATTENTION_SET_UNACK
Health Attention Set Unacknowledged
ESP_BLE_MESH_MODEL_OP_HEALTH_CURRENT_STATUS
ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_STATUS
ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_STATUS
ESP_BLE_MESH_MODEL_OP_ATTENTION_STATUS
ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_GET
ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_SET
ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UNACK
ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_STATUS
Generic Level Message Opcode
ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_GET
ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_SET
ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_SET_UNACK
ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_STATUS
ESP_BLE_MESH_MODEL_OP_GEN_DELTA_SET
ESP_BLE_MESH_MODEL_OP_GEN_DELTA_SET_UNACK
ESP_BLE_MESH_MODEL_OP_GEN_MOVE_SET
ESP_BLE_MESH_MODEL_OP_GEN_MOVE_SET_UNACK
Generic Default Transition Time Message Opcode
ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_GET
ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET
ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET_UNACK
ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_STATUS
Generic Power OnOff Message Opcode
ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_GET
ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_STATUS
Generic Power OnOff Setup Message Opcode
ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET
ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET_UNACK
Generic Power Level Message Opcode
ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_GET
ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET
ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET_UNACK
ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_STATUS
ESP_BLE_MESH_MODEL_OP_GEN_POWER_LAST_GET
ESP_BLE_MESH_MODEL_OP_GEN_POWER_LAST_STATUS
ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_GET
ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_STATUS
ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_GET
ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_STATUS
Generic Power Level Setup Message Opcode
ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET
ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET_UNACK
ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET
ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET_UNACK
Generic Battery Message Opcode
ESP_BLE_MESH_MODEL_OP_GEN_BATTERY_GET
ESP_BLE_MESH_MODEL_OP_GEN_BATTERY_STATUS
Generic Location Message Opcode
ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_GET
ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_STATUS
ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_GET
ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_STATUS
Generic Location Setup Message Opcode
ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET
ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET_UNACK
ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET
ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET_UNACK
Generic Manufacturer Property Message Opcode
ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTIES_GET
ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTIES_STATUS
ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_GET
ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET
ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET_UNACK
ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_STATUS
Generic Admin Property Message Opcode
ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTIES_GET
ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTIES_STATUS
ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_GET
ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET
ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET_UNACK
ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_STATUS
Generic User Property Message Opcode
ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTIES_GET
ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTIES_STATUS
ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_GET
ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET
ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET_UNACK
ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_STATUS
Generic Client Property Message Opcode
ESP_BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_GET
ESP_BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_STATUS
ESP_BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_GET
ESP_BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_STATUS
ESP_BLE_MESH_MODEL_OP_SENSOR_GET
ESP_BLE_MESH_MODEL_OP_SENSOR_STATUS
ESP_BLE_MESH_MODEL_OP_SENSOR_COLUMN_GET
ESP_BLE_MESH_MODEL_OP_SENSOR_COLUMN_STATUS
ESP_BLE_MESH_MODEL_OP_SENSOR_SERIES_GET
ESP_BLE_MESH_MODEL_OP_SENSOR_SERIES_STATUS
Sensor Setup Message Opcode
ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_GET
ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET
ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET_UNACK
ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_STATUS
ESP_BLE_MESH_MODEL_OP_SENSOR_SETTINGS_GET
ESP_BLE_MESH_MODEL_OP_SENSOR_SETTINGS_STATUS
ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_GET
ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_SET
ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_SET_UNACK
ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_STATUS
ESP_BLE_MESH_MODEL_OP_TIME_GET
ESP_BLE_MESH_MODEL_OP_TIME_SET
ESP_BLE_MESH_MODEL_OP_TIME_STATUS
ESP_BLE_MESH_MODEL_OP_TIME_ROLE_GET
ESP_BLE_MESH_MODEL_OP_TIME_ROLE_SET
ESP_BLE_MESH_MODEL_OP_TIME_ROLE_STATUS
ESP_BLE_MESH_MODEL_OP_TIME_ZONE_GET
ESP_BLE_MESH_MODEL_OP_TIME_ZONE_SET
ESP_BLE_MESH_MODEL_OP_TIME_ZONE_STATUS
ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_GET
ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_SET
ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_STATUS
Scene Message Opcode
ESP_BLE_MESH_MODEL_OP_SCENE_GET
ESP_BLE_MESH_MODEL_OP_SCENE_RECALL
ESP_BLE_MESH_MODEL_OP_SCENE_RECALL_UNACK
ESP_BLE_MESH_MODEL_OP_SCENE_STATUS
ESP_BLE_MESH_MODEL_OP_SCENE_REGISTER_GET
ESP_BLE_MESH_MODEL_OP_SCENE_REGISTER_STATUS
Scene Setup Message Opcode
ESP_BLE_MESH_MODEL_OP_SCENE_STORE
ESP_BLE_MESH_MODEL_OP_SCENE_STORE_UNACK
ESP_BLE_MESH_MODEL_OP_SCENE_DELETE
ESP_BLE_MESH_MODEL_OP_SCENE_DELETE_UNACK
Scheduler Message Opcode
ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_GET
ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_STATUS
ESP_BLE_MESH_MODEL_OP_SCHEDULER_GET
ESP_BLE_MESH_MODEL_OP_SCHEDULER_STATUS
Scheduler Setup Message Opcode
ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET
ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LAST_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LAST_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_STATUS
Light Lightness Setup Message Opcode
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET_UNACK
Light CTL Message Opcode
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_STATUS
Light CTL Setup Message Opcode
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET_UNACK
Light HSL Message Opcode
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_TARGET_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_TARGET_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_STATUS
Light HSL Setup Message Opcode
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET_UNACK
Light xyL Message Opcode
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_TARGET_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_TARGET_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_STATUS
Light xyL Setup Message Opcode
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET_UNACK
Light Control Message Opcode
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_STATUS
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_GET
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET_UNACK
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_STATUS
ESP_BLE_MESH_MODEL_STATUS_SUCCESS
ESP_BLE_MESH_MODEL_STATUS_CANNOT_SET_RANGE_MIN
ESP_BLE_MESH_MODEL_STATUS_CANNOT_SET_RANGE_MAX
ESP_BLE_MESH_SERVER_RSP_BY_APP
Response need to be sent in the application
ESP_BLE_MESH_SERVER_AUTO_RSP
Response will be sent internally
Type Definitions
Enumerations
enum esp_ble_mesh_cb_type_t
Values:
enumerator ESP_BLE_MESH_TYPE_PROV_CB
enumerator ESP_BLE_MESH_TYPE_OUTPUT_NUM_CB
enumerator ESP_BLE_MESH_TYPE_OUTPUT_STR_CB
enumerator ESP_BLE_MESH_TYPE_INTPUT_CB
enumerator ESP_BLE_MESH_TYPE_LINK_OPEN_CB
enumerator ESP_BLE_MESH_TYPE_LINK_CLOSE_CB
enumerator ESP_BLE_MESH_TYPE_COMPLETE_CB
enumerator ESP_BLE_MESH_TYPE_RESET_CB
enum esp_ble_mesh_oob_method_t
Values:
enumerator ESP_BLE_MESH_NO_OOB
enumerator ESP_BLE_MESH_STATIC_OOB
enumerator ESP_BLE_MESH_OUTPUT_OOB
enumerator ESP_BLE_MESH_INPUT_OOB
enum esp_ble_mesh_output_action_t
Values:
enumerator ESP_BLE_MESH_NO_OUTPUT
enumerator ESP_BLE_MESH_BLINK
enumerator ESP_BLE_MESH_BEEP
enumerator ESP_BLE_MESH_VIBRATE
enumerator ESP_BLE_MESH_DISPLAY_NUMBER
enumerator ESP_BLE_MESH_DISPLAY_STRING
enum esp_ble_mesh_input_action_t
Values:
enumerator ESP_BLE_MESH_NO_INPUT
enumerator ESP_BLE_MESH_PUSH
enumerator ESP_BLE_MESH_TWIST
enumerator ESP_BLE_MESH_ENTER_NUMBER
enumerator ESP_BLE_MESH_ENTER_STRING
enum esp_ble_mesh_prov_bearer_t
Values:
enumerator ESP_BLE_MESH_PROV_ADV
enumerator ESP_BLE_MESH_PROV_GATT
enum esp_ble_mesh_prov_oob_info_t
Values:
enumerator ESP_BLE_MESH_PROV_OOB_OTHER
enumerator ESP_BLE_MESH_PROV_OOB_URI
enumerator ESP_BLE_MESH_PROV_OOB_2D_CODE
enumerator ESP_BLE_MESH_PROV_OOB_BAR_CODE
enumerator ESP_BLE_MESH_PROV_OOB_NFC
enumerator ESP_BLE_MESH_PROV_OOB_NUMBER
enumerator ESP_BLE_MESH_PROV_OOB_STRING
enumerator ESP_BLE_MESH_PROV_OOB_ON_BOX
enumerator ESP_BLE_MESH_PROV_OOB_IN_BOX
enumerator ESP_BLE_MESH_PROV_OOB_ON_PAPER
enumerator ESP_BLE_MESH_PROV_OOB_IN_MANUAL
enumerator ESP_BLE_MESH_PROV_OOB_ON_DEV
enum esp_ble_mesh_dev_role_t
Values:
enumerator ROLE_NODE
enumerator ROLE_PROVISIONER
enumerator ROLE_FAST_PROV
enum esp_ble_mesh_fast_prov_action_t
Values:
enumerator FAST_PROV_ACT_NONE
enumerator FAST_PROV_ACT_ENTER
enumerator FAST_PROV_ACT_SUSPEND
enumerator FAST_PROV_ACT_EXIT
enumerator FAST_PROV_ACT_MAX
enum esp_ble_mesh_proxy_filter_type_t
Values:
enumerator PROXY_FILTER_WHITELIST
enumerator PROXY_FILTER_BLACKLIST
enum esp_ble_mesh_prov_cb_event_t
Values:
enumerator ESP_BLE_MESH_PROV_REGISTER_COMP_EVT
Initialize BLE Mesh provisioning capabilities and internal data information completion event
enumerator ESP_BLE_MESH_NODE_SET_UNPROV_DEV_NAME_COMP_EVT
Set the unprovisioned device name completion event
enumerator ESP_BLE_MESH_NODE_PROV_ENABLE_COMP_EVT
Enable node provisioning functionality completion event
enumerator ESP_BLE_MESH_NODE_PROV_DISABLE_COMP_EVT
Disable node provisioning functionality completion event
enumerator ESP_BLE_MESH_NODE_PROV_LINK_OPEN_EVT
Establish a BLE Mesh link event
enumerator ESP_BLE_MESH_NODE_PROV_LINK_CLOSE_EVT
Close a BLE Mesh link event
enumerator ESP_BLE_MESH_NODE_PROV_OOB_PUB_KEY_EVT
Generate Node input OOB public key event
enumerator ESP_BLE_MESH_NODE_PROV_OUTPUT_NUMBER_EVT
Generate Node Output Number event
enumerator ESP_BLE_MESH_NODE_PROV_OUTPUT_STRING_EVT
Generate Node Output String event
enumerator ESP_BLE_MESH_NODE_PROV_INPUT_EVT
Event requiring the user to input a number or string
enumerator ESP_BLE_MESH_NODE_PROV_COMPLETE_EVT
Provisioning done event
enumerator ESP_BLE_MESH_NODE_PROV_RESET_EVT
Provisioning reset event
enumerator ESP_BLE_MESH_NODE_PROV_SET_OOB_PUB_KEY_COMP_EVT
Node set oob public key completion event
enumerator ESP_BLE_MESH_NODE_PROV_INPUT_NUMBER_COMP_EVT
Node input number completion event
enumerator ESP_BLE_MESH_NODE_PROV_INPUT_STRING_COMP_EVT
Node input string completion event
enumerator ESP_BLE_MESH_NODE_PROXY_IDENTITY_ENABLE_COMP_EVT
Enable BLE Mesh Proxy Identity advertising completion event
enumerator ESP_BLE_MESH_NODE_PROXY_GATT_ENABLE_COMP_EVT
Enable BLE Mesh GATT Proxy Service completion event
enumerator ESP_BLE_MESH_NODE_PROXY_GATT_DISABLE_COMP_EVT
Disable BLE Mesh GATT Proxy Service completion event
enumerator ESP_BLE_MESH_NODE_ADD_LOCAL_NET_KEY_COMP_EVT
Node add NetKey locally completion event
enumerator ESP_BLE_MESH_NODE_ADD_LOCAL_APP_KEY_COMP_EVT
Node add AppKey locally completion event
enumerator ESP_BLE_MESH_NODE_BIND_APP_KEY_TO_MODEL_COMP_EVT
Node bind AppKey to model locally completion event
enumerator ESP_BLE_MESH_PROVISIONER_PROV_ENABLE_COMP_EVT
Provisioner enable provisioning functionality completion event
enumerator ESP_BLE_MESH_PROVISIONER_PROV_DISABLE_COMP_EVT
Provisioner disable provisioning functionality completion event
enumerator ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT
Provisioner receives unprovisioned device beacon event
enumerator ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_EVT
Provisioner read unprovisioned device OOB public key event
enumerator ESP_BLE_MESH_PROVISIONER_PROV_INPUT_EVT
Provisioner input value for provisioning procedure event
enumerator ESP_BLE_MESH_PROVISIONER_PROV_OUTPUT_EVT
Provisioner output value for provisioning procedure event
enumerator ESP_BLE_MESH_PROVISIONER_PROV_LINK_OPEN_EVT
Provisioner establish a BLE Mesh link event
enumerator ESP_BLE_MESH_PROVISIONER_PROV_LINK_CLOSE_EVT
Provisioner close a BLE Mesh link event
enumerator ESP_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT
Provisioner provisioning done event
enumerator ESP_BLE_MESH_PROVISIONER_ADD_UNPROV_DEV_COMP_EVT
Provisioner add a device to the list which contains devices that are waiting/going to be provisioned com-
pletion event
enumerator ESP_BLE_MESH_PROVISIONER_PROV_DEV_WITH_ADDR_COMP_EVT
Provisioner start to provision an unprovisioned device completion event
enumerator ESP_BLE_MESH_PROVISIONER_DELETE_DEV_COMP_EVT
Provisioner delete a device from the list, close provisioning link with the device completion event
enumerator ESP_BLE_MESH_PROVISIONER_SET_DEV_UUID_MATCH_COMP_EVT
Provisioner set the value to be compared with part of the unprovisioned device UUID completion event
enumerator ESP_BLE_MESH_PROVISIONER_SET_PROV_DATA_INFO_COMP_EVT
Provisioner set net_idx/flags/iv_index used for provisioning completion event
enumerator ESP_BLE_MESH_PROVISIONER_SET_STATIC_OOB_VALUE_COMP_EVT
Provisioner set static oob value used for provisioning completion event
enumerator ESP_BLE_MESH_PROVISIONER_SET_PRIMARY_ELEM_ADDR_COMP_EVT
Provisioner set unicast address of primary element completion event
enumerator ESP_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_COMP_EVT
Provisioner read unprovisioned device OOB public key completion event
enumerator ESP_BLE_MESH_PROVISIONER_PROV_INPUT_NUMBER_COMP_EVT
Provisioner input number completion event
enumerator ESP_BLE_MESH_PROVISIONER_PROV_INPUT_STRING_COMP_EVT
Provisioner input string completion event
enumerator ESP_BLE_MESH_PROVISIONER_SET_NODE_NAME_COMP_EVT
Provisioner set node name completion event
enumerator ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_APP_KEY_COMP_EVT
Provisioner add local app key completion event
enumerator ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_APP_KEY_COMP_EVT
Provisioner update local app key completion event
enumerator ESP_BLE_MESH_PROVISIONER_BIND_APP_KEY_TO_MODEL_COMP_EVT
Provisioner bind local model with local app key completion event
enumerator ESP_BLE_MESH_PROVISIONER_ADD_LOCAL_NET_KEY_COMP_EVT
Provisioner add local network key completion event
enumerator ESP_BLE_MESH_PROVISIONER_UPDATE_LOCAL_NET_KEY_COMP_EVT
Provisioner update local network key completion event
enumerator ESP_BLE_MESH_PROVISIONER_STORE_NODE_COMP_DATA_COMP_EVT
Provisioner store node composition data completion event
enumerator ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_UUID_COMP_EVT
Provisioner delete node with uuid completion event
enumerator ESP_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_ADDR_COMP_EVT
Provisioner delete node with unicast address completion event
enumerator ESP_BLE_MESH_PROVISIONER_ENABLE_HEARTBEAT_RECV_COMP_EVT
Provisioner start to receive heartbeat message completion event
enumerator ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_TYPE_COMP_EVT
Provisioner set the heartbeat filter type completion event
enumerator ESP_BLE_MESH_PROVISIONER_SET_HEARTBEAT_FILTER_INFO_COMP_EVT
Provisioner set the heartbeat filter information completion event
enumerator ESP_BLE_MESH_PROVISIONER_RECV_HEARTBEAT_MESSAGE_EVT
Provisioner receive heartbeat message event
enumerator ESP_BLE_MESH_PROVISIONER_DRIECT_ERASE_SETTINGS_COMP_EVT
Provisioner directly erase settings completion event
enumerator ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_INDEX_COMP_EVT
Provisioner open settings with index completion event
enumerator ESP_BLE_MESH_PROVISIONER_OPEN_SETTINGS_WITH_UID_COMP_EVT
Provisioner open settings with user id completion event
enumerator ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_INDEX_COMP_EVT
Provisioner close settings with index completion event
enumerator ESP_BLE_MESH_PROVISIONER_CLOSE_SETTINGS_WITH_UID_COMP_EVT
Provisioner close settings with user id completion event
enumerator ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_INDEX_COMP_EVT
Provisioner delete settings with index completion event
enumerator ESP_BLE_MESH_PROVISIONER_DELETE_SETTINGS_WITH_UID_COMP_EVT
Provisioner delete settings with user id completion event
enumerator ESP_BLE_MESH_SET_FAST_PROV_INFO_COMP_EVT
Set fast provisioning information (e.g. unicast address range, net_idx, etc.) completion event
enumerator ESP_BLE_MESH_SET_FAST_PROV_ACTION_COMP_EVT
Set fast provisioning action completion event
enumerator ESP_BLE_MESH_HEARTBEAT_MESSAGE_RECV_EVT
Receive Heartbeat message event
enumerator ESP_BLE_MESH_LPN_ENABLE_COMP_EVT
Enable Low Power Node completion event
enumerator ESP_BLE_MESH_LPN_DISABLE_COMP_EVT
Disable Low Power Node completion event
enumerator ESP_BLE_MESH_LPN_POLL_COMP_EVT
Low Power Node send Friend Poll completion event
enumerator ESP_BLE_MESH_LPN_FRIENDSHIP_ESTABLISH_EVT
Low Power Node establishes friendship event
enumerator ESP_BLE_MESH_LPN_FRIENDSHIP_TERMINATE_EVT
Low Power Node terminates friendship event
enumerator ESP_BLE_MESH_FRIEND_FRIENDSHIP_ESTABLISH_EVT
Friend Node establishes friendship event
enumerator ESP_BLE_MESH_FRIEND_FRIENDSHIP_TERMINATE_EVT
Friend Node terminates friendship event
enumerator ESP_BLE_MESH_PROXY_CLIENT_RECV_ADV_PKT_EVT
Proxy Client receives Network ID advertising packet event
enumerator ESP_BLE_MESH_PROXY_CLIENT_CONNECTED_EVT
Proxy Client establishes connection successfully event
enumerator ESP_BLE_MESH_PROXY_CLIENT_DISCONNECTED_EVT
Proxy Client terminates connection successfully event
enumerator ESP_BLE_MESH_PROXY_CLIENT_RECV_FILTER_STATUS_EVT
Proxy Client receives Proxy Filter Status event
enumerator ESP_BLE_MESH_PROXY_CLIENT_CONNECT_COMP_EVT
Proxy Client connect completion event
enumerator ESP_BLE_MESH_PROXY_CLIENT_DISCONNECT_COMP_EVT
Proxy Client disconnect completion event
enumerator ESP_BLE_MESH_PROXY_CLIENT_SET_FILTER_TYPE_COMP_EVT
Proxy Client set filter type completion event
enumerator ESP_BLE_MESH_PROXY_CLIENT_ADD_FILTER_ADDR_COMP_EVT
Proxy Client add filter address completion event
enumerator ESP_BLE_MESH_PROXY_CLIENT_REMOVE_FILTER_ADDR_COMP_EVT
Proxy Client remove filter address completion event
enumerator ESP_BLE_MESH_PROXY_SERVER_CONNECTED_EVT
Proxy Server establishes connection successfully event
enumerator ESP_BLE_MESH_PROXY_SERVER_DISCONNECTED_EVT
Proxy Server terminates connection successfully event
enumerator ESP_BLE_MESH_MODEL_SUBSCRIBE_GROUP_ADDR_COMP_EVT
Local model subscribes group address completion event
enumerator ESP_BLE_MESH_MODEL_UNSUBSCRIBE_GROUP_ADDR_COMP_EVT
Local model unsubscribes group address completion event
enumerator ESP_BLE_MESH_DEINIT_MESH_COMP_EVT
De-initialize BLE Mesh stack completion event
enumerator ESP_BLE_MESH_PROV_EVT_MAX
enum [anonymous]
BLE Mesh server models related definitions.
This enum value is the flag of transition timer operation
Values:
enumerator ESP_BLE_MESH_SERVER_TRANS_TIMER_START
enumerator ESP_BLE_MESH_SERVER_FLAG_MAX
enum esp_ble_mesh_server_state_type_t
This enum value is the type of server model states
Values:
enumerator ESP_BLE_MESH_GENERIC_ONOFF_STATE
enumerator ESP_BLE_MESH_GENERIC_LEVEL_STATE
enumerator ESP_BLE_MESH_GENERIC_ONPOWERUP_STATE
enumerator ESP_BLE_MESH_GENERIC_POWER_ACTUAL_STATE
enumerator ESP_BLE_MESH_LIGHT_LIGHTNESS_ACTUAL_STATE
enumerator ESP_BLE_MESH_LIGHT_LIGHTNESS_LINEAR_STATE
enumerator ESP_BLE_MESH_LIGHT_CTL_LIGHTNESS_STATE
enumerator ESP_BLE_MESH_LIGHT_CTL_TEMP_DELTA_UV_STATE
enumerator ESP_BLE_MESH_LIGHT_HSL_STATE
enumerator ESP_BLE_MESH_LIGHT_HSL_LIGHTNESS_STATE
enumerator ESP_BLE_MESH_LIGHT_HSL_HUE_STATE
enumerator ESP_BLE_MESH_LIGHT_HSL_SATURATION_STATE
enumerator ESP_BLE_MESH_LIGHT_XYL_LIGHTNESS_STATE
enumerator ESP_BLE_MESH_LIGHT_LC_LIGHT_ONOFF_STATE
enumerator ESP_BLE_MESH_SERVER_MODEL_STATE_MAX
enum esp_ble_mesh_model_cb_event_t
Values:
enumerator ESP_BLE_MESH_MODEL_OPERATION_EVT
User-defined models receive messages from peer devices (e.g. get, set, status, etc) event
enumerator ESP_BLE_MESH_MODEL_SEND_COMP_EVT
User-defined models send messages completion event
enumerator ESP_BLE_MESH_MODEL_PUBLISH_COMP_EVT
User-defined models publish messages completion event
enumerator ESP_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT
User-defined client models receive publish messages event
enumerator ESP_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT
Timeout event for the user-defined client models that failed to receive response from peer server models
enumerator ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT
When a model is configured to publish messages periodically, this event will occur during every publish
period
enumerator ESP_BLE_MESH_SERVER_MODEL_UPDATE_STATE_COMP_EVT
Server models update state value completion event
enumerator ESP_BLE_MESH_MODEL_EVT_MAX
This section contains ESP-BLE-MESH Core related APIs, which can be used to initialize ESP-BLE-MESH stack,
provision, send/publish messages, etc.
This API reference covers six components:
• ESP-BLE-MESH Stack Initialization
• Reading of Local Data Information
• Low Power Operation (Updating)
• Send/Publish Messages, add Local AppKey, etc.
• ESP-BLE-MESH Node/Provisioner Provisioning
• ESP-BLE-MESH GATT Proxy Server
Header File
• components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_common_api.h
Functions
esp_err_t esp_ble_mesh_init(esp_ble_mesh_prov_t *prov, esp_ble_mesh_comp_t *comp)
Initialize BLE Mesh module. This API initializes provisioning capabilities and composition data information.
Note: After calling this API, the device needs to call esp_ble_mesh_prov_enable() to enable provisioning
functionality again.
Parameters
• prov –[in] Pointer to the device provisioning capabilities. This pointer must remain valid
during the lifetime of the BLE Mesh device.
• comp –[in] Pointer to the device composition data information. This pointer must remain
valid during the lifetime of the BLE Mesh device.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_deinit(esp_ble_mesh_deinit_param_t *param)
De-initialize BLE Mesh module.
Parameters param –[in] Pointer to the structure of BLE Mesh deinit parameters.
Returns ESP_OK on success or error code otherwise.
Header File
• components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_local_data_operation_api.h
Functions
int32_t esp_ble_mesh_get_model_publish_period(esp_ble_mesh_model_t *model)
Get the model publish period, the unit is ms.
Parameters model –[in] Model instance pointer.
Returns Publish period value on success, 0 or (negative) error code from errno.h on failure.
uint16_t esp_ble_mesh_get_primary_element_address(void)
Get the address of the primary element.
Returns Address of the primary element on success, or
ESP_BLE_MESH_ADDR_UNASSIGNED on failure which means the device has not
been provisioned.
uint16_t *esp_ble_mesh_is_model_subscribed_to_group(esp_ble_mesh_model_t *model, uint16_t
group_addr)
Check if the model has subscribed to the given group address. Note: E.g., once a status message is received
and the destination address is a group address, the model uses this API to check if it is successfully subscribed
to the given group address.
Parameters
• model –[in] Pointer to the model.
• group_addr –[in] Group address.
Returns Pointer to the group address within the Subscription List of the model on success, or
NULL on failure which means the model has not subscribed to the given group address. Note:
With the pointer to the group address returned, you can reset the group address to 0x0000 in
order to unsubscribe the model from the group.
esp_ble_mesh_elem_t *esp_ble_mesh_find_element(uint16_t element_addr)
Find the BLE Mesh element pointer via the element address.
Parameters element_addr –[in] Element address.
Returns Pointer to the element on success, or NULL on failure.
uint8_t esp_ble_mesh_get_element_count(void)
Get the number of elements that have been registered.
Returns Number of elements.
Note: This function shall not be invoked before node is provisioned or Provisioner is enabled.
Parameters
• element_addr –[in] Unicast address of the element to which the model belongs.
• company_id –[in] A 16-bit company identifier.
• model_id –[in] A 16-bit model identifier.
• group_addr –[in] The group address to be subscribed.
Returns ESP_OK on success or error code otherwise.
Note: This function shall not be invoked before node is provisioned or Provisioner is enabled.
Parameters
• element_addr –[in] Unicast address of the element to which the model belongs.
• company_id –[in] A 16-bit company identifier.
• model_id –[in] A 16-bit model identifier.
• group_addr –[in] The subscribed group address.
Returns ESP_OK on success or error code otherwise.
Note: This function can only be called after the device is provisioned.
Parameters
• net_key –[in] NetKey to be added.
• net_idx –[in] NetKey Index.
Returns ESP_OK on success or error code otherwise.
Note: The net_idx must be an existing one. This function can only be called after the device is provisioned.
Parameters
• app_key –[in] AppKey to be added.
• net_idx –[in] NetKey Index.
• app_idx –[in] AppKey Index.
Returns ESP_OK on success or error code otherwise.
Note: If going to bind app_key with local vendor model, the company_id shall be set to 0xFFFF. This function
can only be called after the device is provisioned.
Parameters
• element_addr –[in] Node local element address
• company_id –[in] Node local company id
• model_id –[in] Node local model id
• app_idx –[in] Node local appkey index
Returns ESP_OK on success or error code otherwise.
Header File
• components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_low_power_api.h
Functions
esp_err_t esp_ble_mesh_lpn_enable(void)
Enable BLE Mesh device LPN functionality.
Note: This API enables LPN functionality. Once called, the proper Friend Request will be sent.
Note: The Friend Poll message is sent by a Low Power node to ask the Friend node to send a message that it
has stored for the Low Power node. Users can call this API to send Friend Poll message manually. If this API
is not invoked, the bottom layer of the Low Power node will send Friend Poll before the PollTimeout timer
expires. If the corresponding Friend Update is received and MD is set to 0, which means there are no messages
for the Low Power node, then the Low Power node will stop scanning.
Header File
• components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_networking_api.h
Functions
esp_err_t esp_ble_mesh_register_custom_model_callback(esp_ble_mesh_model_cb_t callback)
Register BLE Mesh callback for user-defined models’operations. This callback can report the following events
generated for the user-defined models:
• Call back the messages received by user-defined client and server models to the application layer;
• If users call esp_ble_mesh_server/client_model_send, this callback notifies the application layer of the
send_complete event;
• If user-defined client model sends a message that requires response, and the response message is received
after the timer expires, the response message will be reported to the application layer as published by a
peer device;
• If the user-defined client model fails to receive the response message during a specified period of time, a
timeout event will be reported to the application layer.
Note: The client models (i.e. Config Client model, Health Client model, Generic Client models, Sensor
Client model, Scene Client model and Lighting Client models) that have been realized internally have their
specific register functions. For example, esp_ble_mesh_register_config_client_callback is the register function
for Config Client Model.
Note: This API is only used to set the opcode of the message.
Parameters
• data –[in] Pointer to the message data.
• opcode –[in] The message opcode.
Returns ESP_OK on success or error code otherwise.
• need_rsp –[in] TRUE if the opcode requires the peer device to reply, FALSE other-
wise.
• device_role –[in] Role of the device (Node/Provisioner) that sends the message.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_model_publish(esp_ble_mesh_model_t *model, uint32_t opcode, uint16_t
length, uint8_t *data, esp_ble_mesh_dev_role_t device_role)
Send a model publication message.
Note: Before calling this function, the user needs to ensure that the model publication message
(esp_ble_mesh_model_pub_t::msg) contains a valid message to be sent. And if users want to update the pub-
lishing message, this API should be called in ESP_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT with
the message updated.
Parameters
• model –[in] Mesh (client) Model publishing the message.
• opcode –[in] Message opcode.
• length –[in] Message length (exclude the message opcode).
• data –[in] Parameters of the Access Payload (exclude the message opcode) to be sent.
• device_role –[in] Role of the device (node/provisioner) publishing the message of
the type esp_ble_mesh_dev_role_t.
Returns ESP_OK on success or error code otherwise.
Note: Currently this API is used to update bound state value, not for all server model states.
Parameters
• model –[in] Server model which is going to update the state.
• type –[in] Server model state type.
• value –[in] Server model state value.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_node_local_reset(void)
Reset the provisioning procedure of the local BLE Mesh node.
Note: All provisioning information in this node will be deleted and the node needs to be reprovisioned. The
API function esp_ble_mesh_node_prov_enable() needs to be called to start a new provisioning procedure.
Parameters
Note: After invoking the function to get the entry of nodes, users can use the “for”loop
combined with the macro CONFIG_BLE_MESH_MAX_PROV_NODES to get each node’
s information. Before trying to read the node’s information, users need to check if the
node exists, i.e. if the *(esp_ble_mesh_node_t **node) is NULL. For example: ``` const
esp_ble_mesh_node_t **entry = esp_ble_mesh_provisioner_get_node_table_entry(); for (int i = 0; i <
Note: app_key: If set to NULL, app_key will be generated internally. net_idx: Should be an existing one.
app_idx: If it is going to be generated internally, it should be set to 0xFFFF, and the new app_idx will be
reported via an event.
Parameters
• app_key –[in] The app key to be set for the local BLE Mesh stack.
• net_idx –[in] The network key index.
• app_idx –[in] The app key index.
Returns ESP_OK on success or error code otherwise.
Note: company_id: If going to bind app_key with local vendor model, company_id should be set to 0xFFFF.
Parameters
• element_addr –[in] Provisioner local element address
• app_idx –[in] Provisioner local appkey index
• model_id –[in] Provisioner local model id
• company_id –[in] Provisioner local company id
Returns ESP_OK on success or error code otherwise.
Note: net_key: If set to NULL, net_key will be generated internally. net_idx: If it is going to be generated
internally, it should be set to 0xFFFF, and the new net_idx will be reported via an event.
Parameters
• net_key –[in] The network key to be added to the Provisioner local BLE Mesh stack.
• net_idx –[in] The network key index.
Returns ESP_OK on success or error code otherwise.
Note: If enabling receiving heartbeat message successfully, the filter will be an empty rejectlist by default,
which means all heartbeat messages received by the Provisioner will be reported to the application layer.
Note: 1. If the filter type is not the same with the current value, then all the filter entries will be cleaned.
a. If the previous type is rejectlist, and changed to acceptlist, then the filter will be an empty acceptlist,
which means no heartbeat messages will be reported. Users need to add SRC or DST into the filter entry,
then heartbeat messages from the SRC or to the DST will be reported.
a. If the operation is “REMOVE”, the “hb_src”can be set to the SRC (can only be a unicast address)
of heartbeat messages, and the “hb_dst”can be set to the DST (unicast address or group address), at
least one of them needs to be set.
• The filter entry with the same SRC or DST will be removed.
Note: 1. If the operation is“ADD”, the“hb_src”can be set to the SRC (can only be a unicast address) of
heartbeat messages, and the “hb_dst”can be set to the DST (unicast address or group address), at least one
of them needs to be set.
• If only one of them is set, the filter entry will only use the configured SRC or DST to filter heartbeat
messages.
• If both of them are set, the SRC and DST will both be used to decide if a heartbeat message will be
handled.
• If SRC or DST already exists in some filter entry, then the corresponding entry will be cleaned firstly,
then a new entry will be allocated to store the information.
Parameters
• op –[in] Add or REMOVE
• info –[in] Heartbeat filter entry information, including: hb_src - Heartbeat source ad-
dress; hb_dst - Heartbeat destination address;
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_provisioner_direct_erase_settings(void)
This function is called by Provisioner to directly erase the mesh information from nvs namespace.
Note: This function can be invoked when the mesh stack is not initialized or has been de-initialized.
Note: Before open another nvs namespace, the previously opened nvs namespace must be closed firstly.
Note: Before open another nvs namespace, the previously opened nvs namespace must be closed firstly.
Parameters
• index –[in] Settings index.
• erase –[in] Indicate if erasing mesh information.
Returns ESP_OK on success or error code otherwise.
Parameters
• uid –[in] Settings user id.
• erase –[in] Indicate if erasing mesh information.
Returns ESP_OK on success or error code otherwise.
Note: When this function is called, the nvs namespace must not be open. This function is used to erase the
mesh information and settings user id which are not used currently.
Note: When this function is called, the nvs namespace must not be open. This function is used to erase the
mesh information and settings user id which are not used currently.
Type Definitions
typedef void (*esp_ble_mesh_model_cb_t)(esp_ble_mesh_model_cb_event_t event,
esp_ble_mesh_model_cb_param_t *param)
: event, event code of user-defined model events; param, parameters of user-defined model events
Header File
• components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_provisioning_api.h
Functions
esp_err_t esp_ble_mesh_register_prov_callback(esp_ble_mesh_prov_cb_t callback)
Register BLE Mesh provisioning callback.
Parameters callback –[in] Pointer to the callback function.
Returns ESP_OK on success or error code otherwise.
bool esp_ble_mesh_node_is_provisioned(void)
Check if a device has been provisioned.
Returns TRUE if the device is provisioned, FALSE if the device is unprovisioned.
Note: PB-ADV: send unprovisioned device beacon. PB-GATT: send connectable advertising packets.
Note: In order to avoid suffering brute-forcing attack (CVE-2020-26559). The Bluetooth SIG recommends
that potentially vulnerable mesh provisioners use an out-of-band mechanism to exchange the public keys. So as
an unprovisioned device, it should use this function to input the Public Key exchanged through the out-of-band
mechanism.
Parameters
• pub_key_x –[in] Unprovisioned device’s Public Key X
• pub_key_y –[in] Unprovisioned device’s Public Key Y
• private_key –[in] Unprovisioned device’s Private Key
Returns ESP_OK on success or error code otherwise.
Note: This API applicable to PB-GATT mode only by setting the name to the scan response data, it doesn’
t apply to PB-ADV mode.
Note: In order to avoid suffering brute-forcing attack (CVE-2020-26559). The Bluetooth SIG recommends
that potentially vulnerable mesh provisioners use an out-of-band mechanism to exchange the public keys.
Parameters
• link_idx –[in] The provisioning link index
• pub_key_x –[in] Unprovisioned device’s Public Key X
• pub_key_y –[in] Unprovisioned device’s Public Key Y
Returns ESP_OK on success or error code otherwise.
Parameters
• string –[in] String input by Provisioner.
• link_idx –[in] The provisioning link index.
Returns ESP_OK on success or error code otherwise.
Parameters
• number –[in] Number input by Provisioner.
• link_idx –[in] The provisioning link index.
Returns ESP_OK on success or error code otherwise.
Note: PB-ADV: Enable BLE scan. PB-GATT: Initialize corresponding BLE Mesh Proxy info.
Note: PB-ADV: Disable BLE scan. PB-GATT: Break any existing BLE Mesh Provisioning connections.
esp_err_t esp_ble_mesh_provisioner_add_unprov_dev(esp_ble_mesh_unprov_dev_add_t
*add_dev, esp_ble_mesh_dev_add_flag_t
flags)
Add unprovisioned device info to the unprov_dev queue.
Note: : 1. Currently address type only supports public address and static random address.
a. If device UUID and/or device address as well as address type already exist in the device queue, but the
bearer is different from the existing one, add operation will also be successful and it will update the
provision bearer supported by the device.
b. For example, if the Provisioner wants to add an unprovisioned device info before receiving its unprovi-
sioned device beacon or Mesh Provisioning advertising packets, the Provisioner can use this API to add
the device info with each one or both of device UUID and device address added. When the Provisioner
gets the device’s advertising packets, it will start provisioning the device internally.
• In this situation, the Provisioner can set bearers with each one or both of
ESP_BLE_MESH_PROV_ADV and ESP_BLE_MESH_PROV_GATT enabled, and cannot
set flags with ADD_DEV_START_PROV_NOW_FLAG enabled.
c. Another example is when the Provisioner receives the unprovisioned device’s beacon or Mesh Pro-
visioning advertising packets, the advertising packets will be reported on to the application layer using
the callback registered by the function esp_ble_mesh_register_prov_callback. And in the callback, the
Provisioner can call this API to start provisioning the device.
• If the Provisioner uses PB-ADV to provision, either one or both of device UUID and device address
can be added, bearers shall be set with ESP_BLE_MESH_PROV_ADV enabled and the flags shall
be set with ADD_DEV_START_PROV_NOW_FLAG enabled.
• If the Provisioner uses PB-GATT to provision, both the device UUID and device address need to
be added, bearers shall be set with ESP_BLE_MESH_PROV_GATT enabled, and the flags shall be
set with ADD_DEV_START_PROV_NOW_FLAG enabled.
• If the Provisioner just wants to store the unprovisioned device info when receiving its advertis-
ing packets and start to provision it the next time (e.g. after receiving its advertising packets
again), then it can add the device info with either one or both of device UUID and device ad-
dress included. Bearers can be set with either one or both of ESP_BLE_MESH_PROV_ADV and
ESP_BLE_MESH_PROV_GATT enabled (recommend to enable the bearer which will receive its
advertising packets, because if the other bearer is enabled, the Provisioner is not aware if the de-
vice supports the bearer), and flags cannot be set with ADD_DEV_START_PROV_NOW_FLAG
enabled.
• Note: ESP_BLE_MESH_PROV_ADV, ESP_BLE_MESH_PROV_GATT and
ADD_DEV_START_PROV_NOW_FLAG can not be enabled at the same time.
Parameters
• add_dev –[in] Pointer to a struct containing the device information
• flags –[in] Flags indicate several operations on the device information
– Remove device information from queue after device has been provisioned (BIT0)
– Start provisioning immediately after device is added to queue (BIT1)
– Device can be removed if device queue is full (BIT2)
Note: : 1. Currently address type only supports public address and static random address.
a. Bearer must be equal to ESP_BLE_MESH_PROV_ADV or ESP_BLE_MESH_PROV_GATT,
since Provisioner will start to provision a device immediately once this function is in-
voked. And the input bearer must be identical with the one within the parameters of the
ESP_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT event.
b. If this function is used by a Provisioner to provision devices, the application should take care of the
assigned unicast address and avoid overlap of the unicast addresses of different nodes.
c. Recommend to use only one of the functions “esp_ble_mesh_provisioner_add_unprov_dev”and
“esp_ble_mesh_provisioner_prov_device_with_addr”by a Provisioner.
Parameters
• uuid –[in] Device UUID of the unprovisioned device
• addr –[in] Device address of the unprovisioned device
• addr_type –[in] Device address type of the unprovisioned device
• bearer –[in] Provisioning bearer going to be used by Provisioner
• oob_info –[in] OOB info of the unprovisioned device
• unicast_addr –[in] Unicast address going to be allocated for the unprovisioned device
Returns Zero on success or (negative) error code otherwise.
Note: If the device is in the queue, remove it from the queue; if the device is being provisioned, terminate
the provisioning procedure. Either one of the device address or device UUID can be used as input.
esp_err_t esp_ble_mesh_provisioner_set_prov_data_info(esp_ble_mesh_prov_data_info_t
*prov_data_info)
This function is called by Provisioner to set provisioning data information before starting to provision.
Parameters prov_data_info –[in] Pointer to a struct containing net_idx or flags or iv_index.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_provisioner_set_static_oob_value(const uint8_t *value, uint8_t
length)
This function is called by Provisioner to set static oob value used for provisioning.
AuthValues selected using a cryptographically secure random or pseudorandom number generator and having
the maximum permitted entropy (128-bits) will be most difficult to brute-force. AuthValues with reduced
entropy or generated in a predictable manner will not grant the same level of protection against this vulnerability.
Selecting a new AuthValue with each provisioning attempt can also make it more difficult to launch a brute-
force attack by requiring the attacker to restart the search with each provisioning attempt (CVE-2020-26556).
Note: The Bluetooth SIG recommends that mesh implementations enforce a randomly selected AuthValue
using all of the available bits, where permitted by the implementation. A large entropy helps ensure that a
brute-force of the AuthValue, even a static AuthValue, cannot normally be completed in a reasonable time
(CVE-2020-26557).
Parameters
• value –[in] Pointer to the static oob value.
• length –[in] Length of the static oob value.
Returns ESP_OK on success or error code otherwise.
Note: This API must be invoked when BLE Mesh initialization is completed successfully, and can be invoked
before Provisioner functionality is enabled. Once this API is invoked successfully, the prov_unicast_addr value
in the struct esp_ble_mesh_prov_t will be ignored, and Provisioner will use this address as its own primary
element address. And if the unicast address going to assigned for the next unprovisioned device is smaller than
the input address + element number of Provisioner, then the address for the next unprovisioned device will be
recalculated internally.
Type Definitions
typedef void (*esp_ble_mesh_prov_cb_t)(esp_ble_mesh_prov_cb_event_t event,
esp_ble_mesh_prov_cb_param_t *param)
: event, event code of provisioning events; param, parameters of provisioning events
typedef void (*esp_ble_mesh_prov_adv_cb_t)(const esp_ble_mesh_bd_addr_t addr, const
esp_ble_mesh_addr_type_t addr_type, const uint8_t adv_type, const uint8_t *dev_uuid, uint16_t oob_info,
esp_ble_mesh_prov_bearer_t bearer)
Callback for Provisioner that received advertising packets from unprovisioned devices which are not in the
unprovisioned device queue.
Report on the unprovisioned device beacon and mesh provisioning service adv data to application.
Param addr [in] Pointer to the unprovisioned device address.
Param addr_type [in] Unprovisioned device address type.
Param adv_type [in] Adv packet type(ADV_IND or ADV_NONCONN_IND).
Param dev_uuid [in] Unprovisioned device UUID pointer.
Param oob_info [in] OOB information of the unprovisioned device.
Param bearer [in] Adv packet received from PB-GATT or PB-ADV bearer.
Header File
• components/bt/esp_ble_mesh/api/core/include/esp_ble_mesh_proxy_api.h
Functions
esp_err_t esp_ble_mesh_proxy_identity_enable(void)
Enable advertising with Node Identity.
Note: This API requires that GATT Proxy support be enabled. Once called, each subnet starts advertising
using Node Identity for the next 60 seconds, and after 60s Network ID will be advertised. Under normal
conditions, the BLE Mesh Proxy Node Identity and Network ID advertising will be enabled automatically by
BLE Mesh stack after the device is provisioned.
• net_idx –[in] NetKey Index related with Network ID in the Mesh Proxy advertising
packet.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_proxy_client_disconnect(uint8_t conn_handle)
Proxy Client terminates a connection with the Proxy Server.
Parameters conn_handle –[in] Proxy connection handle.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_proxy_client_set_filter_type(uint8_t conn_handle, uint16_t net_idx,
esp_ble_mesh_proxy_filter_type_t
filter_type)
Proxy Client sets the filter type of the Proxy Server.
Parameters
• conn_handle –[in] Proxy connection handle.
• net_idx –[in] Corresponding NetKey Index.
• filter_type –[in] whitelist or blacklist.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_proxy_client_add_filter_addr(uint8_t conn_handle, uint16_t net_idx,
uint16_t *addr, uint16_t addr_num)
Proxy Client adds address to the Proxy Server filter list.
Parameters
• conn_handle –[in] Proxy connection handle.
• net_idx –[in] Corresponding NetKey Index.
• addr –[in] Pointer to the filter address.
• addr_num –[in] Number of the filter address.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_proxy_client_remove_filter_addr(uint8_t conn_handle, uint16_t
net_idx, uint16_t *addr, uint16_t
addr_num)
Proxy Client removes address from the Proxy Server filter list.
Parameters
• conn_handle –[in] Proxy connection handle.
• net_idx –[in] Corresponding NetKey Index.
• addr –[in] Pointer to the filter address.
• addr_num –[in] Number of the filter address.
Returns ESP_OK on success or error code otherwise.
This section contains ESP-BLE-MESH Model related APIs, event types, event parameters, etc.
There are six categories of models:
• Configuration Client/Server Models
• Health Client/Server Models
• Generic Client/Server Models
• Sensor Client/Server Models
• Time and Scenes Client/Server Models
• Lighting Client/Server Models
Note: Definitions related to Server Models are being updated, and will be released soon.
Header File
• components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_config_model_api.h
Functions
esp_err_t esp_ble_mesh_register_config_client_callback(esp_ble_mesh_cfg_client_cb_t
callback)
Register BLE Mesh Config Client Model callback.
Parameters callback –[in] Pointer to the callback function.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_register_config_server_callback(esp_ble_mesh_cfg_server_cb_t
callback)
Register BLE Mesh Config Server Model callback.
Parameters callback –[in] Pointer to the callback function.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_config_client_get_state(esp_ble_mesh_client_common_param_t
*params, esp_ble_mesh_cfg_client_get_state_t
*get_state)
Get the value of Config Server Model states using the Config Client Model get messages.
Note: If you want to find the opcodes and corresponding meanings accepted by this API, please refer to
esp_ble_mesh_opcode_config_client_get_t in esp_ble_mesh_defs.h
Parameters
• params –[in] Pointer to BLE Mesh common client parameters.
• get_state –[in] Pointer to a union, each kind of opcode corresponds to one structure
inside. Shall not be set to NULL.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_config_client_set_state(esp_ble_mesh_client_common_param_t
*params, esp_ble_mesh_cfg_client_set_state_t
*set_state)
Set the value of the Configuration Server Model states using the Config Client Model set messages.
Note: If you want to find the opcodes and corresponding meanings accepted by this API, please refer to
esp_ble_mesh_opcode_config_client_set_t in esp_ble_mesh_defs.h
Parameters
• params –[in] Pointer to BLE Mesh common client parameters.
• set_state –[in] Pointer to a union, each kind of opcode corresponds to one structure
inside. Shall not be set to NULL.
Returns ESP_OK on success or error code otherwise.
Unions
union esp_ble_mesh_cfg_client_get_state_t
#include <esp_ble_mesh_config_model_api.h> For ESP_BLE_MESH_MODEL_OP_BEACON_GET
ESP_BLE_MESH_MODEL_OP_COMPOSITION_DATA_GET ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_GET
ESP_BLE_MESH_MODEL_OP_GATT_PROXY_GET ESP_BLE_MESH_MODEL_OP_RELAY_GET
ESP_BLE_MESH_MODEL_OP_MODEL_PUB_GET ESP_BLE_MESH_MODEL_OP_FRIEND_GET
ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_GET ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_GET
the get_state parameter in the esp_ble_mesh_config_client_get_state function should not be set to NULL.
Public Members
esp_ble_mesh_cfg_model_pub_get_t model_pub_get
For ESP_BLE_MESH_MODEL_OP_MODEL_PUB_GET.
esp_ble_mesh_cfg_composition_data_get_t comp_data_get
For ESP_BLE_MESH_MODEL_OP_COMPOSITION_DATA_GET.
esp_ble_mesh_cfg_sig_model_sub_get_t sig_model_sub_get
For ESP_BLE_MESH_MODEL_OP_SIG_MODEL_SUB_GET
esp_ble_mesh_cfg_vnd_model_sub_get_t vnd_model_sub_get
For ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_SUB_GET
esp_ble_mesh_cfg_app_key_get_t app_key_get
For ESP_BLE_MESH_MODEL_OP_APP_KEY_GET.
esp_ble_mesh_cfg_node_identity_get_t node_identity_get
For ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_GET.
esp_ble_mesh_cfg_sig_model_app_get_t sig_model_app_get
For ESP_BLE_MESH_MODEL_OP_SIG_MODEL_APP_GET
esp_ble_mesh_cfg_vnd_model_app_get_t vnd_model_app_get
For ESP_BLE_MESH_MODEL_OP_VENDOR_MODEL_APP_GET
esp_ble_mesh_cfg_kr_phase_get_t kr_phase_get
For ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_GET
esp_ble_mesh_cfg_lpn_polltimeout_get_t lpn_pollto_get
For ESP_BLE_MESH_MODEL_OP_LPN_POLLTIMEOUT_GET
union esp_ble_mesh_cfg_client_set_state_t
#include <esp_ble_mesh_config_model_api.h> For ESP_BLE_MESH_MODEL_OP_BEACON_SET
ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_SET ESP_BLE_MESH_MODEL_OP_GATT_PROXY_SET
ESP_BLE_MESH_MODEL_OP_RELAY_SET ESP_BLE_MESH_MODEL_OP_MODEL_PUB_SET
ESP_BLE_MESH_MODEL_OP_MODEL_SUB_ADD ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR
ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_AD
ESP_BLE_MESH_MODEL_OP_MODEL_SUB_OVERWRITE ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL
ESP_BLE_MESH_MODEL_OP_NET_KEY_ADD ESP_BLE_MESH_MODEL_OP_APP_KEY_ADD
ESP_BLE_MESH_MODEL_OP_MODEL_APP_BIND ESP_BLE_MESH_MODEL_OP_NODE_RESET
ESP_BLE_MESH_MODEL_OP_FRIEND_SET ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_SET
ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_SET the set_state parameter in the
esp_ble_mesh_config_client_set_state function should not be set to NULL.
Public Members
esp_ble_mesh_cfg_beacon_set_t beacon_set
For ESP_BLE_MESH_MODEL_OP_BEACON_SET
esp_ble_mesh_cfg_default_ttl_set_t default_ttl_set
For ESP_BLE_MESH_MODEL_OP_DEFAULT_TTL_SET
esp_ble_mesh_cfg_friend_set_t friend_set
For ESP_BLE_MESH_MODEL_OP_FRIEND_SET
esp_ble_mesh_cfg_gatt_proxy_set_t gatt_proxy_set
For ESP_BLE_MESH_MODEL_OP_GATT_PROXY_SET
esp_ble_mesh_cfg_relay_set_t relay_set
For ESP_BLE_MESH_MODEL_OP_RELAY_SET
esp_ble_mesh_cfg_net_key_add_t net_key_add
For ESP_BLE_MESH_MODEL_OP_NET_KEY_ADD
esp_ble_mesh_cfg_app_key_add_t app_key_add
For ESP_BLE_MESH_MODEL_OP_APP_KEY_ADD
esp_ble_mesh_cfg_model_app_bind_t model_app_bind
For ESP_BLE_MESH_MODEL_OP_MODEL_APP_BIND
esp_ble_mesh_cfg_model_pub_set_t model_pub_set
For ESP_BLE_MESH_MODEL_OP_MODEL_PUB_SET
esp_ble_mesh_cfg_model_sub_add_t model_sub_add
For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_ADD
esp_ble_mesh_cfg_model_sub_delete_t model_sub_delete
For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE
esp_ble_mesh_cfg_model_sub_overwrite_t model_sub_overwrite
For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_OVERWRITE
esp_ble_mesh_cfg_model_sub_va_add_t model_sub_va_add
For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_ADD
esp_ble_mesh_cfg_model_sub_va_delete_t model_sub_va_delete
For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_DELETE
esp_ble_mesh_cfg_model_sub_va_overwrite_t model_sub_va_overwrite
For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_VIRTUAL_ADDR_OVERWRITE
esp_ble_mesh_cfg_heartbeat_pub_set_t heartbeat_pub_set
For ESP_BLE_MESH_MODEL_OP_HEARTBEAT_PUB_SET
esp_ble_mesh_cfg_heartbeat_sub_set_t heartbeat_sub_set
For ESP_BLE_MESH_MODEL_OP_HEARTBEAT_SUB_SET
esp_ble_mesh_cfg_model_pub_va_set_t model_pub_va_set
For ESP_BLE_MESH_MODEL_OP_MODEL_PUB_VIRTUAL_ADDR_SET
esp_ble_mesh_cfg_model_sub_delete_all_t model_sub_delete_all
For ESP_BLE_MESH_MODEL_OP_MODEL_SUB_DELETE_ALL
esp_ble_mesh_cfg_net_key_update_t net_key_update
For ESP_BLE_MESH_MODEL_OP_NET_KEY_UPDATE
esp_ble_mesh_cfg_net_key_delete_t net_key_delete
For ESP_BLE_MESH_MODEL_OP_NET_KEY_DELETE
esp_ble_mesh_cfg_app_key_update_t app_key_update
For ESP_BLE_MESH_MODEL_OP_APP_KEY_UPDATE
esp_ble_mesh_cfg_app_key_delete_t app_key_delete
For ESP_BLE_MESH_MODEL_OP_APP_KEY_DELETE
esp_ble_mesh_cfg_node_identity_set_t node_identity_set
For ESP_BLE_MESH_MODEL_OP_NODE_IDENTITY_SET
esp_ble_mesh_cfg_model_app_unbind_t model_app_unbind
For ESP_BLE_MESH_MODEL_OP_MODEL_APP_UNBIND
esp_ble_mesh_cfg_kr_phase_set_t kr_phase_set
For ESP_BLE_MESH_MODEL_OP_KEY_REFRESH_PHASE_SET
esp_ble_mesh_cfg_net_transmit_set_t net_transmit_set
For ESP_BLE_MESH_MODEL_OP_NETWORK_TRANSMIT_SET
union esp_ble_mesh_cfg_client_common_cb_param_t
#include <esp_ble_mesh_config_model_api.h> Configuration Client Model received message union.
Public Members
esp_ble_mesh_cfg_beacon_status_cb_t beacon_status
The beacon status value
esp_ble_mesh_cfg_comp_data_status_cb_t comp_data_status
The composition data status value
esp_ble_mesh_cfg_default_ttl_status_cb_t default_ttl_status
The default_ttl status value
esp_ble_mesh_cfg_gatt_proxy_status_cb_t gatt_proxy_status
The gatt_proxy status value
esp_ble_mesh_cfg_relay_status_cb_t relay_status
The relay status value
esp_ble_mesh_cfg_model_pub_status_cb_t model_pub_status
The model publication status value
esp_ble_mesh_cfg_model_sub_status_cb_t model_sub_status
The model subscription status value
esp_ble_mesh_cfg_net_key_status_cb_t netkey_status
The netkey status value
esp_ble_mesh_cfg_app_key_status_cb_t appkey_status
The appkey status value
esp_ble_mesh_cfg_mod_app_status_cb_t model_app_status
The model app status value
esp_ble_mesh_cfg_friend_status_cb_t friend_status
The friend status value
esp_ble_mesh_cfg_hb_pub_status_cb_t heartbeat_pub_status
The heartbeat publication status value
esp_ble_mesh_cfg_hb_sub_status_cb_t heartbeat_sub_status
The heartbeat subscription status value
esp_ble_mesh_cfg_net_trans_status_cb_t net_transmit_status
The network transmit status value
esp_ble_mesh_cfg_model_sub_list_cb_t model_sub_list
The model subscription list value
esp_ble_mesh_cfg_net_key_list_cb_t netkey_list
The network key index list value
esp_ble_mesh_cfg_app_key_list_cb_t appkey_list
The application key index list value
esp_ble_mesh_cfg_node_id_status_cb_t node_identity_status
The node identity status value
esp_ble_mesh_cfg_model_app_list_cb_t model_app_list
The model application key index list value
esp_ble_mesh_cfg_kr_phase_status_cb_t kr_phase_status
The key refresh phase status value
esp_ble_mesh_cfg_lpn_pollto_status_cb_t lpn_timeout_status
The low power node poll timeout status value
union esp_ble_mesh_cfg_server_state_change_t
#include <esp_ble_mesh_config_model_api.h> Configuration Server model state change value union.
Public Members
esp_ble_mesh_state_change_cfg_mod_pub_set_t mod_pub_set
The recv_op in ctx can be used to decide which state is changed. Config Model Publication Set
esp_ble_mesh_state_change_cfg_model_sub_add_t mod_sub_add
Config Model Subscription Add
esp_ble_mesh_state_change_cfg_model_sub_delete_t mod_sub_delete
Config Model Subscription Delete
esp_ble_mesh_state_change_cfg_netkey_add_t netkey_add
Config NetKey Add
esp_ble_mesh_state_change_cfg_netkey_update_t netkey_update
Config NetKey Update
esp_ble_mesh_state_change_cfg_netkey_delete_t netkey_delete
Config NetKey Delete
esp_ble_mesh_state_change_cfg_appkey_add_t appkey_add
Config AppKey Add
esp_ble_mesh_state_change_cfg_appkey_update_t appkey_update
Config AppKey Update
esp_ble_mesh_state_change_cfg_appkey_delete_t appkey_delete
Config AppKey Delete
esp_ble_mesh_state_change_cfg_model_app_bind_t mod_app_bind
Config Model App Bind
esp_ble_mesh_state_change_cfg_model_app_unbind_t mod_app_unbind
Config Model App Unbind
esp_ble_mesh_state_change_cfg_kr_phase_set_t kr_phase_set
Config Key Refresh Phase Set
union esp_ble_mesh_cfg_server_cb_value_t
#include <esp_ble_mesh_config_model_api.h> Configuration Server model callback value union.
Public Members
esp_ble_mesh_cfg_server_state_change_t state_change
ESP_BLE_MESH_CFG_SERVER_STATE_CHANGE_EVT
Structures
struct esp_ble_mesh_cfg_srv
Configuration Server Model context
Public Members
esp_ble_mesh_model_t *model
Pointer to Configuration Server Model
uint8_t net_transmit
Network Transmit state
uint8_t relay
Relay Mode state
uint8_t relay_retransmit
Relay Retransmit state
uint8_t beacon
Secure Network Beacon state
uint8_t gatt_proxy
GATT Proxy state
uint8_t friend_state
Friend state
uint8_t default_ttl
Default TTL
uint16_t dst
Destination address for Heartbeat messages
uint16_t count
Number of Heartbeat messages to be sent
Number of Heartbeat messages received
uint8_t period
Period for sending Heartbeat messages
uint8_t ttl
TTL to be used when sending Heartbeat messages
uint16_t feature
Bit field indicating features that trigger Heartbeat messages when changed
uint16_t net_idx
NetKey Index used by Heartbeat Publication
int64_t expiry
Timestamp when Heartbeat subscription period is expired
uint16_t src
Source address for Heartbeat messages
uint8_t min_hops
Minimum hops when receiving Heartbeat messages
uint8_t max_hops
Maximum hops when receiving Heartbeat messages
esp_ble_mesh_cb_t heartbeat_recv_cb
Optional heartbeat subscription tracking function
struct esp_ble_mesh_cfg_composition_data_get_t
Parameters of Config Composition Data Get.
Public Members
uint8_t page
Page number of the Composition Data.
struct esp_ble_mesh_cfg_model_pub_get_t
Parameters of Config Model Publication Get.
Public Members
uint16_t element_addr
The element address
uint16_t model_id
The model id
uint16_t company_id
The company id, if not a vendor model, shall set to 0xFFFF
struct esp_ble_mesh_cfg_sig_model_sub_get_t
Parameters of Config SIG Model Subscription Get.
Public Members
uint16_t element_addr
The element address
uint16_t model_id
The model id
struct esp_ble_mesh_cfg_vnd_model_sub_get_t
Parameters of Config Vendor Model Subscription Get.
Public Members
uint16_t element_addr
The element address
uint16_t model_id
The model id
uint16_t company_id
The company id, if not a vendor model, shall set to 0xFFFF
struct esp_ble_mesh_cfg_app_key_get_t
Parameters of Config AppKey Get.
Public Members
uint16_t net_idx
The network key index
struct esp_ble_mesh_cfg_node_identity_get_t
Parameters of Config Node Identity Get.
Public Members
uint16_t net_idx
The network key index
struct esp_ble_mesh_cfg_sig_model_app_get_t
Parameters of Config SIG Model App Get.
Public Members
uint16_t element_addr
The element address
uint16_t model_id
The model id
struct esp_ble_mesh_cfg_vnd_model_app_get_t
Parameters of Config Vendor Model App Get.
Public Members
uint16_t element_addr
The element address
uint16_t model_id
The model id
uint16_t company_id
The company id, if not a vendor model, shall set to 0xFFFF
struct esp_ble_mesh_cfg_kr_phase_get_t
Parameters of Config Key Refresh Phase Get.
Public Members
uint16_t net_idx
The network key index
struct esp_ble_mesh_cfg_lpn_polltimeout_get_t
Parameters of Config Low Power Node PollTimeout Get.
Public Members
uint16_t lpn_addr
The unicast address of the Low Power node
struct esp_ble_mesh_cfg_beacon_set_t
Parameters of Config Beacon Set.
Public Members
uint8_t beacon
New Secure Network Beacon state
struct esp_ble_mesh_cfg_default_ttl_set_t
Parameters of Config Default TTL Set.
Public Members
uint8_t ttl
The default TTL state value
struct esp_ble_mesh_cfg_friend_set_t
Parameters of Config Friend Set.
Public Members
uint8_t friend_state
The friend state value
struct esp_ble_mesh_cfg_gatt_proxy_set_t
Parameters of Config GATT Proxy Set.
Public Members
uint8_t gatt_proxy
The GATT Proxy state value
struct esp_ble_mesh_cfg_relay_set_t
Parameters of Config Relay Set.
Public Members
uint8_t relay
The relay value
uint8_t relay_retransmit
The relay retransmit value
struct esp_ble_mesh_cfg_net_key_add_t
Parameters of Config NetKey Add.
Public Members
uint16_t net_idx
The network key index
uint8_t net_key[16]
The network key value
struct esp_ble_mesh_cfg_app_key_add_t
Parameters of Config AppKey Add.
Public Members
uint16_t net_idx
The network key index
uint16_t app_idx
The app key index
uint8_t app_key[16]
The app key value
struct esp_ble_mesh_cfg_model_app_bind_t
Parameters of Config Model App Bind.
Public Members
uint16_t element_addr
The element address
uint16_t model_app_idx
Index of the app key to bind with the model
uint16_t model_id
The model id
uint16_t company_id
The company id, if not a vendor model, shall set to 0xFFFF
struct esp_ble_mesh_cfg_model_pub_set_t
Parameters of Config Model Publication Set.
Public Members
uint16_t element_addr
The element address
uint16_t publish_addr
Value of the publish address
uint16_t publish_app_idx
Index of the application key
bool cred_flag
Value of the Friendship Credential Flag
uint8_t publish_ttl
Default TTL value for the publishing messages
uint8_t publish_period
Period for periodic status publishing
uint8_t publish_retransmit
Number of retransmissions and number of 50-millisecond steps between retransmissions
uint16_t model_id
The model id
uint16_t company_id
The company id, if not a vendor model, shall set to 0xFFFF
struct esp_ble_mesh_cfg_model_sub_add_t
Parameters of Config Model Subscription Add.
Public Members
uint16_t element_addr
The element address
uint16_t sub_addr
The address to be added to the Subscription List
uint16_t model_id
The model id
uint16_t company_id
The company id, if not a vendor model, shall set to 0xFFFF
struct esp_ble_mesh_cfg_model_sub_delete_t
Parameters of Config Model Subscription Delete.
Public Members
uint16_t element_addr
The element address
uint16_t sub_addr
The address to be removed from the Subscription List
uint16_t model_id
The model id
uint16_t company_id
The company id, if not a vendor model, shall set to 0xFFFF
struct esp_ble_mesh_cfg_model_sub_overwrite_t
Parameters of Config Model Subscription Overwrite.
Public Members
uint16_t element_addr
The element address
uint16_t sub_addr
The address to be added to the Subscription List
uint16_t model_id
The model id
uint16_t company_id
The company id, if not a vendor model, shall set to 0xFFFF
struct esp_ble_mesh_cfg_model_sub_va_add_t
Parameters of Config Model Subscription Virtual Address Add.
Public Members
uint16_t element_addr
The element address
uint8_t label_uuid[16]
The Label UUID of the virtual address to be added to the Subscription List
uint16_t model_id
The model id
uint16_t company_id
The company id, if not a vendor model, shall set to 0xFFFF
struct esp_ble_mesh_cfg_model_sub_va_delete_t
Parameters of Config Model Subscription Virtual Address Delete.
Public Members
uint16_t element_addr
The element address
uint8_t label_uuid[16]
The Label UUID of the virtual address to be removed from the Subscription List
uint16_t model_id
The model id
uint16_t company_id
The company id, if not a vendor model, shall set to 0xFFFF
struct esp_ble_mesh_cfg_model_sub_va_overwrite_t
Parameters of Config Model Subscription Virtual Address Overwrite.
Public Members
uint16_t element_addr
The element address
uint8_t label_uuid[16]
The Label UUID of the virtual address to be added to the Subscription List
uint16_t model_id
The model id
uint16_t company_id
The company id, if not a vendor model, shall set to 0xFFFF
struct esp_ble_mesh_cfg_model_pub_va_set_t
Parameters of Config Model Publication Virtual Address Set.
Public Members
uint16_t element_addr
The element address
uint8_t label_uuid[16]
Value of the Label UUID publish address
uint16_t publish_app_idx
Index of the application key
bool cred_flag
Value of the Friendship Credential Flag
uint8_t publish_ttl
Default TTL value for the publishing messages
uint8_t publish_period
Period for periodic status publishing
uint8_t publish_retransmit
Number of retransmissions and number of 50-millisecond steps between retransmissions
uint16_t model_id
The model id
uint16_t company_id
The company id, if not a vendor model, shall set to 0xFFFF
struct esp_ble_mesh_cfg_model_sub_delete_all_t
Parameters of Config Model Subscription Delete All.
Public Members
uint16_t element_addr
The element address
uint16_t model_id
The model id
uint16_t company_id
The company id, if not a vendor model, shall set to 0xFFFF
struct esp_ble_mesh_cfg_net_key_update_t
Parameters of Config NetKey Update.
Public Members
uint16_t net_idx
The network key index
uint8_t net_key[16]
The network key value
struct esp_ble_mesh_cfg_net_key_delete_t
Parameters of Config NetKey Delete.
Public Members
uint16_t net_idx
The network key index
struct esp_ble_mesh_cfg_app_key_update_t
Parameters of Config AppKey Update.
Public Members
uint16_t net_idx
The network key index
uint16_t app_idx
The app key index
uint8_t app_key[16]
The app key value
struct esp_ble_mesh_cfg_app_key_delete_t
Parameters of Config AppKey Delete.
Public Members
uint16_t net_idx
The network key index
uint16_t app_idx
The app key index
struct esp_ble_mesh_cfg_node_identity_set_t
Parameters of Config Node Identity Set.
Public Members
uint16_t net_idx
The network key index
uint8_t identity
New Node Identity state
struct esp_ble_mesh_cfg_model_app_unbind_t
Parameters of Config Model App Unbind.
Public Members
uint16_t element_addr
The element address
uint16_t model_app_idx
Index of the app key to bind with the model
uint16_t model_id
The model id
uint16_t company_id
The company id, if not a vendor model, shall set to 0xFFFF
struct esp_ble_mesh_cfg_kr_phase_set_t
Parameters of Config Key Refresh Phase Set.
Public Members
uint16_t net_idx
The network key index
uint8_t transition
New Key Refresh Phase Transition
struct esp_ble_mesh_cfg_net_transmit_set_t
Parameters of Config Network Transmit Set.
Public Members
uint8_t net_transmit
Network Transmit State
struct esp_ble_mesh_cfg_heartbeat_pub_set_t
Parameters of Config Model Heartbeat Publication Set.
Public Members
uint16_t dst
Destination address for Heartbeat messages
uint8_t count
Number of Heartbeat messages to be sent
uint8_t period
Period for sending Heartbeat messages
uint8_t ttl
TTL to be used when sending Heartbeat messages
uint16_t feature
Bit field indicating features that trigger Heartbeat messages when changed
uint16_t net_idx
NetKey Index
struct esp_ble_mesh_cfg_heartbeat_sub_set_t
Parameters of Config Model Heartbeat Subscription Set.
Public Members
uint16_t src
Source address for Heartbeat messages
uint16_t dst
Destination address for Heartbeat messages
uint8_t period
Period for receiving Heartbeat messages
struct esp_ble_mesh_cfg_beacon_status_cb_t
Parameter of Config Beacon Status
Public Members
uint8_t beacon
Secure Network Beacon state value
struct esp_ble_mesh_cfg_comp_data_status_cb_t
Parameters of Config Composition Data Status
Public Members
uint8_t page
Page number of the Composition Data
struct esp_ble_mesh_cfg_default_ttl_status_cb_t
Parameter of Config Default TTL Status
Public Members
uint8_t default_ttl
Default TTL state value
struct esp_ble_mesh_cfg_gatt_proxy_status_cb_t
Parameter of Config GATT Proxy Status
Public Members
uint8_t gatt_proxy
GATT Proxy state value
struct esp_ble_mesh_cfg_relay_status_cb_t
Parameters of Config Relay Status
Public Members
uint8_t relay
Relay state value
uint8_t retransmit
Relay retransmit value(number of retransmissions and number of 10-millisecond steps between retrans-
missions)
struct esp_ble_mesh_cfg_model_pub_status_cb_t
Parameters of Config Model Publication Status
Public Members
uint8_t status
Status Code for the request message
uint16_t element_addr
Address of the element
uint16_t publish_addr
Value of the publish address
uint16_t app_idx
Index of the application key
bool cred_flag
Value of the Friendship Credential Flag
uint8_t ttl
Default TTL value for the outgoing messages
uint8_t period
Period for periodic status publishing
uint8_t transmit
Number of retransmissions and number of 50-millisecond steps between retransmissions
uint16_t company_id
Company ID
uint16_t model_id
Model ID
struct esp_ble_mesh_cfg_model_sub_status_cb_t
Parameters of Config Model Subscription Status
Public Members
uint8_t status
Status Code for the request message
uint16_t element_addr
Address of the element
uint16_t sub_addr
Value of the address
uint16_t company_id
Company ID
uint16_t model_id
Model ID
struct esp_ble_mesh_cfg_net_key_status_cb_t
Parameters of Config NetKey Status
Public Members
uint8_t status
Status Code for the request message
uint16_t net_idx
Index of the NetKey
struct esp_ble_mesh_cfg_app_key_status_cb_t
Parameters of Config AppKey Status
Public Members
uint8_t status
Status Code for the request message
uint16_t net_idx
Index of the NetKey
uint16_t app_idx
Index of the application key
struct esp_ble_mesh_cfg_mod_app_status_cb_t
Parameters of Config Model App Status
Public Members
uint8_t status
Status Code for the request message
uint16_t element_addr
Address of the element
uint16_t app_idx
Index of the application key
uint16_t company_id
Company ID
uint16_t model_id
Model ID
struct esp_ble_mesh_cfg_friend_status_cb_t
Parameter of Config Friend Status
Public Members
uint8_t friend_state
Friend state value
struct esp_ble_mesh_cfg_hb_pub_status_cb_t
Parameters of Config Heartbeat Publication Status
Public Members
uint8_t status
Status Code for the request message
uint16_t dst
Destination address for Heartbeat messages
uint8_t count
Number of Heartbeat messages remaining to be sent
uint8_t period
Period for sending Heartbeat messages
uint8_t ttl
TTL to be used when sending Heartbeat messages
uint16_t features
Features that trigger Heartbeat messages when changed
uint16_t net_idx
Index of the NetKey
struct esp_ble_mesh_cfg_hb_sub_status_cb_t
Parameters of Config Heartbeat Subscription Status
Public Members
uint8_t status
Status Code for the request message
uint16_t src
Source address for Heartbeat messages
uint16_t dst
Destination address for Heartbeat messages
uint8_t period
Remaining Period for processing Heartbeat messages
uint8_t count
Number of Heartbeat messages received
uint8_t min_hops
Minimum hops when receiving Heartbeat messages
uint8_t max_hops
Maximum hops when receiving Heartbeat messages
struct esp_ble_mesh_cfg_net_trans_status_cb_t
Parameters of Config Network Transmit Status
Public Members
uint8_t net_trans_count
Number of transmissions for each Network PDU originating from the node
uint8_t net_trans_step
Maximum hops when receiving Heartbeat messages
struct esp_ble_mesh_cfg_model_sub_list_cb_t
Parameters of Config SIG/Vendor Subscription List
Public Members
uint8_t status
Status Code for the request message
uint16_t element_addr
Address of the element
uint16_t company_id
Company ID
uint16_t model_id
Model ID
struct esp_ble_mesh_cfg_net_key_list_cb_t
Parameter of Config NetKey List
Public Members
struct esp_ble_mesh_cfg_app_key_list_cb_t
Parameters of Config AppKey List
Public Members
uint8_t status
Status Code for the request message
uint16_t net_idx
NetKey Index of the NetKey that the AppKeys are bound to
struct esp_ble_mesh_cfg_node_id_status_cb_t
Parameters of Config Node Identity Status
Public Members
uint8_t status
Status Code for the request message
uint16_t net_idx
Index of the NetKey
uint8_t identity
Node Identity state
struct esp_ble_mesh_cfg_model_app_list_cb_t
Parameters of Config SIG/Vendor Model App List
Public Members
uint8_t status
Status Code for the request message
uint16_t element_addr
Address of the element
uint16_t company_id
Company ID
uint16_t model_id
Model ID
struct esp_ble_mesh_cfg_kr_phase_status_cb_t
Parameters of Config Key Refresh Phase Status
Public Members
uint8_t status
Status Code for the request message
uint16_t net_idx
Index of the NetKey
uint8_t phase
Key Refresh Phase state
struct esp_ble_mesh_cfg_lpn_pollto_status_cb_t
Parameters of Config Low Power Node PollTimeout Status
Public Members
uint16_t lpn_addr
The unicast address of the Low Power node
int32_t poll_timeout
The current value of the PollTimeout timer of the Low Power node
struct esp_ble_mesh_cfg_client_cb_param_t
Configuration Client Model callback parameters
Public Members
int error_code
Appropriate error code
esp_ble_mesh_client_common_param_t *params
The client common parameters
esp_ble_mesh_cfg_client_common_cb_param_t status_cb
The config status message callback values
struct esp_ble_mesh_state_change_cfg_mod_pub_set_t
Configuration Server model related context.
Public Members
uint16_t element_addr
Element Address
uint16_t pub_addr
Publish Address
uint16_t app_idx
AppKey Index
bool cred_flag
Friendship Credential Flag
uint8_t pub_ttl
Publish TTL
uint8_t pub_period
Publish Period
uint8_t pub_retransmit
Publish Retransmit
uint16_t company_id
Company ID
uint16_t model_id
Model ID
struct esp_ble_mesh_state_change_cfg_model_sub_add_t
Parameters of Config Model Subscription Add
Public Members
uint16_t element_addr
Element Address
uint16_t sub_addr
Subscription Address
uint16_t company_id
Company ID
uint16_t model_id
Model ID
struct esp_ble_mesh_state_change_cfg_model_sub_delete_t
Parameters of Config Model Subscription Delete
Public Members
uint16_t element_addr
Element Address
uint16_t sub_addr
Subscription Address
uint16_t company_id
Company ID
uint16_t model_id
Model ID
struct esp_ble_mesh_state_change_cfg_netkey_add_t
Parameters of Config NetKey Add
Public Members
uint16_t net_idx
NetKey Index
uint8_t net_key[16]
NetKey
struct esp_ble_mesh_state_change_cfg_netkey_update_t
Parameters of Config NetKey Update
Public Members
uint16_t net_idx
NetKey Index
uint8_t net_key[16]
NetKey
struct esp_ble_mesh_state_change_cfg_netkey_delete_t
Parameter of Config NetKey Delete
Public Members
uint16_t net_idx
NetKey Index
struct esp_ble_mesh_state_change_cfg_appkey_add_t
Parameters of Config AppKey Add
Public Members
uint16_t net_idx
NetKey Index
uint16_t app_idx
AppKey Index
uint8_t app_key[16]
AppKey
struct esp_ble_mesh_state_change_cfg_appkey_update_t
Parameters of Config AppKey Update
Public Members
uint16_t net_idx
NetKey Index
uint16_t app_idx
AppKey Index
uint8_t app_key[16]
AppKey
struct esp_ble_mesh_state_change_cfg_appkey_delete_t
Parameters of Config AppKey Delete
Public Members
uint16_t net_idx
NetKey Index
uint16_t app_idx
AppKey Index
struct esp_ble_mesh_state_change_cfg_model_app_bind_t
Parameters of Config Model App Bind
Public Members
uint16_t element_addr
Element Address
uint16_t app_idx
AppKey Index
uint16_t company_id
Company ID
uint16_t model_id
Model ID
struct esp_ble_mesh_state_change_cfg_model_app_unbind_t
Parameters of Config Model App Unbind
Public Members
uint16_t element_addr
Element Address
uint16_t app_idx
AppKey Index
uint16_t company_id
Company ID
uint16_t model_id
Model ID
struct esp_ble_mesh_state_change_cfg_kr_phase_set_t
Parameters of Config Key Refresh Phase Set
Public Members
uint16_t net_idx
NetKey Index
uint8_t kr_phase
New Key Refresh Phase Transition
struct esp_ble_mesh_cfg_server_cb_param_t
Configuration Server model callback parameters
Public Members
esp_ble_mesh_model_t *model
Pointer to the server model structure
esp_ble_mesh_msg_ctx_t ctx
Context of the received message
esp_ble_mesh_cfg_server_cb_value_t value
Value of the received configuration messages
Macros
ESP_BLE_MESH_MODEL_CFG_SRV(srv_data)
Define a new Config Server Model.
Note: The Config Server Model can only be included by a Primary Element.
Parameters
• srv_data –Pointer to a unique Config Server Model user_data.
Note: The Config Client Model can only be included by a Primary Element.
Parameters
• cli_data –Pointer to a unique struct esp_ble_mesh_client_t.
Returns New Config Client Model instance.
Type Definitions
Enumerations
enum esp_ble_mesh_cfg_client_cb_event_t
This enum value is the event of Configuration Client Model
Values:
enumerator ESP_BLE_MESH_CFG_CLIENT_GET_STATE_EVT
enumerator ESP_BLE_MESH_CFG_CLIENT_SET_STATE_EVT
enumerator ESP_BLE_MESH_CFG_CLIENT_PUBLISH_EVT
enumerator ESP_BLE_MESH_CFG_CLIENT_TIMEOUT_EVT
enumerator ESP_BLE_MESH_CFG_CLIENT_EVT_MAX
enum esp_ble_mesh_cfg_server_cb_event_t
This enum value is the event of Configuration Server model
Values:
enumerator ESP_BLE_MESH_CFG_SERVER_STATE_CHANGE_EVT
enumerator ESP_BLE_MESH_CFG_SERVER_EVT_MAX
Header File
• components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_health_model_api.h
Functions
esp_err_t esp_ble_mesh_register_health_client_callback(esp_ble_mesh_health_client_cb_t
callback)
Register BLE Mesh Health Model callback, the callback will report Health Client & Server Model events.
Parameters callback –[in] Pointer to the callback function.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_register_health_server_callback(esp_ble_mesh_health_server_cb_t
callback)
Register BLE Mesh Health Server Model callback.
Parameters callback –[in] Pointer to the callback function.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_health_client_get_state(esp_ble_mesh_client_common_param_t
*params, esp_ble_mesh_health_client_get_state_t
*get_state)
This function is called to get the Health Server states using the Health Client Model get messages.
Note: If you want to find the opcodes and corresponding meanings accepted by this API, please refer to
esp_ble_mesh_opcode_health_client_get_t in esp_ble_mesh_defs.h
Parameters
• params –[in] Pointer to BLE Mesh common client parameters.
• get_state –[in] Pointer to a union, each kind of opcode corresponds to one structure
inside. Shall not be set to NULL.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_health_client_set_state(esp_ble_mesh_client_common_param_t
*params, esp_ble_mesh_health_client_set_state_t
*set_state)
This function is called to set the Health Server states using the Health Client Model set messages.
Note: If you want to find the opcodes and corresponding meanings accepted by this API, please refer to
esp_ble_mesh_opcode_health_client_set_t in esp_ble_mesh_defs.h
Parameters
• params –[in] Pointer to BLE Mesh common client parameters.
• set_state –[in] Pointer to a union, each kind of opcode corresponds to one structure
inside. Shall not be set to NULL.
Returns ESP_OK on success or error code otherwise.
Unions
union esp_ble_mesh_health_client_get_state_t
#include <esp_ble_mesh_health_model_api.h> For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_GET
ESP_BLE_MESH_MODEL_OP_ATTENTION_GET ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_GET
the get_state parameter in the esp_ble_mesh_health_client_get_state function should not be set to NULL.
Public Members
esp_ble_mesh_health_fault_get_t fault_get
For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_GET.
union esp_ble_mesh_health_client_set_state_t
#include <esp_ble_mesh_health_model_api.h> For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR
ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR_UNACK ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT
ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST_UNACK ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_
ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET_UNACK ESP_BLE_MESH_MODEL_OP_ATTENTION_SET
ESP_BLE_MESH_MODEL_OP_ATTENTION_SET_UNACK the set_state parameter in the
esp_ble_mesh_health_client_set_state function should not be set to NULL.
Public Members
esp_ble_mesh_health_attention_set_t attention_set
For ESP_BLE_MESH_MODEL_OP_ATTENTION_SET or ESP_BLE_MESH_MODEL_OP_ATTENTION_SET_UNA
esp_ble_mesh_health_period_set_t period_set
For ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET or
ESP_BLE_MESH_MODEL_OP_HEALTH_PERIOD_SET_UNACK.
esp_ble_mesh_health_fault_test_t fault_test
For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST or
ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_TEST_UNACK.
esp_ble_mesh_health_fault_clear_t fault_clear
For ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR or
ESP_BLE_MESH_MODEL_OP_HEALTH_FAULT_CLEAR_UNACK.
union esp_ble_mesh_health_client_common_cb_param_t
#include <esp_ble_mesh_health_model_api.h> Health Client Model received message union.
Public Members
esp_ble_mesh_health_current_status_cb_t current_status
The health current status value
esp_ble_mesh_health_fault_status_cb_t fault_status
The health fault status value
esp_ble_mesh_health_period_status_cb_t period_status
The health period status value
esp_ble_mesh_health_attention_status_cb_t attention_status
The health attention status value
union esp_ble_mesh_health_server_cb_param_t
#include <esp_ble_mesh_health_model_api.h> Health Server Model callback parameters union.
Public Members
esp_ble_mesh_health_fault_update_comp_cb_t fault_update_comp
ESP_BLE_MESH_HEALTH_SERVER_FAULT_UPDATE_COMP_EVT
esp_ble_mesh_health_fault_clear_cb_t fault_clear
ESP_BLE_MESH_HEALTH_SERVER_FAULT_CLEAR_EVT
esp_ble_mesh_health_fault_test_cb_t fault_test
ESP_BLE_MESH_HEALTH_SERVER_FAULT_TEST_EVT
esp_ble_mesh_health_attention_on_cb_t attention_on
ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_ON_EVT
esp_ble_mesh_health_attention_off_cb_t attention_off
ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_OFF_EVT
Structures
struct esp_ble_mesh_health_srv_cb_t
ESP BLE Mesh Health Server callback
Public Members
esp_ble_mesh_cb_t fault_clear
Clear health registered faults. Initialized by the stack.
esp_ble_mesh_cb_t fault_test
Run a specific health test. Initialized by the stack.
esp_ble_mesh_cb_t attention_on
Health attention on callback. Initialized by the stack.
esp_ble_mesh_cb_t attention_off
Health attention off callback. Initialized by the stack.
struct esp_ble_mesh_health_test_t
ESP BLE Mesh Health Server test Context
Public Members
uint8_t id_count
Number of Health self-test ID
uint16_t company_id
Company ID used to identify the Health Fault state
uint8_t prev_test_id
Current test ID of the health fault test
uint8_t current_faults[ESP_BLE_MESH_HEALTH_FAULT_ARRAY_SIZE]
Array of current faults
uint8_t registered_faults[ESP_BLE_MESH_HEALTH_FAULT_ARRAY_SIZE]
Array of registered faults
struct esp_ble_mesh_health_srv_t
ESP BLE Mesh Health Server Model Context
Public Members
esp_ble_mesh_model_t *model
Pointer to Health Server Model
esp_ble_mesh_health_srv_cb_t health_cb
Health callback struct
bool attention_timer_start
Attention Timer start flag
esp_ble_mesh_health_test_t health_test
Health Server fault test
struct esp_ble_mesh_health_fault_get_t
Parameter of Health Fault Get
Public Members
uint16_t company_id
Bluetooth assigned 16-bit Company ID
struct esp_ble_mesh_health_attention_set_t
Parameter of Health Attention Set
Public Members
uint8_t attention
Value of the Attention Timer state
struct esp_ble_mesh_health_period_set_t
Parameter of Health Period Set
Public Members
uint8_t fast_period_divisor
Divider for the Publish Period
struct esp_ble_mesh_health_fault_test_t
Parameter of Health Fault Test
Public Members
uint16_t company_id
Bluetooth assigned 16-bit Company ID
uint8_t test_id
ID of a specific test to be performed
struct esp_ble_mesh_health_fault_clear_t
Parameter of Health Fault Clear
Public Members
uint16_t company_id
Bluetooth assigned 16-bit Company ID
struct esp_ble_mesh_health_current_status_cb_t
Parameters of Health Current Status
Public Members
uint8_t test_id
ID of a most recently performed test
uint16_t company_id
Bluetooth assigned 16-bit Company ID
struct esp_ble_mesh_health_fault_status_cb_t
Parameters of Health Fault Status
Public Members
uint8_t test_id
ID of a most recently performed test
uint16_t company_id
Bluetooth assigned 16-bit Company ID
struct esp_ble_mesh_health_period_status_cb_t
Parameter of Health Period Status
Public Members
uint8_t fast_period_divisor
Divider for the Publish Period
struct esp_ble_mesh_health_attention_status_cb_t
Parameter of Health Attention Status
Public Members
uint8_t attention
Value of the Attention Timer state
struct esp_ble_mesh_health_client_cb_param_t
Health Client Model callback parameters
Public Members
int error_code
Appropriate error code
esp_ble_mesh_client_common_param_t *params
The client common parameters.
esp_ble_mesh_health_client_common_cb_param_t status_cb
The health message status callback values
struct esp_ble_mesh_health_fault_update_comp_cb_t
Parameter of publishing Health Current Status completion event
Public Members
int error_code
The result of publishing Health Current Status
esp_ble_mesh_elem_t *element
Pointer to the element which contains the Health Server Model
struct esp_ble_mesh_health_fault_clear_cb_t
Parameters of Health Fault Clear event
Public Members
esp_ble_mesh_model_t *model
Pointer to the Health Server Model
uint16_t company_id
Bluetooth assigned 16-bit Company ID
struct esp_ble_mesh_health_fault_test_cb_t
Parameters of Health Fault Test event
Public Members
esp_ble_mesh_model_t *model
Pointer to the Health Server Model
uint8_t test_id
ID of a specific test to be performed
uint16_t company_id
Bluetooth assigned 16-bit Company ID
struct esp_ble_mesh_health_attention_on_cb_t
Parameter of Health Attention On event
Public Members
esp_ble_mesh_model_t *model
Pointer to the Health Server Model
uint8_t time
Duration of attention timer on (in seconds)
struct esp_ble_mesh_health_attention_off_cb_t
Parameter of Health Attention Off event
Public Members
esp_ble_mesh_model_t *model
Pointer to the Health Server Model
Macros
ESP_BLE_MESH_MODEL_HEALTH_SRV(srv, pub)
Define a new Health Server Model.
Note: The Health Server Model can only be included by a Primary Element.
Parameters
• srv –Pointer to the unique struct esp_ble_mesh_health_srv_t.
• pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
Returns New Health Server Model instance.
ESP_BLE_MESH_MODEL_HEALTH_CLI(cli_data)
Define a new Health Client Model.
Note: This API needs to be called for each element on which the application needs to have a Health Client
Model.
Parameters
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Health Client Model instance.
ESP_BLE_MESH_HEALTH_STANDARD_TEST
SIG identifier of Health Fault Test. 0x01 ~ 0xFF: Vendor Specific Test.
ESP_BLE_MESH_NO_FAULT
Fault values of Health Fault Test. 0x33 ~ 0x7F: Reserved for Future Use. 0x80 ~ 0xFF: Vendor Specific
Warning/Error.
ESP_BLE_MESH_BATTERY_LOW_WARNING
ESP_BLE_MESH_BATTERY_LOW_ERROR
ESP_BLE_MESH_SUPPLY_VOLTAGE_TOO_LOW_WARNING
ESP_BLE_MESH_SUPPLY_VOLTAGE_TOO_LOW_ERROR
ESP_BLE_MESH_SUPPLY_VOLTAGE_TOO_HIGH_WARNING
ESP_BLE_MESH_SUPPLY_VOLTAGE_TOO_HIGH_ERROR
ESP_BLE_MESH_POWER_SUPPLY_INTERRUPTED_WARNING
ESP_BLE_MESH_POWER_SUPPLY_INTERRUPTED_ERROR
ESP_BLE_MESH_NO_LOAD_WARNING
ESP_BLE_MESH_NO_LOAD_ERROR
ESP_BLE_MESH_OVERLOAD_WARNING
ESP_BLE_MESH_OVERLOAD_ERROR
ESP_BLE_MESH_OVERHEAT_WARNING
ESP_BLE_MESH_OVERHEAT_ERROR
ESP_BLE_MESH_CONDENSATION_WARNING
ESP_BLE_MESH_CONDENSATION_ERROR
ESP_BLE_MESH_VIBRATION_WARNING
ESP_BLE_MESH_VIBRATION_ERROR
ESP_BLE_MESH_CONFIGURATION_WARNING
ESP_BLE_MESH_CONFIGURATION_ERROR
ESP_BLE_MESH_ELEMENT_NOT_CALIBRATED_WARNING
ESP_BLE_MESH_ELEMENT_NOT_CALIBRATED_ERROR
ESP_BLE_MESH_MEMORY_WARNING
ESP_BLE_MESH_MEMORY_ERROR
ESP_BLE_MESH_SELF_TEST_WARNING
ESP_BLE_MESH_SELF_TEST_ERROR
ESP_BLE_MESH_INPUT_TOO_LOW_WARNING
ESP_BLE_MESH_INPUT_TOO_LOW_ERROR
ESP_BLE_MESH_INPUT_TOO_HIGH_WARNING
ESP_BLE_MESH_INPUT_TOO_HIGH_ERROR
ESP_BLE_MESH_INPUT_NO_CHANGE_WARNING
ESP_BLE_MESH_INPUT_NO_CHANGE_ERROR
ESP_BLE_MESH_ACTUATOR_BLOCKED_WARNING
ESP_BLE_MESH_ACTUATOR_BLOCKED_ERROR
ESP_BLE_MESH_HOUSING_OPENED_WARNING
ESP_BLE_MESH_HOUSING_OPENED_ERROR
ESP_BLE_MESH_TAMPER_WARNING
ESP_BLE_MESH_TAMPER_ERROR
ESP_BLE_MESH_DEVICE_MOVED_WARNING
ESP_BLE_MESH_DEVICE_MOVED_ERROR
ESP_BLE_MESH_DEVICE_DROPPED_WARNING
ESP_BLE_MESH_DEVICE_DROPPED_ERROR
ESP_BLE_MESH_OVERFLOW_WARNING
ESP_BLE_MESH_OVERFLOW_ERROR
ESP_BLE_MESH_EMPTY_WARNING
ESP_BLE_MESH_EMPTY_ERROR
ESP_BLE_MESH_INTERNAL_BUS_WARNING
ESP_BLE_MESH_INTERNAL_BUS_ERROR
ESP_BLE_MESH_MECHANISM_JAMMED_WARNING
ESP_BLE_MESH_MECHANISM_JAMMED_ERROR
ESP_BLE_MESH_HEALTH_FAULT_ARRAY_SIZE
Type Definitions
typedef void (*esp_ble_mesh_health_client_cb_t)(esp_ble_mesh_health_client_cb_event_t event,
esp_ble_mesh_health_client_cb_param_t *param)
Bluetooth Mesh Health Client and Server Model function.
Health Client Model callback function type
Param event Event type
Param param Pointer to callback parameter
typedef void (*esp_ble_mesh_health_server_cb_t)(esp_ble_mesh_health_server_cb_event_t event,
esp_ble_mesh_health_server_cb_param_t *param)
Health Server Model callback function type.
Param event Event type
Param param Pointer to callback parameter
Enumerations
enum esp_ble_mesh_health_client_cb_event_t
This enum value is the event of Health Client Model
Values:
enumerator ESP_BLE_MESH_HEALTH_CLIENT_GET_STATE_EVT
enumerator ESP_BLE_MESH_HEALTH_CLIENT_SET_STATE_EVT
enumerator ESP_BLE_MESH_HEALTH_CLIENT_PUBLISH_EVT
enumerator ESP_BLE_MESH_HEALTH_CLIENT_TIMEOUT_EVT
enumerator ESP_BLE_MESH_HEALTH_CLIENT_EVT_MAX
enum esp_ble_mesh_health_server_cb_event_t
This enum value is the event of Health Server Model
Values:
enumerator ESP_BLE_MESH_HEALTH_SERVER_FAULT_UPDATE_COMP_EVT
enumerator ESP_BLE_MESH_HEALTH_SERVER_FAULT_CLEAR_EVT
enumerator ESP_BLE_MESH_HEALTH_SERVER_FAULT_TEST_EVT
enumerator ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_ON_EVT
enumerator ESP_BLE_MESH_HEALTH_SERVER_ATTENTION_OFF_EVT
enumerator ESP_BLE_MESH_HEALTH_SERVER_EVT_MAX
Header File
• components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_generic_model_api.h
Functions
esp_err_t esp_ble_mesh_register_generic_client_callback(esp_ble_mesh_generic_client_cb_t
callback)
Register BLE Mesh Generic Client Model callback.
Parameters callback –[in] Pointer to the callback function.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_generic_client_get_state(esp_ble_mesh_client_common_param_t
*params,
esp_ble_mesh_generic_client_get_state_t
*get_state)
Get the value of Generic Server Model states using the Generic Client Model get messages.
Note: If you want to find the opcodes and corresponding meanings accepted by this API, please refer to
esp_ble_mesh_generic_message_opcode_t in esp_ble_mesh_defs.h
Parameters
• params –[in] Pointer to BLE Mesh common client parameters.
• get_state –[in] Pointer to generic get message value. Shall not be set to NULL.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_generic_client_set_state(esp_ble_mesh_client_common_param_t
*params,
esp_ble_mesh_generic_client_set_state_t
*set_state)
Set the value of Generic Server Model states using the Generic Client Model set messages.
Note: If you want to find the opcodes and corresponding meanings accepted by this API, please refer to
esp_ble_mesh_generic_message_opcode_t in esp_ble_mesh_defs.h
Parameters
• params –[in] Pointer to BLE Mesh common client parameters.
• set_state –[in] Pointer to generic set message value. Shall not be set to NULL.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_register_generic_server_callback(esp_ble_mesh_generic_server_cb_t
callback)
Register BLE Mesh Generic Server Model callback.
Parameters callback –[in] Pointer to the callback function.
Returns ESP_OK on success or error code otherwise.
Unions
union esp_ble_mesh_generic_client_get_state_t
#include <esp_ble_mesh_generic_model_api.h> Generic Client Model get message union.
Public Members
esp_ble_mesh_gen_user_property_get_t user_property_get
For ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_GET
esp_ble_mesh_gen_admin_property_get_t admin_property_get
For ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_GET
esp_ble_mesh_gen_manufacturer_property_get_t manufacturer_property_get
For ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET
esp_ble_mesh_gen_client_properties_get_t client_properties_get
For ESP_BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_GET
union esp_ble_mesh_generic_client_set_state_t
#include <esp_ble_mesh_generic_model_api.h> Generic Client Model set message union.
Public Members
esp_ble_mesh_gen_onoff_set_t onoff_set
For ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_SET & ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_SET_UN
esp_ble_mesh_gen_level_set_t level_set
For ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_SET & ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_SET_UNA
esp_ble_mesh_gen_delta_set_t delta_set
For ESP_BLE_MESH_MODEL_OP_GEN_DELTA_SET & ESP_BLE_MESH_MODEL_OP_GEN_DELTA_SET_UN
esp_ble_mesh_gen_move_set_t move_set
For ESP_BLE_MESH_MODEL_OP_GEN_MOVE_SET & ESP_BLE_MESH_MODEL_OP_GEN_MOVE_SET_UNA
esp_ble_mesh_gen_def_trans_time_set_t def_trans_time_set
For ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET &
ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_SET_UNACK
esp_ble_mesh_gen_onpowerup_set_t power_set
For ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET &
ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_SET_UNACK
esp_ble_mesh_gen_power_level_set_t power_level_set
For ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET &
ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_SET_UNACK
esp_ble_mesh_gen_power_default_set_t power_default_set
For ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET &
ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_SET_UNACK
esp_ble_mesh_gen_power_range_set_t power_range_set
For ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET &
ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_SET_UNACK
esp_ble_mesh_gen_loc_global_set_t loc_global_set
For ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET &
ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_SET_UNACK
esp_ble_mesh_gen_loc_local_set_t loc_local_set
For ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET &
ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_SET_UNACK
esp_ble_mesh_gen_user_property_set_t user_property_set
For ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET &
ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_SET_UNACK
esp_ble_mesh_gen_admin_property_set_t admin_property_set
For ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET &
ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_SET_UNACK
esp_ble_mesh_gen_manufacturer_property_set_t manufacturer_property_set
For ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET &
ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_SET_UNACK
union esp_ble_mesh_gen_client_status_cb_t
#include <esp_ble_mesh_generic_model_api.h> Generic Client Model received message union.
Public Members
esp_ble_mesh_gen_onoff_status_cb_t onoff_status
For ESP_BLE_MESH_MODEL_OP_GEN_ONOFF_STATUS
esp_ble_mesh_gen_level_status_cb_t level_status
For ESP_BLE_MESH_MODEL_OP_GEN_LEVEL_STATUS
esp_ble_mesh_gen_def_trans_time_status_cb_t def_trans_time_status
For ESP_BLE_MESH_MODEL_OP_GEN_DEF_TRANS_TIME_STATUS
esp_ble_mesh_gen_onpowerup_status_cb_t onpowerup_status
For ESP_BLE_MESH_MODEL_OP_GEN_ONPOWERUP_STATUS
esp_ble_mesh_gen_power_level_status_cb_t power_level_status
For ESP_BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_STATUS
esp_ble_mesh_gen_power_last_status_cb_t power_last_status
For ESP_BLE_MESH_MODEL_OP_GEN_POWER_LAST_STATUS
esp_ble_mesh_gen_power_default_status_cb_t power_default_status
For ESP_BLE_MESH_MODEL_OP_GEN_POWER_DEFAULT_STATUS
esp_ble_mesh_gen_power_range_status_cb_t power_range_status
For ESP_BLE_MESH_MODEL_OP_GEN_POWER_RANGE_STATUS
esp_ble_mesh_gen_battery_status_cb_t battery_status
For ESP_BLE_MESH_MODEL_OP_GEN_BATTERY_STATUS
esp_ble_mesh_gen_loc_global_status_cb_t location_global_status
For ESP_BLE_MESH_MODEL_OP_GEN_LOC_GLOBAL_STATUS
esp_ble_mesh_gen_loc_local_status_cb_t location_local_status
ESP_BLE_MESH_MODEL_OP_GEN_LOC_LOCAL_STATUS
esp_ble_mesh_gen_user_properties_status_cb_t user_properties_status
ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTIES_STATUS
esp_ble_mesh_gen_user_property_status_cb_t user_property_status
ESP_BLE_MESH_MODEL_OP_GEN_USER_PROPERTY_STATUS
esp_ble_mesh_gen_admin_properties_status_cb_t admin_properties_status
ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTIES_STATUS
esp_ble_mesh_gen_admin_property_status_cb_t admin_property_status
ESP_BLE_MESH_MODEL_OP_GEN_ADMIN_PROPERTY_STATUS
esp_ble_mesh_gen_manufacturer_properties_status_cb_t manufacturer_properties_status
ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTIES_STATUS
esp_ble_mesh_gen_manufacturer_property_status_cb_t manufacturer_property_status
ESP_BLE_MESH_MODEL_OP_GEN_MANUFACTURER_PROPERTY_STATUS
esp_ble_mesh_gen_client_properties_status_cb_t client_properties_status
ESP_BLE_MESH_MODEL_OP_GEN_CLIENT_PROPERTIES_STATUS
union esp_ble_mesh_generic_server_state_change_t
#include <esp_ble_mesh_generic_model_api.h> Generic Server Model state change value union.
Public Members
esp_ble_mesh_state_change_gen_onoff_set_t onoff_set
The recv_op in ctx can be used to decide which state is changed. Generic OnOff Set
esp_ble_mesh_state_change_gen_level_set_t level_set
Generic Level Set
esp_ble_mesh_state_change_gen_delta_set_t delta_set
Generic Delta Set
esp_ble_mesh_state_change_gen_move_set_t move_set
Generic Move Set
esp_ble_mesh_state_change_gen_def_trans_time_set_t def_trans_time_set
Generic Default Transition Time Set
esp_ble_mesh_state_change_gen_onpowerup_set_t onpowerup_set
Generic OnPowerUp Set
esp_ble_mesh_state_change_gen_power_level_set_t power_level_set
Generic Power Level Set
esp_ble_mesh_state_change_gen_power_default_set_t power_default_set
Generic Power Default Set
esp_ble_mesh_state_change_gen_power_range_set_t power_range_set
Generic Power Range Set
esp_ble_mesh_state_change_gen_loc_global_set_t loc_global_set
Generic Location Global Set
esp_ble_mesh_state_change_gen_loc_local_set_t loc_local_set
Generic Location Local Set
esp_ble_mesh_state_change_gen_user_property_set_t user_property_set
Generic User Property Set
esp_ble_mesh_state_change_gen_admin_property_set_t admin_property_set
Generic Admin Property Set
esp_ble_mesh_state_change_gen_manu_property_set_t manu_property_set
Generic Manufacturer Property Set
union esp_ble_mesh_generic_server_recv_get_msg_t
#include <esp_ble_mesh_generic_model_api.h> Generic Server Model received get message union.
Public Members
esp_ble_mesh_server_recv_gen_user_property_get_t user_property
Generic User Property Get
esp_ble_mesh_server_recv_gen_admin_property_get_t admin_property
Generic Admin Property Get
esp_ble_mesh_server_recv_gen_manufacturer_property_get_t manu_property
Generic Manufacturer Property Get
esp_ble_mesh_server_recv_gen_client_properties_get_t client_properties
Generic Client Properties Get
union esp_ble_mesh_generic_server_recv_set_msg_t
#include <esp_ble_mesh_generic_model_api.h> Generic Server Model received set message union.
Public Members
esp_ble_mesh_server_recv_gen_onoff_set_t onoff
Generic OnOff Set/Generic OnOff Set Unack
esp_ble_mesh_server_recv_gen_level_set_t level
Generic Level Set/Generic Level Set Unack
esp_ble_mesh_server_recv_gen_delta_set_t delta
Generic Delta Set/Generic Delta Set Unack
esp_ble_mesh_server_recv_gen_move_set_t move
Generic Move Set/Generic Move Set Unack
esp_ble_mesh_server_recv_gen_def_trans_time_set_t def_trans_time
Generic Default Transition Time Set/Generic Default Transition Time Set Unack
esp_ble_mesh_server_recv_gen_onpowerup_set_t onpowerup
Generic OnPowerUp Set/Generic OnPowerUp Set Unack
esp_ble_mesh_server_recv_gen_power_level_set_t power_level
Generic Power Level Set/Generic Power Level Set Unack
esp_ble_mesh_server_recv_gen_power_default_set_t power_default
Generic Power Default Set/Generic Power Default Set Unack
esp_ble_mesh_server_recv_gen_power_range_set_t power_range
Generic Power Range Set/Generic Power Range Set Unack
esp_ble_mesh_server_recv_gen_loc_global_set_t location_global
Generic Location Global Set/Generic Location Global Set Unack
esp_ble_mesh_server_recv_gen_loc_local_set_t location_local
Generic Location Local Set/Generic Location Local Set Unack
esp_ble_mesh_server_recv_gen_user_property_set_t user_property
Generic User Property Set/Generic User Property Set Unack
esp_ble_mesh_server_recv_gen_admin_property_set_t admin_property
Generic Admin Property Set/Generic Admin Property Set Unack
esp_ble_mesh_server_recv_gen_manufacturer_property_set_t manu_property
Generic Manufacturer Property Set/Generic Manufacturer Property Set Unack
union esp_ble_mesh_generic_server_cb_value_t
#include <esp_ble_mesh_generic_model_api.h> Generic Server Model callback value union.
Public Members
esp_ble_mesh_generic_server_state_change_t state_change
ESP_BLE_MESH_GENERIC_SERVER_STATE_CHANGE_EVT
esp_ble_mesh_generic_server_recv_get_msg_t get
ESP_BLE_MESH_GENERIC_SERVER_RECV_GET_MSG_EVT
esp_ble_mesh_generic_server_recv_set_msg_t set
ESP_BLE_MESH_GENERIC_SERVER_RECV_SET_MSG_EVT
Structures
struct esp_ble_mesh_gen_onoff_set_t
Bluetooth Mesh Generic Client Model Get and Set parameters structure.
Parameters of Generic OnOff Set.
Public Members
bool op_en
Indicate if optional parameters are included
uint8_t onoff
Target value of Generic OnOff state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_gen_level_set_t
Parameters of Generic Level Set.
Public Members
bool op_en
Indicate if optional parameters are included
int16_t level
Target value of Generic Level state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_gen_delta_set_t
Parameters of Generic Delta Set.
Public Members
bool op_en
Indicate if optional parameters are included
int32_t level
Delta change of Generic Level state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_gen_move_set_t
Parameters of Generic Move Set.
Public Members
bool op_en
Indicate if optional parameters are included
int16_t delta_level
Delta Level step to calculate Move speed for Generic Level state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_gen_def_trans_time_set_t
Parameter of Generic Default Transition Time Set.
Public Members
uint8_t trans_time
The value of the Generic Default Transition Time state
struct esp_ble_mesh_gen_onpowerup_set_t
Parameter of Generic OnPowerUp Set.
Public Members
uint8_t onpowerup
The value of the Generic OnPowerUp state
struct esp_ble_mesh_gen_power_level_set_t
Parameters of Generic Power Level Set.
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t power
Target value of Generic Power Actual state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_gen_power_default_set_t
Parameter of Generic Power Default Set.
Public Members
uint16_t power
The value of the Generic Power Default state
struct esp_ble_mesh_gen_power_range_set_t
Parameters of Generic Power Range Set.
Public Members
uint16_t range_min
Value of Range Min field of Generic Power Range state
uint16_t range_max
Value of Range Max field of Generic Power Range state
struct esp_ble_mesh_gen_loc_global_set_t
Parameters of Generic Location Global Set.
Public Members
int32_t global_latitude
Global Coordinates (Latitude)
int32_t global_longitude
Global Coordinates (Longitude)
int16_t global_altitude
Global Altitude
struct esp_ble_mesh_gen_loc_local_set_t
Parameters of Generic Location Local Set.
Public Members
int16_t local_north
Local Coordinates (North)
int16_t local_east
Local Coordinates (East)
int16_t local_altitude
Local Altitude
uint8_t floor_number
Floor Number
uint16_t uncertainty
Uncertainty
struct esp_ble_mesh_gen_user_property_get_t
Parameter of Generic User Property Get.
Public Members
uint16_t property_id
Property ID identifying a Generic User Property
struct esp_ble_mesh_gen_user_property_set_t
Parameters of Generic User Property Set.
Public Members
uint16_t property_id
Property ID identifying a Generic User Property
struct esp_ble_mesh_gen_admin_property_get_t
Parameter of Generic Admin Property Get.
Public Members
uint16_t property_id
Property ID identifying a Generic Admin Property
struct esp_ble_mesh_gen_admin_property_set_t
Parameters of Generic Admin Property Set.
Public Members
uint16_t property_id
Property ID identifying a Generic Admin Property
uint8_t user_access
Enumeration indicating user access
struct esp_ble_mesh_gen_manufacturer_property_get_t
Parameter of Generic Manufacturer Property Get.
Public Members
uint16_t property_id
Property ID identifying a Generic Manufacturer Property
struct esp_ble_mesh_gen_manufacturer_property_set_t
Parameters of Generic Manufacturer Property Set.
Public Members
uint16_t property_id
Property ID identifying a Generic Manufacturer Property
uint8_t user_access
Enumeration indicating user access
struct esp_ble_mesh_gen_client_properties_get_t
Parameter of Generic Client Properties Get.
Public Members
uint16_t property_id
A starting Client Property ID present within an element
struct esp_ble_mesh_gen_onoff_status_cb_t
Bluetooth Mesh Generic Client Model Get and Set callback parameters structure.
Parameters of Generic OnOff Status.
Public Members
bool op_en
Indicate if optional parameters are included
uint8_t present_onoff
Current value of Generic OnOff state
uint8_t target_onoff
Target value of Generic OnOff state (optional)
uint8_t remain_time
Time to complete state transition (C.1)
struct esp_ble_mesh_gen_level_status_cb_t
Parameters of Generic Level Status.
Public Members
bool op_en
Indicate if optional parameters are included
int16_t present_level
Current value of Generic Level state
int16_t target_level
Target value of the Generic Level state (optional)
uint8_t remain_time
Time to complete state transition (C.1)
struct esp_ble_mesh_gen_def_trans_time_status_cb_t
Parameter of Generic Default Transition Time Status.
Public Members
uint8_t trans_time
The value of the Generic Default Transition Time state
struct esp_ble_mesh_gen_onpowerup_status_cb_t
Parameter of Generic OnPowerUp Status.
Public Members
uint8_t onpowerup
The value of the Generic OnPowerUp state
struct esp_ble_mesh_gen_power_level_status_cb_t
Parameters of Generic Power Level Status.
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t present_power
Current value of Generic Power Actual state
uint16_t target_power
Target value of Generic Power Actual state (optional)
uint8_t remain_time
Time to complete state transition (C.1)
struct esp_ble_mesh_gen_power_last_status_cb_t
Parameter of Generic Power Last Status.
Public Members
uint16_t power
The value of the Generic Power Last state
struct esp_ble_mesh_gen_power_default_status_cb_t
Parameter of Generic Power Default Status.
Public Members
uint16_t power
The value of the Generic Default Last state
struct esp_ble_mesh_gen_power_range_status_cb_t
Parameters of Generic Power Range Status.
Public Members
uint8_t status_code
Status Code for the request message
uint16_t range_min
Value of Range Min field of Generic Power Range state
uint16_t range_max
Value of Range Max field of Generic Power Range state
struct esp_ble_mesh_gen_battery_status_cb_t
Parameters of Generic Battery Status.
Public Members
uint32_t battery_level
Value of Generic Battery Level state
uint32_t time_to_discharge
Value of Generic Battery Time to Discharge state
uint32_t time_to_charge
Value of Generic Battery Time to Charge state
uint32_t flags
Value of Generic Battery Flags state
struct esp_ble_mesh_gen_loc_global_status_cb_t
Parameters of Generic Location Global Status.
Public Members
int32_t global_latitude
Global Coordinates (Latitude)
int32_t global_longitude
Global Coordinates (Longitude)
int16_t global_altitude
Global Altitude
struct esp_ble_mesh_gen_loc_local_status_cb_t
Parameters of Generic Location Local Status.
Public Members
int16_t local_north
Local Coordinates (North)
int16_t local_east
Local Coordinates (East)
int16_t local_altitude
Local Altitude
uint8_t floor_number
Floor Number
uint16_t uncertainty
Uncertainty
struct esp_ble_mesh_gen_user_properties_status_cb_t
Parameter of Generic User Properties Status.
Public Members
struct esp_ble_mesh_gen_user_property_status_cb_t
Parameters of Generic User Property Status.
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t property_id
Property ID identifying a Generic User Property
uint8_t user_access
Enumeration indicating user access (optional)
struct esp_ble_mesh_gen_admin_properties_status_cb_t
Parameter of Generic Admin Properties Status.
Public Members
struct esp_ble_mesh_gen_admin_property_status_cb_t
Parameters of Generic Admin Property Status.
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t property_id
Property ID identifying a Generic Admin Property
uint8_t user_access
Enumeration indicating user access (optional)
struct esp_ble_mesh_gen_manufacturer_properties_status_cb_t
Parameter of Generic Manufacturer Properties Status.
Public Members
struct esp_ble_mesh_gen_manufacturer_property_status_cb_t
Parameters of Generic Manufacturer Property Status.
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t property_id
Property ID identifying a Generic Manufacturer Property
uint8_t user_access
Enumeration indicating user access (optional)
struct esp_ble_mesh_gen_client_properties_status_cb_t
Parameter of Generic Client Properties Status.
Public Members
struct esp_ble_mesh_generic_client_cb_param_t
Generic Client Model callback parameters
Public Members
int error_code
Appropriate error code
esp_ble_mesh_client_common_param_t *params
The client common parameters.
esp_ble_mesh_gen_client_status_cb_t status_cb
The generic status message callback values
struct esp_ble_mesh_gen_onoff_state_t
Parameters of Generic OnOff state
Public Members
uint8_t onoff
The present value of the Generic OnOff state
uint8_t target_onoff
The target value of the Generic OnOff state
struct esp_ble_mesh_gen_onoff_srv_t
User data of Generic OnOff Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Generic OnOff Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_gen_onoff_state_t state
Parameters of the Generic OnOff state
esp_ble_mesh_last_msg_info_t last
Parameters of the last received set message
esp_ble_mesh_state_transition_t transition
Parameters of state transition
struct esp_ble_mesh_gen_level_state_t
Parameters of Generic Level state
Public Members
int16_t level
The present value of the Generic Level state
int16_t target_level
The target value of the Generic Level state
int16_t last_level
When a new transaction starts, level should be set to last_last, and use “level + incoming delta”to
calculate the target level. In another word,“last_level”is used to record“level”of the last transaction,
and“last_delta”is used to record the previously received delta_level value. The last value of the Generic
Level state
int32_t last_delta
The last delta change of the Generic Level state
bool move_start
Indicate if the transition of the Generic Level state has been started
bool positive
Indicate if the transition is positive or negative
struct esp_ble_mesh_gen_level_srv_t
User data of Generic Level Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Generic Level Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_gen_level_state_t state
Parameters of the Generic Level state
esp_ble_mesh_last_msg_info_t last
Parameters of the last received set message
esp_ble_mesh_state_transition_t transition
Parameters of state transition
int32_t tt_delta_level
Delta change value of level state transition
struct esp_ble_mesh_gen_def_trans_time_state_t
Parameter of Generic Default Transition Time state
Public Members
uint8_t trans_time
The value of the Generic Default Transition Time state
struct esp_ble_mesh_gen_def_trans_time_srv_t
User data of Generic Default Transition Time Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Generic Default Transition Time Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_gen_def_trans_time_state_t state
Parameters of the Generic Default Transition Time state
struct esp_ble_mesh_gen_onpowerup_state_t
Parameter of Generic OnPowerUp state
Public Members
uint8_t onpowerup
The value of the Generic OnPowerUp state
struct esp_ble_mesh_gen_power_onoff_srv_t
User data of Generic Power OnOff Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Generic Power OnOff Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_gen_onpowerup_state_t *state
Parameters of the Generic OnPowerUp state
struct esp_ble_mesh_gen_power_onoff_setup_srv_t
User data of Generic Power OnOff Setup Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Generic Power OnOff Setup Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_gen_onpowerup_state_t *state
Parameters of the Generic OnPowerUp state
struct esp_ble_mesh_gen_power_level_state_t
Parameters of Generic Power Level state
Public Members
uint16_t power_actual
The present value of the Generic Power Actual state
uint16_t target_power_actual
The target value of the Generic Power Actual state
uint16_t power_last
The value of the Generic Power Last state
uint16_t power_default
The value of the Generic Power Default state
uint8_t status_code
The status code of setting Generic Power Range state
uint16_t power_range_min
The minimum value of the Generic Power Range state
uint16_t power_range_max
The maximum value of the Generic Power Range state
struct esp_ble_mesh_gen_power_level_srv_t
User data of Generic Power Level Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Generic Power Level Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_gen_power_level_state_t *state
Parameters of the Generic Power Level state
esp_ble_mesh_last_msg_info_t last
Parameters of the last received set message
esp_ble_mesh_state_transition_t transition
Parameters of state transition
int32_t tt_delta_level
Delta change value of level state transition
struct esp_ble_mesh_gen_power_level_setup_srv_t
User data of Generic Power Level Setup Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Generic Power Level Setup Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_gen_power_level_state_t *state
Parameters of the Generic Power Level state
struct esp_ble_mesh_gen_battery_state_t
Parameters of Generic Battery state
Public Members
uint32_t battery_level
The value of the Generic Battery Level state
uint32_t time_to_discharge
The value of the Generic Battery Time to Discharge state
uint32_t time_to_charge
The value of the Generic Battery Time to Charge state
uint32_t battery_flags
The value of the Generic Battery Flags state
struct esp_ble_mesh_gen_battery_srv_t
User data of Generic Battery Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Generic Battery Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_gen_battery_state_t state
Parameters of the Generic Battery state
struct esp_ble_mesh_gen_location_state_t
Parameters of Generic Location state
Public Members
int32_t global_latitude
The value of the Global Latitude field
int32_t global_longitude
The value of the Global Longitude field
int16_t global_altitude
The value of the Global Altitude field
int16_t local_north
The value of the Local North field
int16_t local_east
The value of the Local East field
int16_t local_altitude
The value of the Local Altitude field
uint8_t floor_number
The value of the Floor Number field
uint16_t uncertainty
The value of the Uncertainty field
struct esp_ble_mesh_gen_location_srv_t
User data of Generic Location Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Generic Location Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_gen_location_state_t *state
Parameters of the Generic Location state
struct esp_ble_mesh_gen_location_setup_srv_t
User data of Generic Location Setup Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Generic Location Setup Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_gen_location_state_t *state
Parameters of the Generic Location state
struct esp_ble_mesh_generic_property_t
Parameters of Generic Property states
Public Members
uint16_t id
The value of User/Admin/Manufacturer Property ID
uint8_t user_access
The value of User Access field
uint8_t admin_access
The value of Admin Access field
uint8_t manu_access
The value of Manufacturer Access field
struct esp_ble_mesh_gen_user_prop_srv_t
User data of Generic User Property Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Generic User Property Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
uint8_t property_count
Generic User Property count
esp_ble_mesh_generic_property_t *properties
Parameters of the Generic User Property state
struct esp_ble_mesh_gen_admin_prop_srv_t
User data of Generic Admin Property Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Generic Admin Property Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
uint8_t property_count
Generic Admin Property count
esp_ble_mesh_generic_property_t *properties
Parameters of the Generic Admin Property state
struct esp_ble_mesh_gen_manu_prop_srv_t
User data of Generic Manufacturer Property Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Generic Manufacturer Property Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
uint8_t property_count
Generic Manufacturer Property count
esp_ble_mesh_generic_property_t *properties
Parameters of the Generic Manufacturer Property state
struct esp_ble_mesh_gen_client_prop_srv_t
User data of Generic Client Property Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Generic Client Property Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
uint8_t id_count
Generic Client Property ID count
uint16_t *property_ids
Parameters of the Generic Client Property state
struct esp_ble_mesh_state_change_gen_onoff_set_t
Parameter of Generic OnOff Set state change event
Public Members
uint8_t onoff
The value of Generic OnOff state
struct esp_ble_mesh_state_change_gen_level_set_t
Parameter of Generic Level Set state change event
Public Members
int16_t level
The value of Generic Level state
struct esp_ble_mesh_state_change_gen_delta_set_t
Parameter of Generic Delta Set state change event
Public Members
int16_t level
The value of Generic Level state
struct esp_ble_mesh_state_change_gen_move_set_t
Parameter of Generic Move Set state change event
Public Members
int16_t level
The value of Generic Level state
struct esp_ble_mesh_state_change_gen_def_trans_time_set_t
Parameter of Generic Default Transition Time Set state change event
Public Members
uint8_t trans_time
The value of Generic Default Transition Time state
struct esp_ble_mesh_state_change_gen_onpowerup_set_t
Parameter of Generic OnPowerUp Set state change event
Public Members
uint8_t onpowerup
The value of Generic OnPowerUp state
struct esp_ble_mesh_state_change_gen_power_level_set_t
Parameter of Generic Power Level Set state change event
Public Members
uint16_t power
The value of Generic Power Actual state
struct esp_ble_mesh_state_change_gen_power_default_set_t
Parameter of Generic Power Default Set state change event
Public Members
uint16_t power
The value of Generic Power Default state
struct esp_ble_mesh_state_change_gen_power_range_set_t
Parameters of Generic Power Range Set state change event
Public Members
uint16_t range_min
The minimum value of Generic Power Range state
uint16_t range_max
The maximum value of Generic Power Range state
struct esp_ble_mesh_state_change_gen_loc_global_set_t
Parameters of Generic Location Global Set state change event
Public Members
int32_t latitude
The Global Latitude value of Generic Location state
int32_t longitude
The Global Longitude value of Generic Location state
int16_t altitude
The Global Altitude value of Generic Location state
struct esp_ble_mesh_state_change_gen_loc_local_set_t
Parameters of Generic Location Local Set state change event
Public Members
int16_t north
The Local North value of Generic Location state
int16_t east
The Local East value of Generic Location state
int16_t altitude
The Local Altitude value of Generic Location state
uint8_t floor_number
The Floor Number value of Generic Location state
uint16_t uncertainty
The Uncertainty value of Generic Location state
struct esp_ble_mesh_state_change_gen_user_property_set_t
Parameters of Generic User Property Set state change event
Public Members
uint16_t id
The property id of Generic User Property state
struct esp_ble_mesh_state_change_gen_admin_property_set_t
Parameters of Generic Admin Property Set state change event
Public Members
uint16_t id
The property id of Generic Admin Property state
uint8_t access
The property access of Generic Admin Property state
struct esp_ble_mesh_state_change_gen_manu_property_set_t
Parameters of Generic Manufacturer Property Set state change event
Public Members
uint16_t id
The property id of Generic Manufacturer Property state
uint8_t access
The property value of Generic Manufacturer Property state
struct esp_ble_mesh_server_recv_gen_user_property_get_t
Context of the received Generic User Property Get message
Public Members
uint16_t property_id
Property ID identifying a Generic User Property
struct esp_ble_mesh_server_recv_gen_admin_property_get_t
Context of the received Generic Admin Property Get message
Public Members
uint16_t property_id
Property ID identifying a Generic Admin Property
struct esp_ble_mesh_server_recv_gen_manufacturer_property_get_t
Context of the received Generic Manufacturer Property message
Public Members
uint16_t property_id
Property ID identifying a Generic Manufacturer Property
struct esp_ble_mesh_server_recv_gen_client_properties_get_t
Context of the received Generic Client Properties Get message
Public Members
uint16_t property_id
A starting Client Property ID present within an element
struct esp_ble_mesh_server_recv_gen_onoff_set_t
Context of the received Generic OnOff Set message
Public Members
bool op_en
Indicate if optional parameters are included
uint8_t onoff
Target value of Generic OnOff state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_gen_level_set_t
Context of the received Generic Level Set message
Public Members
bool op_en
Indicate if optional parameters are included
int16_t level
Target value of Generic Level state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_gen_delta_set_t
Context of the received Generic Delta Set message
Public Members
bool op_en
Indicate if optional parameters are included
int32_t delta_level
Delta change of Generic Level state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_gen_move_set_t
Context of the received Generic Move Set message
Public Members
bool op_en
Indicate if optional parameters are included
int16_t delta_level
Delta Level step to calculate Move speed for Generic Level state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_gen_def_trans_time_set_t
Context of the received Generic Default Transition Time Set message
Public Members
uint8_t trans_time
The value of the Generic Default Transition Time state
struct esp_ble_mesh_server_recv_gen_onpowerup_set_t
Context of the received Generic OnPowerUp Set message
Public Members
uint8_t onpowerup
The value of the Generic OnPowerUp state
struct esp_ble_mesh_server_recv_gen_power_level_set_t
Context of the received Generic Power Level Set message
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t power
Target value of Generic Power Actual state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_gen_power_default_set_t
Context of the received Generic Power Default Set message
Public Members
uint16_t power
The value of the Generic Power Default state
struct esp_ble_mesh_server_recv_gen_power_range_set_t
Context of the received Generic Power Range Set message
Public Members
uint16_t range_min
Value of Range Min field of Generic Power Range state
uint16_t range_max
Value of Range Max field of Generic Power Range state
struct esp_ble_mesh_server_recv_gen_loc_global_set_t
Context of the received Generic Location Global Set message
Public Members
int32_t global_latitude
Global Coordinates (Latitude)
int32_t global_longitude
Global Coordinates (Longitude)
int16_t global_altitude
Global Altitude
struct esp_ble_mesh_server_recv_gen_loc_local_set_t
Context of the received Generic Location Local Set message
Public Members
int16_t local_north
Local Coordinates (North)
int16_t local_east
Local Coordinates (East)
int16_t local_altitude
Local Altitude
uint8_t floor_number
Floor Number
uint16_t uncertainty
Uncertainty
struct esp_ble_mesh_server_recv_gen_user_property_set_t
Context of the received Generic User Property Set message
Public Members
uint16_t property_id
Property ID identifying a Generic User Property
struct esp_ble_mesh_server_recv_gen_admin_property_set_t
Context of the received Generic Admin Property Set message
Public Members
uint16_t property_id
Property ID identifying a Generic Admin Property
uint8_t user_access
Enumeration indicating user access
struct esp_ble_mesh_server_recv_gen_manufacturer_property_set_t
Context of the received Generic Manufacturer Property Set message
Public Members
uint16_t property_id
Property ID identifying a Generic Manufacturer Property
uint8_t user_access
Enumeration indicating user access
struct esp_ble_mesh_generic_server_cb_param_t
Generic Server Model callback parameters
Public Members
esp_ble_mesh_model_t *model
Pointer to Generic Server Models
esp_ble_mesh_msg_ctx_t ctx
Context of the received messages
esp_ble_mesh_generic_server_cb_value_t value
Value of the received Generic Messages
Macros
ESP_BLE_MESH_MODEL_GEN_ONOFF_CLI(cli_pub, cli_data)
Define a new Generic OnOff Client Model.
Note: This API needs to be called for each element on which the application needs to have a Generic OnOff
Client Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Generic OnOff Client Model instance.
ESP_BLE_MESH_MODEL_GEN_LEVEL_CLI(cli_pub, cli_data)
Define a new Generic Level Client Model.
Note: This API needs to be called for each element on which the application needs to have a Generic Level
Client Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Generic Level Client Model instance.
ESP_BLE_MESH_MODEL_GEN_DEF_TRANS_TIME_CLI(cli_pub, cli_data)
Define a new Generic Default Transition Time Client Model.
Note: This API needs to be called for each element on which the application needs to have a Generic Default
Transition Time Client Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Generic Default Transition Time Client Model instance.
ESP_BLE_MESH_MODEL_GEN_POWER_ONOFF_CLI(cli_pub, cli_data)
Define a new Generic Power OnOff Client Model.
Note: This API needs to be called for each element on which the application needs to have a Generic Power
OnOff Client Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Generic Power OnOff Client Model instance.
ESP_BLE_MESH_MODEL_GEN_POWER_LEVEL_CLI(cli_pub, cli_data)
Define a new Generic Power Level Client Model.
Note: This API needs to be called for each element on which the application needs to have a Generic Power
Level Client Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Generic Power Level Client Model instance.
ESP_BLE_MESH_MODEL_GEN_BATTERY_CLI(cli_pub, cli_data)
Define a new Generic Battery Client Model.
Note: This API needs to be called for each element on which the application needs to have a Generic Battery
Client Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Generic Battery Client Model instance.
ESP_BLE_MESH_MODEL_GEN_LOCATION_CLI(cli_pub, cli_data)
Define a new Generic Location Client Model.
Note: This API needs to be called for each element on which the application needs to have a Generic Location
Client Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Generic Location Client Model instance.
ESP_BLE_MESH_MODEL_GEN_PROPERTY_CLI(cli_pub, cli_data)
Define a new Generic Property Client Model.
Note: This API needs to be called for each element on which the application needs to have a Generic Property
Client Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Generic Location Client Model instance.
ESP_BLE_MESH_MODEL_GEN_ONOFF_SRV(srv_pub, srv_data)
Generic Server Models related context.
Define a new Generic OnOff Server Model.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_gen_onoff_srv_t.
Returns New Generic OnOff Server Model instance.
ESP_BLE_MESH_MODEL_GEN_LEVEL_SRV(srv_pub, srv_data)
Define a new Generic Level Server Model.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_gen_level_srv_t.
Returns New Generic Level Server Model instance.
ESP_BLE_MESH_MODEL_GEN_DEF_TRANS_TIME_SRV(srv_pub, srv_data)
Define a new Generic Default Transition Time Server Model.
Note: 1. The Generic Default Transition Time Server Model is a root model.
a. This model shall support model publication and model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_gen_def_trans_time_srv_t.
Returns New Generic Default Transition Time Server Model instance.
ESP_BLE_MESH_MODEL_GEN_POWER_ONOFF_SRV(srv_pub, srv_data)
Define a new Generic Power OnOff Server Model.
Note: 1. The Generic Power OnOff Server model extends the Generic OnOff Server model. When this model
is present on an element, the corresponding Generic Power OnOff Setup Server model shall also be present.
a. This model may be used to represent a variety of devices that do not fit any of the model descriptions
that have been defined but support the generic properties of On/Off.
b. This model shall support model publication and model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_gen_power_onoff_srv_t.
Returns New Generic Power OnOff Server Model instance.
ESP_BLE_MESH_MODEL_GEN_POWER_ONOFF_SETUP_SRV(srv_pub, srv_data)
Define a new Generic Power OnOff Setup Server Model.
Note: 1. The Generic Power OnOff Setup Server model extends the Generic Power OnOff Server model and
the Generic Default Transition Time Server model.
a. This model shall support model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_gen_power_onoff_setup_srv_t.
Returns New Generic Power OnOff Setup Server Model instance.
ESP_BLE_MESH_MODEL_GEN_POWER_LEVEL_SRV(srv_pub, srv_data)
Define a new Generic Power Level Server Model.
Note: 1. The Generic Power Level Server model extends the Generic Power OnOff Server model and the
Generic Level Server model. When this model is present on an Element, the corresponding Generic Power
Level Setup Server model shall also be present.
a. This model shall support model publication and model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_gen_power_level_srv_t.
Returns New Generic Power Level Server Model instance.
ESP_BLE_MESH_MODEL_GEN_POWER_LEVEL_SETUP_SRV(srv_pub, srv_data)
Define a new Generic Power Level Setup Server Model.
Note: 1. The Generic Power Level Setup Server model extends the Generic Power Level Server model and
the Generic Power OnOff Setup Server model.
a. This model shall support model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_gen_power_level_setup_srv_t.
Returns New Generic Power Level Setup Server Model instance.
ESP_BLE_MESH_MODEL_GEN_BATTERY_SRV(srv_pub, srv_data)
Define a new Generic Battery Server Model.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_gen_battery_srv_t.
Returns New Generic Battery Server Model instance.
ESP_BLE_MESH_MODEL_GEN_LOCATION_SRV(srv_pub, srv_data)
Define a new Generic Location Server Model.
Note: 1. The Generic Location Server model is a root model. When this model is present on an Element, the
corresponding Generic Location Setup Server model shall also be present.
a. This model shall support model publication and model subscription.
b. The model may be used to represent an element that knows its location (global or local).
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_gen_location_srv_t.
Returns New Generic Location Server Model instance.
ESP_BLE_MESH_MODEL_GEN_LOCATION_SETUP_SRV(srv_pub, srv_data)
Define a new Generic Location Setup Server Model.
Note: 1. The Generic Location Setup Server model extends the Generic Location Server model.
a. This model shall support model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_gen_location_setup_srv_t.
Returns New Generic Location Setup Server Model instance.
ESP_BLE_MESH_MODEL_GEN_USER_PROP_SRV(srv_pub, srv_data)
Define a new Generic User Property Server Model.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_gen_user_prop_srv_t.
Returns New Generic User Property Server Model instance.
ESP_BLE_MESH_MODEL_GEN_ADMIN_PROP_SRV(srv_pub, srv_data)
Define a new Generic Admin Property Server Model.
Note: 1. The Generic Admin Property Server model extends the Generic User Property Server model.
a. This model shall support model publication and model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_gen_admin_prop_srv_t.
Returns New Generic Admin Property Server Model instance.
ESP_BLE_MESH_MODEL_GEN_MANUFACTURER_PROP_SRV(srv_pub, srv_data)
Define a new Generic Manufacturer Property Server Model.
Note: 1. The Generic Manufacturer Property Server model extends the Generic User Property Server model.
a. This model shall support model publication and model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_gen_manu_prop_srv_t.
Returns New Generic Manufacturer Property Server Model instance.
ESP_BLE_MESH_MODEL_GEN_CLIENT_PROP_SRV(srv_pub, srv_data)
Define a new Generic User Property Server Model.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_gen_client_prop_srv_t.
Returns New Generic Client Property Server Model instance.
Type Definitions
Enumerations
enum esp_ble_mesh_generic_client_cb_event_t
This enum value is the event of Generic Client Model
Values:
enumerator ESP_BLE_MESH_GENERIC_CLIENT_GET_STATE_EVT
enumerator ESP_BLE_MESH_GENERIC_CLIENT_SET_STATE_EVT
enumerator ESP_BLE_MESH_GENERIC_CLIENT_PUBLISH_EVT
enumerator ESP_BLE_MESH_GENERIC_CLIENT_TIMEOUT_EVT
enumerator ESP_BLE_MESH_GENERIC_CLIENT_EVT_MAX
enum esp_ble_mesh_gen_user_prop_access_t
This enum value is the access value of Generic User Property
Values:
enumerator ESP_BLE_MESH_GEN_USER_ACCESS_PROHIBIT
enumerator ESP_BLE_MESH_GEN_USER_ACCESS_READ
enumerator ESP_BLE_MESH_GEN_USER_ACCESS_WRITE
enumerator ESP_BLE_MESH_GEN_USER_ACCESS_READ_WRITE
enum esp_ble_mesh_gen_admin_prop_access_t
This enum value is the access value of Generic Admin Property
Values:
enumerator ESP_BLE_MESH_GEN_ADMIN_NOT_USER_PROP
enumerator ESP_BLE_MESH_GEN_ADMIN_ACCESS_READ
enumerator ESP_BLE_MESH_GEN_ADMIN_ACCESS_WRITE
enumerator ESP_BLE_MESH_GEN_ADMIN_ACCESS_READ_WRITE
enum esp_ble_mesh_gen_manu_prop_access_t
This enum value is the access value of Generic Manufacturer Property
Values:
enumerator ESP_BLE_MESH_GEN_MANU_NOT_USER_PROP
enumerator ESP_BLE_MESH_GEN_MANU_ACCESS_READ
enum esp_ble_mesh_generic_server_cb_event_t
This enum value is the event of Generic Server Model
Values:
enumerator ESP_BLE_MESH_GENERIC_SERVER_STATE_CHANGE_EVT
enumerator ESP_BLE_MESH_GENERIC_SERVER_RECV_GET_MSG_EVT
When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to
the application layer when Generic Get messages are received.
enumerator ESP_BLE_MESH_GENERIC_SERVER_RECV_SET_MSG_EVT
When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to
the application layer when Generic Set/Set Unack messages are received.
enumerator ESP_BLE_MESH_GENERIC_SERVER_EVT_MAX
Header File
• components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_sensor_model_api.h
Functions
esp_err_t esp_ble_mesh_register_sensor_client_callback(esp_ble_mesh_sensor_client_cb_t
callback)
Register BLE Mesh Sensor Client Model callback.
Parameters callback –[in] Pointer to the callback function.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_sensor_client_get_state(esp_ble_mesh_client_common_param_t
*params, esp_ble_mesh_sensor_client_get_state_t
*get_state)
Get the value of Sensor Server Model states using the Sensor Client Model get messages.
Note: If you want to know the opcodes and corresponding meanings accepted by this API, please refer to
esp_ble_mesh_sensor_message_opcode_t in esp_ble_mesh_defs.h
Parameters
• params –[in] Pointer to BLE Mesh common client parameters.
• get_state –[in] Pointer to sensor get message value. Shall not be set to NULL.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_sensor_client_set_state(esp_ble_mesh_client_common_param_t
*params, esp_ble_mesh_sensor_client_set_state_t
*set_state)
Set the value of Sensor Server Model states using the Sensor Client Model set messages.
Note: If you want to know the opcodes and corresponding meanings accepted by this API, please refer to
esp_ble_mesh_sensor_message_opcode_t in esp_ble_mesh_defs.h
Parameters
• params –[in] Pointer to BLE Mesh common client parameters.
• set_state –[in] Pointer to sensor set message value. Shall not be set to NULL.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_register_sensor_server_callback(esp_ble_mesh_sensor_server_cb_t
callback)
Register BLE Mesh Sensor Server Model callback.
Parameters callback –[in] Pointer to the callback function.
Returns ESP_OK on success or error code otherwise.
Unions
union esp_ble_mesh_sensor_client_get_state_t
#include <esp_ble_mesh_sensor_model_api.h> Sensor Client Model get message union.
Public Members
esp_ble_mesh_sensor_descriptor_get_t descriptor_get
For ESP_BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_GET
esp_ble_mesh_sensor_cadence_get_t cadence_get
For ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_GET
esp_ble_mesh_sensor_settings_get_t settings_get
For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTINGS_GET
esp_ble_mesh_sensor_setting_get_t setting_get
For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_GET
esp_ble_mesh_sensor_get_t sensor_get
For ESP_BLE_MESH_MODEL_OP_SENSOR_GET
esp_ble_mesh_sensor_column_get_t column_get
For ESP_BLE_MESH_MODEL_OP_SENSOR_COLUMN_GET
esp_ble_mesh_sensor_series_get_t series_get
For ESP_BLE_MESH_MODEL_OP_SENSOR_SERIES_GET
union esp_ble_mesh_sensor_client_set_state_t
#include <esp_ble_mesh_sensor_model_api.h> Sensor Client Model set message union.
Public Members
esp_ble_mesh_sensor_cadence_set_t cadence_set
For ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET &
ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_SET_UNACK
esp_ble_mesh_sensor_setting_set_t setting_set
For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_SET &
ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_SET_UNACK
union esp_ble_mesh_sensor_client_status_cb_t
#include <esp_ble_mesh_sensor_model_api.h> Sensor Client Model received message union.
Public Members
esp_ble_mesh_sensor_descriptor_status_cb_t descriptor_status
For ESP_BLE_MESH_MODEL_OP_SENSOR_DESCRIPTOR_STATUS
esp_ble_mesh_sensor_cadence_status_cb_t cadence_status
For ESP_BLE_MESH_MODEL_OP_SENSOR_CADENCE_STATUS
esp_ble_mesh_sensor_settings_status_cb_t settings_status
For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTINGS_STATUS
esp_ble_mesh_sensor_setting_status_cb_t setting_status
For ESP_BLE_MESH_MODEL_OP_SENSOR_SETTING_STATUS
esp_ble_mesh_sensor_status_cb_t sensor_status
For ESP_BLE_MESH_MODEL_OP_SENSOR_STATUS
esp_ble_mesh_sensor_column_status_cb_t column_status
For ESP_BLE_MESH_MODEL_OP_SENSOR_COLUMN_STATUS
esp_ble_mesh_sensor_series_status_cb_t series_status
For ESP_BLE_MESH_MODEL_OP_SENSOR_SERIES_STATUS
union esp_ble_mesh_sensor_server_state_change_t
#include <esp_ble_mesh_sensor_model_api.h> Sensor Server Model state change value union.
Public Members
esp_ble_mesh_state_change_sensor_cadence_set_t sensor_cadence_set
The recv_op in ctx can be used to decide which state is changed. Sensor Cadence Set
esp_ble_mesh_state_change_sensor_setting_set_t sensor_setting_set
Sensor Setting Set
union esp_ble_mesh_sensor_server_recv_get_msg_t
#include <esp_ble_mesh_sensor_model_api.h> Sensor Server Model received get message union.
Public Members
esp_ble_mesh_server_recv_sensor_descriptor_get_t sensor_descriptor
Sensor Descriptor Get
esp_ble_mesh_server_recv_sensor_cadence_get_t sensor_cadence
Sensor Cadence Get
esp_ble_mesh_server_recv_sensor_settings_get_t sensor_settings
Sensor Settings Get
esp_ble_mesh_server_recv_sensor_setting_get_t sensor_setting
Sensor Setting Get
esp_ble_mesh_server_recv_sensor_get_t sensor_data
Sensor Get
esp_ble_mesh_server_recv_sensor_column_get_t sensor_column
Sensor Column Get
esp_ble_mesh_server_recv_sensor_series_get_t sensor_series
Sensor Series Get
union esp_ble_mesh_sensor_server_recv_set_msg_t
#include <esp_ble_mesh_sensor_model_api.h> Sensor Server Model received set message union.
Public Members
esp_ble_mesh_server_recv_sensor_cadence_set_t sensor_cadence
Sensor Cadence Set
esp_ble_mesh_server_recv_sensor_setting_set_t sensor_setting
Sensor Setting Set
union esp_ble_mesh_sensor_server_cb_value_t
#include <esp_ble_mesh_sensor_model_api.h> Sensor Server Model callback value union.
Public Members
esp_ble_mesh_sensor_server_state_change_t state_change
ESP_BLE_MESH_SENSOR_SERVER_STATE_CHANGE_EVT
esp_ble_mesh_sensor_server_recv_get_msg_t get
ESP_BLE_MESH_SENSOR_SERVER_RECV_GET_MSG_EVT
esp_ble_mesh_sensor_server_recv_set_msg_t set
ESP_BLE_MESH_SENSOR_SERVER_RECV_SET_MSG_EVT
Structures
struct esp_ble_mesh_sensor_descriptor_get_t
Bluetooth Mesh Sensor Client Model Get and Set parameters structure.
Parameters of Sensor Descriptor Get
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t property_id
Property ID of a sensor (optional)
struct esp_ble_mesh_sensor_cadence_get_t
Parameter of Sensor Cadence Get
Public Members
uint16_t property_id
Property ID of a sensor
struct esp_ble_mesh_sensor_cadence_set_t
Parameters of Sensor Cadence Set
Public Members
uint16_t property_id
Property ID for the sensor
uint8_t fast_cadence_period_divisor
Divisor for the publish period
uint8_t status_trigger_type
The unit and format of the Status Trigger Delta fields
uint8_t status_min_interval
Minimum interval between two consecutive Status messages
struct esp_ble_mesh_sensor_settings_get_t
Parameter of Sensor Settings Get
Public Members
uint16_t sensor_property_id
Property ID of a sensor
struct esp_ble_mesh_sensor_setting_get_t
Parameters of Sensor Setting Get
Public Members
uint16_t sensor_property_id
Property ID of a sensor
uint16_t sensor_setting_property_id
Setting ID identifying a setting within a sensor
struct esp_ble_mesh_sensor_setting_set_t
Parameters of Sensor Setting Set
Public Members
uint16_t sensor_property_id
Property ID identifying a sensor
uint16_t sensor_setting_property_id
Setting ID identifying a setting within a sensor
struct esp_ble_mesh_sensor_get_t
Parameters of Sensor Get
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t property_id
Property ID for the sensor (optional)
struct esp_ble_mesh_sensor_column_get_t
Parameters of Sensor Column Get
Public Members
uint16_t property_id
Property identifying a sensor
struct esp_ble_mesh_sensor_series_get_t
Parameters of Sensor Series Get
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t property_id
Property identifying a sensor
struct esp_ble_mesh_sensor_descriptor_status_cb_t
Bluetooth Mesh Sensor Client Model Get and Set callback parameters structure.
Parameter of Sensor Descriptor Status
Public Members
struct esp_ble_mesh_sensor_cadence_status_cb_t
Parameters of Sensor Cadence Status
Public Members
uint16_t property_id
Property for the sensor
struct esp_ble_mesh_sensor_settings_status_cb_t
Parameters of Sensor Settings Status
Public Members
uint16_t sensor_property_id
Property ID identifying a sensor
struct esp_ble_mesh_sensor_setting_status_cb_t
Parameters of Sensor Setting Status
Public Members
bool op_en
Indicate id optional parameters are included
uint16_t sensor_property_id
Property ID identifying a sensor
uint16_t sensor_setting_property_id
Setting ID identifying a setting within a sensor
uint8_t sensor_setting_access
Read/Write access rights for the setting (optional)
struct esp_ble_mesh_sensor_status_cb_t
Parameter of Sensor Status
Public Members
struct esp_ble_mesh_sensor_column_status_cb_t
Parameters of Sensor Column Status
Public Members
uint16_t property_id
Property identifying a sensor and the Y axis
struct esp_ble_mesh_sensor_series_status_cb_t
Parameters of Sensor Series Status
Public Members
uint16_t property_id
Property identifying a sensor and the Y axis
struct esp_ble_mesh_sensor_client_cb_param_t
Sensor Client Model callback parameters
Public Members
int error_code
0: success, otherwise failure. For the error code values please refer to errno.h file. A negative sign is
added to the standard error codes in errno.h.
esp_ble_mesh_client_common_param_t *params
The client common parameters.
esp_ble_mesh_sensor_client_status_cb_t status_cb
The sensor status message callback values
struct esp_ble_mesh_sensor_descriptor_t
Parameters of Sensor Descriptor state
Public Members
uint32_t positive_tolerance
The value of Sensor Positive Tolerance field
uint32_t negative_tolerance
The value of Sensor Negative Tolerance field
uint32_t sampling_function
The value of Sensor Sampling Function field
uint8_t measure_period
The value of Sensor Measurement Period field
uint8_t update_interval
The value of Sensor Update Interval field
struct esp_ble_mesh_sensor_setting_t
Parameters of Sensor Setting state
Public Members
uint16_t property_id
The value of Sensor Setting Property ID field
uint8_t access
The value of Sensor Setting Access field
struct esp_ble_mesh_sensor_cadence_t
Parameters of Sensor Cadence state
Public Members
uint8_t period_divisor
The value of Fast Cadence Period Divisor field
uint8_t trigger_type
The value of Status Trigger Type field
uint8_t min_interval
The value of Status Min Interval field
struct esp_ble_mesh_sensor_data_t
Parameters of Sensor Data state
Public Members
uint8_t format
Format A: The Length field is a 1-based uint4 value (valid range 0x0–0xF, representing range of 1 –16).
Format B: The Length field is a 1-based uint7 value (valid range 0x0–0x7F, representing range of 1 –
127). The value 0x7F represents a length of zero. The value of the Sensor Data format
uint8_t length
The value of the Sensor Data length
struct esp_ble_mesh_sensor_series_column_t
Parameters of Sensor Series Column state
Public Members
struct esp_ble_mesh_sensor_state_t
Parameters of Sensor states
Public Members
uint16_t sensor_property_id
The value of Sensor Property ID field
esp_ble_mesh_sensor_descriptor_t descriptor
Parameters of the Sensor Descriptor state
esp_ble_mesh_sensor_setting_t *settings
Parameters of the Sensor Setting state
esp_ble_mesh_sensor_cadence_t *cadence
The Sensor Cadence state may be not supported by sensors based on device properties referencing“non-
scalar characteristics”such as“histograms”or“composite characteristics”. Parameters of the Sensor
Cadence state
esp_ble_mesh_sensor_data_t sensor_data
Parameters of the Sensor Data state
esp_ble_mesh_sensor_series_column_t series_column
Parameters of the Sensor Series Column state
struct esp_ble_mesh_sensor_srv_t
User data of Sensor Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Sensor Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_sensor_state_t *states
Parameters of the Sensor states
struct esp_ble_mesh_sensor_setup_srv_t
User data of Sensor Setup Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Sensor Setup Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_sensor_state_t *states
Parameters of the Sensor states
struct esp_ble_mesh_state_change_sensor_cadence_set_t
Parameters of Sensor Cadence Set state change event
Public Members
uint16_t property_id
The value of Sensor Property ID state
uint8_t period_divisor
The value of Fast Cadence Period Divisor state
uint8_t trigger_type
The value of Status Trigger Type state
uint8_t min_interval
The value of Status Min Interval state
struct esp_ble_mesh_state_change_sensor_setting_set_t
Parameters of Sensor Setting Set state change event
Public Members
uint16_t property_id
The value of Sensor Property ID state
uint16_t setting_property_id
The value of Sensor Setting Property ID state
struct esp_ble_mesh_server_recv_sensor_descriptor_get_t
Context of the received Sensor Descriptor Get message
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t property_id
Property ID of a sensor (optional)
struct esp_ble_mesh_server_recv_sensor_cadence_get_t
Context of the received Sensor Cadence Get message
Public Members
uint16_t property_id
Property ID of a sensor
struct esp_ble_mesh_server_recv_sensor_settings_get_t
Context of the received Sensor Settings Get message
Public Members
uint16_t property_id
Property ID of a sensor
struct esp_ble_mesh_server_recv_sensor_setting_get_t
Context of the received Sensor Setting Get message
Public Members
uint16_t property_id
Property ID of a sensor
uint16_t setting_property_id
Setting ID identifying a setting within a sensor
struct esp_ble_mesh_server_recv_sensor_get_t
Context of the received Sensor Get message
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t property_id
Property ID for the sensor (optional)
struct esp_ble_mesh_server_recv_sensor_column_get_t
Context of the received Sensor Column Get message
Public Members
uint16_t property_id
Property identifying a sensor
struct esp_ble_mesh_server_recv_sensor_series_get_t
Context of the received Sensor Series Get message
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t property_id
Property identifying a sensor
struct esp_ble_mesh_server_recv_sensor_cadence_set_t
Context of the received Sensor Cadence Set message
Public Members
uint16_t property_id
Property ID for the sensor
struct esp_ble_mesh_server_recv_sensor_setting_set_t
Context of the received Sensor Setting Set message
Public Members
uint16_t property_id
Property ID identifying a sensor
uint16_t setting_property_id
Setting ID identifying a setting within a sensor
struct esp_ble_mesh_sensor_server_cb_param_t
Sensor Server Model callback parameters
Public Members
esp_ble_mesh_model_t *model
Pointer to Sensor Server Models
esp_ble_mesh_msg_ctx_t ctx
Context of the received messages
esp_ble_mesh_sensor_server_cb_value_t value
Value of the received Sensor Messages
Macros
ESP_BLE_MESH_MODEL_SENSOR_CLI(cli_pub, cli_data)
Define a new Sensor Client Model.
Note: This API needs to be called for each element on which the application needs to have a Sensor Client
Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Sensor Client Model instance.
ESP_BLE_MESH_MODEL_SENSOR_SRV(srv_pub, srv_data)
Sensor Server Models related context.
Define a new Sensor Server Model.
Note: 1. The Sensor Server model is a root model. When this model is present on an element, the corre-
sponding Sensor Setup Server model shall also be present.
a. This model shall support model publication and model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_sensor_srv_t.
Returns New Sensor Server Model instance.
ESP_BLE_MESH_MODEL_SENSOR_SETUP_SRV(srv_pub, srv_data)
Define a new Sensor Setup Server Model.
Note: 1. The Sensor Setup Server model extends the Sensor Server model.
a. This model shall support model publication and model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_sensor_setup_srv_t.
Returns New Sensor Setup Server Model instance.
ESP_BLE_MESH_INVALID_SENSOR_PROPERTY_ID
Invalid Sensor Property ID
ESP_BLE_MESH_SENSOR_PROPERTY_ID_LEN
Length of Sensor Property ID
ESP_BLE_MESH_SENSOR_DESCRIPTOR_LEN
Length of Sensor Descriptor state
ESP_BLE_MESH_SENSOR_UNSPECIFIED_POS_TOLERANCE
Unspecified Sensor Positive Tolerance
ESP_BLE_MESH_SENSOR_UNSPECIFIED_NEG_TOLERANCE
Unspecified Sensor Negative Tolerance
ESP_BLE_MESH_SENSOR_NOT_APPL_MEASURE_PERIOD
Not applicable Sensor Measurement Period
ESP_BLE_MESH_SENSOR_NOT_APPL_UPDATE_INTERVAL
Not applicable Sensor Update Interval
ESP_BLE_MESH_INVALID_SENSOR_SETTING_PROPERTY_ID
Invalid Sensor Setting Property ID
ESP_BLE_MESH_SENSOR_SETTING_PROPERTY_ID_LEN
Length of Sensor Setting Property ID
ESP_BLE_MESH_SENSOR_SETTING_ACCESS_LEN
Length of Sensor Setting Access
ESP_BLE_MESH_SENSOR_SETTING_ACCESS_READ
Sensor Setting Access - Read
ESP_BLE_MESH_SENSOR_SETTING_ACCESS_READ_WRITE
Sensor Setting Access - Read & Write
ESP_BLE_MESH_SENSOR_DIVISOR_TRIGGER_TYPE_LEN
Length of Sensor Divisor Trigger Type
ESP_BLE_MESH_SENSOR_STATUS_MIN_INTERVAL_LEN
Length of Sensor Status Min Interval
ESP_BLE_MESH_SENSOR_PERIOD_DIVISOR_MAX_VALUE
Maximum value of Sensor Period Divisor
ESP_BLE_MESH_SENSOR_STATUS_MIN_INTERVAL_MAX
Maximum value of Sensor Status Min Interval
ESP_BLE_MESH_SENSOR_STATUS_TRIGGER_TYPE_CHAR
Sensor Status Trigger Type - Format Type of the characteristic that the Sensor Property ID state references
ESP_BLE_MESH_SENSOR_STATUS_TRIGGER_TYPE_UINT16
Sensor Status Trigger Type - Format Type “uint16”
ESP_BLE_MESH_SENSOR_DATA_FORMAT_A
Sensor Data Format A
ESP_BLE_MESH_SENSOR_DATA_FORMAT_B
Sensor Data Format B
ESP_BLE_MESH_SENSOR_DATA_FORMAT_A_MPID_LEN
MPID length of Sensor Data Format A
ESP_BLE_MESH_SENSOR_DATA_FORMAT_B_MPID_LEN
MPID length of Sensor Data Format B
ESP_BLE_MESH_SENSOR_DATA_ZERO_LEN
Zero length of Sensor Data.
Note: The Length field is a 1-based uint7 value (valid range 0x0–0x7F, representing range of 1–127). The
value 0x7F represents a length of zero.
ESP_BLE_MESH_GET_SENSOR_DATA_FORMAT(_data)
Get format of the sensor data.
Note: Multiple sensor data may be concatenated. Make sure the _data pointer is updated before getting the
format of the corresponding sensor data.
Parameters
• _data –Pointer to the start of the sensor data.
Returns Format of the sensor data.
ESP_BLE_MESH_GET_SENSOR_DATA_LENGTH(_data, _fmt)
Get length of the sensor data.
Note: Multiple sensor data may be concatenated. Make sure the _data pointer is updated before getting the
length of the corresponding sensor data.
Parameters
• _data –Pointer to the start of the sensor data.
• _fmt –Format of the sensor data.
Returns Length (zero-based) of the sensor data.
ESP_BLE_MESH_GET_SENSOR_DATA_PROPERTY_ID(_data, _fmt)
Get Sensor Property ID of the sensor data.
Note: Multiple sensor data may be concatenated. Make sure the _data pointer is updated before getting
Sensor Property ID of the corresponding sensor data.
Parameters
• _data –Pointer to the start of the sensor data.
• _fmt –Format of the sensor data.
Returns Sensor Property ID of the sensor data.
ESP_BLE_MESH_SENSOR_DATA_FORMAT_A_MPID(_len, _id)
Generate a MPID value for sensor data with Format A.
Note: 1. The Format field is 0b0 and indicates that Format A is used.
a. The Length field is a 1-based uint4 value (valid range 0x0–0xF, representing range of 1–16).
b. The Property ID is an 11-bit bit field representing 11 LSb of a Property ID.
c. This format may be used for Property Values that are not longer than 16 octets and for Property IDs less
than 0x0800.
Parameters
• _len –Length of Sensor Raw value.
• _id –Sensor Property ID.
Returns 2-octet MPID value for sensor data with Format A.
ESP_BLE_MESH_SENSOR_DATA_FORMAT_B_MPID(_len, _id)
Generate a MPID value for sensor data with Format B.
a. The Length field is a 1-based uint7 value (valid range 0x0–0x7F, representing range of 1–127). The
value 0x7F represents a length of zero.
b. The Property ID is a 16-bit bit field representing a Property ID.
c. This format may be used for Property Values not longer than 128 octets and for any Property IDs. Prop-
erty values longer than 128 octets are not supported by the Sensor Status message.
d. Exclude the generated 1-octet value, the 2-octet Sensor Property ID
Parameters
• _len –Length of Sensor Raw value.
• _id –Sensor Property ID.
Returns 3-octet MPID value for sensor data with Format B.
Type Definitions
typedef void (*esp_ble_mesh_sensor_client_cb_t)(esp_ble_mesh_sensor_client_cb_event_t event,
esp_ble_mesh_sensor_client_cb_param_t *param)
Bluetooth Mesh Sensor Client Model function.
Sensor Client Model callback function type
Param event Event type
Param param Pointer to callback parameter
typedef void (*esp_ble_mesh_sensor_server_cb_t)(esp_ble_mesh_sensor_server_cb_event_t event,
esp_ble_mesh_sensor_server_cb_param_t *param)
Bluetooth Mesh Sensor Server Model function.
Sensor Server Model callback function type
Param event Event type
Param param Pointer to callback parameter
Enumerations
enum esp_ble_mesh_sensor_client_cb_event_t
This enum value is the event of Sensor Client Model
Values:
enumerator ESP_BLE_MESH_SENSOR_CLIENT_GET_STATE_EVT
enumerator ESP_BLE_MESH_SENSOR_CLIENT_SET_STATE_EVT
enumerator ESP_BLE_MESH_SENSOR_CLIENT_PUBLISH_EVT
enumerator ESP_BLE_MESH_SENSOR_CLIENT_TIMEOUT_EVT
enumerator ESP_BLE_MESH_SENSOR_CLIENT_EVT_MAX
enum esp_ble_mesh_sensor_sample_func
This enum value is value of Sensor Sampling Function
Values:
enumerator ESP_BLE_MESH_SAMPLE_FUNC_UNSPECIFIED
enumerator ESP_BLE_MESH_SAMPLE_FUNC_INSTANTANEOUS
enumerator ESP_BLE_MESH_SAMPLE_FUNC_ARITHMETIC_MEAN
enumerator ESP_BLE_MESH_SAMPLE_FUNC_RMS
enumerator ESP_BLE_MESH_SAMPLE_FUNC_MAXIMUM
enumerator ESP_BLE_MESH_SAMPLE_FUNC_MINIMUM
enumerator ESP_BLE_MESH_SAMPLE_FUNC_ACCUMULATED
enumerator ESP_BLE_MESH_SAMPLE_FUNC_COUNT
enum esp_ble_mesh_sensor_server_cb_event_t
This enum value is the event of Sensor Server Model
Values:
enumerator ESP_BLE_MESH_SENSOR_SERVER_STATE_CHANGE_EVT
enumerator ESP_BLE_MESH_SENSOR_SERVER_RECV_GET_MSG_EVT
When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to
the application layer when Sensor Get messages are received.
enumerator ESP_BLE_MESH_SENSOR_SERVER_RECV_SET_MSG_EVT
When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to
the application layer when Sensor Set/Set Unack messages are received.
enumerator ESP_BLE_MESH_SENSOR_SERVER_EVT_MAX
Header File
• components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_time_scene_model_api.h
Functions
esp_err_t esp_ble_mesh_register_time_scene_client_callback(esp_ble_mesh_time_scene_client_cb_t
callback)
Register BLE Mesh Time Scene Client Model callback.
Parameters callback –[in] Pointer to the callback function.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_time_scene_client_get_state(esp_ble_mesh_client_common_param_t
*params,
esp_ble_mesh_time_scene_client_get_state_t
*get_state)
Get the value of Time Scene Server Model states using the Time Scene Client Model get messages.
Note: If you want to know the opcodes and corresponding meanings accepted by this API, please refer to
esp_ble_mesh_time_scene_message_opcode_t in esp_ble_mesh_defs.h
Parameters
• params –[in] Pointer to BLE Mesh common client parameters.
• get_state –[in] Pointer to time scene get message value. Shall not be set to NULL.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_time_scene_client_set_state(esp_ble_mesh_client_common_param_t
*params,
esp_ble_mesh_time_scene_client_set_state_t
*set_state)
Set the value of Time Scene Server Model states using the Time Scene Client Model set messages.
Note: If you want to know the opcodes and corresponding meanings accepted by this API, please refer to
esp_ble_mesh_time_scene_message_opcode_t in esp_ble_mesh_defs.h
Parameters
• params –[in] Pointer to BLE Mesh common client parameters.
• set_state –[in] Pointer to time scene set message value. Shall not be set to NULL.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_register_time_scene_server_callback(esp_ble_mesh_time_scene_server_cb_t
callback)
Register BLE Mesh Time and Scenes Server Model callback.
Parameters callback –[in] Pointer to the callback function.
Returns ESP_OK on success or error code otherwise.
Unions
union esp_ble_mesh_time_scene_client_get_state_t
#include <esp_ble_mesh_time_scene_model_api.h> Time Scene Client Model get message union.
Public Members
esp_ble_mesh_scheduler_act_get_t scheduler_act_get
For ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_GET
union esp_ble_mesh_time_scene_client_set_state_t
#include <esp_ble_mesh_time_scene_model_api.h> Time Scene Client Model set message union.
Public Members
esp_ble_mesh_time_set_t time_set
For ESP_BLE_MESH_MODEL_OP_TIME_SET
esp_ble_mesh_time_zone_set_t time_zone_set
For ESP_BLE_MESH_MODEL_OP_TIME_ZONE_SET
esp_ble_mesh_tai_utc_delta_set_t tai_utc_delta_set
For ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_SET
esp_ble_mesh_time_role_set_t time_role_set
For ESP_BLE_MESH_MODEL_OP_TIME_ROLE_SET
esp_ble_mesh_scene_store_t scene_store
For ESP_BLE_MESH_MODEL_OP_SCENE_STORE & ESP_BLE_MESH_MODEL_OP_SCENE_STORE_UNACK
esp_ble_mesh_scene_recall_t scene_recall
For ESP_BLE_MESH_MODEL_OP_SCENE_RECALL & ESP_BLE_MESH_MODEL_OP_SCENE_RECALL_UNAC
esp_ble_mesh_scene_delete_t scene_delete
For ESP_BLE_MESH_MODEL_OP_SCENE_DELETE & ESP_BLE_MESH_MODEL_OP_SCENE_DELETE_UNAC
esp_ble_mesh_scheduler_act_set_t scheduler_act_set
For ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET &
ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_SET_UNACK
union esp_ble_mesh_time_scene_client_status_cb_t
#include <esp_ble_mesh_time_scene_model_api.h> Time Scene Client Model received message union.
Public Members
esp_ble_mesh_time_status_cb_t time_status
For ESP_BLE_MESH_MODEL_OP_TIME_STATUS
esp_ble_mesh_time_zone_status_cb_t time_zone_status
For ESP_BLE_MESH_MODEL_OP_TIME_ZONE_STATUS
esp_ble_mesh_tai_utc_delta_status_cb_t tai_utc_delta_status
For ESP_BLE_MESH_MODEL_OP_TAI_UTC_DELTA_STATUS
esp_ble_mesh_time_role_status_cb_t time_role_status
For ESP_BLE_MESH_MODEL_OP_TIME_ROLE_STATUS
esp_ble_mesh_scene_status_cb_t scene_status
For ESP_BLE_MESH_MODEL_OP_SCENE_STATUS
esp_ble_mesh_scene_register_status_cb_t scene_register_status
For ESP_BLE_MESH_MODEL_OP_SCENE_REGISTER_STATUS
esp_ble_mesh_scheduler_status_cb_t scheduler_status
For ESP_BLE_MESH_MODEL_OP_SCHEDULER_STATUS
esp_ble_mesh_scheduler_act_status_cb_t scheduler_act_status
For ESP_BLE_MESH_MODEL_OP_SCHEDULER_ACT_STATUS
union esp_ble_mesh_time_scene_server_state_change_t
#include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model state change value union.
Public Members
esp_ble_mesh_state_change_time_set_t time_set
The recv_op in ctx can be used to decide which state is changed. Time Set
esp_ble_mesh_state_change_time_status_t time_status
Time Status
esp_ble_mesh_state_change_time_zone_set_t time_zone_set
Time Zone Set
esp_ble_mesh_state_change_tai_utc_delta_set_t tai_utc_delta_set
TAI UTC Delta Set
esp_ble_mesh_state_change_time_role_set_t time_role_set
Time Role Set
esp_ble_mesh_state_change_scene_store_t scene_store
Scene Store
esp_ble_mesh_state_change_scene_recall_t scene_recall
Scene Recall
esp_ble_mesh_state_change_scene_delete_t scene_delete
Scene Delete
esp_ble_mesh_state_change_scheduler_act_set_t scheduler_act_set
Scheduler Action Set
union esp_ble_mesh_time_scene_server_recv_get_msg_t
#include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model received get message union.
Public Members
esp_ble_mesh_server_recv_scheduler_act_get_t scheduler_act
Scheduler Action Get
union esp_ble_mesh_time_scene_server_recv_set_msg_t
#include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model received set message union.
Public Members
esp_ble_mesh_server_recv_time_set_t time
Time Set
esp_ble_mesh_server_recv_time_zone_set_t time_zone
Time Zone Set
esp_ble_mesh_server_recv_tai_utc_delta_set_t tai_utc_delta
TAI-UTC Delta Set
esp_ble_mesh_server_recv_time_role_set_t time_role
Time Role Set
esp_ble_mesh_server_recv_scene_store_t scene_store
Scene Store/Scene Store Unack
esp_ble_mesh_server_recv_scene_recall_t scene_recall
Scene Recall/Scene Recall Unack
esp_ble_mesh_server_recv_scene_delete_t scene_delete
Scene Delete/Scene Delete Unack
esp_ble_mesh_server_recv_scheduler_act_set_t scheduler_act
Scheduler Action Set/Scheduler Action Set Unack
union esp_ble_mesh_time_scene_server_recv_status_msg_t
#include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model received status message union.
Public Members
esp_ble_mesh_server_recv_time_status_t time_status
Time Status
union esp_ble_mesh_time_scene_server_cb_value_t
#include <esp_ble_mesh_time_scene_model_api.h> Time Scene Server Model callback value union.
Public Members
esp_ble_mesh_time_scene_server_state_change_t state_change
ESP_BLE_MESH_TIME_SCENE_SERVER_STATE_CHANGE_EVT
esp_ble_mesh_time_scene_server_recv_get_msg_t get
ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_GET_MSG_EVT
esp_ble_mesh_time_scene_server_recv_set_msg_t set
ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_SET_MSG_EVT
esp_ble_mesh_time_scene_server_recv_status_msg_t status
ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_STATUS_MSG_EVT
Structures
struct esp_ble_mesh_time_set_t
Bluetooth Mesh Time Scene Client Model Get and Set parameters structure.
Parameters of Time Set
Public Members
uint8_t tai_seconds[5]
The current TAI time in seconds
uint8_t sub_second
The sub-second time in units of 1/256 second
uint8_t uncertainty
The estimated uncertainty in 10-millisecond steps
uint16_t time_authority
0 = No Time Authority, 1 = Time Authority
uint16_t tai_utc_delta
Current difference between TAI and UTC in seconds
uint8_t time_zone_offset
The local time zone offset in 15-minute increments
struct esp_ble_mesh_time_zone_set_t
Parameters of Time Zone Set
Public Members
uint8_t time_zone_offset_new
Upcoming local time zone offset
uint8_t tai_zone_change[5]
TAI Seconds time of the upcoming Time Zone Offset change
struct esp_ble_mesh_tai_utc_delta_set_t
Parameters of TAI-UTC Delta Set
Public Members
uint16_t tai_utc_delta_new
Upcoming difference between TAI and UTC in seconds
uint16_t padding
Always 0b0. Other values are Prohibited.
uint8_t tai_delta_change[5]
TAI Seconds time of the upcoming TAI-UTC Delta change
struct esp_ble_mesh_time_role_set_t
Parameter of Time Role Set
Public Members
uint8_t time_role
The Time Role for the element
struct esp_ble_mesh_scene_store_t
Parameter of Scene Store
Public Members
uint16_t scene_number
The number of scenes to be stored
struct esp_ble_mesh_scene_recall_t
Parameters of Scene Recall
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t scene_number
The number of scenes to be recalled
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_scene_delete_t
Parameter of Scene Delete
Public Members
uint16_t scene_number
The number of scenes to be deleted
struct esp_ble_mesh_scheduler_act_get_t
Parameter of Scheduler Action Get
Public Members
uint8_t index
Index of the Schedule Register entry to get
struct esp_ble_mesh_scheduler_act_set_t
Parameters of Scheduler Action Set
Public Members
uint64_t index
Index of the Schedule Register entry to set
uint64_t year
Scheduled year for the action
uint64_t month
Scheduled month for the action
uint64_t day
Scheduled day of the month for the action
uint64_t hour
Scheduled hour for the action
uint64_t minute
Scheduled minute for the action
uint64_t second
Scheduled second for the action
uint64_t day_of_week
Schedule days of the week for the action
uint64_t action
Action to be performed at the scheduled time
uint64_t trans_time
Transition time for this action
uint16_t scene_number
Transition time for this action
struct esp_ble_mesh_time_status_cb_t
Bluetooth Mesh Time Scene Client Model Get and Set callback parameters structure.
Parameters of Time Status
Public Members
uint8_t tai_seconds[5]
The current TAI time in seconds
uint8_t sub_second
The sub-second time in units of 1/256 second
uint8_t uncertainty
The estimated uncertainty in 10-millisecond steps
uint16_t time_authority
0 = No Time Authority, 1 = Time Authority
uint16_t tai_utc_delta
Current difference between TAI and UTC in seconds
uint8_t time_zone_offset
The local time zone offset in 15-minute increments
struct esp_ble_mesh_time_zone_status_cb_t
Parameters of Time Zone Status
Public Members
uint8_t time_zone_offset_curr
Current local time zone offset
uint8_t time_zone_offset_new
Upcoming local time zone offset
uint8_t tai_zone_change[5]
TAI Seconds time of the upcoming Time Zone Offset change
struct esp_ble_mesh_tai_utc_delta_status_cb_t
Parameters of TAI-UTC Delta Status
Public Members
uint16_t tai_utc_delta_curr
Current difference between TAI and UTC in seconds
uint16_t padding_1
Always 0b0. Other values are Prohibited.
uint16_t tai_utc_delta_new
Upcoming difference between TAI and UTC in seconds
uint16_t padding_2
Always 0b0. Other values are Prohibited.
uint8_t tai_delta_change[5]
TAI Seconds time of the upcoming TAI-UTC Delta change
struct esp_ble_mesh_time_role_status_cb_t
Parameter of Time Role Status
Public Members
uint8_t time_role
The Time Role for the element
struct esp_ble_mesh_scene_status_cb_t
Parameters of Scene Status
Public Members
bool op_en
Indicate if optional parameters are included
uint8_t status_code
Status code of the last operation
uint16_t current_scene
Scene Number of the current scene
uint16_t target_scene
Scene Number of the target scene (optional)
uint8_t remain_time
Time to complete state transition (C.1)
struct esp_ble_mesh_scene_register_status_cb_t
Parameters of Scene Register Status
Public Members
uint8_t status_code
Status code for the previous operation
uint16_t current_scene
Scene Number of the current scene
struct esp_ble_mesh_scheduler_status_cb_t
Parameter of Scheduler Status
Public Members
uint16_t schedules
Bit field indicating defined Actions in the Schedule Register
struct esp_ble_mesh_scheduler_act_status_cb_t
Parameters of Scheduler Action Status
Public Members
uint64_t index
Enumerates (selects) a Schedule Register entry
uint64_t year
Scheduled year for the action
uint64_t month
Scheduled month for the action
uint64_t day
Scheduled day of the month for the action
uint64_t hour
Scheduled hour for the action
uint64_t minute
Scheduled minute for the action
uint64_t second
Scheduled second for the action
uint64_t day_of_week
Schedule days of the week for the action
uint64_t action
Action to be performed at the scheduled time
uint64_t trans_time
Transition time for this action
uint16_t scene_number
Transition time for this action
struct esp_ble_mesh_time_scene_client_cb_param_t
Time Scene Client Model callback parameters
Public Members
int error_code
Appropriate error code
esp_ble_mesh_client_common_param_t *params
The client common parameters.
esp_ble_mesh_time_scene_client_status_cb_t status_cb
The scene status message callback values
struct esp_ble_mesh_time_state_t
Parameters of Time state
Public Members
uint8_t tai_seconds[5]
The value of the TAI Seconds state
uint8_t subsecond
The value of the Subsecond field
uint8_t uncertainty
The value of the Uncertainty field
uint8_t time_zone_offset_curr
The value of the Time Zone Offset Current field
uint8_t time_zone_offset_new
The value of the Time Zone Offset New state
uint8_t tai_zone_change[5]
The value of the TAI of Zone Chaneg field
uint16_t time_authority
The value of the Time Authority bit
uint16_t tai_utc_delta_curr
The value of the TAI-UTC Delta Current state
uint16_t tai_utc_delta_new
The value of the TAI-UTC Delta New state
uint8_t tai_delta_change[5]
The value of the TAI of Delta Change field
uint8_t time_role
The value of the Time Role state
struct esp_ble_mesh_time_srv_t
User data of Time Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Time Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_time_state_t *state
Parameters of the Time state
struct esp_ble_mesh_time_setup_srv_t
User data of Time Setup Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Time Setup Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_time_state_t *state
Parameters of the Time state
struct esp_ble_mesh_scene_register_t
Public Members
uint16_t scene_number
The value of the Scene Number
uint8_t scene_type
The value of the Scene Type
struct esp_ble_mesh_scenes_state_t
Parameters of Scenes state.
Scenes serve as memory banks for storage of states (e.g., a power level or a light level/color). Values of states
of an element can be stored as a scene and can be recalled later from the scene memory.
A scene is represented by a Scene Number, which is a 16-bit non-zero, mesh-wide value. (There can be a
maximum of 65535 scenes in a mesh network.) The meaning of a scene, as well as the state storage container
associated with it, are determined by a model.
The Scenes state change may start numerous parallel model transitions. In that case, each individual model
handles the transition internally.
The scene transition is defined as a group of individual model transitions started by a Scene Recall operation.
The scene transition is in progress when at least one transition from the group of individual model transitions
is in progress.
Public Members
esp_ble_mesh_scene_register_t *scenes
Parameters of the Scenes state
uint16_t current_scene
The Current Scene state is a 16-bit value that contains either the Scene Number of the currently active
scene or a value of 0x0000 when no scene is active.
When a Scene Store operation or a Scene Recall operation completes with success, the Current Scene
state value shall be to the Scene Number used during that operation.
When the Current Scene Number is deleted from a Scene Register state as a result of Scene Delete
operation, the Current Scene state shall be set to 0x0000.
When any of the element’s state that is marked as “Stored with Scene”has changed not as a result of
a Scene Recall operation, the value of the Current Scene state shall be set to 0x0000.
When a scene transition is in progress, the value of the Current Scene state shall be set to 0x0000. The
value of the Current Scene state
uint16_t target_scene
The Target Scene state is a 16-bit value that contains the target Scene Number when a scene transition is
in progress.
When the scene transition is in progress and the target Scene Number is deleted from a Scene Register
state as a result of Scene Delete operation, the Target Scene state shall be set to 0x0000.
When the scene transition is in progress and a new Scene Number is stored in the Scene Register as a
result of Scene Store operation, the Target Scene state shall be set to the new Scene Number.
When the scene transition is not in progress, the value of the Target Scene state shall be set to 0x0000.
The value of the Target Scene state
uint8_t status_code
The status code of the last scene operation
bool in_progress
Indicate if the scene transition is in progress
struct esp_ble_mesh_scene_srv_t
User data of Scene Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Scene Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_scenes_state_t *state
Parameters of the Scenes state
esp_ble_mesh_last_msg_info_t last
Parameters of the last received set message
esp_ble_mesh_state_transition_t transition
Parameters of state transition
struct esp_ble_mesh_scene_setup_srv_t
User data of Scene Setup Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Scene Setup Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_scenes_state_t *state
Parameters of the Scenes state
struct esp_ble_mesh_schedule_register_t
Parameters of Scheduler Register state
Public Members
bool in_use
Indicate if the registered schedule is in use
uint64_t year
The value of Scheduled year for the action
uint64_t month
The value of Scheduled month for the action
uint64_t day
The value of Scheduled day of the month for the action
uint64_t hour
The value of Scheduled hour for the action
uint64_t minute
The value of Scheduled minute for the action
uint64_t second
The value of Scheduled second for the action
uint64_t day_of_week
The value of Schedule days of the week for the action
uint64_t action
The value of Action to be performed at the scheduled time
uint64_t trans_time
The value of Transition time for this action
uint16_t scene_number
The value of Scene Number to be used for some actions
struct esp_ble_mesh_scheduler_state_t
Parameters of Scheduler state
Public Members
esp_ble_mesh_schedule_register_t *schedules
Up to 16 scheduled entries
struct esp_ble_mesh_scheduler_srv_t
User data of Scheduler Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Scheduler Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_scheduler_state_t *state
Parameters of the Scheduler state
struct esp_ble_mesh_scheduler_setup_srv_t
User data of Scheduler Setup Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Scheduler Setup Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_scheduler_state_t *state
Parameters of the Scheduler state
struct esp_ble_mesh_state_change_time_set_t
Parameters of Time Set state change event
Public Members
uint8_t tai_seconds[5]
The current TAI time in seconds
uint8_t subsecond
The sub-second time in units of 1/256 second
uint8_t uncertainty
The estimated uncertainty in 10-millisecond steps
uint16_t time_authority
0 = No Time Authority, 1 = Time Authority
uint16_t tai_utc_delta_curr
Current difference between TAI and UTC in seconds
uint8_t time_zone_offset_curr
The local time zone offset in 15-minute increments
struct esp_ble_mesh_state_change_time_status_t
Parameters of Time Status state change event
Public Members
uint8_t tai_seconds[5]
The current TAI time in seconds
uint8_t subsecond
The sub-second time in units of 1/256 second
uint8_t uncertainty
The estimated uncertainty in 10-millisecond steps
uint16_t time_authority
0 = No Time Authority, 1 = Time Authority
uint16_t tai_utc_delta_curr
Current difference between TAI and UTC in seconds
uint8_t time_zone_offset_curr
The local time zone offset in 15-minute increments
struct esp_ble_mesh_state_change_time_zone_set_t
Parameters of Time Zone Set state change event
Public Members
uint8_t time_zone_offset_new
Upcoming local time zone offset
uint8_t tai_zone_change[5]
TAI Seconds time of the upcoming Time Zone Offset change
struct esp_ble_mesh_state_change_tai_utc_delta_set_t
Parameters of TAI UTC Delta Set state change event
Public Members
uint16_t tai_utc_delta_new
Upcoming difference between TAI and UTC in seconds
uint8_t tai_delta_change[5]
TAI Seconds time of the upcoming TAI-UTC Delta change
struct esp_ble_mesh_state_change_time_role_set_t
Parameter of Time Role Set state change event
Public Members
uint8_t time_role
The Time Role for the element
struct esp_ble_mesh_state_change_scene_store_t
Parameter of Scene Store state change event
Public Members
uint16_t scene_number
The number of scenes to be stored
struct esp_ble_mesh_state_change_scene_recall_t
Parameter of Scene Recall state change event
Public Members
uint16_t scene_number
The number of scenes to be recalled
struct esp_ble_mesh_state_change_scene_delete_t
Parameter of Scene Delete state change event
Public Members
uint16_t scene_number
The number of scenes to be deleted
struct esp_ble_mesh_state_change_scheduler_act_set_t
Parameter of Scheduler Action Set state change event
Public Members
uint64_t index
Index of the Schedule Register entry to set
uint64_t year
Scheduled year for the action
uint64_t month
Scheduled month for the action
uint64_t day
Scheduled day of the month for the action
uint64_t hour
Scheduled hour for the action
uint64_t minute
Scheduled minute for the action
uint64_t second
Scheduled second for the action
uint64_t day_of_week
Schedule days of the week for the action
uint64_t action
Action to be performed at the scheduled time
uint64_t trans_time
Transition time for this action
uint16_t scene_number
Scene number to be used for some actions
struct esp_ble_mesh_server_recv_scheduler_act_get_t
Context of the received Scheduler Action Get message
Public Members
uint8_t index
Index of the Schedule Register entry to get
struct esp_ble_mesh_server_recv_time_set_t
Context of the received Time Set message
Public Members
uint8_t tai_seconds[5]
The current TAI time in seconds
uint8_t subsecond
The sub-second time in units of 1/256 second
uint8_t uncertainty
The estimated uncertainty in 10-millisecond steps
uint16_t time_authority
0 = No Time Authority, 1 = Time Authority
uint16_t tai_utc_delta
Current difference between TAI and UTC in seconds
uint8_t time_zone_offset
The local time zone offset in 15-minute increments
struct esp_ble_mesh_server_recv_time_zone_set_t
Context of the received Time Zone Set message
Public Members
uint8_t time_zone_offset_new
Upcoming local time zone offset
uint8_t tai_zone_change[5]
TAI Seconds time of the upcoming Time Zone Offset change
struct esp_ble_mesh_server_recv_tai_utc_delta_set_t
Context of the received TAI UTC Delta Set message
Public Members
uint16_t tai_utc_delta_new
Upcoming difference between TAI and UTC in seconds
uint16_t padding
Always 0b0. Other values are Prohibited.
uint8_t tai_delta_change[5]
TAI Seconds time of the upcoming TAI-UTC Delta change
struct esp_ble_mesh_server_recv_time_role_set_t
Context of the received Time Role Set message
Public Members
uint8_t time_role
The Time Role for the element
struct esp_ble_mesh_server_recv_scene_store_t
Context of the received Scene Store message
Public Members
uint16_t scene_number
The number of scenes to be stored
struct esp_ble_mesh_server_recv_scene_recall_t
Context of the received Scene Recall message
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t scene_number
The number of scenes to be recalled
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_scene_delete_t
Context of the received Scene Delete message
Public Members
uint16_t scene_number
The number of scenes to be deleted
struct esp_ble_mesh_server_recv_scheduler_act_set_t
Context of the received Scheduler Action Set message
Public Members
uint64_t index
Index of the Schedule Register entry to set
uint64_t year
Scheduled year for the action
uint64_t month
Scheduled month for the action
uint64_t day
Scheduled day of the month for the action
uint64_t hour
Scheduled hour for the action
uint64_t minute
Scheduled minute for the action
uint64_t second
Scheduled second for the action
uint64_t day_of_week
Schedule days of the week for the action
uint64_t action
Action to be performed at the scheduled time
uint64_t trans_time
Transition time for this action
uint16_t scene_number
Scene number to be used for some actions
struct esp_ble_mesh_server_recv_time_status_t
Context of the received Time Status message
Public Members
uint8_t tai_seconds[5]
The current TAI time in seconds
uint8_t subsecond
The sub-second time in units of 1/256 second
uint8_t uncertainty
The estimated uncertainty in 10-millisecond steps
uint16_t time_authority
0 = No Time Authority, 1 = Time Authority
uint16_t tai_utc_delta
Current difference between TAI and UTC in seconds
uint8_t time_zone_offset
The local time zone offset in 15-minute increments
struct esp_ble_mesh_time_scene_server_cb_param_t
Time Scene Server Model callback parameters
Public Members
esp_ble_mesh_model_t *model
Pointer to Time and Scenes Server Models
esp_ble_mesh_msg_ctx_t ctx
Context of the received messages
esp_ble_mesh_time_scene_server_cb_value_t value
Value of the received Time and Scenes Messages
Macros
ESP_BLE_MESH_MODEL_TIME_CLI(cli_pub, cli_data)
Define a new Time Client Model.
Note: This API needs to be called for each element on which the application needs to have a Time Client
Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Time Client Model instance.
ESP_BLE_MESH_MODEL_SCENE_CLI(cli_pub, cli_data)
Define a new Scene Client Model.
Note: This API needs to be called for each element on which the application needs to have a Scene Client
Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Scene Client Model instance.
ESP_BLE_MESH_MODEL_SCHEDULER_CLI(cli_pub, cli_data)
Define a new Scheduler Client Model.
Note: This API needs to be called for each element on which the application needs to have a Scheduler Client
Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Scheduler Client Model instance.
ESP_BLE_MESH_MODEL_TIME_SRV(srv_pub, srv_data)
Time Scene Server Models related context.
Define a new Time Server Model.
Note: 1. The Time Server model is a root model. When this model is present on an Element, the corresponding
Time Setup Server model shall also be present.
a. This model shall support model publication and model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_time_srv_t.
Returns New Time Server Model instance.
ESP_BLE_MESH_MODEL_TIME_SETUP_SRV(srv_data)
Define a new Time Setup Server Model.
Note: 1. The Time Setup Server model extends the Time Server model. Time is sensitive information that is
propagated across a mesh network.
a. Only an authorized Time Client should be allowed to change the Time and Time Role states. A dedicated
application key Bluetooth SIG Proprietary should be used on the Time Setup Server to restrict access to
the server to only authorized Time Clients.
b. This model does not support subscribing nor publishing.
Parameters
• srv_data –Pointer to the unique struct esp_ble_mesh_time_setup_srv_t.
Returns New Time Setup Server Model instance.
ESP_BLE_MESH_MODEL_SCENE_SRV(srv_pub, srv_data)
Define a new Scene Server Model.
Note: 1. The Scene Server model is a root model. When this model is present on an Element, the corre-
sponding Scene Setup Server model shall also be present.
a. This model shall support model publication and model subscription.
b. The model may be present only on the Primary element of a node.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_scene_srv_t.
ESP_BLE_MESH_MODEL_SCENE_SETUP_SRV(srv_pub, srv_data)
Define a new Scene Setup Server Model.
Note: 1. The Scene Setup Server model extends the Scene Server model and the Generic Default Transition
Time Server model.
a. This model shall support model subscription.
b. The model may be present only on the Primary element of a node.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_scene_setup_srv_t.
Returns New Scene Setup Server Model instance.
ESP_BLE_MESH_MODEL_SCHEDULER_SRV(srv_pub, srv_data)
Define a new Scheduler Server Model.
Note: 1. The Scheduler Server model extends the Scene Server model. When this model is present on an
Element, the corresponding Scheduler Setup Server model shall also be present.
a. This model shall support model publication and model subscription.
b. The model may be present only on the Primary element of a node.
c. The model requires the Time Server model shall be present on the element.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_scheduler_srv_t.
Returns New Scheduler Server Model instance.
ESP_BLE_MESH_MODEL_SCHEDULER_SETUP_SRV(srv_pub, srv_data)
Define a new Scheduler Setup Server Model.
Note: 1. The Scheduler Setup Server model extends the Scheduler Server and the Scene Setup Server models.
a. This model shall support model subscription.
b. The model may be present only on the Primary element of a node.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_scheduler_setup_srv_t.
Returns New Scheduler Setup Server Model instance.
ESP_BLE_MESH_UNKNOWN_TAI_SECONDS
Unknown TAI Seconds
ESP_BLE_MESH_UNKNOWN_TAI_ZONE_CHANGE
Unknown TAI of Zone Change
ESP_BLE_MESH_UNKNOWN_TAI_DELTA_CHANGE
Unknown TAI of Delta Change
ESP_BLE_MESH_TAI_UTC_DELTA_MAX_VALUE
Maximum TAI-UTC Delta value
ESP_BLE_MESH_TAI_SECONDS_LEN
Length of TAI Seconds
ESP_BLE_MESH_TAI_OF_ZONE_CHANGE_LEN
Length of TAI of Zone Change
ESP_BLE_MESH_TAI_OF_DELTA_CHANGE_LEN
Length of TAI of Delta Change
ESP_BLE_MESH_INVALID_SCENE_NUMBER
Invalid Scene Number
ESP_BLE_MESH_SCENE_NUMBER_LEN
Length of the Scene Number
ESP_BLE_MESH_SCHEDULE_YEAR_ANY_YEAR
Any year of the Scheduled year
ESP_BLE_MESH_SCHEDULE_DAY_ANY_DAY
Any day of the Scheduled day
ESP_BLE_MESH_SCHEDULE_HOUR_ANY_HOUR
Any hour of the Scheduled hour
ESP_BLE_MESH_SCHEDULE_HOUR_ONCE_A_DAY
Any hour of the Scheduled Day
ESP_BLE_MESH_SCHEDULE_SEC_ANY_OF_HOUR
Any minute of the Scheduled hour
ESP_BLE_MESH_SCHEDULE_SEC_EVERY_15_MIN
Every 15 minutes of the Scheduled hour
ESP_BLE_MESH_SCHEDULE_SEC_EVERY_20_MIN
Every 20 minutes of the Scheduled hour
ESP_BLE_MESH_SCHEDULE_SEC_ONCE_AN_HOUR
Once of the Scheduled hour
ESP_BLE_MESH_SCHEDULE_SEC_ANY_OF_MIN
Any second of the Scheduled minute
ESP_BLE_MESH_SCHEDULE_SEC_EVERY_15_SEC
Every 15 seconds of the Scheduled minute
ESP_BLE_MESH_SCHEDULE_SEC_EVERY_20_SEC
Every 20 seconds of the Scheduled minute
ESP_BLE_MESH_SCHEDULE_SEC_ONCE_AN_MIN
Once of the Scheduled minute
ESP_BLE_MESH_SCHEDULE_ACT_TURN_OFF
Scheduled Action - Turn Off
ESP_BLE_MESH_SCHEDULE_ACT_TURN_ON
Scheduled Action - Turn On
ESP_BLE_MESH_SCHEDULE_ACT_SCENE_RECALL
Scheduled Action - Scene Recall
ESP_BLE_MESH_SCHEDULE_ACT_NO_ACTION
Scheduled Action - No Action
ESP_BLE_MESH_SCHEDULE_SCENE_NO_SCENE
Scheduled Scene - No Scene
ESP_BLE_MESH_SCHEDULE_ENTRY_MAX_INDEX
Maximum number of Scheduled entries
ESP_BLE_MESH_TIME_NONE
Time Role - None
ESP_BLE_MESH_TIME_AUTHORITY
Time Role - Mesh Time Authority
ESP_BLE_MESH_TIME_RELAY
Time Role - Mesh Time Relay
ESP_BLE_MESH_TIME_CLINET
Time Role - Mesh Time Client
ESP_BLE_MESH_SCENE_SUCCESS
Scene operation - Success
ESP_BLE_MESH_SCENE_REG_FULL
Scene operation - Scene Register Full
ESP_BLE_MESH_SCENE_NOT_FOUND
Scene operation - Scene Not Found
Type Definitions
Enumerations
enum esp_ble_mesh_time_scene_client_cb_event_t
This enum value is the event of Time Scene Client Model
Values:
enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_GET_STATE_EVT
enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_SET_STATE_EVT
enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_PUBLISH_EVT
enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_TIMEOUT_EVT
enumerator ESP_BLE_MESH_TIME_SCENE_CLIENT_EVT_MAX
enum esp_ble_mesh_time_scene_server_cb_event_t
This enum value is the event of Time Scene Server Model
Values:
enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_STATE_CHANGE_EVT
enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_GET_MSG_EVT
When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to
the application layer when Time Scene Get messages are received.
enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_SET_MSG_EVT
When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to
the application layer when Time Scene Set/Set Unack messages are received.
enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_RECV_STATUS_MSG_EVT
When status_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback
to the application layer when TIme Status message is received.
enumerator ESP_BLE_MESH_TIME_SCENE_SERVER_EVT_MAX
Header File
• components/bt/esp_ble_mesh/api/models/include/esp_ble_mesh_lighting_model_api.h
Functions
esp_err_t esp_ble_mesh_register_light_client_callback(esp_ble_mesh_light_client_cb_t
callback)
Register BLE Mesh Light Client Model callback.
Parameters callback –[in] pointer to the callback function.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_light_client_get_state(esp_ble_mesh_client_common_param_t *params,
esp_ble_mesh_light_client_get_state_t *get_state)
Get the value of Light Server Model states using the Light Client Model get messages.
Note: If you want to know the opcodes and corresponding meanings accepted by this API, please refer to
esp_ble_mesh_light_message_opcode_t in esp_ble_mesh_defs.h
Parameters
• params –[in] Pointer to BLE Mesh common client parameters.
• get_state –[in] Pointer of light get message value. Shall not be set to NULL.
Returns ESP_OK on success or error code otherwise.
Note: If you want to know the opcodes and corresponding meanings accepted by this API, please refer to
esp_ble_mesh_light_message_opcode_t in esp_ble_mesh_defs.h
Parameters
• params –[in] Pointer to BLE Mesh common client parameters.
• set_state –[in] Pointer of light set message value. Shall not be set to NULL.
Returns ESP_OK on success or error code otherwise.
esp_err_t esp_ble_mesh_register_lighting_server_callback(esp_ble_mesh_lighting_server_cb_t
callback)
Register BLE Mesh Lighting Server Model callback.
Parameters callback –[in] Pointer to the callback function.
Returns ESP_OK on success or error code otherwise.
Unions
union esp_ble_mesh_light_client_get_state_t
#include <esp_ble_mesh_lighting_model_api.h> Lighting Client Model get message union.
Public Members
esp_ble_mesh_light_lc_property_get_t lc_property_get
For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_GET
union esp_ble_mesh_light_client_set_state_t
#include <esp_ble_mesh_lighting_model_api.h> Lighting Client Model set message union.
Public Members
esp_ble_mesh_light_lightness_set_t lightness_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_SET_UNACK
esp_ble_mesh_light_lightness_linear_set_t lightness_linear_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_SET_UNACK
esp_ble_mesh_light_lightness_default_set_t lightness_default_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_SET_UNACK
esp_ble_mesh_light_lightness_range_set_t lightness_range_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_SET_UNACK
esp_ble_mesh_light_ctl_set_t ctl_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_SET_UNA
esp_ble_mesh_light_ctl_temperature_set_t ctl_temperature_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_SET_UNACK
esp_ble_mesh_light_ctl_temperature_range_set_t ctl_temperature_range_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_SET_UNACK
esp_ble_mesh_light_ctl_default_set_t ctl_default_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_SET_UNACK
esp_ble_mesh_light_hsl_set_t hsl_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SET_UNAC
esp_ble_mesh_light_hsl_hue_set_t hsl_hue_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE
esp_ble_mesh_light_hsl_saturation_set_t hsl_saturation_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_SET_UNACK
esp_ble_mesh_light_hsl_default_set_t hsl_default_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_SET_UNACK
esp_ble_mesh_light_hsl_range_set_t hsl_range_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_SET_UNACK
esp_ble_mesh_light_xyl_set_t xyl_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_SET_UNA
esp_ble_mesh_light_xyl_default_set_t xyl_default_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_SET_UNACK
esp_ble_mesh_light_xyl_range_set_t xyl_range_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_SET_UNACK
esp_ble_mesh_light_lc_mode_set_t lc_mode_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_SET_UNACK
esp_ble_mesh_light_lc_om_set_t lc_om_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET & ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_SET
esp_ble_mesh_light_lc_light_onoff_set_t lc_light_onoff_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_SET_UNACK
esp_ble_mesh_light_lc_property_set_t lc_property_set
For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET &
ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_SET_UNACK
union esp_ble_mesh_light_client_status_cb_t
#include <esp_ble_mesh_lighting_model_api.h> Lighting Client Model received message union.
Public Members
esp_ble_mesh_light_lightness_status_cb_t lightness_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_STATUS
esp_ble_mesh_light_lightness_linear_status_cb_t lightness_linear_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_STATUS
esp_ble_mesh_light_lightness_last_status_cb_t lightness_last_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LAST_STATUS
esp_ble_mesh_light_lightness_default_status_cb_t lightness_default_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_DEFAULT_STATUS
esp_ble_mesh_light_lightness_range_status_cb_t lightness_range_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_RANGE_STATUS
esp_ble_mesh_light_ctl_status_cb_t ctl_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_STATUS
esp_ble_mesh_light_ctl_temperature_status_cb_t ctl_temperature_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_STATUS
esp_ble_mesh_light_ctl_temperature_range_status_cb_t ctl_temperature_range_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_RANGE_STATUS
esp_ble_mesh_light_ctl_default_status_cb_t ctl_default_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_CTL_DEFAULT_STATUS
esp_ble_mesh_light_hsl_status_cb_t hsl_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_STATUS
esp_ble_mesh_light_hsl_target_status_cb_t hsl_target_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_TARGET_STATUS
esp_ble_mesh_light_hsl_hue_status_cb_t hsl_hue_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_STATUS
esp_ble_mesh_light_hsl_saturation_status_cb_t hsl_saturation_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_STATUS
esp_ble_mesh_light_hsl_default_status_cb_t hsl_default_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_DEFAULT_STATUS
esp_ble_mesh_light_hsl_range_status_cb_t hsl_range_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_HSL_RANGE_STATUS
esp_ble_mesh_light_xyl_status_cb_t xyl_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_STATUS
esp_ble_mesh_light_xyl_target_status_cb_t xyl_target_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_TARGET_STATUS
esp_ble_mesh_light_xyl_default_status_cb_t xyl_default_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_DEFAULT_STATUS
esp_ble_mesh_light_xyl_range_status_cb_t xyl_range_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_XYL_RANGE_STATUS
esp_ble_mesh_light_lc_mode_status_cb_t lc_mode_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_MODE_STATUS
esp_ble_mesh_light_lc_om_status_cb_t lc_om_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_OM_STATUS
esp_ble_mesh_light_lc_light_onoff_status_cb_t lc_light_onoff_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_STATUS
esp_ble_mesh_light_lc_property_status_cb_t lc_property_status
For ESP_BLE_MESH_MODEL_OP_LIGHT_LC_PROPERTY_STATUS
union esp_ble_mesh_lighting_server_state_change_t
#include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model state change value union.
Public Members
esp_ble_mesh_state_change_light_lightness_set_t lightness_set
The recv_op in ctx can be used to decide which state is changed. Light Lightness Set
esp_ble_mesh_state_change_light_lightness_linear_set_t lightness_linear_set
Light Lightness Linear Set
esp_ble_mesh_state_change_light_lightness_default_set_t lightness_default_set
Light Lightness Default Set
esp_ble_mesh_state_change_light_lightness_range_set_t lightness_range_set
Light Lightness Range Set
esp_ble_mesh_state_change_light_ctl_set_t ctl_set
Light CTL Set
esp_ble_mesh_state_change_light_ctl_temperature_set_t ctl_temp_set
Light CTL Temperature Set
esp_ble_mesh_state_change_light_ctl_temperature_range_set_t ctl_temp_range_set
Light CTL Temperature Range Set
esp_ble_mesh_state_change_light_ctl_default_set_t ctl_default_set
Light CTL Default Set
esp_ble_mesh_state_change_light_hsl_set_t hsl_set
Light HSL Set
esp_ble_mesh_state_change_light_hsl_hue_set_t hsl_hue_set
Light HSL Hue Set
esp_ble_mesh_state_change_light_hsl_saturation_set_t hsl_saturation_set
Light HSL Saturation Set
esp_ble_mesh_state_change_light_hsl_default_set_t hsl_default_set
Light HSL Default Set
esp_ble_mesh_state_change_light_hsl_range_set_t hsl_range_set
Light HSL Range Set
esp_ble_mesh_state_change_light_xyl_set_t xyl_set
Light xyL Set
esp_ble_mesh_state_change_light_xyl_default_set_t xyl_default_set
Light xyL Default Set
esp_ble_mesh_state_change_light_xyl_range_set_t xyl_range_set
Light xyL Range Set
esp_ble_mesh_state_change_light_lc_mode_set_t lc_mode_set
Light LC Mode Set
esp_ble_mesh_state_change_light_lc_om_set_t lc_om_set
Light LC Occupancy Mode Set
esp_ble_mesh_state_change_light_lc_light_onoff_set_t lc_light_onoff_set
Light LC Light OnOff Set
esp_ble_mesh_state_change_light_lc_property_set_t lc_property_set
Light LC Property Set
esp_ble_mesh_state_change_sensor_status_t sensor_status
Sensor Status
union esp_ble_mesh_lighting_server_recv_get_msg_t
#include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model received get message union.
Public Members
esp_ble_mesh_server_recv_light_lc_property_get_t lc_property
Light LC Property Get
union esp_ble_mesh_lighting_server_recv_set_msg_t
#include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model received set message union.
Public Members
esp_ble_mesh_server_recv_light_lightness_set_t lightness
Light Lightness Set/Light Lightness Set Unack
esp_ble_mesh_server_recv_light_lightness_linear_set_t lightness_linear
Light Lightness Linear Set/Light Lightness Linear Set Unack
esp_ble_mesh_server_recv_light_lightness_default_set_t lightness_default
Light Lightness Default Set/Light Lightness Default Set Unack
esp_ble_mesh_server_recv_light_lightness_range_set_t lightness_range
Light Lightness Range Set/Light Lightness Range Set Unack
esp_ble_mesh_server_recv_light_ctl_set_t ctl
Light CTL Set/Light CTL Set Unack
esp_ble_mesh_server_recv_light_ctl_temperature_set_t ctl_temp
Light CTL Temperature Set/Light CTL Temperature Set Unack
esp_ble_mesh_server_recv_light_ctl_temperature_range_set_t ctl_temp_range
Light CTL Temperature Range Set/Light CTL Temperature Range Set Unack
esp_ble_mesh_server_recv_light_ctl_default_set_t ctl_default
Light CTL Default Set/Light CTL Default Set Unack
esp_ble_mesh_server_recv_light_hsl_set_t hsl
Light HSL Set/Light HSL Set Unack
esp_ble_mesh_server_recv_light_hsl_hue_set_t hsl_hue
Light HSL Hue Set/Light HSL Hue Set Unack
esp_ble_mesh_server_recv_light_hsl_saturation_set_t hsl_saturation
Light HSL Saturation Set/Light HSL Saturation Set Unack
esp_ble_mesh_server_recv_light_hsl_default_set_t hsl_default
Light HSL Default Set/Light HSL Default Set Unack
esp_ble_mesh_server_recv_light_hsl_range_set_t hsl_range
Light HSL Range Set/Light HSL Range Set Unack
esp_ble_mesh_server_recv_light_xyl_set_t xyl
Light xyL Set/Light xyL Set Unack
esp_ble_mesh_server_recv_light_xyl_default_set_t xyl_default
Light xyL Default Set/Light xyL Default Set Unack
esp_ble_mesh_server_recv_light_xyl_range_set_t xyl_range
Light xyL Range Set/Light xyL Range Set Unack
esp_ble_mesh_server_recv_light_lc_mode_set_t lc_mode
Light LC Mode Set/Light LC Mode Set Unack
esp_ble_mesh_server_recv_light_lc_om_set_t lc_om
Light LC OM Set/Light LC OM Set Unack
esp_ble_mesh_server_recv_light_lc_light_onoff_set_t lc_light_onoff
Light LC Light OnOff Set/Light LC Light OnOff Set Unack
esp_ble_mesh_server_recv_light_lc_property_set_t lc_property
Light LC Property Set/Light LC Property Set Unack
union esp_ble_mesh_lighting_server_recv_status_msg_t
#include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model received status message union.
Public Members
esp_ble_mesh_server_recv_sensor_status_t sensor_status
Sensor Status
union esp_ble_mesh_lighting_server_cb_value_t
#include <esp_ble_mesh_lighting_model_api.h> Lighting Server Model callback value union.
Public Members
esp_ble_mesh_lighting_server_state_change_t state_change
ESP_BLE_MESH_LIGHTING_SERVER_STATE_CHANGE_EVT
esp_ble_mesh_lighting_server_recv_get_msg_t get
ESP_BLE_MESH_LIGHTING_SERVER_RECV_GET_MSG_EVT
esp_ble_mesh_lighting_server_recv_set_msg_t set
ESP_BLE_MESH_LIGHTING_SERVER_RECV_SET_MSG_EVT
esp_ble_mesh_lighting_server_recv_status_msg_t status
ESP_BLE_MESH_LIGHTING_SERVER_RECV_STATUS_MSG_EVT
Structures
struct esp_ble_mesh_light_lightness_set_t
Bluetooth Mesh Light Lightness Client Model Get and Set parameters structure.
Parameters of Light Lightness Set
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t lightness
Target value of light lightness actual state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_light_lightness_linear_set_t
Parameters of Light Lightness Linear Set
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t lightness
Target value of light lightness linear state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_light_lightness_default_set_t
Parameter of Light Lightness Default Set
Public Members
uint16_t lightness
The value of the Light Lightness Default state
struct esp_ble_mesh_light_lightness_range_set_t
Parameters of Light Lightness Range Set
Public Members
uint16_t range_min
Value of range min field of light lightness range state
uint16_t range_max
Value of range max field of light lightness range state
struct esp_ble_mesh_light_ctl_set_t
Parameters of Light CTL Set
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t ctl_lightness
Target value of light ctl lightness state
uint16_t ctl_temperatrue
Target value of light ctl temperature state
int16_t ctl_delta_uv
Target value of light ctl delta UV state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_light_ctl_temperature_set_t
Parameters of Light CTL Temperature Set
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t ctl_temperatrue
Target value of light ctl temperature state
int16_t ctl_delta_uv
Target value of light ctl delta UV state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_light_ctl_temperature_range_set_t
Parameters of Light CTL Temperature Range Set
Public Members
uint16_t range_min
Value of temperature range min field of light ctl temperature range state
uint16_t range_max
Value of temperature range max field of light ctl temperature range state
struct esp_ble_mesh_light_ctl_default_set_t
Parameters of Light CTL Default Set
Public Members
uint16_t lightness
Value of light lightness default state
uint16_t temperature
Value of light temperature default state
int16_t delta_uv
Value of light delta UV default state
struct esp_ble_mesh_light_hsl_set_t
Parameters of Light HSL Set
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t hsl_lightness
Target value of light hsl lightness state
uint16_t hsl_hue
Target value of light hsl hue state
uint16_t hsl_saturation
Target value of light hsl saturation state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_light_hsl_hue_set_t
Parameters of Light HSL Hue Set
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t hue
Target value of light hsl hue state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_light_hsl_saturation_set_t
Parameters of Light HSL Saturation Set
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t saturation
Target value of light hsl hue state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_light_hsl_default_set_t
Parameters of Light HSL Default Set
Public Members
uint16_t lightness
Value of light lightness default state
uint16_t hue
Value of light hue default state
uint16_t saturation
Value of light saturation default state
struct esp_ble_mesh_light_hsl_range_set_t
Parameters of Light HSL Range Set
Public Members
uint16_t hue_range_min
Value of hue range min field of light hsl hue range state
uint16_t hue_range_max
Value of hue range max field of light hsl hue range state
uint16_t saturation_range_min
Value of saturation range min field of light hsl saturation range state
uint16_t saturation_range_max
Value of saturation range max field of light hsl saturation range state
struct esp_ble_mesh_light_xyl_set_t
Parameters of Light xyL Set
Public Members
bool op_en
Indicate whether optional parameters included
uint16_t xyl_lightness
The target value of the Light xyL Lightness state
uint16_t xyl_x
The target value of the Light xyL x state
uint16_t xyl_y
The target value of the Light xyL y state
uint8_t tid
Transaction Identifier
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_light_xyl_default_set_t
Parameters of Light xyL Default Set
Public Members
uint16_t lightness
The value of the Light Lightness Default state
uint16_t xyl_x
The value of the Light xyL x Default state
uint16_t xyl_y
The value of the Light xyL y Default state
struct esp_ble_mesh_light_xyl_range_set_t
Parameters of Light xyL Range Set
Public Members
uint16_t xyl_x_range_min
The value of the xyL x Range Min field of the Light xyL x Range state
uint16_t xyl_x_range_max
The value of the xyL x Range Max field of the Light xyL x Range state
uint16_t xyl_y_range_min
The value of the xyL y Range Min field of the Light xyL y Range state
uint16_t xyl_y_range_max
The value of the xyL y Range Max field of the Light xyL y Range state
struct esp_ble_mesh_light_lc_mode_set_t
Parameter of Light LC Mode Set
Public Members
uint8_t mode
The target value of the Light LC Mode state
struct esp_ble_mesh_light_lc_om_set_t
Parameter of Light LC OM Set
Public Members
uint8_t mode
The target value of the Light LC Occupancy Mode state
struct esp_ble_mesh_light_lc_light_onoff_set_t
Parameters of Light LC Light OnOff Set
Public Members
bool op_en
Indicate whether optional parameters included
uint8_t light_onoff
The target value of the Light LC Light OnOff state
uint8_t tid
Transaction Identifier
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_light_lc_property_get_t
Parameter of Light LC Property Get
Public Members
uint16_t property_id
Property ID identifying a Light LC Property
struct esp_ble_mesh_light_lc_property_set_t
Parameters of Light LC Property Set
Public Members
uint16_t property_id
Property ID identifying a Light LC Property
struct esp_ble_mesh_light_lightness_status_cb_t
Bluetooth Mesh Light Lightness Client Model Get and Set callback parameters structure.
Parameters of Light Lightness Status
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t present_lightness
Current value of light lightness actual state
uint16_t target_lightness
Target value of light lightness actual state (optional)
uint8_t remain_time
Time to complete state transition (C.1)
struct esp_ble_mesh_light_lightness_linear_status_cb_t
Parameters of Light Lightness Linear Status
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t present_lightness
Current value of light lightness linear state
uint16_t target_lightness
Target value of light lightness linear state (optional)
uint8_t remain_time
Time to complete state transition (C.1)
struct esp_ble_mesh_light_lightness_last_status_cb_t
Parameter of Light Lightness Last Status
Public Members
uint16_t lightness
The value of the Light Lightness Last state
struct esp_ble_mesh_light_lightness_default_status_cb_t
Parameter of Light Lightness Default Status
Public Members
uint16_t lightness
The value of the Light Lightness default State
struct esp_ble_mesh_light_lightness_range_status_cb_t
Parameters of Light Lightness Range Status
Public Members
uint8_t status_code
Status Code for the request message
uint16_t range_min
Value of range min field of light lightness range state
uint16_t range_max
Value of range max field of light lightness range state
struct esp_ble_mesh_light_ctl_status_cb_t
Parameters of Light CTL Status
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t present_ctl_lightness
Current value of light ctl lightness state
uint16_t present_ctl_temperature
Current value of light ctl temperature state
uint16_t target_ctl_lightness
Target value of light ctl lightness state (optional)
uint16_t target_ctl_temperature
Target value of light ctl temperature state (C.1)
uint8_t remain_time
Time to complete state transition (C.1)
struct esp_ble_mesh_light_ctl_temperature_status_cb_t
Parameters of Light CTL Temperature Status
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t present_ctl_temperature
Current value of light ctl temperature state
uint16_t present_ctl_delta_uv
Current value of light ctl delta UV state
uint16_t target_ctl_temperature
Target value of light ctl temperature state (optional)
uint16_t target_ctl_delta_uv
Target value of light ctl delta UV state (C.1)
uint8_t remain_time
Time to complete state transition (C.1)
struct esp_ble_mesh_light_ctl_temperature_range_status_cb_t
Parameters of Light CTL Temperature Range Status
Public Members
uint8_t status_code
Status code for the request message
uint16_t range_min
Value of temperature range min field of light ctl temperature range state
uint16_t range_max
Value of temperature range max field of light ctl temperature range state
struct esp_ble_mesh_light_ctl_default_status_cb_t
Parameters of Light CTL Default Status
Public Members
uint16_t lightness
Value of light lightness default state
uint16_t temperature
Value of light temperature default state
int16_t delta_uv
Value of light delta UV default state
struct esp_ble_mesh_light_hsl_status_cb_t
Parameters of Light HSL Status
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t hsl_lightness
Current value of light hsl lightness state
uint16_t hsl_hue
Current value of light hsl hue state
uint16_t hsl_saturation
Current value of light hsl saturation state
uint8_t remain_time
Time to complete state transition (optional)
struct esp_ble_mesh_light_hsl_target_status_cb_t
Parameters of Light HSL Target Status
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t hsl_lightness_target
Target value of light hsl lightness state
uint16_t hsl_hue_target
Target value of light hsl hue state
uint16_t hsl_saturation_target
Target value of light hsl saturation state
uint8_t remain_time
Time to complete state transition (optional)
struct esp_ble_mesh_light_hsl_hue_status_cb_t
Parameters of Light HSL Hue Status
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t present_hue
Current value of light hsl hue state
uint16_t target_hue
Target value of light hsl hue state (optional)
uint8_t remain_time
Time to complete state transition (C.1)
struct esp_ble_mesh_light_hsl_saturation_status_cb_t
Parameters of Light HSL Saturation Status
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t present_saturation
Current value of light hsl saturation state
uint16_t target_saturation
Target value of light hsl saturation state (optional)
uint8_t remain_time
Time to complete state transition (C.1)
struct esp_ble_mesh_light_hsl_default_status_cb_t
Parameters of Light HSL Default Status
Public Members
uint16_t lightness
Value of light lightness default state
uint16_t hue
Value of light hue default state
uint16_t saturation
Value of light saturation default state
struct esp_ble_mesh_light_hsl_range_status_cb_t
Parameters of Light HSL Range Status
Public Members
uint8_t status_code
Status code for the request message
uint16_t hue_range_min
Value of hue range min field of light hsl hue range state
uint16_t hue_range_max
Value of hue range max field of light hsl hue range state
uint16_t saturation_range_min
Value of saturation range min field of light hsl saturation range state
uint16_t saturation_range_max
Value of saturation range max field of light hsl saturation range state
struct esp_ble_mesh_light_xyl_status_cb_t
Parameters of Light xyL Status
Public Members
bool op_en
Indicate whether optional parameters included
uint16_t xyl_lightness
The present value of the Light xyL Lightness state
uint16_t xyl_x
The present value of the Light xyL x state
uint16_t xyl_y
The present value of the Light xyL y state
uint8_t remain_time
Time to complete state transition (optional)
struct esp_ble_mesh_light_xyl_target_status_cb_t
Parameters of Light xyL Target Status
Public Members
bool op_en
Indicate whether optional parameters included
uint16_t target_xyl_lightness
The target value of the Light xyL Lightness state
uint16_t target_xyl_x
The target value of the Light xyL x state
uint16_t target_xyl_y
The target value of the Light xyL y state
uint8_t remain_time
Time to complete state transition (optional)
struct esp_ble_mesh_light_xyl_default_status_cb_t
Parameters of Light xyL Default Status
Public Members
uint16_t lightness
The value of the Light Lightness Default state
uint16_t xyl_x
The value of the Light xyL x Default state
uint16_t xyl_y
The value of the Light xyL y Default state
struct esp_ble_mesh_light_xyl_range_status_cb_t
Parameters of Light xyL Range Status
Public Members
uint8_t status_code
Status Code for the requesting message
uint16_t xyl_x_range_min
The value of the xyL x Range Min field of the Light xyL x Range state
uint16_t xyl_x_range_max
The value of the xyL x Range Max field of the Light xyL x Range state
uint16_t xyl_y_range_min
The value of the xyL y Range Min field of the Light xyL y Range state
uint16_t xyl_y_range_max
The value of the xyL y Range Max field of the Light xyL y Range state
struct esp_ble_mesh_light_lc_mode_status_cb_t
Parameter of Light LC Mode Status
Public Members
uint8_t mode
The present value of the Light LC Mode state
struct esp_ble_mesh_light_lc_om_status_cb_t
Parameter of Light LC OM Status
Public Members
uint8_t mode
The present value of the Light LC Occupancy Mode state
struct esp_ble_mesh_light_lc_light_onoff_status_cb_t
Parameters of Light LC Light OnOff Status
Public Members
bool op_en
Indicate whether optional parameters included
uint8_t present_light_onoff
The present value of the Light LC Light OnOff state
uint8_t target_light_onoff
The target value of the Light LC Light OnOff state (Optional)
uint8_t remain_time
Time to complete state transition (C.1)
struct esp_ble_mesh_light_lc_property_status_cb_t
Parameters of Light LC Property Status
Public Members
uint16_t property_id
Property ID identifying a Light LC Property
struct esp_ble_mesh_light_client_cb_param_t
Lighting Client Model callback parameters
Public Members
int error_code
Appropriate error code
esp_ble_mesh_client_common_param_t *params
The client common parameters.
esp_ble_mesh_light_client_status_cb_t status_cb
The light status message callback values
struct esp_ble_mesh_light_lightness_state_t
Parameters of Light Lightness state
Public Members
uint16_t lightness_linear
The present value of Light Lightness Linear state
uint16_t target_lightness_linear
The target value of Light Lightness Linear state
uint16_t lightness_actual
The present value of Light Lightness Actual state
uint16_t target_lightness_actual
The target value of Light Lightness Actual state
uint16_t lightness_last
The value of Light Lightness Last state
uint16_t lightness_default
The value of Light Lightness Default state
uint8_t status_code
The status code of setting Light Lightness Range state
uint16_t lightness_range_min
The minimum value of Light Lightness Range state
uint16_t lightness_range_max
The maximum value of Light Lightness Range state
struct esp_ble_mesh_light_lightness_srv_t
User data of Light Lightness Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Lighting Lightness Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_light_lightness_state_t *state
Parameters of the Light Lightness state
esp_ble_mesh_last_msg_info_t last
Parameters of the last received set message
esp_ble_mesh_state_transition_t actual_transition
Parameters of state transition
esp_ble_mesh_state_transition_t linear_transition
Parameters of state transition
int32_t tt_delta_lightness_actual
Delta change value of lightness actual state transition
int32_t tt_delta_lightness_linear
Delta change value of lightness linear state transition
struct esp_ble_mesh_light_lightness_setup_srv_t
User data of Light Lightness Setup Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Lighting Lightness Setup Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_light_lightness_state_t *state
Parameters of the Light Lightness state
struct esp_ble_mesh_light_ctl_state_t
Parameters of Light CTL state
Public Members
uint16_t lightness
The present value of Light CTL Lightness state
uint16_t target_lightness
The target value of Light CTL Lightness state
uint16_t temperature
The present value of Light CTL Temperature state
uint16_t target_temperature
The target value of Light CTL Temperature state
int16_t delta_uv
The present value of Light CTL Delta UV state
int16_t target_delta_uv
The target value of Light CTL Delta UV state
uint8_t status_code
The statue code of setting Light CTL Temperature Range state
uint16_t temperature_range_min
The minimum value of Light CTL Temperature Range state
uint16_t temperature_range_max
The maximum value of Light CTL Temperature Range state
uint16_t lightness_default
The value of Light Lightness Default state
uint16_t temperature_default
The value of Light CTL Temperature Default state
int16_t delta_uv_default
The value of Light CTL Delta UV Default state
struct esp_ble_mesh_light_ctl_srv_t
User data of Light CTL Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Lighting CTL Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_light_ctl_state_t *state
Parameters of the Light CTL state
esp_ble_mesh_last_msg_info_t last
Parameters of the last received set message
esp_ble_mesh_state_transition_t transition
Parameters of state transition
int32_t tt_delta_lightness
Delta change value of lightness state transition
int32_t tt_delta_temperature
Delta change value of temperature state transition
int32_t tt_delta_delta_uv
Delta change value of delta uv state transition
struct esp_ble_mesh_light_ctl_setup_srv_t
User data of Light CTL Setup Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Lighting CTL Setup Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_light_ctl_state_t *state
Parameters of the Light CTL state
struct esp_ble_mesh_light_ctl_temp_srv_t
User data of Light CTL Temperature Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Lighting CTL Temperature Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_light_ctl_state_t *state
Parameters of the Light CTL state
esp_ble_mesh_last_msg_info_t last
Parameters of the last received set message
esp_ble_mesh_state_transition_t transition
Parameters of state transition
int32_t tt_delta_temperature
Delta change value of temperature state transition
int32_t tt_delta_delta_uv
Delta change value of delta uv state transition
struct esp_ble_mesh_light_hsl_state_t
Parameters of Light HSL state
Public Members
uint16_t lightness
The present value of Light HSL Lightness state
uint16_t target_lightness
The target value of Light HSL Lightness state
uint16_t hue
The present value of Light HSL Hue state
uint16_t target_hue
The target value of Light HSL Hue state
uint16_t saturation
The present value of Light HSL Saturation state
uint16_t target_saturation
The target value of Light HSL Saturation state
uint16_t lightness_default
The value of Light Lightness Default state
uint16_t hue_default
The value of Light HSL Hue Default state
uint16_t saturation_default
The value of Light HSL Saturation Default state
uint8_t status_code
The status code of setting Light HSL Hue & Saturation Range state
uint16_t hue_range_min
The minimum value of Light HSL Hue Range state
uint16_t hue_range_max
The maximum value of Light HSL Hue Range state
uint16_t saturation_range_min
The minimum value of Light HSL Saturation state
uint16_t saturation_range_max
The maximum value of Light HSL Saturation state
struct esp_ble_mesh_light_hsl_srv_t
User data of Light HSL Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Lighting HSL Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_light_hsl_state_t *state
Parameters of the Light HSL state
esp_ble_mesh_last_msg_info_t last
Parameters of the last received set message
esp_ble_mesh_state_transition_t transition
Parameters of state transition
int32_t tt_delta_lightness
Delta change value of lightness state transition
int32_t tt_delta_hue
Delta change value of hue state transition
int32_t tt_delta_saturation
Delta change value of saturation state transition
struct esp_ble_mesh_light_hsl_setup_srv_t
User data of Light HSL Setup Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Lighting HSL Setup Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_light_hsl_state_t *state
Parameters of the Light HSL state
struct esp_ble_mesh_light_hsl_hue_srv_t
User data of Light HSL Hue Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Lighting HSL Hue Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_light_hsl_state_t *state
Parameters of the Light HSL state
esp_ble_mesh_last_msg_info_t last
Parameters of the last received set message
esp_ble_mesh_state_transition_t transition
Parameters of state transition
int32_t tt_delta_hue
Delta change value of hue state transition
struct esp_ble_mesh_light_hsl_sat_srv_t
User data of Light HSL Saturation Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Lighting HSL Saturation Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_light_hsl_state_t *state
Parameters of the Light HSL state
esp_ble_mesh_last_msg_info_t last
Parameters of the last received set message
esp_ble_mesh_state_transition_t transition
Parameters of state transition
int32_t tt_delta_saturation
Delta change value of saturation state transition
struct esp_ble_mesh_light_xyl_state_t
Parameters of Light xyL state
Public Members
uint16_t lightness
The present value of Light xyL Lightness state
uint16_t target_lightness
The target value of Light xyL Lightness state
uint16_t x
The present value of Light xyL x state
uint16_t target_x
The target value of Light xyL x state
uint16_t y
The present value of Light xyL y state
uint16_t target_y
The target value of Light xyL y state
uint16_t lightness_default
The value of Light Lightness Default state
uint16_t x_default
The value of Light xyL x Default state
uint16_t y_default
The value of Light xyL y Default state
uint8_t status_code
The status code of setting Light xyL x & y Range state
uint16_t x_range_min
The minimum value of Light xyL x Range state
uint16_t x_range_max
The maximum value of Light xyL x Range state
uint16_t y_range_min
The minimum value of Light xyL y Range state
uint16_t y_range_max
The maximum value of Light xyL y Range state
struct esp_ble_mesh_light_xyl_srv_t
User data of Light xyL Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Lighting xyL Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_light_xyl_state_t *state
Parameters of the Light xyL state
esp_ble_mesh_last_msg_info_t last
Parameters of the last received set message
esp_ble_mesh_state_transition_t transition
Parameters of state transition
int32_t tt_delta_lightness
Delta change value of lightness state transition
int32_t tt_delta_x
Delta change value of x state transition
int32_t tt_delta_y
Delta change value of y state transition
struct esp_ble_mesh_light_xyl_setup_srv_t
User data of Light xyL Setup Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Lighting xyL Setup Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_light_xyl_state_t *state
Parameters of the Light xyL state
struct esp_ble_mesh_light_lc_state_t
Parameters of Light LC states
Public Members
uint32_t mode
0b0 The controller is turned off.
• The binding with the Light Lightness state is disabled. 0b1 The controller is turned on.
• The binding with the Light Lightness state is enabled. The value of Light LC Mode state
uint32_t occupancy_mode
The value of Light LC Occupancy Mode state
uint32_t light_onoff
The present value of Light LC Light OnOff state
uint32_t target_light_onoff
The target value of Light LC Light OnOff state
uint32_t occupancy
The value of Light LC Occupancy state
uint32_t ambient_luxlevel
The value of Light LC Ambient LuxLevel state
uint16_t linear_output
struct esp_ble_mesh_light_lc_property_state_t
Parameters of Light Property states. The Light LC Property states are read / write states that determine the
configuration of a Light Lightness Controller. Each state is represented by a device property and is controlled
by Light LC Property messages.
Public Members
uint32_t time_occupancy_delay
A timing state that determines the delay for changing the Light LC Occupancy state upon receiving a
Sensor Status message from an occupancy sensor. The value of Light LC Time Occupancy Delay state
uint32_t time_fade_on
A timing state that determines the time the controlled lights fade to the level determined by the Light LC
Lightness On state. The value of Light LC Time Fade On state
uint32_t time_run_on
A timing state that determines the time the controlled lights stay at the level determined by the Light LC
Lightness On state. The value of Light LC Time Run On state
uint32_t time_fade
A timing state that determines the time the controlled lights fade from the level determined by the Light
LC Lightness On state to the level determined by the Light Lightness Prolong state. The value of Light
LC Time Fade state
uint32_t time_prolong
A timing state that determines the time the controlled lights stay at the level determined by the Light LC
Lightness Prolong state. The value of Light LC Time Prolong state
uint32_t time_fade_standby_auto
A timing state that determines the time the controlled lights fade from the level determined by the Light
LC Lightness Prolong state to the level determined by the Light LC Lightness Standby state when the
transition is automatic. The value of Light LC Time Fade Standby Auto state
uint32_t time_fade_standby_manual
A timing state that determines the time the controlled lights fade from the level determined by the Light
LC Lightness Prolong state to the level determined by the Light LC Lightness Standby state when the
transition is triggered by a change in the Light LC Light OnOff state. The value of Light LC Time Fade
Standby Manual state
uint16_t lightness_on
A lightness state that determines the perceptive light lightness at the Occupancy and Run internal con-
troller states. The value of Light LC Lightness On state
uint16_t lightness_prolong
A lightness state that determines the light lightness at the Prolong internal controller state. The value of
Light LC Lightness Prolong state
uint16_t lightness_standby
A lightness state that determines the light lightness at the Standby internal controller state. The value of
Light LC Lightness Standby state
uint16_t ambient_luxlevel_on
A uint16 state representing the Ambient LuxLevel level that determines if the controller transitions from
the Light Control Standby state. The value of Light LC Ambient LuxLevel On state
uint16_t ambient_luxlevel_prolong
A uint16 state representing the required Ambient LuxLevel level in the Prolong state. The value of Light
LC Ambient LuxLevel Prolong state
uint16_t ambient_luxlevel_standby
A uint16 state representing the required Ambient LuxLevel level in the Standby state. The value of Light
LC Ambient LuxLevel Standby state
float regulator_kiu
A float32 state representing the integral coefficient that determines the integral part of the equation defin-
ing the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is less than
LuxLevel Out. Valid range: 0.0 ~ 1000.0. The default value is 250.0. The value of Light LC Regulator
Kiu state
float regulator_kid
A float32 state representing the integral coefficient that determines the integral part of the equation defin-
ing the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is greater than
or equal to the value of the LuxLevel Out state. Valid range: 0.0 ~ 1000.0. The default value is 25.0.
The value of Light LC Regulator Kid state
float regulator_kpu
A float32 state representing the proportional coefficient that determines the proportional part of the equa-
tion defining the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is
less than the value of the LuxLevel Out state. Valid range: 0.0 ~ 1000.0. The default value is 80.0. The
value of Light LC Regulator Kpu state
float regulator_kpd
A float32 state representing the proportional coefficient that determines the proportional part of the equa-
tion defining the output of the Light LC PI Feedback Regulator, when Light LC Ambient LuxLevel is
greater than or equal to the value of the LuxLevel Out state. Valid range: 0.0 ~ 1000.0. The default value
is 80.0. The value of Light LC Regulator Kpd state
int8_t regulator_accuracy
A int8 state representing the percentage accuracy of the Light LC PI Feedback Regulator. Valid range:
0.0 ~ 100.0. The default value is 2.0. The value of Light LC Regulator Accuracy state
uint32_t set_occupancy_to_1_delay
If the message Raw field contains a Raw Value for the Time Since Motion Sensed device property,
which represents a value less than or equal to the value of the Light LC Occupancy Delay state, it shall
delay setting the Light LC Occupancy state to 0b1 by the difference between the value of the Light LC
Occupancy Delay state and the received Time Since Motion value. The value of the difference between
value of the Light LC Occupancy Delay state and the received Time Since Motion value
struct esp_ble_mesh_light_lc_state_machine_t
Parameters of Light LC state machine
Public Members
uint8_t fade_on
The value of transition time of Light LC Time Fade On
uint8_t fade
The value of transition time of Light LC Time Fade
uint8_t fade_standby_auto
The value of transition time of Light LC Time Fade Standby Auto
uint8_t fade_standby_manual
The value of transition time of Light LC Time Fade Standby Manual
esp_ble_mesh_lc_state_t state
The value of Light LC state machine state
struct esp_ble_mesh_light_control_t
Parameters of Light Lightness controller
Public Members
esp_ble_mesh_light_lc_state_t state
Parameters of Light LC state
esp_ble_mesh_light_lc_property_state_t prop_state
Parameters of Light LC Property state
esp_ble_mesh_light_lc_state_machine_t state_machine
Parameters of Light LC state machine
struct esp_ble_mesh_light_lc_srv_t
User data of Light LC Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Lighting LC Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_light_control_t *lc
Parameters of the Light controller
esp_ble_mesh_last_msg_info_t last
Parameters of the last received set message
esp_ble_mesh_state_transition_t transition
Parameters of state transition
struct esp_ble_mesh_light_lc_setup_srv_t
User data of Light LC Setup Server Model
Public Members
esp_ble_mesh_model_t *model
Pointer to the Lighting LC Setup Server Model. Initialized internally.
esp_ble_mesh_server_rsp_ctrl_t rsp_ctrl
Response control of the server model received messages
esp_ble_mesh_light_control_t *lc
Parameters of the Light controller
struct esp_ble_mesh_state_change_light_lightness_set_t
Parameter of Light Lightness Actual state change event
Public Members
uint16_t lightness
The value of Light Lightness Actual state
struct esp_ble_mesh_state_change_light_lightness_linear_set_t
Parameter of Light Lightness Linear state change event
Public Members
uint16_t lightness
The value of Light Lightness Linear state
struct esp_ble_mesh_state_change_light_lightness_default_set_t
Parameter of Light Lightness Default state change event
Public Members
uint16_t lightness
The value of Light Lightness Default state
struct esp_ble_mesh_state_change_light_lightness_range_set_t
Parameters of Light Lightness Range state change event
Public Members
uint16_t range_min
The minimum value of Light Lightness Range state
uint16_t range_max
The maximum value of Light Lightness Range state
struct esp_ble_mesh_state_change_light_ctl_set_t
Parameters of Light CTL state change event
Public Members
uint16_t lightness
The value of Light CTL Lightness state
uint16_t temperature
The value of Light CTL Temperature state
int16_t delta_uv
The value of Light CTL Delta UV state
struct esp_ble_mesh_state_change_light_ctl_temperature_set_t
Parameters of Light CTL Temperature state change event
Public Members
uint16_t temperature
The value of Light CTL Temperature state
int16_t delta_uv
The value of Light CTL Delta UV state
struct esp_ble_mesh_state_change_light_ctl_temperature_range_set_t
Parameters of Light CTL Temperature Range state change event
Public Members
uint16_t range_min
The minimum value of Light CTL Temperature Range state
uint16_t range_max
The maximum value of Light CTL Temperature Range state
struct esp_ble_mesh_state_change_light_ctl_default_set_t
Parameters of Light CTL Default state change event
Public Members
uint16_t lightness
The value of Light Lightness Default state
uint16_t temperature
The value of Light CTL Temperature Default state
int16_t delta_uv
The value of Light CTL Delta UV Default state
struct esp_ble_mesh_state_change_light_hsl_set_t
Parameters of Light HSL state change event
Public Members
uint16_t lightness
The value of Light HSL Lightness state
uint16_t hue
The value of Light HSL Hue state
uint16_t saturation
The value of Light HSL Saturation state
struct esp_ble_mesh_state_change_light_hsl_hue_set_t
Parameter of Light HSL Hue state change event
Public Members
uint16_t hue
The value of Light HSL Hue state
struct esp_ble_mesh_state_change_light_hsl_saturation_set_t
Parameter of Light HSL Saturation state change event
Public Members
uint16_t saturation
The value of Light HSL Saturation state
struct esp_ble_mesh_state_change_light_hsl_default_set_t
Parameters of Light HSL Default state change event
Public Members
uint16_t lightness
The value of Light HSL Lightness Default state
uint16_t hue
The value of Light HSL Hue Default state
uint16_t saturation
The value of Light HSL Saturation Default state
struct esp_ble_mesh_state_change_light_hsl_range_set_t
Parameters of Light HSL Range state change event
Public Members
uint16_t hue_range_min
The minimum hue value of Light HSL Range state
uint16_t hue_range_max
The maximum hue value of Light HSL Range state
uint16_t saturation_range_min
The minimum saturation value of Light HSL Range state
uint16_t saturation_range_max
The maximum saturation value of Light HSL Range state
struct esp_ble_mesh_state_change_light_xyl_set_t
Parameters of Light xyL state change event
Public Members
uint16_t lightness
The value of Light xyL Lightness state
uint16_t x
The value of Light xyL x state
uint16_t y
The value of Light xyL y state
struct esp_ble_mesh_state_change_light_xyl_default_set_t
Parameters of Light xyL Default state change event
Public Members
uint16_t lightness
The value of Light Lightness Default state
uint16_t x
The value of Light xyL x Default state
uint16_t y
The value of Light xyL y Default state
struct esp_ble_mesh_state_change_light_xyl_range_set_t
Parameters of Light xyL Range state change event
Public Members
uint16_t x_range_min
The minimum value of Light xyL x Range state
uint16_t x_range_max
The maximum value of Light xyL x Range state
uint16_t y_range_min
The minimum value of Light xyL y Range state
uint16_t y_range_max
The maximum value of Light xyL y Range state
struct esp_ble_mesh_state_change_light_lc_mode_set_t
Parameter of Light LC Mode state change event
Public Members
uint8_t mode
The value of Light LC Mode state
struct esp_ble_mesh_state_change_light_lc_om_set_t
Parameter of Light LC Occupancy Mode state change event
Public Members
uint8_t mode
The value of Light LC Occupancy Mode state
struct esp_ble_mesh_state_change_light_lc_light_onoff_set_t
Parameter of Light LC Light OnOff state change event
Public Members
uint8_t onoff
The value of Light LC Light OnOff state
struct esp_ble_mesh_state_change_light_lc_property_set_t
Parameters of Light LC Property state change event
Public Members
uint16_t property_id
The property id of Light LC Property state
struct esp_ble_mesh_state_change_sensor_status_t
Parameters of Sensor Status state change event
Public Members
uint16_t property_id
The value of Sensor Property ID
uint8_t occupancy
The value of Light LC Occupancy state
uint32_t set_occupancy_to_1_delay
The value of Light LC Set Occupancy to 1 Delay state
uint32_t ambient_luxlevel
The value of Light LC Ambient Luxlevel state
struct esp_ble_mesh_server_recv_light_lc_property_get_t
Context of the received Light LC Property Get message
Public Members
uint16_t property_id
Property ID identifying a Light LC Property
struct esp_ble_mesh_server_recv_light_lightness_set_t
Context of the received Light Lightness Set message
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t lightness
Target value of light lightness actual state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_light_lightness_linear_set_t
Context of the received Light Lightness Linear Set message
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t lightness
Target value of light lightness linear state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_light_lightness_default_set_t
Context of the received Light Lightness Default Set message
Public Members
uint16_t lightness
The value of the Light Lightness Default state
struct esp_ble_mesh_server_recv_light_lightness_range_set_t
Context of the received Light Lightness Range Set message
Public Members
uint16_t range_min
Value of range min field of light lightness range state
uint16_t range_max
Value of range max field of light lightness range state
struct esp_ble_mesh_server_recv_light_ctl_set_t
Context of the received Light CTL Set message
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t lightness
Target value of light ctl lightness state
uint16_t temperature
Target value of light ctl temperature state
int16_t delta_uv
Target value of light ctl delta UV state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_light_ctl_temperature_set_t
Context of the received Light CTL Temperature Set message
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t temperature
Target value of light ctl temperature state
int16_t delta_uv
Target value of light ctl delta UV state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_light_ctl_temperature_range_set_t
Context of the received Light CTL Temperature Range Set message
Public Members
uint16_t range_min
Value of temperature range min field of light ctl temperature range state
uint16_t range_max
Value of temperature range max field of light ctl temperature range state
struct esp_ble_mesh_server_recv_light_ctl_default_set_t
Context of the received Light CTL Default Set message
Public Members
uint16_t lightness
Value of light lightness default state
uint16_t temperature
Value of light temperature default state
int16_t delta_uv
Value of light delta UV default state
struct esp_ble_mesh_server_recv_light_hsl_set_t
Context of the received Light HSL Set message
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t lightness
Target value of light hsl lightness state
uint16_t hue
Target value of light hsl hue state
uint16_t saturation
Target value of light hsl saturation state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_light_hsl_hue_set_t
Context of the received Light HSL Hue Set message
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t hue
Target value of light hsl hue state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_light_hsl_saturation_set_t
Context of the received Light HSL Saturation Set message
Public Members
bool op_en
Indicate if optional parameters are included
uint16_t saturation
Target value of light hsl hue state
uint8_t tid
Transaction ID
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_light_hsl_default_set_t
Context of the received Light HSL Default Set message
Public Members
uint16_t lightness
Value of light lightness default state
uint16_t hue
Value of light hue default state
uint16_t saturation
Value of light saturation default state
struct esp_ble_mesh_server_recv_light_hsl_range_set_t
Context of the received Light HSL Range Set message
Public Members
uint16_t hue_range_min
Value of hue range min field of light hsl hue range state
uint16_t hue_range_max
Value of hue range max field of light hsl hue range state
uint16_t saturation_range_min
Value of saturation range min field of light hsl saturation range state
uint16_t saturation_range_max
Value of saturation range max field of light hsl saturation range state
struct esp_ble_mesh_server_recv_light_xyl_set_t
Context of the received Light xyL Set message
Public Members
bool op_en
Indicate whether optional parameters included
uint16_t lightness
The target value of the Light xyL Lightness state
uint16_t x
The target value of the Light xyL x state
uint16_t y
The target value of the Light xyL y state
uint8_t tid
Transaction Identifier
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_light_xyl_default_set_t
Context of the received Light xyL Default Set message
Public Members
uint16_t lightness
The value of the Light Lightness Default state
uint16_t x
The value of the Light xyL x Default state
uint16_t y
The value of the Light xyL y Default state
struct esp_ble_mesh_server_recv_light_xyl_range_set_t
Context of the received Light xyl Range Set message
Public Members
uint16_t x_range_min
The value of the xyL x Range Min field of the Light xyL x Range state
uint16_t x_range_max
The value of the xyL x Range Max field of the Light xyL x Range state
uint16_t y_range_min
The value of the xyL y Range Min field of the Light xyL y Range state
uint16_t y_range_max
The value of the xyL y Range Max field of the Light xyL y Range state
struct esp_ble_mesh_server_recv_light_lc_mode_set_t
Context of the received Light LC Mode Set message
Public Members
uint8_t mode
The target value of the Light LC Mode state
struct esp_ble_mesh_server_recv_light_lc_om_set_t
Context of the received Light OM Set message
Public Members
uint8_t mode
The target value of the Light LC Occupancy Mode state
struct esp_ble_mesh_server_recv_light_lc_light_onoff_set_t
Context of the received Light LC Light OnOff Set message
Public Members
bool op_en
Indicate whether optional parameters included
uint8_t light_onoff
The target value of the Light LC Light OnOff state
uint8_t tid
Transaction Identifier
uint8_t trans_time
Time to complete state transition (optional)
uint8_t delay
Indicate message execution delay (C.1)
struct esp_ble_mesh_server_recv_light_lc_property_set_t
Context of the received Light LC Property Set message
Public Members
uint16_t property_id
Property ID identifying a Light LC Property
struct esp_ble_mesh_server_recv_sensor_status_t
Context of the received Sensor Status message
Public Members
struct esp_ble_mesh_lighting_server_cb_param_t
Lighting Server Model callback parameters
Public Members
esp_ble_mesh_model_t *model
Pointer to Lighting Server Models
esp_ble_mesh_msg_ctx_t ctx
Context of the received messages
esp_ble_mesh_lighting_server_cb_value_t value
Value of the received Lighting Messages
Macros
ESP_BLE_MESH_MODEL_LIGHT_LIGHTNESS_CLI(cli_pub, cli_data)
Define a new Light Lightness Client Model.
Note: This API needs to be called for each element on which the application needs to have a Light Lightness
Client Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Light Lightness Client Model instance.
ESP_BLE_MESH_MODEL_LIGHT_CTL_CLI(cli_pub, cli_data)
Define a new Light CTL Client Model.
Note: This API needs to be called for each element on which the application needs to have a Light CTL Client
Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Light CTL Client Model instance.
ESP_BLE_MESH_MODEL_LIGHT_HSL_CLI(cli_pub, cli_data)
Define a new Light HSL Client Model.
Note: This API needs to be called for each element on which the application needs to have a Light HSL Client
Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Light HSL Client Model instance.
ESP_BLE_MESH_MODEL_LIGHT_XYL_CLI(cli_pub, cli_data)
Define a new Light xyL Client Model.
Note: This API needs to be called for each element on which the application needs to have a Light xyL Client
Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Light xyL Client Model instance.
ESP_BLE_MESH_MODEL_LIGHT_LC_CLI(cli_pub, cli_data)
Define a new Light LC Client Model.
Note: This API needs to be called for each element on which the application needs to have a Light LC Client
Model.
Parameters
• cli_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• cli_data –Pointer to the unique struct esp_ble_mesh_client_t.
Returns New Light LC Client Model instance.
ESP_BLE_MESH_MODEL_LIGHT_LIGHTNESS_SRV(srv_pub, srv_data)
Lighting Server Models related context.
Define a new Light Lightness Server Model.
Note: 1. The Light Lightness Server model extends the Generic Power OnOff Server model and the Generic
Level Server model. When this model is present on an Element, the corresponding Light Lightness Setup
Server model shall also be present.
a. This model shall support model publication and model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_light_lightness_srv_t.
ESP_BLE_MESH_MODEL_LIGHT_LIGHTNESS_SETUP_SRV(srv_pub, srv_data)
Define a new Light Lightness Setup Server Model.
Note: 1. The Light Lightness Setup Server model extends the Light Lightness Server model and the Generic
Power OnOff Setup Server model.
a. This model shall support model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_light_lightness_setup_srv_t.
Returns New Light Lightness Setup Server Model instance.
ESP_BLE_MESH_MODEL_LIGHT_CTL_SRV(srv_pub, srv_data)
Define a new Light CTL Server Model.
Note: 1. The Light CTL Server model extends the Light Lightness Server model. When this model is present
on an Element, the corresponding Light CTL Temperature Server model and the corresponding Light CTL
Setup Server model shall also be present.
a. This model shall support model publication and model subscription.
b. The model requires two elements: the main element and the Temperature element. The Temperature
element contains the corresponding Light CTL Temperature Server model and an instance of a Generic
Level state bound to the Light CTL Temperature state on the Temperature element. The Light CTL
Temperature state on the Temperature element is bound to the Light CTL state on the main element.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_light_ctl_srv_t.
Returns New Light CTL Server Model instance.
ESP_BLE_MESH_MODEL_LIGHT_CTL_SETUP_SRV(srv_pub, srv_data)
Define a new Light CTL Setup Server Model.
Note: 1. The Light CTL Setup Server model extends the Light CTL Server and the Light Lightness Setup
Server.
a. This model shall support model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_light_ctl_setup_srv_t.
Returns New Light CTL Setup Server Model instance.
ESP_BLE_MESH_MODEL_LIGHT_CTL_TEMP_SRV(srv_pub, srv_data)
Define a new Light CTL Temperature Server Model.
Note: 1. The Light CTL Temperature Server model extends the Generic Level Server model.
a. This model shall support model publication and model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_light_ctl_temp_srv_t.
Returns New Light CTL Temperature Server Model instance.
ESP_BLE_MESH_MODEL_LIGHT_HSL_SRV(srv_pub, srv_data)
Define a new Light HSL Server Model.
Note: 1. The Light HSL Server model extends the Light Lightness Server model. When this model is present
on an Element, the corresponding Light HSL Hue Server model and the corresponding Light HSL Saturation
Server model and the corresponding Light HSL Setup Server model shall also be present.
a. This model shall support model publication and model subscription.
b. The model requires three elements: the main element and the Hue element and the Saturation element.
The Hue element contains the corresponding Light HSL Hue Server model and an instance of a Generic
Level state bound to the Light HSL Hue state on the Hue element. The Saturation element contains the
corresponding Light HSL Saturation Server model and an instance of a Generic Level state bound to the
Light HSL Saturation state on the Saturation element. The Light HSL Hue state on the Hue element is
bound to the Light HSL state on the main element and the Light HSL Saturation state on the Saturation
element is bound to the Light HSL state on the main element.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_light_hsl_srv_t.
Returns New Light HSL Server Model instance.
ESP_BLE_MESH_MODEL_LIGHT_HSL_SETUP_SRV(srv_pub, srv_data)
Define a new Light HSL Setup Server Model.
Note: 1. The Light HSL Setup Server model extends the Light HSL Server and the Light Lightness Setup
Server.
a. This model shall support model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_light_hsl_setup_srv_t.
Returns New Light HSL Setup Server Model instance.
ESP_BLE_MESH_MODEL_LIGHT_HSL_HUE_SRV(srv_pub, srv_data)
Define a new Light HSL Hue Server Model.
Note: 1. The Light HSL Hue Server model extends the Generic Level Server model. This model is associated
with the Light HSL Server model.
a. This model shall support model publication and model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_light_hsl_hue_srv_t.
Returns New Light HSL Hue Server Model instance.
ESP_BLE_MESH_MODEL_LIGHT_HSL_SAT_SRV(srv_pub, srv_data)
Define a new Light HSL Saturation Server Model.
Note: 1. The Light HSL Saturation Server model extends the Generic Level Server model. This model is
associated with the Light HSL Server model.
a. This model shall support model publication and model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_light_hsl_sat_srv_t.
Returns New Light HSL Saturation Server Model instance.
ESP_BLE_MESH_MODEL_LIGHT_XYL_SRV(srv_pub, srv_data)
Define a new Light xyL Server Model.
Note: 1. The Light xyL Server model extends the Light Lightness Server model. When this model is present
on an Element, the corresponding Light xyL Setup Server model shall also be present.
a. This model shall support model publication and model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_light_xyl_srv_t.
Returns New Light xyL Server Model instance.
ESP_BLE_MESH_MODEL_LIGHT_XYL_SETUP_SRV(srv_pub, srv_data)
Define a new Light xyL Setup Server Model.
Note: 1. The Light xyL Setup Server model extends the Light xyL Server and the Light Lightness Setup
Server.
a. This model shall support model subscription.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_light_xyl_setup_srv_t.
Returns New Light xyL Setup Server Model instance.
ESP_BLE_MESH_MODEL_LIGHT_LC_SRV(srv_pub, srv_data)
Define a new Light LC Server Model.
Note: 1. The Light LC (Lightness Control) Server model extends the Light Lightness Server model and the
Generic OnOff Server model. When this model is present on an Element, the corresponding Light LC Setup
Server model shall also be present.
a. This model shall support model publication and model subscription.
b. This model may be used to represent an element that is a client to a Sensor Server model and controls the
Light Lightness Actual state via defined state bindings.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_light_lc_srv_t.
ESP_BLE_MESH_MODEL_LIGHT_LC_SETUP_SRV(srv_pub, srv_data)
Define a new Light LC Setup Server Model.
Note: 1. The Light LC (Lightness Control) Setup model extends the Light LC Server model.
a. This model shall support model publication and model subscription.
b. This model may be used to configure setup parameters for the Light LC Server model.
Parameters
• srv_pub –Pointer to the unique struct esp_ble_mesh_model_pub_t.
• srv_data –Pointer to the unique struct esp_ble_mesh_light_lc_setup_srv_t.
Returns New Light LC Setup Server Model instance.
Type Definitions
typedef void (*esp_ble_mesh_light_client_cb_t)(esp_ble_mesh_light_client_cb_event_t event,
esp_ble_mesh_light_client_cb_param_t *param)
Bluetooth Mesh Light Client Model function.
Lighting Client Model callback function type
Param event Event type
Param param Pointer to callback parameter
typedef void (*esp_ble_mesh_lighting_server_cb_t)(esp_ble_mesh_lighting_server_cb_event_t event,
esp_ble_mesh_lighting_server_cb_param_t *param)
Bluetooth Mesh Lighting Server Model function.
Lighting Server Model callback function type
Param event Event type
Param param Pointer to callback parameter
Enumerations
enum esp_ble_mesh_light_client_cb_event_t
This enum value is the event of Lighting Client Model
Values:
enumerator ESP_BLE_MESH_LIGHT_CLIENT_GET_STATE_EVT
enumerator ESP_BLE_MESH_LIGHT_CLIENT_SET_STATE_EVT
enumerator ESP_BLE_MESH_LIGHT_CLIENT_PUBLISH_EVT
enumerator ESP_BLE_MESH_LIGHT_CLIENT_TIMEOUT_EVT
enumerator ESP_BLE_MESH_LIGHT_CLIENT_EVT_MAX
enum esp_ble_mesh_lc_state_t
This enum value is the Light LC State Machine states
Values:
enumerator ESP_BLE_MESH_LC_OFF
enumerator ESP_BLE_MESH_LC_STANDBY
enumerator ESP_BLE_MESH_LC_FADE_ON
enumerator ESP_BLE_MESH_LC_RUN
enumerator ESP_BLE_MESH_LC_FADE
enumerator ESP_BLE_MESH_LC_PROLONG
enumerator ESP_BLE_MESH_LC_FADE_STANDBY_AUTO
enumerator ESP_BLE_MESH_LC_FADE_STANDBY_MANUAL
enum esp_ble_mesh_lighting_server_cb_event_t
This enum value is the event of Lighting Server Model
Values:
enumerator ESP_BLE_MESH_LIGHTING_SERVER_STATE_CHANGE_EVT
enumerator ESP_BLE_MESH_LIGHTING_SERVER_RECV_GET_MSG_EVT
When get_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to
the application layer when Lighting Get messages are received.
enumerator ESP_BLE_MESH_LIGHTING_SERVER_RECV_SET_MSG_EVT
When set_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback to
the application layer when Lighting Set/Set Unack messages are received.
enumerator ESP_BLE_MESH_LIGHTING_SERVER_RECV_STATUS_MSG_EVT
When status_auto_rsp is set to ESP_BLE_MESH_SERVER_RSP_BY_APP, this event will be callback
to the application layer when Sensor Status message is received.
enumerator ESP_BLE_MESH_LIGHTING_SERVER_EVT_MAX
Overview
Apache MyNewt NimBLE is a highly configurable and BT SIG qualifiable BLE stack providing both host and con-
troller functionalities. ESP-IDF supports NimBLE host stack which is specifically ported for ESP32 platform and
FreeRTOS. The underlying controller is still the same (as in case of Bluedroid) providing VHCI interface. Refer
to NimBLE user guide for a complete list of features and additional information on NimBLE stack. Most features
of NimBLE including BLE Mesh are supported by ESP-IDF. The porting layer is kept cleaner by maintaining all
the existing APIs of NimBLE along with a single ESP-NimBLE API for initialization, making it simpler for the
application developers.
Architecture
Currently, NimBLE host and controller support different transports such as UART and RAM between them. How-
ever, RAM transport cannot be used as is in case of ESP as ESP controller supports VHCI interface and buffering
schemes used by NimBLE host is incompatible with that used by ESP controller. Therefore, a new transport between
NimBLE host and ESP controller has been added. This is depicted in the figure below. This layer is responsible for
maintaining pool of transport buffers and formatting buffers exchanges between host and controller as per the re-
quirements.
Threading Model
The NimBLE host can run inside the application thread or can have its own independent thread. This flexibil-
ity is inherently provided by NimBLE design. By default, a thread is spawned by the porting function nim-
ble_port_freertos_init. This behavior can be changed by overriding the same function. For BLE Mesh,
additional thread (advertising thread) is used which keeps on feeding advertisement events to the main thread.
Programming Sequence
To begin with, make sure that the NimBLE stack is enabled from menuconfig choose NimBLE for the Bluetooth host.
Typical programming sequence with NimBLE stack consists of the following steps:
• Initialize NVS flash using nvs_flash_init() API. This is because ESP controller uses NVS during
initialization.
• Call esp_nimble_hci_and_controller_init() to initialize ESP controller as well as trans-
port layer. This will also link the host and controller modules together. Alternatively, if ESP controller
is already initialized, then esp_nimble_hci_init() can be called for the remaining initialization.
• Initialize the host stack using nimble_port_init.
• Initialize the required NimBLE host configuration parameters and callbacks
• Perform application specific tasks/initialization
• Run the thread for host stack using nimble_port_freertos_init
This documentation does not cover NimBLE APIs. Refer to NimBLE tutorial for more details on the programming
sequence/NimBLE APIs for different scenarios.
API Reference
Header File
• components/bt/host/nimble/esp-hci/include/esp_nimble_hci.h
Functions
esp_err_t esp_nimble_hci_init(void)
Initialize VHCI transport layer between NimBLE Host and ESP Bluetooth controller.
This function initializes the transport buffers to be exchanged between NimBLE host and ESP controller. It
also registers required host callbacks with the controller.
Returns
• ESP_OK if the initialization is successful
• Appropriate error code from esp_err_t in case of an error
esp_err_t esp_nimble_hci_and_controller_init(void)
Initialize ESP Bluetooth controller(link layer) and VHCI transport layer between NimBLE Host and ESP
Bluetooth controller.
This function initializes ESP controller in BLE only mode and the transport buffers to be exchanged between
NimBLE host and ESP controller. It also registers required host callbacks with the controller.
Below is the sequence of APIs to be called to init/enable NimBLE host and ESP controller:
nimble_port_freertos_deinit();
}
return;
}
nimble_port_init();
nimble_port_freertos_init(ble_host_task);
nimble_port_freertos_init() is an optional call that creates a new task in which the NimBLE host will run.
The task function should have a call to nimble_port_run(). If a separate task is not required, calling nim-
ble_port_run() will run the NimBLE host in the current task.
Returns
• ESP_OK if the initialization is successful
• Appropriate error code from esp_err_t in case of an error
esp_err_t esp_nimble_hci_deinit(void)
Deinitialize VHCI transport layer between NimBLE Host and ESP Bluetooth controller.
Note: This function should be called after the NimBLE host is deinitialized.
Returns
• ESP_OK if the deinitialization is successful
• Appropriate error codes from esp_err_t in case of an error
esp_err_t esp_nimble_hci_and_controller_deinit(void)
Deinitialize VHCI transport layer between NimBLE Host and ESP Bluetooth controller and disable and deini-
tialize the controller.
Below is the sequence of APIs to be called to disable/deinit NimBLE host and ESP controller:
ret = esp_nimble_hci_and_controller_deinit();
if (ret != ESP_OK) {
ESP_LOGE(TAG, "esp_nimble_hci_and_controller_deinit() failed with␣
,→error: %d", ret);
}
}
Note: This function should not be executed in the context of Bluetooth host task.
Note: This function should be called after the NimBLE host is deinitialized.
Returns
• ESP_OK if the deinitialization is successful
• Appropriate error codes from esp_err_t in case of an error
Macros
BLE_HCI_UART_H4_NONE
BLE_HCI_UART_H4_CMD
BLE_HCI_UART_H4_ACL
BLE_HCI_UART_H4_SCO
BLE_HCI_UART_H4_EVT
ESP-IDF currently supports two host stacks. The Bluedroid based stack (default) supports classic Bluetooth as well
as BLE. On the other hand, Apache NimBLE based stack is BLE only. For users to make a choice:
• For usecases involving classic Bluetooth as well as BLE, Bluedroid should be used.
• For BLE-only usecases, using NimBLE is recommended. It is less demanding in terms of code footprint and
runtime memory, making it suitable for such scenarios.
For the overview of the ESP32 Bluetooth stack architecture, follow the links below:
• ESP32 Bluetooth Architecture (PDF)
Code examples for this API section are provided in the bluetooth/bluedroid directory of ESP-IDF examples.
The following examples contain detailed walkthroughs:
• GATT Client Example Walkthrough
• GATT Server Service Table Example Walkthrough
• GATT Server Example Walkthrough
ESP_ERR_NVS_NO_FREE_PAGES (0x110d): NVS partition doesn’t contain any empty pages. This may happen
if NVS partition was truncated. Erase the whole partition and call nvs_flash_init again.
ESP_ERR_NVS_VALUE_TOO_LONG (0x110e): Value doesn’t fit into the entry or string or blob length is longer
than supported by the implementation
ESP_ERR_NVS_PART_NOT_FOUND (0x110f): Partition with specified name is not found in the partition table
ESP_ERR_NVS_NEW_VERSION_FOUND (0x1110): NVS partition contains data in new format and cannot be
recognized by this version of code
ESP_ERR_NVS_XTS_ENCR_FAILED (0x1111): XTS encryption failed while writing NVS entry
ESP_ERR_NVS_XTS_DECR_FAILED (0x1112): XTS decryption failed while reading NVS entry
ESP_ERR_NVS_XTS_CFG_FAILED (0x1113): XTS configuration setting failed
ESP_ERR_NVS_XTS_CFG_NOT_FOUND (0x1114): XTS configuration not found
ESP_ERR_NVS_ENCR_NOT_SUPPORTED (0x1115): NVS encryption is not supported in this version
ESP_ERR_NVS_KEYS_NOT_INITIALIZED (0x1116): NVS key partition is uninitialized
ESP_ERR_NVS_CORRUPT_KEY_PART (0x1117): NVS key partition is corrupt
ESP_ERR_NVS_CONTENT_DIFFERS (0x1118): Internal error; never returned by nvs API functions. NVS key is
different in comparison
ESP_ERR_NVS_WRONG_ENCRYPTION (0x1119): NVS partition is marked as encrypted with generic flash en-
cryption. This is forbidden since the NVS encryption works differently.
ESP_ERR_ULP_BASE (0x1200): Offset for ULP-related error codes
ESP_ERR_ULP_SIZE_TOO_BIG (0x1201): Program doesn’t fit into RTC memory reserved for the ULP
ESP_ERR_ULP_INVALID_LOAD_ADDR (0x1202): Load address is outside of RTC memory reserved for the
ULP
ESP_ERR_ULP_DUPLICATE_LABEL (0x1203): More than one label with the same number was defined
ESP_ERR_ULP_UNDEFINED_LABEL (0x1204): Branch instructions references an undefined label
ESP_ERR_ULP_BRANCH_OUT_OF_RANGE (0x1205): Branch target is out of range of B instruction (try replacing
with BX)
ESP_ERR_OTA_BASE (0x1500): Base error code for ota_ops api
ESP_ERR_OTA_PARTITION_CONFLICT (0x1501): Error if request was to write or erase the current running
partition
ESP_ERR_OTA_SELECT_INFO_INVALID (0x1502): Error if OTA data partition contains invalid content
ESP_ERR_OTA_VALIDATE_FAILED (0x1503): Error if OTA app image is invalid
ESP_ERR_OTA_SMALL_SEC_VER (0x1504): Error if the firmware has a secure version less than the running
firmware.
ESP_ERR_OTA_ROLLBACK_FAILED (0x1505): Error if flash does not have valid firmware in passive partition
and hence rollback is not possible
ESP_ERR_OTA_ROLLBACK_INVALID_STATE (0x1506): Error if current active firmware is still marked in
pending validation state (ESP_OTA_IMG_PENDING_VERIFY), essentially first boot of firmware image post up-
grade and hence firmware upgrade is not possible
ESP_ERR_EFUSE (0x1600): Base error code for efuse api.
ESP_OK_EFUSE_CNT (0x1601): OK the required number of bits is set.
ESP_ERR_EFUSE_CNT_IS_FULL (0x1602): Error field is full.
ESP_ERR_EFUSE_REPEATED_PROG (0x1603): Error repeated programming of programmed bits is strictly for-
bidden.
ESP_ERR_ESP_NETIF_DRIVER_ATTACH_FAILED (0x5008)
ESP_ERR_ESP_NETIF_INIT_FAILED (0x5009)
ESP_ERR_ESP_NETIF_DNS_NOT_CONFIGURED (0x500a)
ESP_ERR_ESP_NETIF_MLD6_FAILED (0x500b)
ESP_ERR_ESP_NETIF_IP6_ADDR_FAILED (0x500c)
ESP_ERR_FLASH_BASE (0x6000): Starting number of flash error codes
ESP_ERR_FLASH_OP_FAIL (0x6001)
ESP_ERR_FLASH_OP_TIMEOUT (0x6002)
ESP_ERR_FLASH_NOT_INITIALISED (0x6003)
ESP_ERR_FLASH_UNSUPPORTED_HOST (0x6004)
ESP_ERR_FLASH_UNSUPPORTED_CHIP (0x6005)
ESP_ERR_FLASH_PROTECTED (0x6006)
ESP_ERR_HTTP_BASE (0x7000): Starting number of HTTP error codes
ESP_ERR_HTTP_MAX_REDIRECT (0x7001): The error exceeds the number of HTTP redirects
ESP_ERR_HTTP_CONNECT (0x7002): Error open the HTTP connection
ESP_ERR_HTTP_WRITE_DATA (0x7003): Error write HTTP data
ESP_ERR_HTTP_FETCH_HEADER (0x7004): Error read HTTP header from server
ESP_ERR_HTTP_INVALID_TRANSPORT (0x7005): There are no transport support for the input scheme
ESP_ERR_HTTP_CONNECTING (0x7006): HTTP connection hasn’t been established yet
ESP_ERR_HTTP_EAGAIN (0x7007): Mapping of errno EAGAIN to esp_err_t
ESP_ERR_HTTP_CONNECTION_CLOSED (0x7008): Read FIN from peer and the connection closed
ESP_ERR_ESP_TLS_BASE (0x8000): Starting number of ESP-TLS error codes
ESP_ERR_ESP_TLS_CANNOT_RESOLVE_HOSTNAME (0x8001): Error if hostname couldn’t be resolved upon
tls connection
ESP_ERR_ESP_TLS_CANNOT_CREATE_SOCKET (0x8002): Failed to create socket
ESP_ERR_ESP_TLS_UNSUPPORTED_PROTOCOL_FAMILY (0x8003): Unsupported protocol family
ESP_ERR_ESP_TLS_FAILED_CONNECT_TO_HOST (0x8004): Failed to connect to host
ESP_ERR_ESP_TLS_SOCKET_SETOPT_FAILED (0x8005): failed to set/get socket option
ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT (0x8006): new connection in esp_tls_low_level_conn connec-
tion timeouted
ESP_ERR_ESP_TLS_SE_FAILED (0x8007)
ESP_ERR_ESP_TLS_TCP_CLOSED_FIN (0x8008)
ESP_ERR_MBEDTLS_CERT_PARTLY_OK (0x8010): mbedtls parse certificates was partly successful
ESP_ERR_MBEDTLS_CTR_DRBG_SEED_FAILED (0x8011): mbedtls api returned error
ESP_ERR_MBEDTLS_SSL_SET_HOSTNAME_FAILED (0x8012): mbedtls api returned error
ESP_ERR_MBEDTLS_SSL_CONFIG_DEFAULTS_FAILED (0x8013): mbedtls api returned error
ESP_ERR_MBEDTLS_SSL_CONF_ALPN_PROTOCOLS_FAILED (0x8014): mbedtls api returned error
ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED (0x8015): mbedtls api returned error
ESP_ERR_MBEDTLS_SSL_CONF_OWN_CERT_FAILED (0x8016): mbedtls api returned error
ESP_ERR_MBEDTLS_SSL_SETUP_FAILED (0x8017): mbedtls api returned error
ESP_ERR_MEMPROT_WORLD_INVALID (0xd006)
ESP_ERR_MEMPROT_AREA_INVALID (0xd007)
ESP_ERR_MEMPROT_CPUID_INVALID (0xd008)
ESP_ERR_TCP_TRANSPORT_BASE (0xe000): Starting number of TCP Transport error codes
ESP_ERR_TCP_TRANSPORT_CONNECTION_TIMEOUT (0xe001): Connection has timed out
ESP_ERR_TCP_TRANSPORT_CONNECTION_CLOSED_BY_FIN (0xe002): Read FIN from peer and the con-
nection has closed (in a clean way)
ESP_ERR_TCP_TRANSPORT_CONNECTION_FAILED (0xe003): Failed to connect to the peer
ESP_ERR_TCP_TRANSPORT_NO_MEM (0xe004): Memory allocation failed
2.5.1 Wi-Fi
ESP-NOW
Overview ESP-NOW is a kind of connectionless Wi-Fi communication protocol that is defined by Espressif. In
ESP-NOW, application data is encapsulated in a vendor-specific action frame and then transmitted from one Wi-Fi
device to another without connection. CTR with CBC-MAC Protocol(CCMP) is used to protect the action frame for
security. ESP-NOW is widely used in smart light, remote controlling, sensor, etc.
Frame Format ESP-NOW uses a vendor-specific action frame to transmit ESP-NOW data. The default ESP-
NOW bit rate is 1 Mbps. The format of the vendor-specific action frame is as follows:
-----------------------------------------------------------------------------------
,→-------------------------
• Category Code: The Category Code field is set to the value(127) indicating the vendor-specific category.
• Organization Identifier: The Organization Identifier contains a unique identifier (0x18fe34), which is the first
three bytes of MAC address applied by Espressif.
• Random Value: The Random Value filed is used to prevents relay attacks.
• Vendor Specific Content: The Vendor Specific Content contains vendor-specific fields as follows:
-------------------------------------------------------------------------------
| Element ID | Length | Organization Identifier | Type | Version | Body |
-------------------------------------------------------------------------------
1 byte 1 byte 3 bytes 1 byte 1 byte 0~250 bytes
• Element ID: The Element ID field is set to the value (221), indicating the vendor-specific element.
• Length: The length is the total length of Organization Identifier, Type, Version and Body.
• Organization Identifier: The Organization Identifier contains a unique identifier(0x18fe34), which is the first
three bytes of MAC address applied by Espressif.
• Type: The Type field is set to the value (4) indicating ESP-NOW.
• Version: The Version field is set to the version of ESP-NOW.
• Body: The Body contains the ESP-NOW data.
As ESP-NOW is connectionless, the MAC header is a little different from that of standard frames. The FromDS and
ToDS bits of FrameControl field are both 0. The first address field is set to the destination address. The second address
field is set to the source address. The third address field is set to broadcast address (0xff:0xff:0xff:0xff:0xff:0xff).
Security
ESP-NOW uses the CCMP method, which is described in IEEE Std. 802.11-2012, to protect the vendor-specific action frame
• PMK is used to encrypt LMK with the AES-128 algorithm. Call esp_now_set_pmk() to set PMK.
If PMK is not set, a default PMK will be used.
• LMK of the paired device is used to encrypt the vendor-specific action frame with the CCMP method.
The maximum number of different LMKs is six. If the LMK of the paired device is not set, the vendor-
specific action frame will not be encrypted.
Encrypting multicast vendor-specific action frame is not supported.
Add Paired Device Call esp_now_add_peer() to add the device to the paired device list before you send
data to this device. If security is enabled, the LMK must be set. You can send ESP-NOW data via both the Station
and the SoftAP interface. Make sure that the interface is enabled before sending ESP-NOW data.
The maximum number of paired devices is 20, and the paired encryption devices are no more than 16, the default is
6.
A device with a broadcast MAC address must be added before sending broadcast data. The range of the channel of
paired devices is from 0 to 14. If the channel is set to 0, data will be sent on the current channel. Otherwise, the
channel must be set as the channel that the local device is on.
Application Examples
• Example of sending and receiving ESP-NOW data between two devices: wifi/espnow.
• For more application examples of how to use ESP-NOW, please visit ESP-NOW repository.
API Reference
Header File
• components/esp_wifi/include/esp_now.h
Functions
esp_err_t esp_now_init(void)
Initialize ESPNOW function.
Returns
• ESP_OK : succeed
• ESP_ERR_ESPNOW_INTERNAL : Internal error
esp_err_t esp_now_deinit(void)
De-initialize ESPNOW function.
Returns
• ESP_OK : succeed
esp_err_t esp_now_get_version(uint32_t *version)
Get the version of ESPNOW.
Parameters version –ESPNOW version
Returns
• ESP_OK : succeed
• ESP_ERR_ESPNOW_ARG : invalid argument
esp_err_t esp_now_register_recv_cb(esp_now_recv_cb_t cb)
Register callback function of receiving ESPNOW data.
Parameters cb –callback function of receiving ESPNOW data
Returns
• ESP_OK : succeed
• ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized
• ESP_ERR_ESPNOW_INTERNAL : internal error
esp_err_t esp_now_unregister_recv_cb(void)
Unregister callback function of receiving ESPNOW data.
Returns
• ESP_OK : succeed
• ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized
esp_err_t esp_now_register_send_cb(esp_now_send_cb_t cb)
Register callback function of sending ESPNOW data.
Parameters cb –callback function of sending ESPNOW data
Returns
• ESP_OK : succeed
• ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized
• ESP_ERR_ESPNOW_INTERNAL : internal error
esp_err_t esp_now_unregister_send_cb(void)
Unregister callback function of sending ESPNOW data.
Returns
• ESP_OK : succeed
• ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized
esp_err_t esp_now_send(const uint8_t *peer_addr, const uint8_t *data, size_t len)
Send ESPNOW data.
Attention 1. If peer_addr is not NULL, send data to the peer whose MAC address matches peer_addr
Attention 2. If peer_addr is NULL, send data to all of the peers that are added to the peer list
Attention 3. The maximum length of data must be less than ESP_NOW_MAX_DATA_LEN
Attention 4. The buffer pointed to by data argument does not need to be valid after esp_now_send returns
Parameters
• peer_addr –peer MAC address
• data –data to send
• len –length of data
Returns
• ESP_OK : succeed
• ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized
• ESP_ERR_ESPNOW_ARG : invalid argument
• ESP_ERR_ESPNOW_INTERNAL : internal error
• ESP_ERR_ESPNOW_NO_MEM : out of memory, when this happens, you can delay a
while before sending the next data
• ESP_ERR_ESPNOW_NOT_FOUND : peer is not found
• ESP_ERR_ESPNOW_IF : current WiFi interface doesn’t match that of peer
Parameters
• ifx –Interface to be configured.
• rate –Phy rate to be configured.
Returns
• ESP_OK: succeed
• others: failed
Parameters window –Milliseconds would the chip keep waked each interval, from 0 to 65535.
Returns
• ESP_OK : succeed
• ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized
Structures
struct esp_now_peer_info
ESPNOW peer information parameters.
Public Members
uint8_t peer_addr[ESP_NOW_ETH_ALEN]
ESPNOW peer MAC address that is also the MAC address of station or softap
uint8_t lmk[ESP_NOW_KEY_LEN]
ESPNOW peer local master key that is used to encrypt data
uint8_t channel
Wi-Fi channel that peer uses to send/receive ESPNOW data. If the value is 0, use the current channel
which station or softap is on. Otherwise, it must be set as the channel that station or softap is on.
wifi_interface_t ifidx
Wi-Fi interface that peer uses to send/receive ESPNOW data
bool encrypt
ESPNOW data that this peer sends/receives is encrypted or not
void *priv
ESPNOW peer private data
struct esp_now_peer_num
Number of ESPNOW peers which exist currently.
Public Members
int total_num
Total number of ESPNOW peers, maximum value is ESP_NOW_MAX_TOTAL_PEER_NUM
int encrypt_num
Number of encrypted ESPNOW peers, maximum value is ESP_NOW_MAX_ENCRYPT_PEER_NUM
Macros
ESP_ERR_ESPNOW_BASE
ESPNOW error number base.
ESP_ERR_ESPNOW_NOT_INIT
ESPNOW is not initialized.
ESP_ERR_ESPNOW_ARG
Invalid argument
ESP_ERR_ESPNOW_NO_MEM
Out of memory
ESP_ERR_ESPNOW_FULL
ESPNOW peer list is full
ESP_ERR_ESPNOW_NOT_FOUND
ESPNOW peer is not found
ESP_ERR_ESPNOW_INTERNAL
Internal error
ESP_ERR_ESPNOW_EXIST
ESPNOW peer has existed
ESP_ERR_ESPNOW_IF
Interface error
ESP_NOW_ETH_ALEN
Length of ESPNOW peer MAC address
ESP_NOW_KEY_LEN
Length of ESPNOW peer local master key
ESP_NOW_MAX_TOTAL_PEER_NUM
Maximum number of ESPNOW total peers
ESP_NOW_MAX_ENCRYPT_PEER_NUM
Maximum number of ESPNOW encrypted peers
ESP_NOW_MAX_DATA_LEN
Maximum length of ESPNOW data which is sent very time
Type Definitions
typedef void (*esp_now_recv_cb_t)(const uint8_t *mac_addr, const uint8_t *data, int data_len)
Callback function of receiving ESPNOW data.
Param mac_addr peer MAC address
Param data received data
Param data_len length of received data
Enumerations
enum esp_now_send_status_t
Status of sending ESPNOW data .
Values:
enumerator ESP_NOW_SEND_SUCCESS
Send ESPNOW data successfully
enumerator ESP_NOW_SEND_FAIL
Send ESPNOW data fail
This is a programming guide for ESP-WIFI-MESH, including the API reference and coding examples. This guide is
split into the following parts:
1. ESP-WIFI-MESH Programming Model
2. Writing an ESP-WIFI-MESH Application
3. Self Organized Networking
4. Application Examples
5. API Reference
For documentation regarding the ESP-WIFI-MESH protocol, please see the ESP-WIFI-MESH API Guide. For more
information about ESP-WIFI-MESH Development Framework, please see ESP-WIFI-MESH Development Frame-
work.
Software Stack The ESP-WIFI-MESH software stack is built atop the Wi-Fi Driver/FreeRTOS and may use the
LwIP Stack in some instances (i.e. the root node). The following diagram illustrates the ESP-WIFI-MESH software
stack.
System Events An application interfaces with ESP-WIFI-MESH via ESP-WIFI-MESH Events. Since ESP-
WIFI-MESH is built atop the Wi-Fi stack, it is also possible for the application to interface with the Wi-Fi driver
via the Wi-Fi Event Task. The following diagram illustrates the interfaces for the various System Events in an
ESP-WIFI-MESH application.
The mesh_event_id_t defines all possible ESP-WIFI-MESH events and can indicate events such as the con-
nection/disconnection of parent/child. Before ESP-WIFI-MESH events can be used, the application must register
a Mesh Events handler via esp_event_handler_register() to the default event task. The Mesh Events
handler that is registered contain handlers for each ESP-WIFI-MESH event relevant to the application.
Typical use cases of mesh events include using events such as MESH_EVENT_PARENT_CONNECTED and
MESH_EVENT_CHILD_CONNECTED to indicate when a node can begin transmitting data upstream and down-
stream respectively. Likewise, IP_EVENT_STA_GOT_IP and IP_EVENT_STA_LOST_IP can be used to indi-
cate when the root node can and cannot transmit data to the external IP network.
Warning: When using ESP-WIFI-MESH under self-organized mode, users must ensure that no calls to Wi-
Fi API are made. This is due to the fact that the self-organizing mode will internally make Wi-Fi API calls
to connect/disconnect/scan etc. Any Wi-Fi calls from the application (including calls from callbacks and
handlers of Wi-Fi events) may interfere with ESP-WIFI-MESH’s self-organizing behavior. Therefore,
users should not call Wi-Fi APIs after esp_mesh_start() is called, and before esp_mesh_stop() is
called.
LwIP & ESP-WIFI-MESH The application can access the ESP-WIFI-MESH stack directly without having to
go through the LwIP stack. The LwIP stack is only required by the root node to transmit/receive data to/from an
external IP network. However, since every node can potentially become the root node (due to automatic root node
selection), each node must still initialize the LwIP stack.
Each node that could become root is required to initialize LwIP by calling esp_netif_init(). In order
to prevent non-root node access to LwIP, the application should not create or register any network interfaces using
esp_netif APIs.
ESP-WIFI-MESH requires a root node to be connected with a router. Therefore, in the event that a node
becomes the root, the corresponding handler must start the DHCP client service and immediately
obtain an IP address. Doing so will allow other nodes to begin transmitting/receiving packets to/from
the external IP network. However, this step is unnecessary if static IP settings are used.
Writing an ESP-WIFI-MESH Application The prerequisites for starting ESP-WIFI-MESH is to initialize LwIP
and Wi-Fi, The following code snippet demonstrates the necessary prerequisite steps before ESP-WIFI-MESH itself
can be initialized.
ESP_ERROR_CHECK(esp_netif_init());
/* event initialization */
ESP_ERROR_CHECK(esp_event_loop_create_default());
/* Wi-Fi initialization */
wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&config));
/* register IP events handler */
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &ip_
,→event_handler, NULL));
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_FLASH));
ESP_ERROR_CHECK(esp_wifi_start());
After initializing LwIP and Wi-Fi, the process of getting an ESP-WIFI-MESH network up and running can be
summarized into the following three steps:
1. Initialize Mesh
2. Configuring an ESP-WIFI-MESH Network
3. Start Mesh
Initialize Mesh The following code snippet demonstrates how to initialize ESP-WIFI-MESH
/* mesh initialization */
ESP_ERROR_CHECK(esp_mesh_init());
/* register mesh events handler */
ESP_ERROR_CHECK(esp_event_handler_register(MESH_EVENT, ESP_EVENT_ANY_ID, &mesh_
,→event_handler, NULL));
Parameter Description
Channel Range from 1 to 14
Mesh ID ID of ESP-WIFI-MESH Network, see mesh_addr_t
Router Router Configuration, see mesh_router_t
Mesh AP Mesh AP Configuration, see mesh_ap_cfg_t
Crypto Functions Crypto Functions for Mesh IE, see mesh_crypto_funcs_t
Start Mesh The following code snippet demonstrates how to start ESP-WIFI-MESH.
/* mesh start */
ESP_ERROR_CHECK(esp_mesh_start());
After starting ESP-WIFI-MESH, the application should check for ESP-WIFI-MESH events to determine when it
has connected to the network. After connecting, the application can start transmitting and receiving packets over the
ESP-WIFI-MESH network using esp_mesh_send() and esp_mesh_recv().
Self Organized Networking Self organized networking is a feature of ESP-WIFI-MESH where nodes can au-
tonomously scan/select/connect/reconnect to other nodes and routers. This feature allows an ESP-WIFI-MESH net-
work to operate with high degree of autonomy by making the network robust to dynamic network topologies and
conditions. With self organized networking enabled, nodes in an ESP-WIFI-MESH network are able to carry out the
following actions without autonomously:
• Selection or election of the root node (see Automatic Root Node Selection in Building a Network)
• Selection of a preferred parent node (see Parent Node Selection in Building a Network)
• Automatic reconnection upon detecting a disconnection (see Intermediate Parent Node Failure in Managing
a Network)
When self organized networking is enabled, the ESP-WIFI-MESH stack will internally make calls to Wi-Fi APIs.
Therefore, the application layer should not make any calls to Wi-Fi APIs whilst self organized networking is
enabled as doing so would risk interfering with ESP-WIFI-MESH.
Toggling Self Organized Networking Self organized networking can be enabled or disabled by the application
at runtime by calling the esp_mesh_set_self_organized() function. The function has the two following
parameters:
• bool enable specifies whether to enable or disable self organized networking.
• bool select_parent specifies whether a new parent node should be selected when enabling self orga-
nized networking. Selecting a new parent has different effects depending the node type and the node’s current
state. This parameter is unused when disabling self organized networking.
Disabling Self Organized Networking The following code snippet demonstrates how to disable self organized
networking.
ESP-WIFI-MESH will attempt to maintain the node’s current Wi-Fi state when disabling self organized networking.
• If the node was previously connected to other nodes, it will remain connected.
• If the node was previously disconnected and was scanning for a parent node or router, it will stop scanning.
• If the node was previously attempting to reconnect to a parent node or router, it will stop reconnecting.
Enabling Self Organized Networking ESP-WIFI-MESH will attempt to maintain the node’s current Wi-Fi state
when enabling self organized networking. However, depending on the node type and whether a new parent is selected,
the Wi-Fi state of the node can change. The following table shows effects of enabling self organized networking.
Y
• A root node already con-
nected to router will stay con-
nected.
• A root node disconnected
from router will need to call
esp_mesh_connect()
to reconnect.
Y N
• Nodes without a parent node
will automatically select a
preferred parent and connect.
• Nodes already connected to
a parent node will discon-
nect, reselect a preferred par-
ent node, and connect.
Y
• For a root node to connect to
a parent node, it must give up
it’s role as root. Therefore,
a root node will disconnect
from the router and all child
nodes, select a preferred par-
ent node, and connect.
The following code snipping demonstrates how to enable self organized networking.
...
Calling Wi-Fi API There can be instances in which an application may want to directly call Wi-Fi API whilst
using ESP-WIFI-MESH. For example, an application may want to manually scan for neighboring APs. However,
self organized networking must be disabled before the application calls any Wi-Fi APIs. This will prevent the
ESP-WIFI-MESH stack from attempting to call any Wi-Fi APIs and potentially interfering with the application’s
calls.
Therefore, application calls to Wi-Fi APIs should be placed in between calls of
esp_mesh_set_self_organized() which disable and enable self organized networking. The follow-
ing code snippet demonstrates how an application can safely call esp_wifi_scan_start() whilst using
ESP-WIFI-MESH.
...
...
...
API Reference
Header File
• components/esp_wifi/include/esp_mesh.h
Functions
esp_err_t esp_mesh_init(void)
Mesh initialization.
Returns
• ESP_OK
• ESP_FAIL
esp_err_t esp_mesh_deinit(void)
Mesh de-initialization.
Returns
• ESP_OK
• ESP_FAIL
esp_err_t esp_mesh_start(void)
Start mesh.
Attention This API shall be called after mesh initialization and configuration.
Returns
• ESP_OK
• ESP_FAIL
• ESP_ERR_MESH_NOT_INIT
• ESP_ERR_MESH_NOT_CONFIG
• ESP_ERR_MESH_NO_MEMORY
esp_err_t esp_mesh_stop(void)
Stop mesh.
Returns
• ESP_OK
• ESP_FAIL
esp_err_t esp_mesh_send(const mesh_addr_t *to, const mesh_data_t *data, int flag, const mesh_opt_t opt[],
int opt_count)
Send a packet over the mesh network.
Parameters
• to –[in] the address of the final destination of the packet
– If the packet is to the root, set this parameter to NULL.
– If the packet is to an external IP network, set this parameter to the IPv4:PORT combi-
nation. This packet will be delivered to the root firstly, then the root will forward this
packet to the final IP server address.
• data –[in] pointer to a sending mesh packet
– Field size should not exceed MESH_MPS. Note that the size of one mesh packet should
not exceed MESH_MTU.
– Field proto should be set to data protocol in use (default is MESH_PROTO_BIN for
binary).
– Field tos should be set to transmission tos (type of service) in use (default is
MESH_TOS_P2P for point-to-point reliable).
• flag –[in] bitmap for data sent
– Speed up the route search
∗ If the packet is to the root and “to”parameter is NULL, set this parameter to 0.
∗ If the packet is to an internal device, MESH_DATA_P2P should be set.
∗ If the packet is to the root (“to”parameter isn’t NULL) or to external IP network,
MESH_DATA_TODS should be set.
∗ If the packet is from the root to an internal device, MESH_DATA_FROMDS should
be set.
– Specify whether this API is block or non-block, block by default
∗ If needs non-blocking, MESH_DATA_NONBLOCK should be set. Otherwise, may
use esp_mesh_send_block_time() to specify a blocking time.
– In the situation of the root change, MESH_DATA_DROP identifies this packet can be
dropped by the new root for upstream data to external IP network, we try our best to
avoid data loss caused by the root change, but there is a risk that the new root is running
out of memory because most of memory is occupied by the pending data which isn’t
read out in time by esp_mesh_recv_toDS().
Generally, we suggest esp_mesh_recv_toDS() is called after a connection with IP net-
work is created. Thus data outgoing to external IP network via socket is just from
reading esp_mesh_recv_toDS() which avoids unnecessary memory copy.
• opt –[in] options
– In case of sending a packet to a certain group, MESH_OPT_SEND_GROUP is a good
choice. In this option, the value field should be set to the target receiver addresses in
this group.
– Root sends a packet to an internal device, this packet is from external IP network in case
the receiver device responds this packet, MESH_OPT_RECV_DS_ADDR is required
to attach the target DS address.
• opt_count –[in] option count
– Currently, this API only takes one option, so opt_count is only supported to be 1.
Returns
• ESP_OK
• ESP_FAIL
• ESP_ERR_MESH_ARGUMENT
• ESP_ERR_MESH_NOT_START
• ESP_ERR_MESH_DISCONNECTED
• ESP_ERR_MESH_OPT_UNKNOWN
• ESP_ERR_MESH_EXCEED_MTU
• ESP_ERR_MESH_NO_MEMORY
• ESP_ERR_MESH_TIMEOUT
• ESP_ERR_MESH_QUEUE_FULL
• ESP_ERR_MESH_NO_ROUTE_FOUND
• ESP_ERR_MESH_DISCARD
esp_err_t esp_mesh_recv(mesh_addr_t *from, mesh_data_t *data, int timeout_ms, int *flag, mesh_opt_t
opt[], int opt_count)
Receive a packet targeted to self over the mesh network.
Parameters
• from –[out] the address of the original source of the packet
• data –[out] pointer to the received mesh packet
– Field proto is the data protocol in use. Should follow it to parse the received data.
– Field tos is the transmission tos (type of service) in use.
• timeout_ms –[in] wait time if a packet isn’t immediately available (0:no wait, port-
MAX_DELAY:wait forever)
• flag –[out] bitmap for data received
– MESH_DATA_FROMDS represents data from external IP network
– MESH_DATA_TODS represents data directed upward within the mesh network
• opt –[out] options desired to receive
– MESH_OPT_RECV_DS_ADDR attaches the DS address
• opt_count –[in] option count desired to receive
– Currently, this API only takes one option, so opt_count is only supported to be 1.
Returns
• ESP_OK
• ESP_ERR_MESH_ARGUMENT
• ESP_ERR_MESH_NOT_START
• ESP_ERR_MESH_TIMEOUT
• ESP_ERR_MESH_DISCARD
• If no socket connection is ready to send out the received packets and this esp_mesh_recv_toDS() hasn’
t been called by applications, packets from the whole mesh network will be pending in toDS queue.
Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting to be received
by applications in case of running out of memory in the root.
Using esp_mesh_set_xon_qsize() users may configure the RX queue size, default:32. If this size is too large,
and esp_mesh_recv_toDS() isn’t called in time, there is a risk that a great deal of memory is occupied by the
pending packets. If this size is too small, it will impact the efficiency on upstream. How to decide this value
depends on the specific application scenarios.
Parameters
• from –[out] the address of the original source of the packet
• to –[out] the address contains remote IP address and port (IPv4:PORT)
• data –[out] pointer to the received packet
– Contain the protocol and applications should follow it to parse the data.
• timeout_ms –[in] wait time if a packet isn’t immediately available (0:no wait, port-
MAX_DELAY:wait forever)
• flag –[out] bitmap for data received
– MESH_DATA_TODS represents the received data target to external IP network. Root
shall forward this data to external IP network via the association with router.
• opt –[out] options desired to receive
• opt_count –[in] option count desired to receive
Returns
• ESP_OK
• ESP_ERR_MESH_ARGUMENT
• ESP_ERR_MESH_NOT_START
• ESP_ERR_MESH_TIMEOUT
• ESP_ERR_MESH_DISCARD
• ESP_ERR_MESH_RECV_RELEASE
Attention This API shall be called before mesh is started after mesh is initialized.
Attention This API is used to dynamically modify the router configuration after mesh is configured.
Attention This API is used to dynamically modify the mesh network ID.
mesh_type_t esp_mesh_get_type(void)
Get device type over mesh network.
Attention This API shall be called after having received the event
MESH_EVENT_PARENT_CONNECTED.
int esp_mesh_get_max_layer(void)
Get max layer value.
Returns max layer value
esp_err_t esp_mesh_set_ap_password(const uint8_t *pwd, int len)
Set mesh softAP password.
Parameters
• pwd –[in] pointer to the password
• len –[in] password length
Returns
• ESP_OK
• ESP_ERR_MESH_ARGUMENT
• ESP_ERR_MESH_NOT_ALLOWED
• ESP_OK
• ESP_ERR_MESH_ARGUMENT
• ESP_ERR_MESH_NOT_ALLOWED
wifi_auth_mode_t esp_mesh_get_ap_authmode(void)
Get mesh softAP authentication mode.
Returns authentication mode
esp_err_t esp_mesh_set_ap_connections(int connections)
Set mesh max connection value.
• Set mesh softAP max connection = mesh max connection + non-mesh max connection
int esp_mesh_get_ap_connections(void)
Get mesh max connection configuration.
Returns the number of mesh max connections
int esp_mesh_get_non_mesh_connections(void)
Get non-mesh max connection configuration.
Returns the number of non-mesh max connections
int esp_mesh_get_layer(void)
Get current layer value over the mesh network.
Attention This API shall be called after having received the event
MESH_EVENT_PARENT_CONNECTED.
Attention This API shall be called after having received the event
MESH_EVENT_PARENT_CONNECTED.
bool esp_mesh_is_root(void)
Return whether the device is the root node of the network.
Returns true/false
• Self-organized networking has three main functions: select the root node; find a preferred parent; initiate
reconnection if a disconnection is detected.
• Self-organized networking is enabled by default.
• If self-organized is disabled, users should set a parent for the device via esp_mesh_set_parent().
Attention This API is used to dynamically modify whether to enable the self organizing.
Parameters
• enable –[in] enable or disable self-organized networking
• select_parent –[in] Only valid when self-organized networking is enabled.
– if select_parent is set to true, the root will give up its mesh root status and search for a
new parent like other non-root devices.
Returns
• ESP_OK
• ESP_FAIL
bool esp_mesh_get_self_organized(void)
Return whether enable self-organized networking or not.
Returns true/false
esp_err_t esp_mesh_waive_root(const mesh_vote_t *vote, int reason)
Cause the root device to give up (waive) its mesh root status.
• A device is elected root primarily based on RSSI from the external router.
• If external router conditions change, users can call this API to perform a root switch.
• In this API, users could specify a desired root address to replace itself or specify an attempts value to
ask current root to initiate a new round of voting. During the voting, a better root candidate would be
expected to find to replace the current one.
• If no desired root candidate, the vote will try a specified number of attempts (at least 15). If no better
root candidate is found, keep the current one. If a better candidate is found, the new better one will send
a root switch request to the current root, current root will respond with a root switch acknowledgment.
• After that, the new candidate will connect to the router to be a new root, the previous root will disconnect
with the router and choose another parent instead.
Root switch is completed with minimal disruption to the whole mesh network.
Parameters
• vote –[in] vote configuration
– If this parameter is set NULL, the vote will perform the default 15 times.
– Field percentage threshold is 0.9 by default.
– Field is_rc_specified shall be false.
– Field attempts shall be at least 15 times.
• reason –[in] only accept MESH_VOTE_REASON_ROOT_INITIATED for now
Returns
• ESP_OK
• ESP_ERR_MESH_QUEUE_FULL
• ESP_ERR_MESH_DISCARD
• ESP_FAIL
• During the networking, only obtaining vote percentage reaches this threshold, the device could be a root.
float esp_mesh_get_vote_percentage(void)
Get vote percentage threshold for approval of being a root.
Returns percentage threshold
esp_err_t esp_mesh_set_ap_assoc_expire(int seconds)
Set mesh softAP associate expired time (default:10 seconds)
• If mesh softAP hasn’t received any data from an associated child within this time, mesh softAP will
take this child inactive and disassociate it.
• If mesh softAP is encrypted, this value should be set a greater value, such as 30 seconds.
int esp_mesh_get_ap_assoc_expire(void)
Get mesh softAP associate expired time.
Returns seconds
int esp_mesh_get_total_node_num(void)
Get total number of devices in current network (including the root)
Attention The returned value might be incorrect when the network is changing.
int esp_mesh_get_routing_table_size(void)
Get the number of devices in this device’s sub-network (including self)
Returns the number of devices over this device’s sub-network (including self)
esp_err_t esp_mesh_get_routing_table(mesh_addr_t *mac, int len, int *size)
Get routing table of this device’s sub-network (including itself)
Parameters
• mac –[out] pointer to routing table
• len –[in] routing table size(in bytes)
• size –[out] pointer to the number of devices in routing table (including itself)
Returns
• ESP_OK
• ESP_ERR_MESH_ARGUMENT
Parameters reachable –[in] this state represents whether the root is able to access external IP
network
Returns
• ESP_OK
• ESP_FAIL
int esp_mesh_get_xon_qsize(void)
Get queue size.
Returns the number of queue
esp_err_t esp_mesh_allow_root_conflicts(bool allowed)
Set whether allow more than one root existing in one network.
Parameters allowed –[in] allow or not
Returns
• ESP_OK
• ESP_WIFI_ERR_NOT_INIT
• ESP_WIFI_ERR_NOT_START
bool esp_mesh_is_root_conflicts_allowed(void)
Check whether allow more than one root to exist in one network.
Returns true/false
esp_err_t esp_mesh_set_group_id(const mesh_addr_t *addr, int num)
Set group ID addresses.
Parameters
• addr –[in] pointer to new group ID addresses
• num –[in] the number of group ID addresses
Returns
• ESP_OK
• ESP_MESH_ERR_ARGUMENT
esp_err_t esp_mesh_delete_group_id(const mesh_addr_t *addr, int num)
Delete group ID addresses.
Parameters
• addr –[in] pointer to deleted group ID address
• num –[in] the number of group ID addresses
Returns
• ESP_OK
• ESP_MESH_ERR_ARGUMENT
int esp_mesh_get_group_num(void)
Get the number of group ID addresses.
Returns the number of group ID addresses
esp_err_t esp_mesh_get_group_list(mesh_addr_t *addr, int num)
Get group ID addresses.
Parameters
• addr –[out] pointer to group ID addresses
• num –[in] the number of group ID addresses
Returns
• ESP_OK
• ESP_MESH_ERR_ARGUMENT
bool esp_mesh_is_my_group(const mesh_addr_t *addr)
Check whether the specified group address is my group.
Returns true/false
esp_err_t esp_mesh_set_capacity_num(int num)
Set mesh network capacity (max:1000, default:300)
int esp_mesh_get_capacity_num(void)
Get mesh network capacity.
Returns mesh network capacity
Attention This API can be called at any time after mesh is initialized.
Attention This API can be called at any time after mesh is initialized.
Parameters
• key –[in] ASCII crypto key
• len –[in] length in bytes, range:8~64
Returns
• ESP_OK
• ESP_MESH_ERR_ARGUMENT
• Enabling fixed root disables automatic election of the root node via voting.
• All devices in the network shall use the same Fixed Root Setting (enabled or disabled).
• If Fixed Root is enabled, users should make sure a root node is designated for the network.
bool esp_mesh_is_root_fixed(void)
Check whether network Fixed Root Setting is enabled.
Returns true/false
Attention This API can be called at any time after mesh is configured.
Parameters
• parent –[in] parent configuration, the SSID and the channel of the parent are mandatory.
– If the BSSID is set, make sure that the SSID and BSSID represent the same parent,
otherwise the device will never find this specified parent.
• parent_mesh_id –[in] parent mesh ID,
– If this value is not set, the original mesh ID is used.
• my_type –[in] mesh type
– MESH_STA is not supported.
– If the parent set for the device is the same as the router in the network configuration,
then my_type shall set MESH_ROOT and my_layer shall set MESH_ROOT_LAYER.
• my_layer –[in] mesh layer
– my_layer of the device may change after joining the network.
– If my_type is set MESH_NODE, my_layer shall be greater than
MESH_ROOT_LAYER.
– If my_type is set MESH_LEAF, the device becomes a standalone Wi-Fi station and no
longer has the ability to extend the network.
Returns
• ESP_OK
• ESP_ERR_ARGUMENT
• ESP_ERR_MESH_NOT_CONFIG
Attention Different from esp_wifi_scan_get_ap_records(), this API only gets one of APs scanned each time.
See “manual_networking”example.
Parameters
• ap_record –[out] pointer to one AP record
• buffer –[out] pointer to the mesh networking IE of this AP
Returns
• ESP_OK
• ESP_ERR_WIFI_NOT_INIT
• ESP_ERR_WIFI_ARG
• ESP_ERR_WIFI_FAIL
esp_err_t esp_mesh_flush_upstream_packets(void)
Flush upstream packets pending in to_parent queue and to_parent_p2p queue.
Returns
• ESP_OK
esp_err_t esp_mesh_get_subnet_nodes_num(const mesh_addr_t *child_mac, int *nodes_num)
Get the number of nodes in the subnet of a specific child.
Parameters
• child_mac –[in] an associated child address of this device
• nodes_num –[out] pointer to the number of nodes in the subnet of a specific child
Returns
• ESP_OK
• ESP_ERR_MESH_NOT_START
• ESP_ERR_MESH_ARGUMENT
esp_err_t esp_mesh_get_subnet_nodes_list(const mesh_addr_t *child_mac, mesh_addr_t *nodes, int
nodes_num)
Get nodes in the subnet of a specific child.
Parameters
• child_mac –[in] an associated child address of this device
• nodes –[out] pointer to nodes in the subnet of a specific child
• nodes_num –[in] the number of nodes in the subnet of a specific child
Returns
• ESP_OK
• ESP_ERR_MESH_NOT_START
• ESP_ERR_MESH_ARGUMENT
esp_err_t esp_mesh_disconnect(void)
Disconnect from current parent.
Returns
• ESP_OK
esp_err_t esp_mesh_connect(void)
Connect to current parent.
Returns
• ESP_OK
esp_err_t esp_mesh_flush_scan_result(void)
Flush scan result.
Returns
• ESP_OK
esp_err_t esp_mesh_switch_channel(const uint8_t *new_bssid, int csa_newchan, int csa_count)
Cause the root device to add Channel Switch Announcement Element (CSA IE) to beacon.
Parameters
• new_bssid –[in] the new router BSSID if the router changes
• csa_newchan –[in] the new channel number to which the whole network is moving
• csa_count –[in] channel switch period(beacon count), unit is based on beacon interval
of its softAP, the default value is 15.
Returns
• ESP_OK
esp_mesh_topology_t esp_mesh_get_topology(void)
Get mesh topology.
Returns MESH_TOPO_TREE or MESH_TOPO_CHAIN
esp_err_t esp_mesh_enable_ps(void)
Enable mesh Power Save function.
Returns
• ESP_OK
• ESP_ERR_WIFI_NOT_INIT
• ESP_ERR_MESH_NOT_ALLOWED
esp_err_t esp_mesh_disable_ps(void)
Disable mesh Power Save function.
Returns
• ESP_OK
• ESP_ERR_WIFI_NOT_INIT
• ESP_ERR_MESH_NOT_ALLOWED
bool esp_mesh_is_ps_enabled(void)
Check whether the mesh Power Save function is enabled.
Returns true/false
bool esp_mesh_is_device_active(void)
Check whether the device is in active state.
• If the device is not in active state, it will neither transmit nor receive frames.
Returns true/false
Attention This API can be called at any time after mesh is started.
Parameters
• dev_duty –[in] device duty cycle
• dev_duty_type –[in] device PS duty cycle type, not accept
MESH_PS_NETWORK_DUTY_MASTER
Returns
• ESP_OK
• ESP_FAIL
• duration_mins specifies how long the specified nwk_duty will be used. Once duration_mins expires, the
root will take over as the NWK-DUTY-MASTER. If an existing NWK-DUTY-MASTER leaves the
network, the root will take over as the NWK-DUTY-MASTER again.
• duration_mins = (-1) represents nwk_duty will be used until a new NWK-DUTY-MASTER with a dif-
ferent nwk_duty appears.
• Only the root can set duration_mins to (-1).
• If applied_rule is set to MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE, the nwk_duty will be
used by the entire network.
• If applied_rule is set to MESH_PS_NETWORK_DUTY_APPLIED_UPLINK, the nwk_duty will only
be used by the up-link path nodes.
• The root does not accept MESH_PS_NETWORK_DUTY_APPLIED_UPLINK.
• A nwk_duty with duration_mins(-1) set by the root is the default network duty cycle used by the entire
network.
Attention This API can be called at any time after mesh is started.
• In self-organized network, if this API is called before mesh is started in all devices, (1)nwk_duty
shall be set to the same value for all devices; (2)duration_mins shall be set to (-1); (3)applied_rule
shall be set to MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE; after the voted root appears,
the root will become the NWK-DUTY-MASTER and broadcast the nwk_duty and its identity of
NWK-DUTY-MASTER.
• If the root is specified (FIXED-ROOT), call this API in the root to provide a default nwk_duty for
the entire network.
• After joins the network, any device can call this API to change the nwk_duty, duration_mins or
applied_rule.
Parameters
• nwk_duty –[in] network duty cycle
• duration_mins –[in] duration (unit: minutes)
• applied_rule –[in] only support MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE
Returns
• ESP_OK
• ESP_FAIL
and transmit packets if they do have pending packets for their parents or for their children. Note that
Low-duty-cycle means devices may not be active in most of the time, the latency of data transmission
might be greater.
Unions
union mesh_addr_t
#include <esp_mesh.h> Mesh address.
Public Members
uint8_t addr[6]
mac address
mip_t mip
mip address
union mesh_event_info_t
#include <esp_mesh.h> Mesh event information.
Public Members
mesh_event_channel_switch_t channel_switch
channel switch
mesh_event_child_connected_t child_connected
child connected
mesh_event_child_disconnected_t child_disconnected
child disconnected
mesh_event_routing_table_change_t routing_table
routing table change
mesh_event_connected_t connected
parent connected
mesh_event_disconnected_t disconnected
parent disconnected
mesh_event_no_parent_found_t no_parent
no parent found
mesh_event_layer_change_t layer_change
layer change
mesh_event_toDS_state_t toDS_state
toDS state, devices shall check this state firstly before trying to send packets to external IP network. This
state indicates right now whether the root is capable of sending packets out. If not, devices had better to
wait until this state changes to be MESH_TODS_REACHABLE.
mesh_event_vote_started_t vote_started
vote started
mesh_event_root_address_t root_addr
root address
mesh_event_root_switch_req_t switch_req
root switch request
mesh_event_root_conflict_t root_conflict
other powerful root
mesh_event_root_fixed_t root_fixed
fixed root
mesh_event_scan_done_t scan_done
scan done
mesh_event_network_state_t network_state
network state, such as whether current mesh network has a root.
mesh_event_find_network_t find_network
network found that can join
mesh_event_router_switch_t router_switch
new router information
mesh_event_ps_duty_t ps_duty
PS duty information
union mesh_rc_config_t
#include <esp_mesh.h> Vote address configuration.
Public Members
int attempts
max vote attempts before a new root is elected automatically by mesh network. (min:15, 15 by default)
mesh_addr_t rc_addr
a new root address specified by users for API esp_mesh_waive_root()
Structures
struct mip_t
IP address and port.
Public Members
ip4_addr_t ip4
IP address
uint16_t port
port
struct mesh_event_channel_switch_t
Channel switch information.
Public Members
uint8_t channel
new channel
struct mesh_event_connected_t
Parent connected information.
Public Members
wifi_event_sta_connected_t connected
parent information, same as Wi-Fi event SYSTEM_EVENT_STA_CONNECTED does
uint16_t self_layer
layer
uint8_t duty
parent duty
struct mesh_event_no_parent_found_t
No parent found information.
Public Members
int scan_times
scan times being through
struct mesh_event_layer_change_t
Layer change information.
Public Members
uint16_t new_layer
new layer
struct mesh_event_vote_started_t
vote started information
Public Members
int reason
vote reason, vote could be initiated by children or by the root itself
int attempts
max vote attempts before stopped
mesh_addr_t rc_addr
root address specified by users via API esp_mesh_waive_root()
struct mesh_event_find_network_t
find a mesh network that this device can join
Public Members
uint8_t channel
channel number of the new found network
uint8_t router_bssid[6]
router BSSID
struct mesh_event_root_switch_req_t
Root switch request information.
Public Members
int reason
root switch reason, generally root switch is initialized by users via API esp_mesh_waive_root()
mesh_addr_t rc_addr
the address of root switch requester
struct mesh_event_root_conflict_t
Other powerful root address.
Public Members
int8_t rssi
rssi with router
uint16_t capacity
the number of devices in current network
uint8_t addr[6]
other powerful root address
struct mesh_event_routing_table_change_t
Routing table change.
Public Members
uint16_t rt_size_new
the new value
uint16_t rt_size_change
the changed value
struct mesh_event_root_fixed_t
Root fixed.
Public Members
bool is_fixed
status
struct mesh_event_scan_done_t
Scan done event information.
Public Members
uint8_t number
the number of APs scanned
struct mesh_event_network_state_t
Network state information.
Public Members
bool is_rootless
whether current mesh network has a root
struct mesh_event_ps_duty_t
PS duty information.
Public Members
uint8_t duty
parent or child duty
mesh_event_child_connected_t child_connected
child info
struct mesh_opt_t
Mesh option.
Public Members
uint8_t type
option type
uint16_t len
option length
uint8_t *val
option value
struct mesh_data_t
Mesh data for esp_mesh_send() and esp_mesh_recv()
Public Members
uint8_t *data
data
uint16_t size
data size
mesh_proto_t proto
data protocol
mesh_tos_t tos
data type of service
struct mesh_router_t
Router configuration.
Public Members
uint8_t ssid[32]
SSID
uint8_t ssid_len
length of SSID
uint8_t bssid[6]
BSSID, if this value is specified, users should also specify “allow_router_switch”.
uint8_t password[64]
password
bool allow_router_switch
if the BSSID is specified and this value is also set, when the router of this specified BSSID fails to be
found after “fail”(mesh_attempts_t) times, the whole network is allowed to switch to another router
with the same SSID. The new router might also be on a different channel. The default value is false.
There is a risk that if the password is different between the new switched router and the previous one, the
mesh network could be established but the root will never connect to the new switched router.
struct mesh_ap_cfg_t
Mesh softAP configuration.
Public Members
uint8_t password[64]
mesh softAP password
uint8_t max_connection
max number of stations allowed to connect in, default 6, max 10 = max_connection + non-
mesh_max_connection max mesh connections
uint8_t nonmesh_max_connection
max non-mesh connections
struct mesh_cfg_t
Mesh initialization configuration.
Public Members
uint8_t channel
channel, the mesh network on
bool allow_channel_switch
if this value is set, when “fail”(mesh_attempts_t) times is reached, device will change to a full channel
scan for a network that could join. The default value is false.
mesh_addr_t mesh_id
mesh network identification
mesh_router_t router
router configuration
mesh_ap_cfg_t mesh_ap
mesh softAP configuration
struct mesh_vote_t
Vote.
Public Members
float percentage
vote percentage threshold for approval of being a root
bool is_rc_specified
if true, rc_addr shall be specified (Unimplemented). if false, attempts value shall be specified to make
network start root election.
mesh_rc_config_t config
vote address configuration
struct mesh_tx_pending_t
The number of packets pending in the queue waiting to be sent by the mesh stack.
Public Members
int to_parent
to parent queue
int to_parent_p2p
to parent (P2P) queue
int to_child
to child queue
int to_child_p2p
to child (P2P) queue
int mgmt
management queue
int broadcast
broadcast and multicast queue
struct mesh_rx_pending_t
The number of packets available in the queue waiting to be received by applications.
Public Members
int toDS
to external DS
int toSelf
to self
Macros
MESH_ROOT_LAYER
root layer value
MESH_MTU
max transmit unit(in bytes)
MESH_MPS
max payload size(in bytes)
ESP_ERR_MESH_WIFI_NOT_START
Mesh error code definition.
Wi-Fi isn’t started
ESP_ERR_MESH_NOT_INIT
mesh isn’t initialized
ESP_ERR_MESH_NOT_CONFIG
mesh isn’t configured
ESP_ERR_MESH_NOT_START
mesh isn’t started
ESP_ERR_MESH_NOT_SUPPORT
not supported yet
ESP_ERR_MESH_NOT_ALLOWED
operation is not allowed
ESP_ERR_MESH_NO_MEMORY
out of memory
ESP_ERR_MESH_ARGUMENT
illegal argument
ESP_ERR_MESH_EXCEED_MTU
packet size exceeds MTU
ESP_ERR_MESH_TIMEOUT
timeout
ESP_ERR_MESH_DISCONNECTED
disconnected with parent on station interface
ESP_ERR_MESH_QUEUE_FAIL
queue fail
ESP_ERR_MESH_QUEUE_FULL
queue full
ESP_ERR_MESH_NO_PARENT_FOUND
no parent found to join the mesh network
ESP_ERR_MESH_NO_ROUTE_FOUND
no route found to forward the packet
ESP_ERR_MESH_OPTION_NULL
no option found
ESP_ERR_MESH_OPTION_UNKNOWN
unknown option
ESP_ERR_MESH_XON_NO_WINDOW
no window for software flow control on upstream
ESP_ERR_MESH_INTERFACE
low-level Wi-Fi interface error
ESP_ERR_MESH_DISCARD_DUPLICATE
discard the packet due to the duplicate sequence number
ESP_ERR_MESH_DISCARD
discard the packet
ESP_ERR_MESH_VOTING
vote in progress
ESP_ERR_MESH_XMIT
XMIT
ESP_ERR_MESH_QUEUE_READ
error in reading queue
ESP_ERR_MESH_PS
mesh PS is not specified as enable or disable
ESP_ERR_MESH_RECV_RELEASE
release esp_mesh_recv_toDS
MESH_DATA_ENC
Flags bitmap for esp_mesh_send() and esp_mesh_recv()
data encrypted (Unimplemented)
MESH_DATA_P2P
point-to-point delivery over the mesh network
MESH_DATA_FROMDS
receive from external IP network
MESH_DATA_TODS
identify this packet is target to external IP network
MESH_DATA_NONBLOCK
esp_mesh_send() non-block
MESH_DATA_DROP
in the situation of the root having been changed, identify this packet can be dropped by new root
MESH_DATA_GROUP
identify this packet is target to a group address
MESH_OPT_SEND_GROUP
Option definitions for esp_mesh_send() and esp_mesh_recv()
data transmission by group; used with esp_mesh_send() and shall have payload
MESH_OPT_RECV_DS_ADDR
return a remote IP address; used with esp_mesh_send() and esp_mesh_recv()
MESH_ASSOC_FLAG_VOTE_IN_PROGRESS
Flag of mesh networking IE.
vote in progress
MESH_ASSOC_FLAG_NETWORK_FREE
no root in current network
MESH_ASSOC_FLAG_ROOTS_FOUND
root conflict is found
MESH_ASSOC_FLAG_ROOT_FIXED
fixed root
MESH_PS_DEVICE_DUTY_REQUEST
Mesh PS (Power Save) duty cycle type.
requests to join a network PS without specifying a device duty cycle. After the device joins the network, a
network duty cycle will be provided by the network
MESH_PS_DEVICE_DUTY_DEMAND
requests to join a network PS and specifies a demanded device duty cycle
MESH_PS_NETWORK_DUTY_MASTER
indicates the device is the NWK-DUTY-MASTER (network duty cycle master)
MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE
Mesh PS (Power Save) duty cycle applied rule.
MESH_PS_NETWORK_DUTY_APPLIED_UPLINK
MESH_INIT_CONFIG_DEFAULT()
Type Definitions
Enumerations
enum mesh_event_id_t
Enumerated list of mesh event id.
Values:
enumerator MESH_EVENT_STARTED
mesh is started
enumerator MESH_EVENT_STOPPED
mesh is stopped
enumerator MESH_EVENT_CHANNEL_SWITCH
channel switch
enumerator MESH_EVENT_CHILD_CONNECTED
a child is connected on softAP interface
enumerator MESH_EVENT_CHILD_DISCONNECTED
a child is disconnected on softAP interface
enumerator MESH_EVENT_ROUTING_TABLE_ADD
routing table is changed by adding newly joined children
enumerator MESH_EVENT_ROUTING_TABLE_REMOVE
routing table is changed by removing leave children
enumerator MESH_EVENT_PARENT_CONNECTED
parent is connected on station interface
enumerator MESH_EVENT_PARENT_DISCONNECTED
parent is disconnected on station interface
enumerator MESH_EVENT_NO_PARENT_FOUND
no parent found
enumerator MESH_EVENT_LAYER_CHANGE
layer changes over the mesh network
enumerator MESH_EVENT_TODS_STATE
state represents whether the root is able to access external IP network
enumerator MESH_EVENT_VOTE_STARTED
the process of voting a new root is started either by children or by the root
enumerator MESH_EVENT_VOTE_STOPPED
the process of voting a new root is stopped
enumerator MESH_EVENT_ROOT_ADDRESS
the root address is obtained. It is posted by mesh stack automatically.
enumerator MESH_EVENT_ROOT_SWITCH_REQ
root switch request sent from a new voted root candidate
enumerator MESH_EVENT_ROOT_SWITCH_ACK
root switch acknowledgment responds the above request sent from current root
enumerator MESH_EVENT_ROOT_ASKED_YIELD
the root is asked yield by a more powerful existing root. If self organized is disabled and this device is
specified to be a root by users, users should set a new parent for this device. if self organized is enabled,
this device will find a new parent by itself, users could ignore this event.
enumerator MESH_EVENT_ROOT_FIXED
when devices join a network, if the setting of Fixed Root for one device is different from that of its parent,
the device will update the setting the same as its parent’s. Fixed Root Setting of each device is variable
as that setting changes of the root.
enumerator MESH_EVENT_SCAN_DONE
if self-organized networking is disabled, user can call esp_wifi_scan_start() to trigger this event, and add
the corresponding scan done handler in this event.
enumerator MESH_EVENT_NETWORK_STATE
network state, such as whether current mesh network has a root.
enumerator MESH_EVENT_STOP_RECONNECTION
the root stops reconnecting to the router and non-root devices stop reconnecting to their parents.
enumerator MESH_EVENT_FIND_NETWORK
when the channel field in mesh configuration is set to zero, mesh stack will perform a full channel scan
to find a mesh network that can join, and return the channel value after finding it.
enumerator MESH_EVENT_ROUTER_SWITCH
if users specify BSSID of the router in mesh configuration, when the root connects to another router with
the same SSID, this event will be posted and the new router information is attached.
enumerator MESH_EVENT_PS_PARENT_DUTY
parent duty
enumerator MESH_EVENT_PS_CHILD_DUTY
child duty
enumerator MESH_EVENT_PS_DEVICE_DUTY
device duty
enumerator MESH_EVENT_MAX
enum mesh_type_t
Device type.
Values:
enumerator MESH_IDLE
hasn’t joined the mesh network yet
enumerator MESH_ROOT
the only sink of the mesh network. Has the ability to access external IP network
enumerator MESH_NODE
intermediate device. Has the ability to forward packets over the mesh network
enumerator MESH_LEAF
has no forwarding ability
enumerator MESH_STA
connect to router with a standlone Wi-Fi station mode, no network expansion capability
enum mesh_proto_t
Protocol of transmitted application data.
Values:
enumerator MESH_PROTO_BIN
binary
enumerator MESH_PROTO_HTTP
HTTP protocol
enumerator MESH_PROTO_JSON
JSON format
enumerator MESH_PROTO_MQTT
MQTT protocol
enumerator MESH_PROTO_AP
IP network mesh communication of node’s AP interface
enumerator MESH_PROTO_STA
IP network mesh communication of node’s STA interface
enum mesh_tos_t
For reliable transmission, mesh stack provides three type of services.
Values:
enumerator MESH_TOS_P2P
provide P2P (point-to-point) retransmission on mesh stack by default
enumerator MESH_TOS_E2E
provide E2E (end-to-end) retransmission on mesh stack (Unimplemented)
enumerator MESH_TOS_DEF
no retransmission on mesh stack
enum mesh_vote_reason_t
Vote reason.
Values:
enumerator MESH_VOTE_REASON_ROOT_INITIATED
vote is initiated by the root
enumerator MESH_VOTE_REASON_CHILD_INITIATED
vote is initiated by children
enum mesh_disconnect_reason_t
Mesh disconnect reason code.
Values:
enumerator MESH_REASON_CYCLIC
cyclic is detected
enumerator MESH_REASON_PARENT_IDLE
parent is idle
enumerator MESH_REASON_LEAF
the connected device is changed to a leaf
enumerator MESH_REASON_DIFF_ID
in different mesh ID
enumerator MESH_REASON_ROOTS
root conflict is detected
enumerator MESH_REASON_PARENT_STOPPED
parent has stopped the mesh
enumerator MESH_REASON_SCAN_FAIL
scan fail
enumerator MESH_REASON_IE_UNKNOWN
unknown IE
enumerator MESH_REASON_WAIVE_ROOT
waive root
enumerator MESH_REASON_PARENT_WORSE
parent with very poor RSSI
enumerator MESH_REASON_EMPTY_PASSWORD
use an empty password to connect to an encrypted parent
enumerator MESH_REASON_PARENT_UNENCRYPTED
connect to an unencrypted parent/router
enum esp_mesh_topology_t
Mesh topology.
Values:
enumerator MESH_TOPO_TREE
tree topology
enumerator MESH_TOPO_CHAIN
chain topology
enum mesh_event_toDS_state_t
The reachability of the root to a DS (distribute system)
Values:
enumerator MESH_TODS_UNREACHABLE
the root isn’t able to access external IP network
enumerator MESH_TODS_REACHABLE
the root is able to access external IP network
SmartConfig
The SmartConfigTM is a provisioning technology developed by TI to connect a new Wi-Fi device to a Wi-Fi network.
It uses a mobile app to broadcast the network credentials from a smartphone, or a tablet, to an un-provisioned Wi-Fi
device.
The advantage of this technology is that the device does not need to directly know SSID or password of an Access
Point (AP). This information is provided using the smartphone. This is particularly important to headless device and
systems, due to their lack of a user interface.
If you are looking for other options to provision your ESP32 devices, check Provisioning API.
API Reference
Header File
• components/esp_wifi/include/esp_smartconfig.h
Functions
const char *esp_smartconfig_get_version(void)
Get the version of SmartConfig.
Returns
• SmartConfig version const char.
esp_err_t esp_smartconfig_start(const smartconfig_start_config_t *config)
Start SmartConfig, config ESP device to connect AP. You need to broadcast information by phone APP. Device
sniffer special packets from the air that containing SSID and password of target AP.
esp_err_t esp_smartconfig_stop(void)
Stop SmartConfig, free the buffer taken by esp_smartconfig_start.
Attention Whether connect to AP succeed or not, this API should be called to free memory taken by smart-
config_start.
Returns
• ESP_OK: succeed
• others: fail
Attention Timing starts from SC_STATUS_FIND_CHANNEL status. SmartConfig will restart if timeout.
Attention If users need to set the SmartConfig type, please set it before calling esp_smartconfig_start.
Structures
struct smartconfig_event_got_ssid_pswd_t
Argument structure for SC_EVENT_GOT_SSID_PSWD event
Public Members
uint8_t ssid[32]
SSID of the AP. Null terminated string.
uint8_t password[64]
Password of the AP. Null terminated string.
bool bssid_set
whether set MAC address of target AP or not.
uint8_t bssid[6]
MAC address of target AP.
smartconfig_type_t type
Type of smartconfig(ESPTouch or AirKiss).
uint8_t token
Token from cellphone which is used to send ACK to cellphone.
uint8_t cellphone_ip[4]
IP address of cellphone.
struct smartconfig_start_config_t
Configure structure for esp_smartconfig_start
Public Members
bool enable_log
Enable smartconfig logs.
bool esp_touch_v2_enable_crypt
Enable ESPTouch v2 crypt.
char *esp_touch_v2_key
ESPTouch v2 crypt key, len should be 16.
Macros
SMARTCONFIG_START_CONFIG_DEFAULT()
Enumerations
enum smartconfig_type_t
Values:
enumerator SC_TYPE_ESPTOUCH
protocol: ESPTouch
enumerator SC_TYPE_AIRKISS
protocol: AirKiss
enumerator SC_TYPE_ESPTOUCH_AIRKISS
protocol: ESPTouch and AirKiss
enumerator SC_TYPE_ESPTOUCH_V2
protocol: ESPTouch v2
enum smartconfig_event_t
Smartconfig event declarations
Values:
enumerator SC_EVENT_SCAN_DONE
ESP32 station smartconfig has finished to scan for APs
enumerator SC_EVENT_FOUND_CHANNEL
ESP32 station smartconfig has found the channel of the target AP
enumerator SC_EVENT_GOT_SSID_PSWD
ESP32 station smartconfig got the SSID and password
enumerator SC_EVENT_SEND_ACK_DONE
ESP32 station smartconfig has sent ACK to cellphone
Wi-Fi
Introduction The Wi-Fi libraries provide support for configuring and monitoring the ESP32 Wi-Fi networking
functionality. This includes configuration for:
• Station mode (aka STA mode or Wi-Fi client mode). ESP32 connects to an access point.
• AP mode (aka Soft-AP mode or Access Point mode). Stations connect to the ESP32.
• Station/AP-coexistence mode (ESP32 is concurrently an access point and a station connected to another access
point).
• Various security modes for the above (WPA, WPA2, WEP, etc.)
• Scanning for access points (active & passive scanning).
• Promiscuous mode for monitoring of IEEE802.11 Wi-Fi packets.
Application Examples The wifi directory of ESP-IDF examples contains the following applications:
• Code examples for Wi-Fi.
• A simple esp-idf-template application to demonstrate a minimal IDF project structure.
API Reference
Header File
• components/esp_wifi/include/esp_wifi.h
Functions
esp_err_t esp_wifi_init(const wifi_init_config_t *config)
Initialize WiFi Allocate resource for WiFi driver, such as WiFi control structure, RX/TX buffer, WiFi NVS
structure etc. This WiFi also starts WiFi task.
Attention 1. This API must be called before all other WiFi API can be called
Attention 2. Always use WIFI_INIT_CONFIG_DEFAULT macro to initialize the configuration to default
values, this can guarantee all the fields get correct value when more fields are added into wifi_init_config_t
in future release. If you want to set your own initial values, overwrite the default values which are set
by WIFI_INIT_CONFIG_DEFAULT. Please be notified that the field ‘magic’of wifi_init_config_t
should always be WIFI_INIT_CONFIG_MAGIC!
Parameters config –pointer to WiFi initialized configuration structure; can point to a temporary
variable.
Returns
• ESP_OK: succeed
• ESP_ERR_NO_MEM: out of memory
• others: refer to error code esp_err.h
esp_err_t esp_wifi_deinit(void)
Deinit WiFi Free all resource allocated in esp_wifi_init and stop WiFi task.
Attention 1. This API should be called if you want to remove WiFi driver from the system
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
esp_err_t esp_wifi_connect(void)
Connect the ESP32 WiFi station to the AP.
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start
• ESP_ERR_WIFI_CONN: WiFi internal error, station or soft-AP control block wrong
• ESP_ERR_WIFI_SSID: SSID of AP which station connects is invalid
esp_err_t esp_wifi_disconnect(void)
Disconnect the ESP32 WiFi station from the AP.
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi was not initialized by esp_wifi_init
• ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start
• ESP_FAIL: other WiFi internal errors
esp_err_t esp_wifi_clear_fast_connect(void)
Currently this API is just an stub API.
Returns
• ESP_OK: succeed
• others: fail
esp_err_t esp_wifi_deauth_sta(uint16_t aid)
deauthenticate all stations or associated id equals to aid
Parameters aid –when aid is 0, deauthenticate all stations, otherwise deauthenticate station
whose associated id is aid
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start
• ESP_ERR_INVALID_ARG: invalid argument
• ESP_ERR_WIFI_MODE: WiFi mode is wrong
esp_err_t esp_wifi_scan_start(const wifi_scan_config_t *config, bool block)
Scan all available APs.
Attention If this API is called, the found APs are stored in WiFi driver dynamic allocated memory and the
will be freed in esp_wifi_scan_get_ap_records, so generally, call esp_wifi_scan_get_ap_records to cause
the memory to be freed once the scan is done
Attention The values of maximum active scan time and passive scan time per channel are limited to 1500
milliseconds. Values above 1500ms may cause station to disconnect from AP and are not recommended.
Parameters
• config –configuration of scanning
• block –if block is true, this API will block the caller until the scan is done, otherwise it
will return immediately
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start
• ESP_ERR_WIFI_TIMEOUT: blocking scan is timeout
• ESP_ERR_WIFI_STATE: wifi still connecting when invoke esp_wifi_scan_start
• others: refer to error code in esp_err.h
esp_err_t esp_wifi_scan_stop(void)
Stop the scan in process.
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start
esp_err_t esp_wifi_scan_get_ap_num(uint16_t *number)
Get number of APs found in last scan.
Attention This API can only be called when the scan is completed, otherwise it may get wrong value.
Attention When the obtained country information is empty, it means that the AP does not carry country
information
Parameters ap_info –the wifi_ap_record_t to hold AP information sta can get the connected
ap’s phy mode info through the struct member phy_11b,phy_11g,phy_11n,phy_lr in the
wifi_ap_record_t struct. For example, phy_11b = 1 imply that ap support 802.11b mode
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_CONN: The station interface don’t initialized
• ESP_ERR_WIFI_NOT_CONNECT: The station is in disconnect status
Parameters
• ifx –interfaces
• protocol_bitmap –WiFi protocol bitmap
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_WIFI_IF: invalid interface
• others: refer to error codes in esp_err.h
Attention 1. API return false if try to configure an interface that is not enabled
Attention 2. WIFI_BW_HT40 is supported only when the interface support 11N
Parameters
• ifx –interface to be configured
• bw –bandwidth
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_WIFI_IF: invalid interface
• ESP_ERR_INVALID_ARG: invalid argument
• others: refer to error codes in esp_err.h
Attention 1. API return false if try to get a interface that is not enable
Parameters
• ifx –interface to be configured
• bw –[out] store bandwidth of interface ifx
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_WIFI_IF: invalid interface
• ESP_ERR_INVALID_ARG: invalid argument
Parameters
• primary –for HT20, primary is the channel number, for HT40, primary is the primary
channel
• second –for HT20, second is ignored, for HT40, second is the second channel
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_WIFI_IF: invalid interface
• ESP_ERR_INVALID_ARG: invalid argument
Attention 1. API return false if try to get a interface that is not enable
Parameters
• primary –store current primary channel
• second –[out] store current second channel
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_INVALID_ARG: invalid argument
Attention 1. It is discouraged to call this API since this doesn’t validate the per-country rules, it’s up to
the user to fill in all fields according to local regulations. Please use esp_wifi_set_country_code instead.
Attention 2. The default country is CHINA {.cc=”CN”, .schan=1, .nchan=13, pol-
icy=WIFI_COUNTRY_POLICY_AUTO}
Attention 3. When the country policy is WIFI_COUNTRY_POLICY_AUTO, the country info of the AP to
which the station is connected is used. E.g. if the configured country info is {.cc=”USA”, .schan=1,
.nchan=11} and the country info of the AP to which the station is connected is {.cc=”JP”, .schan=1,
.nchan=14} then the country info that will be used is {.cc=”JP”, .schan=1, .nchan=14}. If the station
disconnected from the AP the country info is set back to the country info of the station automatically,
{.cc=”US”, .schan=1, .nchan=11} in the example.
Attention 4. When the country policy is WIFI_COUNTRY_POLICY_MANUAL, then the configured coun-
try info is used always.
Attention 5. When the country info is changed because of configuration or because the station connects to a
different external AP, the country IE in probe response/beacon of the soft-AP is also changed.
Attention 6. The country configuration is stored into flash.
Attention 7. When this API is called, the PHY init data will switch to the PHY init data type corresponding
to the country info.
Attention 1. This API can only be called when the interface is disabled
Attention 2. ESP32 soft-AP and station have different MAC addresses, do not set them to be the same.
Attention 3. The bit 0 of the first byte of ESP32 MAC address can not be 1. For example, the MAC address
can set to be “1a:XX:XX:XX:XX:XX”, but can not be “15:XX:XX:XX:XX:XX”.
Parameters
• ifx –interface
• mac –the MAC address
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_INVALID_ARG: invalid argument
• ESP_ERR_WIFI_IF: invalid interface
• ESP_ERR_WIFI_MAC: invalid mac address
• ESP_ERR_WIFI_MODE: WiFi mode is wrong
• others: refer to error codes in esp_err.h
Parameters filter –the subtype of the control packet filtered in promiscuous mode.
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
Attention 1. This API can be called only when specified interface is enabled, otherwise, API fail
Attention 2. For station configuration, bssid_set needs to be 0; and it needs to be 1 only when users need to
check the MAC address of the AP.
Attention 3. ESP32 is limited to only one channel, so when in the soft-AP+station mode, the soft-AP will
adjust its channel automatically to be the same as the channel of the ESP32 station.
Parameters
• interface –interface
• conf –station or soft-AP configuration
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_INVALID_ARG: invalid argument
• ESP_ERR_WIFI_IF: invalid interface
• ESP_ERR_WIFI_MODE: invalid mode
• ESP_ERR_WIFI_PASSWORD: invalid password
• ESP_ERR_WIFI_NVS: WiFi internal NVS error
• others: refer to the erro code in esp_err.h
Parameters sta –[out] station list ap can get the connected sta’s phy mode info through the struct
member phy_11b,phy_11g,phy_11n,phy_lr in the wifi_sta_info_t struct. For example,
phy_11b = 1 imply that sta support 802.11b mode
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_INVALID_ARG: invalid argument
• ESP_ERR_WIFI_MODE: WiFi mode is wrong
• ESP_ERR_WIFI_CONN: WiFi internal error, the station/soft-AP control block is invalid
Attention 1. Maximum power before wifi startup is limited by PHY init data bin.
Attention 2. The value set by this API will be mapped to the max_tx_power of the structure wifi_country_t
variable.
Attention 3. Mapping Table {Power, max_tx_power} = {{8, 2}, {20, 5}, {28, 7}, {34, 8}, {44, 11}, {52,
13}, {56, 14}, {60, 15}, {66, 16}, {72, 18}, {80, 20}}.
Attention 4. Param power unit is 0.25dBm, range is [8, 84] corresponding to 2dBm - 20dBm.
Attention 5. Relationship between set value and actual value. As follows: {set value range, actual value} =
{{[8, 19],8}, {[20, 27],20}, {[28, 33],28}, {[34, 43],34}, {[44, 51],44}, {[52, 55],52}, {[56, 59],56},
{[60, 65],60}, {[66, 71],66}, {[72, 79],72}, {[80, 84],80}}.
Attention 1. Mask can be created by logical OR of various WIFI_EVENT_MASK_ constants. Events which
have corresponding bit set in the mask will not be delivered to the system event handler.
Attention 2. Default WiFi event mask is WIFI_EVENT_MASK_AP_PROBEREQRECVED.
Attention 3. There may be lots of stations sending probe request data around. Don’t unmask this event
unless you need to receive probe request data.
Attention Currently only support for sending beacon/probe request/probe response/action and non-QoS data
frame
Parameters
• ifx –interface if the Wi-Fi mode is Station, the ifx should be WIFI_IF_STA. If the Wi-Fi
mode is SoftAP, the ifx should be WIFI_IF_AP. If the Wi-Fi mode is Station+SoftAP,
the ifx should be WIFI_IF_STA or WIFI_IF_AP. If the ifx is wrong, the API returns
ESP_ERR_WIFI_IF.
• buffer –raw ieee80211 buffer
• len –the length of raw buffer, the len must be <= 1500 Bytes and >= 24 Bytes
• en_sys_seq –indicate whether use the internal sequence number. If en_sys_seq is
false, the sequence in raw buffer is unchanged, otherwise it will be overwritten by WiFi
driver with the system sequence number. Generally, if esp_wifi_80211_tx is called before
the Wi-Fi connection has been set up, both en_sys_seq==true and en_sys_seq==false are
fine. However, if the API is called after the Wi-Fi connection has been set up, en_sys_seq
must be true, otherwise ESP_ERR_WIFI_ARG is returned.
Returns
• ESP_OK: success
• ESP_ERR_WIFI_IF: Invalid interface
• ESP_ERR_INVALID_ARG: Invalid parameter
• ESP_ERR_WIFI_NO_MEM: out of memory
Each time a CSI data is received, the callback function will be called.
Parameters
• cb –callback
• ctx –context argument, passed to callback function
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
return
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start or promiscuous mode is not en-
abled
• ESP_ERR_INVALID_ARG: invalid argument
return
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start or promiscuous mode is not en-
abled
• ESP_ERR_INVALID_ARG: invalid argument
Attention Enabling power save may cause the return value inaccurate, except WiFi modem sleep
Attention 1. For Station, If the station does not receive a beacon frame from the connected SoftAP during
the inactive time, disconnect from SoftAP. Default 6s.
Attention 2. For SoftAP, If the softAP doesn’t receive any data from the connected STA during inactive
time, the softAP will force deauth the STA. Default is 300s.
Attention 3. The inactive time configuration is not stored into flash
Parameters
• ifx –interface to be configured.
• sec –Inactive time. Unit seconds.
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start
• ESP_ERR_WIFI_ARG: invalid argument, For Station, if sec is less than 3. For SoftAP,
if sec is less than 10.
Attention This API needs to be called every time after WIFI_EVENT_STA_BSS_RSSI_LOW event is re-
ceived.
esp_err_t esp_wifi_ftm_end_session(void)
End the ongoing FTM Initiator session.
Returns
• ESP_OK: succeed
• others: failed
Attention Use this API only in AP mode before performing FTM as responder
Attention 1. This API should be called after esp_wifi_init() and before esp_wifi_start().
Attention 2. Only when really need to disable 11b rate call this API otherwise don’t call this.
Parameters
• ifx –Interface to be configured.
• disable –true means disable 11b rate while false means enable 11b rate.
Returns
• ESP_OK: succeed
• others: failed
Parameters wake_interval –Milliseconds after would the chip wake up, from 1 to 65535.
Attention 1. When ieee80211d_enabled, the country info of the AP to which the station is connected is used.
E.g. if the configured country is US and the country info of the AP to which the station is connected is
JP then the country info that will be used is JP. If the station disconnected from the AP the country info
is set back to the country info of the station automatically, US in the example.
Attention 2. When ieee80211d_enabled is disabled, then the configured country info is used always.
Attention 3. When the country info is changed because of configuration or because the station connects to a
different external AP, the country IE in probe response/beacon of the soft-AP is also changed.
Attention 4. The country configuration is stored into flash.
Attention 5. When this API is called, the PHY init data will switch to the PHY init data type corresponding
to the country info.
Attention 6. Supported country codes are“01”(world safe mode)“AT”,”AU”,”BE”,”BG”,”BR”
, “CA”,”CH”,”CN”,”CY”,”CZ”,”DE”,”DK”,”EE”,”ES”,”FI”,”FR”,”GB”
,”GR”,”HK”,”HR”,”HU”, “IE”,”IN”,”IS”,”IT”,”JP”,”KR”,”LI”,”LT”,”
LU”,”LV”,”MT”,”MX”,”NL”,”NO”,”NZ”,”PL”,”PT”, “RO”,”SE”,”SI”,”
SK”,”TW”,”US”
Attention 7. When country code “01”(world safe mode) is set, SoftAP mode won’t contain country IE.
Attention 8. The default country is “01”(world safe mode) and ieee80211d_enabled is TRUE.
Parameters
• country –the configured country ISO code
• ieee80211d_enabled –802.11d is enabled or not
Returns
• ESP_OK: succeed
• ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
• ESP_ERR_INVALID_ARG: invalid argument
Attention 1. This API should be called after esp_wifi_init() and before esp_wifi_start().
Parameters
• ifx –Interface to be configured.
• rate –Phy rate to be configured.
Returns
• ESP_OK: succeed
• others: failed
Attention This API should be called after esp_wifi_set_config() and before esp_wifi_start().
Structures
struct wifi_init_config_t
WiFi stack configuration parameters passed to esp_wifi_init call.
Public Members
wifi_osi_funcs_t *osi_funcs
WiFi OS functions
wpa_crypto_funcs_t wpa_crypto_funcs
WiFi station crypto functions when connect
int static_rx_buf_num
WiFi static RX buffer number
int dynamic_rx_buf_num
WiFi dynamic RX buffer number
int tx_buf_type
WiFi TX buffer type
int static_tx_buf_num
WiFi static TX buffer number
int dynamic_tx_buf_num
WiFi dynamic TX buffer number
int cache_tx_buf_num
WiFi TX cache buffer number
int csi_enable
WiFi channel state information enable flag
int ampdu_rx_enable
WiFi AMPDU RX feature enable flag
int ampdu_tx_enable
WiFi AMPDU TX feature enable flag
int amsdu_tx_enable
WiFi AMSDU TX feature enable flag
int nvs_enable
WiFi NVS flash enable flag
int nano_enable
Nano option for printf/scan family enable flag
int rx_ba_win
WiFi Block Ack RX window size
int wifi_task_core_id
WiFi Task Core ID
int beacon_max_len
WiFi softAP maximum length of the beacon
int mgmt_sbuf_num
WiFi management short buffer number, the minimum value is 6, the maximum value is 32
uint64_t feature_caps
Enables additional WiFi features and capabilities
bool sta_disconnected_pm
WiFi Power Management for station at disconnected status
int magic
WiFi init magic number, it should be the last field
Macros
ESP_ERR_WIFI_NOT_INIT
WiFi driver was not installed by esp_wifi_init
ESP_ERR_WIFI_NOT_STARTED
WiFi driver was not started by esp_wifi_start
ESP_ERR_WIFI_NOT_STOPPED
WiFi driver was not stopped by esp_wifi_stop
ESP_ERR_WIFI_IF
WiFi interface error
ESP_ERR_WIFI_MODE
WiFi mode error
ESP_ERR_WIFI_STATE
WiFi internal state error
ESP_ERR_WIFI_CONN
WiFi internal control block of station or soft-AP error
ESP_ERR_WIFI_NVS
WiFi internal NVS module error
ESP_ERR_WIFI_MAC
MAC address is invalid
ESP_ERR_WIFI_SSID
SSID is invalid
ESP_ERR_WIFI_PASSWORD
Password is invalid
ESP_ERR_WIFI_TIMEOUT
Timeout error
ESP_ERR_WIFI_WAKE_FAIL
WiFi is in sleep state(RF closed) and wakeup fail
ESP_ERR_WIFI_WOULD_BLOCK
The caller would block
ESP_ERR_WIFI_NOT_CONNECT
Station still in disconnect status
ESP_ERR_WIFI_POST
Failed to post the event to WiFi task
ESP_ERR_WIFI_INIT_STATE
Invalid WiFi state when init/deinit is called
ESP_ERR_WIFI_STOP_STATE
Returned when WiFi is stopping
ESP_ERR_WIFI_NOT_ASSOC
The WiFi connection is not associated
ESP_ERR_WIFI_TX_DISALLOW
The WiFi TX is disallowed
WIFI_STATIC_TX_BUFFER_NUM
WIFI_CACHE_TX_BUFFER_NUM
WIFI_DYNAMIC_TX_BUFFER_NUM
WIFI_CSI_ENABLED
WIFI_AMPDU_RX_ENABLED
WIFI_AMPDU_TX_ENABLED
WIFI_AMSDU_TX_ENABLED
WIFI_NVS_ENABLED
WIFI_NANO_FORMAT_ENABLED
WIFI_INIT_CONFIG_MAGIC
WIFI_DEFAULT_RX_BA_WIN
WIFI_TASK_CORE_ID
WIFI_SOFTAP_BEACON_MAX_LEN
WIFI_MGMT_SBUF_NUM
WIFI_STA_DISCONNECTED_PM_ENABLED
CONFIG_FEATURE_WPA3_SAE_BIT
CONFIG_FEATURE_CACHE_TX_BUF_BIT
CONFIG_FEATURE_FTM_INITIATOR_BIT
CONFIG_FEATURE_FTM_RESPONDER_BIT
WIFI_INIT_CONFIG_DEFAULT()
Type Definitions
Each time a CSI data is received, the callback function will be called.
Param ctx context argument, passed to esp_wifi_set_csi_rx_cb() when registering callback func-
tion.
Param data CSI data received. The memory that it points to will be deallocated after callback
function returns.
Header File
• components/esp_wifi/include/esp_wifi_types.h
Unions
union wifi_config_t
#include <esp_wifi_types.h> Configuration data for ESP32 AP or STA.
The usage of this union (for ap or sta configuration) is determined by the accompanying interface argument
passed to esp_wifi_set_config() or esp_wifi_get_config()
Public Members
wifi_ap_config_t ap
configuration of AP
wifi_sta_config_t sta
configuration of STA
Structures
struct wifi_country_t
Structure describing WiFi country-based regional restrictions.
Public Members
char cc[3]
country code string
uint8_t schan
start channel
uint8_t nchan
total channel number
int8_t max_tx_power
This field is used for getting WiFi maximum transmitting power, call esp_wifi_set_max_tx_power to set
the maximum transmitting power.
wifi_country_policy_t policy
country policy
struct wifi_active_scan_time_t
Range of active scan times per channel.
Public Members
uint32_t min
minimum active scan time per channel, units: millisecond
uint32_t max
maximum active scan time per channel, units: millisecond, values above 1500ms may cause station to
disconnect from AP and are not recommended.
struct wifi_scan_time_t
Aggregate of active & passive scan time per channel.
Public Members
wifi_active_scan_time_t active
active scan time per channel, units: millisecond.
uint32_t passive
passive scan time per channel, units: millisecond, values above 1500ms may cause station to disconnect
from AP and are not recommended.
struct wifi_scan_config_t
Parameters for an SSID scan.
Public Members
uint8_t *ssid
SSID of AP
uint8_t *bssid
MAC address of AP
uint8_t channel
channel, scan the specific channel
bool show_hidden
enable to scan AP whose SSID is hidden
wifi_scan_type_t scan_type
scan type, active or passive
wifi_scan_time_t scan_time
scan time per channel
struct wifi_ap_record_t
Description of a WiFi AP.
Public Members
uint8_t bssid[6]
MAC address of AP
uint8_t ssid[33]
SSID of AP
uint8_t primary
channel of AP
wifi_second_chan_t second
secondary channel of AP
int8_t rssi
signal strength of AP
wifi_auth_mode_t authmode
authmode of AP
wifi_cipher_type_t pairwise_cipher
pairwise cipher of AP
wifi_cipher_type_t group_cipher
group cipher of AP
wifi_ant_t ant
antenna used to receive beacon from AP
uint32_t phy_11b
bit: 0 flag to identify if 11b mode is enabled or not
uint32_t phy_11g
bit: 1 flag to identify if 11g mode is enabled or not
uint32_t phy_11n
bit: 2 flag to identify if 11n mode is enabled or not
uint32_t phy_lr
bit: 3 flag to identify if low rate is enabled or not
uint32_t wps
bit: 4 flag to identify if WPS is supported or not
uint32_t ftm_responder
bit: 5 flag to identify if FTM is supported in responder mode
uint32_t ftm_initiator
bit: 6 flag to identify if FTM is supported in initiator mode
uint32_t reserved
bit: 7..31 reserved
wifi_country_t country
country information of AP
struct wifi_scan_threshold_t
Structure describing parameters for a WiFi fast scan.
Public Members
int8_t rssi
The minimum rssi to accept in the fast scan mode
wifi_auth_mode_t authmode
The weakest authmode to accept in the fast scan mode
struct wifi_pmf_config_t
Configuration structure for Protected Management Frame
Public Members
bool capable
Deprecated variable. Device will always connect in PMF mode if other device also advertizes PMF
capability.
bool required
Advertizes that Protected Management Frame is required. Device will not associate to non-PMF capable
devices.
struct wifi_ap_config_t
Soft-AP configuration settings for the ESP32.
Public Members
uint8_t ssid[32]
SSID of ESP32 soft-AP. If ssid_len field is 0, this must be a Null terminated string. Otherwise, length
is set according to ssid_len.
uint8_t password[64]
Password of ESP32 soft-AP.
uint8_t ssid_len
Optional length of SSID field.
uint8_t channel
Channel of ESP32 soft-AP
wifi_auth_mode_t authmode
Auth mode of ESP32 soft-AP. Do not support AUTH_WEP in soft-AP mode
uint8_t ssid_hidden
Broadcast SSID or not, default 0, broadcast the SSID
uint8_t max_connection
Max number of stations allowed to connect in, default 4, max 10
uint16_t beacon_interval
Beacon interval which should be multiples of 100. Unit: TU(time unit, 1 TU = 1024 us). Range: 100 ~
60000. Default value: 100
wifi_cipher_type_t pairwise_cipher
pairwise cipher of SoftAP, group cipher will be derived using this. cipher values are
valid starting from WIFI_CIPHER_TYPE_TKIP, enum values before that will be consid-
ered as invalid and default cipher suites(TKIP+CCMP) will be used. Valid cipher suites
in softAP mode are WIFI_CIPHER_TYPE_TKIP, WIFI_CIPHER_TYPE_CCMP and
WIFI_CIPHER_TYPE_TKIP_CCMP.
bool ftm_responder
Enable FTM Responder mode
wifi_pmf_config_t pmf_cfg
Configuration for Protected Management Frame
struct wifi_sta_config_t
STA configuration settings for the ESP32.
Public Members
uint8_t ssid[32]
SSID of target AP.
uint8_t password[64]
Password of target AP.
wifi_scan_method_t scan_method
do all channel scan or fast scan
bool bssid_set
whether set MAC address of target AP or not. Generally, station_config.bssid_set needs to be 0; and it
needs to be 1 only when users need to check the MAC address of the AP.
uint8_t bssid[6]
MAC address of target AP
uint8_t channel
channel of target AP. Set to 1~13 to scan starting from the specified channel before connecting to AP. If
the channel of AP is unknown, set it to 0.
uint16_t listen_interval
Listen interval for ESP32 station to receive beacon when WIFI_PS_MAX_MODEM is set. Units: AP
beacon intervals. Defaults to 3 if set to 0.
wifi_sort_method_t sort_method
sort the connect AP in the list by rssi or security mode
wifi_scan_threshold_t threshold
When sort_method is set, only APs which have an auth mode that is more secure than the selected auth
mode and a signal stronger than the minimum RSSI will be used.
wifi_pmf_config_t pmf_cfg
Configuration for Protected Management Frame. Will be advertized in RSN Capabilities in RSN IE.
uint32_t rm_enabled
Whether Radio Measurements are enabled for the connection
uint32_t btm_enabled
Whether BSS Transition Management is enabled for the connection
uint32_t mbo_enabled
Whether MBO is enabled for the connection
uint32_t ft_enabled
Whether FT is enabled for the connection
uint32_t owe_enabled
Whether OWE is enabled for the connection
uint32_t sae_pwe_h2e
Whether SAE hash to element is enabled
uint32_t reserved
Reserved for future feature set
struct wifi_sta_info_t
Description of STA associated with AP.
Public Members
uint8_t mac[6]
mac address
int8_t rssi
current average rssi of sta connected
uint32_t phy_11b
bit: 0 flag to identify if 11b mode is enabled or not
uint32_t phy_11g
bit: 1 flag to identify if 11g mode is enabled or not
uint32_t phy_11n
bit: 2 flag to identify if 11n mode is enabled or not
uint32_t phy_lr
bit: 3 flag to identify if low rate is enabled or not
uint32_t is_mesh_child
bit: 4 flag to identify mesh child
uint32_t reserved
bit: 5..31 reserved
struct wifi_sta_list_t
List of stations associated with the ESP32 Soft-AP.
Public Members
wifi_sta_info_t sta[ESP_WIFI_MAX_CONN_NUM]
station list
int num
number of stations in the list (other entries are invalid)
struct vendor_ie_data_t
Vendor Information Element header.
The first bytes of the Information Element will match this header. Payload follows.
Public Members
uint8_t element_id
Should be set to WIFI_VENDOR_IE_ELEMENT_ID (0xDD)
uint8_t length
Length of all bytes in the element data following this field. Minimum 4.
uint8_t vendor_oui[3]
Vendor identifier (OUI).
uint8_t vendor_oui_type
Vendor-specific OUI type.
uint8_t payload[0]
Payload. Length is equal to value in ‘length’field, minus 4.
struct wifi_pkt_rx_ctrl_t
Received packet radio metadata header, this is the common header at the beginning of all promiscuous mode
RX callback buffers.
Public Members
signed rssi
Received Signal Strength Indicator(RSSI) of packet. unit: dBm
unsigned rate
PHY rate encoding of the packet. Only valid for non HT(11bg) packet
unsigned __pad0__
reserved
unsigned sig_mode
0: non HT(11bg) packet; 1: HT(11n) packet; 3: VHT(11ac) packet
unsigned __pad1__
reserved
unsigned mcs
Modulation Coding Scheme. If is HT(11n) packet, shows the modulation, range from 0 to 76(MSC0 ~
MCS76)
unsigned cwb
Channel Bandwidth of the packet. 0: 20MHz; 1: 40MHz
unsigned __pad2__
reserved
unsigned smoothing
reserved
unsigned not_sounding
reserved
unsigned __pad3__
reserved
unsigned aggregation
Aggregation. 0: MPDU packet; 1: AMPDU packet
unsigned stbc
Space Time Block Code(STBC). 0: non STBC packet; 1: STBC packet
unsigned fec_coding
Flag is set for 11n packets which are LDPC
unsigned sgi
Short Guide Interval(SGI). 0: Long GI; 1: Short GI
signed noise_floor
noise floor of Radio Frequency Module(RF). unit: dBm
unsigned ampdu_cnt
ampdu cnt
unsigned channel
primary channel on which this packet is received
unsigned secondary_channel
secondary channel on which this packet is received. 0: none; 1: above; 2: below
unsigned __pad4__
reserved
unsigned timestamp
timestamp. The local time when this packet is received. It is precise only if modem sleep or light sleep
is not enabled. unit: microsecond
unsigned __pad5__
reserved
unsigned __pad6__
reserved
unsigned ant
antenna number from which this packet is received. 0: WiFi antenna 0; 1: WiFi antenna 1
unsigned sig_len
length of packet including Frame Check Sequence(FCS)
unsigned __pad7__
reserved
unsigned rx_state
state of the packet. 0: no error; others: error numbers which are not public
struct wifi_promiscuous_pkt_t
Payload passed to ‘buf’parameter of promiscuous mode RX callback.
Public Members
wifi_pkt_rx_ctrl_t rx_ctrl
metadata header
uint8_t payload[0]
Data or management payload. Length of payload is described by rx_ctrl.sig_len. Type of content deter-
mined by packet type argument of callback.
struct wifi_promiscuous_filter_t
Mask for filtering different packet types in promiscuous mode.
Public Members
uint32_t filter_mask
OR of one or more filter values WIFI_PROMIS_FILTER_*
struct wifi_csi_config_t
Channel state information(CSI) configuration type.
Public Members
bool lltf_en
enable to receive legacy long training field(lltf) data. Default enabled
bool htltf_en
enable to receive HT long training field(htltf) data. Default enabled
bool stbc_htltf2_en
enable to receive space time block code HT long training field(stbc-htltf2) data. Default enabled
bool ltf_merge_en
enable to generate htlft data by averaging lltf and ht_ltf data when receiving HT packet. Otherwise, use
ht_ltf data directly. Default enabled
bool channel_filter_en
enable to turn on channel filter to smooth adjacent sub-carrier. Disable it to keep independence of adjacent
sub-carrier. Default enabled
bool manu_scale
manually scale the CSI data by left shifting or automatically scale the CSI data. If set true, please set the
shift bits. false: automatically. true: manually. Default false
uint8_t shift
manually left shift bits of the scale of the CSI data. The range of the left shift bits is 0~15
struct wifi_csi_info_t
CSI data type.
Public Members
wifi_pkt_rx_ctrl_t rx_ctrl
received packet radio metadata header of the CSI data
uint8_t mac[6]
source MAC address of the CSI data
bool first_word_invalid
first four bytes of the CSI data is invalid or not
int8_t *buf
buffer of CSI data
uint16_t len
length of CSI data
struct wifi_ant_gpio_t
WiFi GPIO configuration for antenna selection.
Public Members
uint8_t gpio_select
Whether this GPIO is connected to external antenna switch
uint8_t gpio_num
The GPIO number that connects to external antenna switch
struct wifi_ant_gpio_config_t
WiFi GPIOs configuration for antenna selection.
Public Members
wifi_ant_gpio_t gpio_cfg[4]
The configurations of GPIOs that connect to external antenna switch
struct wifi_ant_config_t
WiFi antenna configuration.
Public Members
wifi_ant_mode_t rx_ant_mode
WiFi antenna mode for receiving
wifi_ant_t rx_ant_default
Default antenna mode for receiving, it’s ignored if rx_ant_mode is not WIFI_ANT_MODE_AUTO
wifi_ant_mode_t tx_ant_mode
WiFi antenna mode for transmission, it can be set to WIFI_ANT_MODE_AUTO only if rx_ant_mode
is set to WIFI_ANT_MODE_AUTO
uint8_t enabled_ant0
Index (in antenna GPIO configuration) of enabled WIFI_ANT_MODE_ANT0
uint8_t enabled_ant1
Index (in antenna GPIO configuration) of enabled WIFI_ANT_MODE_ANT1
struct wifi_action_tx_req_t
Action Frame Tx Request.
Public Members
wifi_interface_t ifx
WiFi interface to send request to
uint8_t dest_mac[6]
Destination MAC address
bool no_ack
Indicates no ack required
wifi_action_rx_cb_t rx_cb
Rx Callback to receive any response
uint32_t data_len
Length of the appended Data
uint8_t data[0]
Appended Data payload
struct wifi_ftm_initiator_cfg_t
FTM Initiator configuration.
Public Members
uint8_t resp_mac[6]
MAC address of the FTM Responder
uint8_t channel
Primary channel of the FTM Responder
uint8_t frm_count
No. of FTM frames requested in terms of 4 or 8 bursts (allowed values - 0(No pref), 16, 24, 32, 64)
uint16_t burst_period
Requested time period between consecutive FTM bursts in 100’s of milliseconds (0 - No pref)
struct wifi_event_sta_scan_done_t
Argument structure for WIFI_EVENT_SCAN_DONE event
Public Members
uint32_t status
status of scanning APs: 0 —success, 1 - failure
uint8_t number
number of scan results
uint8_t scan_id
scan sequence number, used for block scan
struct wifi_event_sta_connected_t
Argument structure for WIFI_EVENT_STA_CONNECTED event
Public Members
uint8_t ssid[32]
SSID of connected AP
uint8_t ssid_len
SSID length of connected AP
uint8_t bssid[6]
BSSID of connected AP
uint8_t channel
channel of connected AP
wifi_auth_mode_t authmode
authentication mode used by AP
struct wifi_event_sta_disconnected_t
Argument structure for WIFI_EVENT_STA_DISCONNECTED event
Public Members
uint8_t ssid[32]
SSID of disconnected AP
uint8_t ssid_len
SSID length of disconnected AP
uint8_t bssid[6]
BSSID of disconnected AP
uint8_t reason
reason of disconnection
struct wifi_event_sta_authmode_change_t
Argument structure for WIFI_EVENT_STA_AUTHMODE_CHANGE event
Public Members
wifi_auth_mode_t old_mode
the old auth mode of AP
wifi_auth_mode_t new_mode
the new auth mode of AP
struct wifi_event_sta_wps_er_pin_t
Argument structure for WIFI_EVENT_STA_WPS_ER_PIN event
Public Members
uint8_t pin_code[8]
PIN code of station in enrollee mode
struct wifi_event_sta_wps_er_success_t
Argument structure for WIFI_EVENT_STA_WPS_ER_SUCCESS event
Public Members
uint8_t ap_cred_cnt
Number of AP credentials received
uint8_t ssid[MAX_SSID_LEN]
SSID of AP
uint8_t passphrase[MAX_PASSPHRASE_LEN]
Passphrase for the AP
struct wifi_event_ap_staconnected_t
Argument structure for WIFI_EVENT_AP_STACONNECTED event
Public Members
uint8_t mac[6]
MAC address of the station connected to ESP32 soft-AP
uint8_t aid
the aid that ESP32 soft-AP gives to the station connected to
bool is_mesh_child
flag to identify mesh child
struct wifi_event_ap_stadisconnected_t
Argument structure for WIFI_EVENT_AP_STADISCONNECTED event
Public Members
uint8_t mac[6]
MAC address of the station disconnects to ESP32 soft-AP
uint8_t aid
the aid that ESP32 soft-AP gave to the station disconnects to
bool is_mesh_child
flag to identify mesh child
struct wifi_event_ap_probe_req_rx_t
Argument structure for WIFI_EVENT_AP_PROBEREQRECVED event
Public Members
int rssi
Received probe request signal strength
uint8_t mac[6]
MAC address of the station which send probe request
struct wifi_event_bss_rssi_low_t
Argument structure for WIFI_EVENT_STA_BSS_RSSI_LOW event
Public Members
int32_t rssi
RSSI value of bss
struct wifi_ftm_report_entry_t
Argument structure for
Public Members
uint8_t dlog_token
Dialog Token of the FTM frame
int8_t rssi
RSSI of the FTM frame received
uint32_t rtt
Round Trip Time in pSec with a peer
uint64_t t1
Time of departure of FTM frame from FTM Responder in pSec
uint64_t t2
Time of arrival of FTM frame at FTM Initiator in pSec
uint64_t t3
Time of departure of ACK from FTM Initiator in pSec
uint64_t t4
Time of arrival of ACK at FTM Responder in pSec
struct wifi_event_ftm_report_t
Argument structure for WIFI_EVENT_FTM_REPORT event
Public Members
uint8_t peer_mac[6]
MAC address of the FTM Peer
wifi_ftm_status_t status
Status of the FTM operation
uint32_t rtt_raw
Raw average Round-Trip-Time with peer in Nano-Seconds
uint32_t rtt_est
Estimated Round-Trip-Time with peer in Nano-Seconds
uint32_t dist_est
Estimated one-way distance in Centi-Meters
wifi_ftm_report_entry_t *ftm_report_data
Pointer to FTM Report with multiple entries, should be freed after use
uint8_t ftm_report_num_entries
Number of entries in the FTM Report data
struct wifi_event_action_tx_status_t
Argument structure for WIFI_EVENT_ACTION_TX_STATUS event
Public Members
wifi_interface_t ifx
WiFi interface to send request to
uint32_t context
Context to identify the request
uint8_t da[6]
Destination MAC address
uint8_t status
Status of the operation
struct wifi_event_roc_done_t
Argument structure for WIFI_EVENT_ROC_DONE event
Public Members
uint32_t context
Context to identify the request
Macros
WIFI_OFFCHAN_TX_REQ
WIFI_OFFCHAN_TX_CANCEL
WIFI_ROC_REQ
WIFI_ROC_CANCEL
WIFI_PROTOCOL_11B
WIFI_PROTOCOL_11G
WIFI_PROTOCOL_11N
WIFI_PROTOCOL_LR
ESP_WIFI_MAX_CONN_NUM
max number of stations which can connect to ESP32 soft-AP
WIFI_VENDOR_IE_ELEMENT_ID
WIFI_PROMIS_FILTER_MASK_ALL
filter all packets
WIFI_PROMIS_FILTER_MASK_MGMT
filter the packets with type of WIFI_PKT_MGMT
WIFI_PROMIS_FILTER_MASK_CTRL
filter the packets with type of WIFI_PKT_CTRL
WIFI_PROMIS_FILTER_MASK_DATA
filter the packets with type of WIFI_PKT_DATA
WIFI_PROMIS_FILTER_MASK_MISC
filter the packets with type of WIFI_PKT_MISC
WIFI_PROMIS_FILTER_MASK_DATA_MPDU
filter the MPDU which is a kind of WIFI_PKT_DATA
WIFI_PROMIS_FILTER_MASK_DATA_AMPDU
filter the AMPDU which is a kind of WIFI_PKT_DATA
WIFI_PROMIS_FILTER_MASK_FCSFAIL
filter the FCS failed packets, do not open it in general
WIFI_PROMIS_CTRL_FILTER_MASK_ALL
filter all control packets
WIFI_PROMIS_CTRL_FILTER_MASK_WRAPPER
filter the control packets with subtype of Control Wrapper
WIFI_PROMIS_CTRL_FILTER_MASK_BAR
filter the control packets with subtype of Block Ack Request
WIFI_PROMIS_CTRL_FILTER_MASK_BA
filter the control packets with subtype of Block Ack
WIFI_PROMIS_CTRL_FILTER_MASK_PSPOLL
filter the control packets with subtype of PS-Poll
WIFI_PROMIS_CTRL_FILTER_MASK_RTS
filter the control packets with subtype of RTS
WIFI_PROMIS_CTRL_FILTER_MASK_CTS
filter the control packets with subtype of CTS
WIFI_PROMIS_CTRL_FILTER_MASK_ACK
filter the control packets with subtype of ACK
WIFI_PROMIS_CTRL_FILTER_MASK_CFEND
filter the control packets with subtype of CF-END
WIFI_PROMIS_CTRL_FILTER_MASK_CFENDACK
filter the control packets with subtype of CF-END+CF-ACK
WIFI_EVENT_MASK_ALL
mask all WiFi events
WIFI_EVENT_MASK_NONE
mask none of the WiFi events
WIFI_EVENT_MASK_AP_PROBEREQRECVED
mask SYSTEM_EVENT_AP_PROBEREQRECVED event
MAX_SSID_LEN
MAX_PASSPHRASE_LEN
MAX_WPS_AP_CRED
WIFI_STATIS_BUFFER
WIFI_STATIS_RXTX
WIFI_STATIS_HW
WIFI_STATIS_DIAG
WIFI_STATIS_PS
WIFI_STATIS_ALL
Type Definitions
typedef int (*wifi_action_rx_cb_t)(uint8_t *hdr, uint8_t *payload, size_t len, uint8_t channel)
The Rx callback function of Action Tx operations.
Param hdr pointer to the IEEE 802.11 Header structure
Param payload pointer to the Payload following 802.11 Header
Param len length of the Payload
Param channel channel number the frame is received on
Enumerations
enum wifi_mode_t
Values:
enumerator WIFI_MODE_NULL
null mode
enumerator WIFI_MODE_STA
WiFi station mode
enumerator WIFI_MODE_AP
WiFi soft-AP mode
enumerator WIFI_MODE_APSTA
WiFi station + soft-AP mode
enumerator WIFI_MODE_MAX
enum wifi_interface_t
Values:
enumerator WIFI_IF_STA
enumerator WIFI_IF_AP
enum wifi_country_policy_t
Values:
enumerator WIFI_COUNTRY_POLICY_AUTO
Country policy is auto, use the country info of AP to which the station is connected
enumerator WIFI_COUNTRY_POLICY_MANUAL
Country policy is manual, always use the configured country info
enum wifi_auth_mode_t
Values:
enumerator WIFI_AUTH_OPEN
authenticate mode : open
enumerator WIFI_AUTH_WEP
authenticate mode : WEP
enumerator WIFI_AUTH_WPA_PSK
authenticate mode : WPA_PSK
enumerator WIFI_AUTH_WPA2_PSK
authenticate mode : WPA2_PSK
enumerator WIFI_AUTH_WPA_WPA2_PSK
authenticate mode : WPA_WPA2_PSK
enumerator WIFI_AUTH_WPA2_ENTERPRISE
authenticate mode : WPA2_ENTERPRISE
enumerator WIFI_AUTH_WPA3_PSK
authenticate mode : WPA3_PSK
enumerator WIFI_AUTH_WPA2_WPA3_PSK
authenticate mode : WPA2_WPA3_PSK
enumerator WIFI_AUTH_WAPI_PSK
authenticate mode : WAPI_PSK
enumerator WIFI_AUTH_OWE
authenticate mode : OWE
enumerator WIFI_AUTH_MAX
enum wifi_err_reason_t
Values:
enumerator WIFI_REASON_UNSPECIFIED
enumerator WIFI_REASON_AUTH_EXPIRE
enumerator WIFI_REASON_AUTH_LEAVE
enumerator WIFI_REASON_ASSOC_EXPIRE
enumerator WIFI_REASON_ASSOC_TOOMANY
enumerator WIFI_REASON_NOT_AUTHED
enumerator WIFI_REASON_NOT_ASSOCED
enumerator WIFI_REASON_ASSOC_LEAVE
enumerator WIFI_REASON_ASSOC_NOT_AUTHED
enumerator WIFI_REASON_DISASSOC_PWRCAP_BAD
enumerator WIFI_REASON_DISASSOC_SUPCHAN_BAD
enumerator WIFI_REASON_BSS_TRANSITION_DISASSOC
enumerator WIFI_REASON_IE_INVALID
enumerator WIFI_REASON_MIC_FAILURE
enumerator WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT
enumerator WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT
enumerator WIFI_REASON_IE_IN_4WAY_DIFFERS
enumerator WIFI_REASON_GROUP_CIPHER_INVALID
enumerator WIFI_REASON_PAIRWISE_CIPHER_INVALID
enumerator WIFI_REASON_AKMP_INVALID
enumerator WIFI_REASON_UNSUPP_RSN_IE_VERSION
enumerator WIFI_REASON_INVALID_RSN_IE_CAP
enumerator WIFI_REASON_802_1X_AUTH_FAILED
enumerator WIFI_REASON_CIPHER_SUITE_REJECTED
enumerator WIFI_REASON_INVALID_PMKID
enumerator WIFI_REASON_BEACON_TIMEOUT
enumerator WIFI_REASON_NO_AP_FOUND
enumerator WIFI_REASON_AUTH_FAIL
enumerator WIFI_REASON_ASSOC_FAIL
enumerator WIFI_REASON_HANDSHAKE_TIMEOUT
enumerator WIFI_REASON_CONNECTION_FAIL
enumerator WIFI_REASON_AP_TSF_RESET
enumerator WIFI_REASON_ROAMING
enum wifi_second_chan_t
Values:
enumerator WIFI_SECOND_CHAN_NONE
the channel width is HT20
enumerator WIFI_SECOND_CHAN_ABOVE
the channel width is HT40 and the secondary channel is above the primary channel
enumerator WIFI_SECOND_CHAN_BELOW
the channel width is HT40 and the secondary channel is below the primary channel
enum wifi_scan_type_t
Values:
enumerator WIFI_SCAN_TYPE_ACTIVE
active scan
enumerator WIFI_SCAN_TYPE_PASSIVE
passive scan
enum wifi_cipher_type_t
Values:
enumerator WIFI_CIPHER_TYPE_NONE
the cipher type is none
enumerator WIFI_CIPHER_TYPE_WEP40
the cipher type is WEP40
enumerator WIFI_CIPHER_TYPE_WEP104
the cipher type is WEP104
enumerator WIFI_CIPHER_TYPE_TKIP
the cipher type is TKIP
enumerator WIFI_CIPHER_TYPE_CCMP
the cipher type is CCMP
enumerator WIFI_CIPHER_TYPE_TKIP_CCMP
the cipher type is TKIP and CCMP
enumerator WIFI_CIPHER_TYPE_AES_CMAC128
the cipher type is AES-CMAC-128
enumerator WIFI_CIPHER_TYPE_SMS4
the cipher type is SMS4
enumerator WIFI_CIPHER_TYPE_GCMP
the cipher type is GCMP
enumerator WIFI_CIPHER_TYPE_GCMP256
the cipher type is GCMP-256
enumerator WIFI_CIPHER_TYPE_AES_GMAC128
the cipher type is AES-GMAC-128
enumerator WIFI_CIPHER_TYPE_AES_GMAC256
the cipher type is AES-GMAC-256
enumerator WIFI_CIPHER_TYPE_UNKNOWN
the cipher type is unknown
enum wifi_ant_t
WiFi antenna.
Values:
enumerator WIFI_ANT_ANT0
WiFi antenna 0
enumerator WIFI_ANT_ANT1
WiFi antenna 1
enumerator WIFI_ANT_MAX
Invalid WiFi antenna
enum wifi_scan_method_t
Values:
enumerator WIFI_FAST_SCAN
Do fast scan, scan will end after find SSID match AP
enumerator WIFI_ALL_CHANNEL_SCAN
All channel scan, scan will end after scan all the channel
enum wifi_sort_method_t
Values:
enumerator WIFI_CONNECT_AP_BY_SIGNAL
Sort match AP in scan list by RSSI
enumerator WIFI_CONNECT_AP_BY_SECURITY
Sort match AP in scan list by security mode
enum wifi_ps_type_t
Values:
enumerator WIFI_PS_NONE
No power save
enumerator WIFI_PS_MIN_MODEM
Minimum modem power saving. In this mode, station wakes up to receive beacon every DTIM period
enumerator WIFI_PS_MAX_MODEM
Maximum modem power saving. In this mode, interval to receive beacons is determined by the lis-
ten_interval parameter in wifi_sta_config_t
enum wifi_bandwidth_t
Values:
enumerator WIFI_BW_HT20
enumerator WIFI_BW_HT40
enum wifi_storage_t
Values:
enumerator WIFI_STORAGE_FLASH
all configuration will store in both memory and flash
enumerator WIFI_STORAGE_RAM
all configuration will only store in the memory
enum wifi_vendor_ie_type_t
Vendor Information Element type.
Determines the frame type that the IE will be associated with.
Values:
enumerator WIFI_VND_IE_TYPE_BEACON
enumerator WIFI_VND_IE_TYPE_PROBE_REQ
enumerator WIFI_VND_IE_TYPE_PROBE_RESP
enumerator WIFI_VND_IE_TYPE_ASSOC_REQ
enumerator WIFI_VND_IE_TYPE_ASSOC_RESP
enum wifi_vendor_ie_id_t
Vendor Information Element index.
Each IE type can have up to two associated vendor ID elements.
Values:
enumerator WIFI_VND_IE_ID_0
enumerator WIFI_VND_IE_ID_1
enum wifi_promiscuous_pkt_type_t
Promiscuous frame type.
Passed to promiscuous mode RX callback to indicate the type of parameter in the buffer.
Values:
enumerator WIFI_PKT_MGMT
Management frame, indicates ‘buf’argument is wifi_promiscuous_pkt_t
enumerator WIFI_PKT_CTRL
Control frame, indicates ‘buf’argument is wifi_promiscuous_pkt_t
enumerator WIFI_PKT_DATA
Data frame, indiciates ‘buf’argument is wifi_promiscuous_pkt_t
enumerator WIFI_PKT_MISC
Other type, such as MIMO etc.‘buf’argument is wifi_promiscuous_pkt_t but the payload is zero length.
enum wifi_ant_mode_t
WiFi antenna mode.
Values:
enumerator WIFI_ANT_MODE_ANT0
Enable WiFi antenna 0 only
enumerator WIFI_ANT_MODE_ANT1
Enable WiFi antenna 1 only
enumerator WIFI_ANT_MODE_AUTO
Enable WiFi antenna 0 and 1, automatically select an antenna
enumerator WIFI_ANT_MODE_MAX
Invalid WiFi enabled antenna
enum wifi_phy_rate_t
WiFi PHY rate encodings.
Values:
enumerator WIFI_PHY_RATE_1M_L
1 Mbps with long preamble
enumerator WIFI_PHY_RATE_2M_L
2 Mbps with long preamble
enumerator WIFI_PHY_RATE_5M_L
5.5 Mbps with long preamble
enumerator WIFI_PHY_RATE_11M_L
11 Mbps with long preamble
enumerator WIFI_PHY_RATE_2M_S
2 Mbps with short preamble
enumerator WIFI_PHY_RATE_5M_S
5.5 Mbps with short preamble
enumerator WIFI_PHY_RATE_11M_S
11 Mbps with short preamble
enumerator WIFI_PHY_RATE_48M
48 Mbps
enumerator WIFI_PHY_RATE_24M
24 Mbps
enumerator WIFI_PHY_RATE_12M
12 Mbps
enumerator WIFI_PHY_RATE_6M
6 Mbps
enumerator WIFI_PHY_RATE_54M
54 Mbps
enumerator WIFI_PHY_RATE_36M
36 Mbps
enumerator WIFI_PHY_RATE_18M
18 Mbps
enumerator WIFI_PHY_RATE_9M
9 Mbps
enumerator WIFI_PHY_RATE_MCS0_LGI
MCS0 with long GI, 6.5 Mbps for 20MHz, 13.5 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS1_LGI
MCS1 with long GI, 13 Mbps for 20MHz, 27 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS2_LGI
MCS2 with long GI, 19.5 Mbps for 20MHz, 40.5 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS3_LGI
MCS3 with long GI, 26 Mbps for 20MHz, 54 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS4_LGI
MCS4 with long GI, 39 Mbps for 20MHz, 81 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS5_LGI
MCS5 with long GI, 52 Mbps for 20MHz, 108 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS6_LGI
MCS6 with long GI, 58.5 Mbps for 20MHz, 121.5 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS7_LGI
MCS7 with long GI, 65 Mbps for 20MHz, 135 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS0_SGI
MCS0 with short GI, 7.2 Mbps for 20MHz, 15 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS1_SGI
MCS1 with short GI, 14.4 Mbps for 20MHz, 30 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS2_SGI
MCS2 with short GI, 21.7 Mbps for 20MHz, 45 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS3_SGI
MCS3 with short GI, 28.9 Mbps for 20MHz, 60 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS4_SGI
MCS4 with short GI, 43.3 Mbps for 20MHz, 90 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS5_SGI
MCS5 with short GI, 57.8 Mbps for 20MHz, 120 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS6_SGI
MCS6 with short GI, 65 Mbps for 20MHz, 135 Mbps for 40MHz
enumerator WIFI_PHY_RATE_MCS7_SGI
MCS7 with short GI, 72.2 Mbps for 20MHz, 150 Mbps for 40MHz
enumerator WIFI_PHY_RATE_LORA_250K
250 Kbps
enumerator WIFI_PHY_RATE_LORA_500K
500 Kbps
enumerator WIFI_PHY_RATE_MAX
enum wifi_event_t
WiFi event declarations
Values:
enumerator WIFI_EVENT_WIFI_READY
ESP32 WiFi ready
enumerator WIFI_EVENT_SCAN_DONE
ESP32 finish scanning AP
enumerator WIFI_EVENT_STA_START
ESP32 station start
enumerator WIFI_EVENT_STA_STOP
ESP32 station stop
enumerator WIFI_EVENT_STA_CONNECTED
ESP32 station connected to AP
enumerator WIFI_EVENT_STA_DISCONNECTED
ESP32 station disconnected from AP
enumerator WIFI_EVENT_STA_AUTHMODE_CHANGE
the auth mode of AP connected by ESP32 station changed
enumerator WIFI_EVENT_STA_WPS_ER_SUCCESS
ESP32 station wps succeeds in enrollee mode
enumerator WIFI_EVENT_STA_WPS_ER_FAILED
ESP32 station wps fails in enrollee mode
enumerator WIFI_EVENT_STA_WPS_ER_TIMEOUT
ESP32 station wps timeout in enrollee mode
enumerator WIFI_EVENT_STA_WPS_ER_PIN
ESP32 station wps pin code in enrollee mode
enumerator WIFI_EVENT_STA_WPS_ER_PBC_OVERLAP
ESP32 station wps overlap in enrollee mode
enumerator WIFI_EVENT_AP_START
ESP32 soft-AP start
enumerator WIFI_EVENT_AP_STOP
ESP32 soft-AP stop
enumerator WIFI_EVENT_AP_STACONNECTED
a station connected to ESP32 soft-AP
enumerator WIFI_EVENT_AP_STADISCONNECTED
a station disconnected from ESP32 soft-AP
enumerator WIFI_EVENT_AP_PROBEREQRECVED
Receive probe request packet in soft-AP interface
enumerator WIFI_EVENT_FTM_REPORT
Receive report of FTM procedure
enumerator WIFI_EVENT_STA_BSS_RSSI_LOW
AP’s RSSI crossed configured threshold
enumerator WIFI_EVENT_ACTION_TX_STATUS
Status indication of Action Tx operation
enumerator WIFI_EVENT_ROC_DONE
Remain-on-Channel operation complete
enumerator WIFI_EVENT_STA_BEACON_TIMEOUT
ESP32 station beacon timeout
enumerator WIFI_EVENT_CONNECTIONLESS_MODULE_WAKE_INTERVAL_START
ESP32 connectionless module wake interval start
enumerator WIFI_EVENT_MAX
Invalid WiFi event ID
enum wifi_event_sta_wps_fail_reason_t
Argument structure for WIFI_EVENT_STA_WPS_ER_FAILED event
Values:
enumerator WPS_FAIL_REASON_NORMAL
ESP32 WPS normal fail reason
enumerator WPS_FAIL_REASON_RECV_M2D
ESP32 WPS receive M2D frame
enumerator WPS_FAIL_REASON_MAX
enum wifi_ftm_status_t
FTM operation status types.
Values:
enumerator FTM_STATUS_SUCCESS
FTM exchange is successful
enumerator FTM_STATUS_UNSUPPORTED
Peer does not support FTM
enumerator FTM_STATUS_CONF_REJECTED
Peer rejected FTM configuration in FTM Request
enumerator FTM_STATUS_NO_RESPONSE
Peer did not respond to FTM Requests
enumerator FTM_STATUS_FAIL
Unknown error during FTM exchange
Wi-Fi Easy ConnectTM , also known as Device Provisioning Protocol (DPP) or Easy Connect, is a provisioning pro-
tocol certified by Wi-Fi Alliance. It is a secure and standardized provisioning protocol for configuration of Wi-Fi
Devices. With Easy Connect adding a new device to a network is as simple as scanning a QR Code. This reduces
complexity and enhances user experience while onboarding devices without UI like Smart Home and IoT products.
Unlike old protocols like WiFi Protected Setup (WPS), Wi-Fi Easy Connect incorporates strong encryption through
public key cryptography to ensure networks remain secure as new devices are added. Easy Connect brings many
benefits in the User Experience:
• Simple and intuitive to use; no lengthy instructions to follow for new device setup
• No need to remember and enter passwords into the device being provisioned
• Works with electronic or printed QR codes, or human-readable strings
• Supports both WPA2 and WPA3 networks
Please refer to Wi-Fi Alliance’s official page on Easy Connect for more information.
ESP32 supports Enrollee mode of Easy Connect with QR Code as the provisioning method. A display is required to
display this QR Code. Users can scan this QR Code using their capable device and provision the ESP32 to their Wi-Fi
network. The provisioning device needs to be connected to the AP which need not support Wi-Fi Easy Connect™.
Easy Connect is still an evolving protocol. Of known platforms that support the QR Code method are some Android
smartphones with Android 10 or higher. To use Easy Connect no additional App needs to be installed on the supported
smartphone.
API Reference
Header File
• components/wpa_supplicant/esp_supplicant/include/esp_dpp.h
Functions
esp_err_t esp_supp_dpp_init(esp_supp_dpp_event_cb_t evt_cb)
Initialize DPP Supplicant.
return
• ESP_OK: Success
• ESP_FAIL: Failure
Parameters
• chan_list –List of channels device will be available on for listening
• type –Bootstrap method type, only QR Code method is supported for now.
• key –(Optional) 32 byte Raw Private Key for generating a Bootstrapping Public Key
• info –(Optional) Ancilliary Device Information like Serial Number
Returns
• ESP_OK: Success
• ESP_FAIL: Failure
esp_err_t esp_supp_dpp_start_listen(void)
Start listening on Channels provided during esp_supp_dpp_bootstrap_gen.
Listens on every Channel from Channel List for a pre-defined wait time.
Returns
• ESP_OK: Success
• ESP_FAIL: Generic Failure
• ESP_ERR_INVALID_STATE: ROC attempted before WiFi is started
• ESP_ERR_NO_MEM: Memory allocation failed while posting ROC request
void esp_supp_dpp_stop_listen(void)
Stop listening on Channels.
Macros
ESP_ERR_DPP_FAILURE
Generic failure during DPP Operation
ESP_ERR_DPP_TX_FAILURE
DPP Frame Tx failed OR not Acked
ESP_ERR_DPP_INVALID_ATTR
Encountered invalid DPP Attribute
Type Definitions
Enumerations
enum dpp_bootstrap_type
Types of Bootstrap Methods for DPP.
Values:
enumerator DPP_BOOTSTRAP_QR_CODE
QR Code Method
enumerator DPP_BOOTSTRAP_PKEX
Proof of Knowledge Method
enumerator DPP_BOOTSTRAP_NFC_URI
NFC URI record Method
enum esp_supp_dpp_event_t
Types of Callback Events received from DPP Supplicant.
Values:
enumerator ESP_SUPP_DPP_URI_READY
URI is ready through Bootstrapping
enumerator ESP_SUPP_DPP_CFG_RECVD
Config received via DPP Authentication
enumerator ESP_SUPP_DPP_FAIL
DPP Authentication failure
Code examples for the Wi-Fi API are provided in the wifi directory of ESP-IDF examples.
Code examples for ESP-WIFI-MESH are provided in the mesh directory of ESP-IDF examples.
2.5.2 Ethernet
Ethernet
Overview ESP-IDF provides a set of consistent and flexible APIs to support both internal Ethernet MAC (EMAC)
controller and external SPI-Ethernet modules.
This programming guide is split into the following sections:
1. Basic Ethernet Concepts
2. Configure MAC and PHY
3. Connect Driver to TCP/IP Stack
4. Misc control of Ethernet driver
Basic Ethernet Concepts Ethernet is an asynchronous Carrier Sense Multiple Access with Collision Detect
(CSMA/CD) protocol/interface. It is generally not well suited for low power applications. However, with ubiq-
uitous deployment, internet connectivity, high data rates and limitless rage expandability, Ethernet can accommodate
nearly all wired communications.
Normal IEEE 802.3 compliant Ethernet frames are between 64 and 1518 bytes in length. They are made up of
five or six different fields: a destination MAC address (DA), a source MAC address (SA), a type/length field, data
payload, an optional padding field and a Cyclic Redundancy Check (CRC). Additionally, when transmitted on the
Ethernet medium, a 7-byte preamble field and Start-of-Frame (SOF) delimiter byte are appended to the beginning
of the Ethernet packet.
Thus the traffic on the twist-pair cabling will appear as shown blow:
Preamble and Start-of-Frame Delimiter The preamble contains seven bytes of 55H, it allows the receiver to lock
onto the stream of data before the actual frame arrives. The Start-of-Frame Delimiter (SFD) is a binary sequence
10101011 (as seen on the physical medium). It is sometimes considered to be part of the preamble.
When transmitting and receiving data, the preamble and SFD bytes will automatically be generated or stripped from
the packets.
Destination Address The destination address field contains a 6-byte length MAC address of the device that the
packet is directed to. If the Least Significant bit in the first byte of the MAC address is set, the address is a multi-cast
destination. For example, 01-00-00-00-F0-00 and 33-45-67-89-AB-CD are multi-cast addresses, while 00-00-00-
00-F0-00 and 32-45-67-89-AB-CD are not. Packets with multi-cast destination addresses are designed to arrive and
be important to a selected group of Ethernet nodes. If the destination address field is the reserved multi-cast address,
i.e. FF-FF-FF-FF-FF-FF, the packet is a broadcast packet and it will be directed to everyone sharing the network.
If the Least Significant bit in the first byte of the MAC address is clear, the address is a uni-cast address and will be
designed for usage by only the addressed node.
Normally the EMAC controller incorporates receive filters which can be used to discard or accept packets with multi-
cast, broadcast and/or uni-cast destination addresses. When transmitting packets, the host controller is responsible
for writing the desired destination address into the transmit buffer.
Source Address The source address field contains a 6-byte length MAC address of the node which created the
Ethernet packet. Users of Ethernet must generate a unique MAC address for each controller used. MAC addresses
consist of two portions. The first three bytes are known as the Organizationally Unique Identifier (OUI). OUIs are
distributed by the IEEE. The last three bytes are address bytes at the discretion of the company that purchased the
OUI. More information about MAC Address used in ESP-IDF, please see MAC Address Allocation.
When transmitting packets, the assigned source MAC address must be written into the transmit buffer by the host
controller.
Type / Length The type/length field is a 2-byte field, if the value in this field is <= 1500 (decimal), it is considered
a length field and it specifies the amount of non-padding data which follows in the data field. If the value is >= 1536,
it represents the protocol the following packet data belongs to. The following are the most common type values:
• IPv4 = 0800H
• IPv6 = 86DDH
• ARP = 0806H
Users implementing proprietary networks may choose to treat this field as a length field, while applications imple-
menting protocols such as the Internet Protocol (IP) or Address Resolution Protocol (ARP), should program this field
with the appropriate type defined by the protocol’s specification when transmitting packets.
Payload The payload field is a variable length field, anywhere from 0 to 1500 bytes. Larger data packets will
violate Ethernet standards and will be dropped by most Ethernet nodes. This field contains the client data, such as an
IP datagram.
Padding and FCS The padding field is a variable length field added to meet IEEE 802.3 specification requirements
when small data payloads are used. The DA, SA, type, payload and padding of an Ethernet packet must be no smaller
than 60 bytes. Adding the required 4-byte FCS field, packets must be no smaller than 64 bytes. If the data field is
less than 46 bytes long, a padding field is required.
The FCS field is a 4-byte field which contains an industry standard 32-bit CRC calculated with the data from the
DA, SA, type, payload and padding fields. Given the complexity of calculating a CRC, the hardware normally will
automatically generate a valid CRC and transmit it. Otherwise, the host controller must generate the CRC and place
it in the transmit buffer.
Normally, the host controller does not need to concern itself with padding and the CRC which the hardware EMAC
will also be able to automatically generate when transmitting and verify when receiving. However, the padding and
CRC fields will be written into the receive buffer when packets arrive, so they may be evaluated by the host controller
if needed.
Note: Besides the basic data frame described above, there’re two other common frame types in 10/100 Mbps
Ethernet: control frames and VLAN tagged frames. They’re not supported in ESP-IDF.
Configure MAC and PHY Ethernet driver is composed of two parts: MAC and PHY.
The communication between MAC and PHY can have diverse choices: MII (Media Independent Interface), RMII
(Reduced Media Independent Interface) and etc.
One of the obvious difference between MII and RMII is the signal consumption. For MII, it usually costs up to 18
signals. Instead, RMII interface can reduce the consumption to 9.
In RMII mode, both the receiver and transmitter signals are referenced to the REF_CLK. REF_CLK must be stable
during any access to PHY and MAC. Generally there’re three ways to generate the REF_CLK depending on the
PHY device in your design:
• Some PHY chip can derive the REF_CLK from its external connected 25MHz crystal oscillator (as seen
the option a in the picture). In this case, you should select CONFIG_ETH_RMII_CLK_INPUT in CON-
FIG_ETH_RMII_CLK_MODE.
• Some PHY chip uses an external connected 50MHz crystal oscillator or other clock source, which can also be
used as the REF_CLK for MAC side (as seen the option b in the picture). In this case, you still need to select
CONFIG_ETH_RMII_CLK_INPUT in CONFIG_ETH_RMII_CLK_MODE.
• Some EMAC controller can generate the REF_CLK using its internal high precision PLL (as seen the
option c in the picture). In this case, you should select CONFIG_ETH_RMII_CLK_OUTPUT in CON-
FIG_ETH_RMII_CLK_MODE.
Note: REF_CLK is configured via Project Configuration as described above by default. However, it can be
overwritten from user application code by appropriately setting eth_esp32_emac_config_t::interface
and eth_esp32_emac_config_t::clock_config members. See emac_rmii_clock_mode_t and
emac_rmii_clock_gpio_t for more details.
Warning: If the RMII clock mode is selected to CONFIG_ETH_RMII_CLK_OUTPUT, then GPIO0 can be
used to output the REF_CLK signal. See CONFIG_ETH_RMII_CLK_OUTPUT_GPIO0 for more information.
What’s more, if you’re not using PSRAM in your design, GPIO16 and GPIO17 are also available to output
the reference clock. See CONFIG_ETH_RMII_CLK_OUT_GPIO for more information.
If the RMII clock mode is selected to CONFIG_ETH_RMII_CLK_INPUT, then GPIO0 is the only choice to
input the REF_CLK signal. Please note that, GPIO0 is also an important strapping GPIO on ESP32. If GPIO0
samples a low level during power up, ESP32 will go into download mode. The system will get halted until a
manually reset. The workaround of this issue is disabling the REF_CLK in hardware by default, so that the
strapping pin won’t be interfered by other signals in boot stage. Then re-enable the REF_CLK in Ethernet driver
installation stage. The ways to disable the REF_CLK signal can be:
• Disable or power down the crystal oscillator (as the case b in the picture).
• Force the PHY device in reset status (as the case a in the picture). This could fail for some PHY device
(i.e. it still outputs signal to GPIO0 even in reset state).
No matter which RMII clock mode you select, you really need to take care of the signal integrity of REF_CLK
in your hardware design! Keep the trace as short as possible. Keep it away from RF devices. Keep it away from
inductor elements.
Note: ESP-IDF only supports the RMII interface (i.e. always select CONFIG_ETH_PHY_INTERFACE_RMII in
Kconfig option CONFIG_ETH_PHY_INTERFACE).
Signals used in data plane are fixed to specific GPIOs via MUX, they can’t be modified to other GPIOs. Signals
used in control plane can be routed to any free GPIOs via Matrix. Please refer to ESP32-Ethernet-Kit for hardware
design example.
We need to setup necessary parameters for MAC and PHY respectively based on your Ethernet board design and
then combine the two together, completing the driver installation.
Configuration for MAC is described in eth_mac_config_t, including:
• eth_phy_config_t::phy_addr: multiple PHY device can share the same SMI bus, so each PHY
needs a unique address. Usually this address is configured during hardware design by pulling up/down some
PHY strapping pins. You can set the value from 0 to 15 based on your Ethernet board. Especially, if the SMI
bus is shared by only one PHY device, setting this value to -1 can enable the driver to detect the PHY address
automatically.
• eth_phy_config_t::reset_timeout_ms: reset timeout value, in milliseconds, typically PHY reset
should be finished within 100ms.
• eth_phy_config_t::autonego_timeout_ms: auto-negotiation timeout value, in milliseconds.
Ethernet driver will start negotiation with the peer Ethernet node automatically, to determine to duplex and
speed mode. This value usually depends on the ability of the PHY device on your board.
• eth_phy_config_t::reset_gpio_num: if your board also connect the PHY reset pin to one of the
GPIO, then set it here. Otherwise, set this field to -1.
ESP-IDF provides a default configuration for MAC and PHY in macro ETH_MAC_DEFAULT_CONFIG and
ETH_PHY_DEFAULT_CONFIG.
Create MAC and PHY Instance Ethernet driver is implemented in an Object-Oriented style. Any operation on
MAC and PHY should be based on the instance of them two.
Optional Runtime MAC Clock Configuration EMAC REF_CLK can be optionally configured from user appli-
cation code.
// ...
SPI-Ethernet Module
eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG(); // apply default MAC␣
,→configuration
// Install GPIO interrupt service (as the SPI-Ethernet module is interrupt driven)
gpio_install_isr_service(0);
// SPI bus configuration
spi_device_handle_t spi_handle = NULL;
spi_bus_config_t buscfg = {
.miso_io_num = CONFIG_EXAMPLE_ETH_SPI_MISO_GPIO,
.mosi_io_num = CONFIG_EXAMPLE_ETH_SPI_MOSI_GPIO,
.sclk_io_num = CONFIG_EXAMPLE_ETH_SPI_SCLK_GPIO,
.quadwp_io_num = -1,
.quadhd_io_num = -1,
};
ESP_ERROR_CHECK(spi_bus_initialize(CONFIG_EXAMPLE_ETH_SPI_HOST, &buscfg, 1));
// Allocate SPI device from the bus
spi_device_interface_config_t devcfg = {
.command_bits = 1,
.address_bits = 7,
.mode = 0,
.clock_speed_hz = CONFIG_EXAMPLE_ETH_SPI_CLOCK_MHZ * 1000 * 1000,
.spics_io_num = CONFIG_EXAMPLE_ETH_SPI_CS_GPIO,
.queue_size = 20
};
ESP_ERROR_CHECK(spi_bus_add_device(CONFIG_EXAMPLE_ETH_SPI_HOST, &devcfg, &spi_
,→handle));
Note:
• When creating MAC and PHY instance for SPI-Ethernet modules (e.g. DM9051), the constructor function
must have the same suffix (e.g. esp_eth_mac_new_dm9051 and esp_eth_phy_new_dm9051). This is because
we don’t have other choices but the integrated PHY.
• We have to create an SPI device handle firstly and then pass it to the MAC constructor function. More instruc-
tions on creating SPI device handle, please refer to SPI Master.
• The SPI device configuration (i.e. spi_device_interface_config_t) can be different for other Ethernet modules.
Please check out your module’s spec and the examples in esp-idf.
Install Driver To install the Ethernet driver, we need to combine the instance of MAC and PHY and set some
additional high-level configurations (i.e. not specific to either MAC or PHY) in esp_eth_config_t:
• esp_eth_config_t::mac: instance that created from MAC generator (e.g.
esp_eth_mac_new_esp32()).
• esp_eth_config_t::phy: instance that created from PHY generator (e.g.
esp_eth_phy_new_ip101()).
• esp_eth_config_t::check_link_period_ms: Ethernet driver starts an OS timer to check the link
status periodically, this field is used to set the interval, in milliseconds.
• esp_eth_config_t::stack_input: In most of Ethernet IoT applications, any Ethernet frame that
received by driver should be passed to upper layer (e.g. TCP/IP stack). This field is set to a function which
is responsible to deal with the incoming frames. You can even update this field at runtime via function
esp_eth_update_input_path() after driver installation.
• esp_eth_config_t::on_lowlevel_init_done and esp_eth_config_t::on_lowlevel_deinit_done:
These two fields are used to specify the hooks which get invoked when low level hardware has been initialized
or de-initialized.
ESP-IDF provides a default configuration for driver installation in macro ETH_DEFAULT_CONFIG.
Ethernet driver also includes event-driven model, which will send useful and important event to user space. We need to
initialize the event loop before installing the Ethernet driver. For more information about event-driven programming,
please refer to ESP Event.
switch (event_id) {
case ETHERNET_EVENT_CONNECTED:
esp_eth_ioctl(eth_handle, ETH_CMD_G_MAC_ADDR, mac_addr);
ESP_LOGI(TAG, "Ethernet Link Up");
ESP_LOGI(TAG, "Ethernet HW Addr %02x:%02x:%02x:%02x:%02x:%02x",
mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_
,→addr[4], mac_addr[5]);
break;
case ETHERNET_EVENT_DISCONNECTED:
ESP_LOGI(TAG, "Ethernet Link Down");
break;
case ETHERNET_EVENT_START:
ESP_LOGI(TAG, "Ethernet Started");
break;
case ETHERNET_EVENT_STOP:
(continues on next page)
Start Ethernet Driver After driver installation, we can start Ethernet immediately.
Connect Driver to TCP/IP Stack Up until now, we have installed the Ethernet driver. From the view of OSI
(Open System Interconnection), we’re still on level 2 (i.e. Data Link Layer). We can detect link up and down event,
we can gain MAC address in user space, but we can’t obtain IP address, let alone send HTTP request. The TCP/IP
stack used in ESP-IDF is called LwIP, for more information about it, please refer to LwIP.
To connect Ethernet driver to TCP/IP stack, these three steps need to follow:
1. Create network interface for Ethernet driver
2. Attach the network interface to Ethernet driver
3. Register IP event handlers
More information about network interface, please refer to Network Interface.
Warning: It is recommended to fully initialize the Ethernet driver and network interface prior registering user’
s Ethernet/IP event handlers, i.e. register the event handlers as the last thing prior starting the Ethernet driver.
Such approach ensures that Ethernet/IP events get executed first by the Ethernet driver or network interface and
so the system is in expected state when executing user’s handlers.
Misc control of Ethernet driver The following functions should only be invoked after the Ethernet driver has been
installed.
• Stop Ethernet driver: esp_eth_stop()
• Update Ethernet data input path: esp_eth_update_input_path()
• Misc get/set of Ethernet driver attributes: esp_eth_ioctl()
Flow control Ethernet on MCU usually has a limitation in the number of frames it can handle during network
congestion, because of the limitation in RAM size. A sending station might be transmitting data faster than the
peer end can accept it. Ethernet flow control mechanism allows the receiving node to signal the sender requesting
suspension of transmissions until the receiver catches up. The magic behind that is the pause frame, which was defined
in IEEE 802.3x.
Pause frame is a special Ethernet frame used to carry the pause command, whose EtherType field is 0x8808, with
the Control opcode set to 0x0001. Only stations configured for full-duplex operation may send pause frames. When
a station wishes to pause the other end of a link, it sends a pause frame to the 48-bit reserved multicast address
of 01-80-C2-00-00-01. The pause frame also includes the period of pause time being requested, in the form of a
two-byte integer, ranging from 0 to 65535.
After Ethernet driver installation, the flow control feature is disabled by default. You can enable it by:
One thing should be kept in mind, is that the pause frame ability will be advertised to peer end by PHY during auto
negotiation. Ethernet driver sends pause frame only when both sides of the link support it.
Application Examples
• Ethernet basic example: ethernet/basic.
• Ethernet iperf example: ethernet/iperf.
• Ethernet to Wi-Fi AP “router”: ethernet/eth2ap.
• Most of protocol examples should also work for Ethernet: protocols.
Advanced Topics
Custom PHY Driver There are multiple PHY manufactures with their wide portfolios of chips available. The
ESP-IDF already supports several PHY chips however one can easily get to a point where none of them satisfies user’
s actual needs due to either price, features, stock availability etc.
Luckily, a management interface between EMAC and PHY is standardized by IEEE 802.3 in 22.2.4 Management
functions section. It defines provisions of so called “MII Management Interface”for the purposes of control-
ling the PHY and gathering status from the PHY. A set of management registers is defined to control chip be-
havior, link properties, auto-negotiation configuration etc. This basic management functionality is addressed by
esp_eth/src/esp_eth_phy_802_3.c in ESP-IDF and so it makes a creation of new custom PHY chip driver quite a
simple task.
Note: Always consult with PHY datasheet since some PHY chips may not comply with IEEE 802.3, Section 22.2.4.
It does not mean you are not able to create a custom PHY driver, it will just require more effort. You will have to
define all PHY management functions.
Majority of PHY management functionality required by the ESP-IDF Ethernet driver is covered by the
esp_eth/src/esp_eth_phy_802_3.c however, the following may require developing chip specific management func-
tions:
• link status which is almost always chip specific,
• chip initialization, even though it is not strictly required, should be customized to at least ensure that expected
chip is used and
• chip specific features configuration.
Steps to create custom PHY driver:
1. Define vendor specific registry layout based on PHY datasheet. See esp_eth/src/esp_eth_phy_ip101.c as an
example.
2. Prepare derived PHY management object infostructure which
• must contain at least parent IEEE 802.3 phy_802_3_t object and
• optionally contain additional variables needed to support non-IEEE 802.3 or customized functionality.
See esp_eth/src/esp_eth_phy_ksz80xx.c as an example.
3. Define chip specific management call-back functions.
4. Initialize parent IEEE 802.3 object and re-assign chip specific management call-back functions.
Once you finish the new custom PHY driver implementation, consider sharing it among with other users via IDF
Component Registry.
API Reference
Header File
• components/esp_eth/include/esp_eth.h
Header File
• components/esp_eth/include/esp_eth_driver.h
Functions
esp_err_t esp_eth_driver_install(const esp_eth_config_t *config, esp_eth_handle_t *out_hdl)
Install Ethernet driver.
Parameters
• config –[in] configuration of the Ethernet driver
• out_hdl –[out] handle of Ethernet driver
Returns
• ESP_OK: install esp_eth driver successfully
Note: It’s not recommended to uninstall Ethernet driver unless it won’t get used any more in application
code. To uninstall Ethernet driver, you have to make sure, all references to the driver are released. Ethernet
driver can only be uninstalled successfully when reference counter equals to one.
Note: This API will start driver state machine and internal software timer (for checking link status).
Note: After install driver, Ethernet still don’t know where to deliver the input buffer. In fact, this API
registers a callback function which get invoked when Ethernet received new packets.
Parameters
• hdl –[in] handle of Ethernet driver
• stack_input –[in] function pointer, which does the actual process on incoming pack-
ets
• priv –[in] private resource, which gets passed to stack_input callback without any
modification
Returns
• ESP_OK: update input path successfully
• ESP_ERR_INVALID_ARG: update input path failed because of some invalid argument
• ESP_FAIL: update input path failed because some other error occurred
• ETH_CMD_S_AUTONEGO enables or disables Ethernet link speed and duplex mode autonegotiation.
data argument is pointer to memory of bool datatype from which the configuration option is read.
Preconditions: Ethernet driver needs to be stopped.
• ETH_CMD_G_AUTONEGO gets current configuration of the Ethernet link speed and duplex mode au-
tonegotiation. data argument is pointer to memory of bool datatype to which the current configuration
is to be stored.
• ETH_CMD_S_SPEED sets the Ethernet link speed. data argument is pointer to memory of eth_speed_t
datatype from which the configuration option is read. Preconditions: Ethernet driver needs to be stopped
and auto-negotiation disabled.
• ETH_CMD_G_SPEED gets current Ethernet link speed. data argument is pointer to memory of
eth_speed_t datatype to which the speed is to be stored.
• ETH_CMD_S_PROMISCUOUS sets/resets Ethernet interface promiscuous mode. data argument is
pointer to memory of bool datatype from which the configuration option is read.
• ETH_CMD_S_FLOW_CTRL sets/resets Ethernet interface flow control. data argument is pointer to
memory of bool datatype from which the configuration option is read.
• ETH_CMD_S_DUPLEX_MODE sets the Ethernet duplex mode. data argument is pointer to memory of
eth_duplex_t datatype from which the configuration option is read. Preconditions: Ethernet driver needs
to be stopped and auto-negotiation disabled.
• ETH_CMD_G_DUPLEX_MODE gets current Ethernet link duplex mode. data argument is pointer to
memory of eth_duplex_t datatype to which the duplex mode is to be stored.
• ETH_CMD_S_PHY_LOOPBACK sets/resets PHY to/from loopback mode. data argument is pointer
to memory of bool datatype from which the configuration option is read.
• Note that additional control commands may be available for specific MAC or PHY chips. Please consult
specific MAC or PHY documentation or driver code.
Parameters
• hdl –[in] handle of Ethernet driver
• cmd –[in] IO control command
• data –[inout] address of data for set command or address where to store the data when
used with get command
Returns
• ESP_OK: process io command successfully
• ESP_ERR_INVALID_ARG: process io command failed because of some invalid argu-
ment
• ESP_FAIL: process io command failed because some other error occurred
• ESP_ERR_NOT_SUPPORTED: requested feature is not supported
Note: Ethernet driver handle can be obtained by os timer, netif, etc. It’s dangerous when thread A is using
Ethernet but thread B uninstall the driver. Using reference counter can prevent such risk, but care should be
taken, when you obtain Ethernet driver, this API must be invoked so that the driver won’t be uninstalled
during your using time.
Structures
struct esp_eth_config_t
Configuration of Ethernet driver.
Public Members
esp_eth_mac_t *mac
Ethernet MAC object.
esp_eth_phy_t *phy
Ethernet PHY object.
uint32_t check_link_period_ms
Period time of checking Ethernet link status.
Note: Usually the PHY register read/write function is provided by MAC (SMI interface), but if the
PHY device is managed by other interface (e.g. I2C), then user needs to implement the corresponding
read/write. Setting this to NULL means your PHY device is managed by MAC’s SMI interface.
Note: Usually the PHY register read/write function is provided by MAC (SMI interface), but if the
PHY device is managed by other interface (e.g. I2C), then user needs to implement the corresponding
read/write. Setting this to NULL means your PHY device is managed by MAC’s SMI interface.
Macros
ETH_DEFAULT_CONFIG(emac, ephy)
Default configuration for Ethernet driver.
Type Definitions
Enumerations
enum esp_eth_io_cmd_t
Command list for ioctl API.
Values:
enumerator ETH_CMD_G_MAC_ADDR
Get MAC address
enumerator ETH_CMD_S_MAC_ADDR
Set MAC address
enumerator ETH_CMD_G_PHY_ADDR
Get PHY address
enumerator ETH_CMD_S_PHY_ADDR
Set PHY address
enumerator ETH_CMD_G_AUTONEGO
Get PHY Auto Negotiation
enumerator ETH_CMD_S_AUTONEGO
Set PHY Auto Negotiation
enumerator ETH_CMD_G_SPEED
Get Speed
enumerator ETH_CMD_S_SPEED
Set Speed
enumerator ETH_CMD_S_PROMISCUOUS
Set promiscuous mode
enumerator ETH_CMD_S_FLOW_CTRL
Set flow control
enumerator ETH_CMD_G_DUPLEX_MODE
Get Duplex mode
enumerator ETH_CMD_S_DUPLEX_MODE
Set Duplex mode
enumerator ETH_CMD_S_PHY_LOOPBACK
Set PHY loopback
enumerator ETH_CMD_CUSTOM_MAC_CMDS
enumerator ETH_CMD_CUSTOM_PHY_CMDS
Header File
• components/esp_eth/include/esp_eth_com.h
Structures
struct esp_eth_mediator_s
Ethernet mediator.
Public Members
Type Definitions
Enumerations
enum esp_eth_state_t
Ethernet driver state.
Values:
enumerator ETH_STATE_LLINIT
Lowlevel init done
enumerator ETH_STATE_DEINIT
Deinit done
enumerator ETH_STATE_LINK
Link status changed
enumerator ETH_STATE_SPEED
Speed updated
enumerator ETH_STATE_DUPLEX
Duplex updated
enumerator ETH_STATE_PAUSE
Pause ability updated
enum eth_event_t
Ethernet event declarations.
Values:
enumerator ETHERNET_EVENT_START
Ethernet driver start
enumerator ETHERNET_EVENT_STOP
Ethernet driver stop
enumerator ETHERNET_EVENT_CONNECTED
Ethernet got a valid link
enumerator ETHERNET_EVENT_DISCONNECTED
Ethernet lost a valid link
Header File
• components/esp_eth/include/esp_eth_mac.h
Functions
esp_eth_mac_t *esp_eth_mac_new_esp32(const eth_esp32_emac_config_t *esp32_config, const
eth_mac_config_t *config)
Create ESP32 Ethernet MAC instance.
Parameters
• esp32_config –EMAC specific configuration
• config –Ethernet MAC configuration
Returns
• instance: create MAC instance successfully
• NULL: create MAC instance failed because some error occurred
Unions
union eth_mac_clock_config_t
#include <esp_eth_mac.h> Ethernet MAC Clock Configuration.
Public Members
emac_rmii_clock_mode_t clock_mode
RMII Clock Mode Configuration
emac_rmii_clock_gpio_t clock_gpio
RMII Clock GPIO Configuration
Structures
struct esp_eth_mac_s
Ethernet MAC.
Public Members
Note: Returned error codes may differ for each specific MAC chip.
Note: Typical intended use case is to make possible to construct a frame from multiple higher layer
buffers without a need of buffer reallocations. However, other use cases are not limited.
Note: Returned error codes may differ for each specific MAC chip.
Note: Memory of buf is allocated in the Layer2, make sure it get free after process.
Note: Before this function got invoked, the value of “length”should set by user, equals the size of
buffer. After the function returned, the value of “length”means the real length of received data.
Note: This function may not be assigned when the MAC chip supports only most common set of
configuration options.
struct eth_mac_config_t
Configuration of Ethernet MAC object.
Public Members
uint32_t sw_reset_timeout_ms
Software reset timeout value (Unit: ms)
uint32_t rx_task_stack_size
Stack size of the receive task
uint32_t rx_task_prio
Priority of the receive task
uint32_t flags
Flags that specify extra capability for mac driver
struct eth_esp32_emac_config_t
EMAC specific configuration.
Public Members
int smi_mdc_gpio_num
SMI MDC GPIO number, set to -1 could bypass the SMI GPIO configuration
int smi_mdio_gpio_num
SMI MDIO GPIO number, set to -1 could bypass the SMI GPIO configuration
eth_data_interface_t interface
EMAC Data interface to PHY (MII/RMII)
eth_mac_clock_config_t clock_config
EMAC Interface clock configuration
eth_mac_dma_burst_len_t dma_burst_len
EMAC DMA burst length for both Tx and Rx
Macros
ETH_MAC_FLAG_WORK_WITH_CACHE_DISABLE
MAC driver can work when cache is disabled
ETH_MAC_FLAG_PIN_TO_CORE
Pin MAC task to the CPU core where driver installation happened
ETH_MAC_DEFAULT_CONFIG()
Default configuration for Ethernet MAC object.
ETH_ESP32_EMAC_DEFAULT_CONFIG()
Default ESP32’s EMAC specific configuration.
Type Definitions
Enumerations
enum emac_rmii_clock_mode_t
RMII Clock Mode Options.
Values:
enumerator EMAC_CLK_DEFAULT
Default values configured using Kconfig are going to be used when “Default”selected.
enumerator EMAC_CLK_EXT_IN
Input RMII Clock from external. EMAC Clock GPIO number needs to be configured when this option
is selected.
Note: MAC will get RMII clock from outside. Note that ESP32 only supports GPIO0 to input the RMII
clock.
enumerator EMAC_CLK_OUT
Output RMII Clock from internal APLL Clock. EMAC Clock GPIO number needs to be configured
when this option is selected.
enum emac_rmii_clock_gpio_t
RMII Clock GPIO number Options.
Values:
enumerator EMAC_CLK_IN_GPIO
MAC will get RMII clock from outside at this GPIO.
enumerator EMAC_APPL_CLK_OUT_GPIO
Output RMII Clock from internal APLL Clock available at GPIO0.
Note: GPIO0 can be set to output a pre-divided PLL clock (test only!). Enabling this option will
configure GPIO0 to output a 50MHz clock. In fact this clock doesn’t have directly relationship with
EMAC peripheral. Sometimes this clock won’t work well with your PHY chip. You might need to
add some extra devices after GPIO0 (e.g. inverter). Note that outputting RMII clock on GPIO0 is an
experimental practice. If you want the Ethernet to work with WiFi, don’t select GPIO0 output mode
for stability.
enumerator EMAC_CLK_OUT_GPIO
Output RMII Clock from internal APLL Clock available at GPIO16.
enumerator EMAC_CLK_OUT_180_GPIO
Inverted Output RMII Clock from internal APLL Clock available at GPIO17.
Header File
• components/esp_eth/include/esp_eth_phy.h
Functions
esp_eth_phy_t *esp_eth_phy_new_ip101(const eth_phy_config_t *config)
Create a PHY instance of IP101.
Parameters config –[in] configuration of PHY
Returns
• instance: create PHY instance successfully
• NULL: create PHY instance failed because some error occurred
esp_eth_phy_t *esp_eth_phy_new_rtl8201(const eth_phy_config_t *config)
Create a PHY instance of RTL8201.
Parameters config –[in] configuration of PHY
Returns
• instance: create PHY instance successfully
• NULL: create PHY instance failed because some error occurred
esp_eth_phy_t *esp_eth_phy_new_lan87xx(const eth_phy_config_t *config)
Create a PHY instance of LAN87xx.
Structures
struct esp_eth_phy_s
Ethernet PHY.
Public Members
Note: Hardware reset is mostly done by pull down and up PHY’s nRST pin
• ESP_FAIL: set Ethernet PHY address failed because some error occurred
Note: Autonegotiation feature needs to be disabled prior to calling this function for the new setting to
be applied
Note: Autonegotiation feature needs to be disabled prior to calling this function for the new setting to
be applied
Note: This function may not be assigned when the PHY chip supports only most common set of con-
figuration options.
struct eth_phy_config_t
Ethernet PHY configuration.
Public Members
int32_t phy_addr
PHY address, set -1 to enable PHY address detection at initialization stage
uint32_t reset_timeout_ms
Reset timeout value (Unit: ms)
uint32_t autonego_timeout_ms
Auto-negotiation timeout value (Unit: ms)
int reset_gpio_num
Reset GPIO number, -1 means no hardware reset
Macros
ESP_ETH_PHY_ADDR_AUTO
ETH_PHY_DEFAULT_CONFIG()
Default configuration for Ethernet PHY object.
Type Definitions
Enumerations
enum eth_phy_autoneg_cmd_t
Auto-negotiation controll commands.
Values:
enumerator ESP_ETH_PHY_AUTONEGO_RESTART
enumerator ESP_ETH_PHY_AUTONEGO_EN
enumerator ESP_ETH_PHY_AUTONEGO_DIS
enumerator ESP_ETH_PHY_AUTONEGO_G_STAT
Header File
• components/esp_eth/include/esp_eth_phy_802_3.h
Functions
esp_err_t esp_eth_phy_802_3_reset_hw(phy_802_3_t *phy_802_3, uint32_t reset_assert_us)
Performs hardware reset with specific reset pin assertion time.
Parameters
• phy_802_3 –IEEE 802.3 PHY object infostructure
• reset_assert_us –Hardware reset pin assertion time
Returns
• ESP_OK: reset Ethernet PHY successfully
esp_err_t esp_eth_phy_802_3_detect_phy_addr(esp_eth_mediator_t *eth, int *detected_addr)
Detect PHY address.
Parameters
• eth –Mediator of Ethernet driver
• detected_addr –[out] a valid address after detection
Returns
• ESP_OK: detect phy address successfully
• ESP_ERR_INVALID_ARG: invalid parameter
• ESP_ERR_NOT_FOUND: can’t detect any PHY device
• ESP_FAIL: detect phy address failed because some error occurred
esp_err_t esp_eth_phy_802_3_basic_phy_init(phy_802_3_t *phy_802_3)
Performs basic PHY chip initialization.
Note: It should be called as the first function in PHY specific driver instance
Note: It should be called as the last function in PHY specific driver instance
Structures
struct phy_802_3_t
IEEE 802.3 PHY object infostructure.
Public Members
esp_eth_phy_t parent
Parent Ethernet PHY instance
esp_eth_mediator_t *eth
Mediator of Ethernet driver
int addr
PHY address
uint32_t reset_timeout_ms
Reset timeout value (Unit: ms)
uint32_t autonego_timeout_ms
Auto-negotiation timeout value (Unit: ms)
eth_link_t link_status
Current Link status
int reset_gpio_num
Reset GPIO number, -1 means no hardware reset
Header File
• components/esp_eth/include/esp_eth_netif_glue.h
Functions
esp_eth_netif_glue_handle_t esp_eth_new_netif_glue(esp_eth_handle_t eth_hdl)
Create a netif glue for Ethernet driver.
Type Definitions
2.5.3 Thread
Thread
Introduction Thread is a IP-based mesh networking protocol. It’s based on the 802.15.4 physical and MAC
layer.
Application Examples The openthread directory of ESP-IDF examples contains the following applications:
• The OpenThread interactive shell openthread/ot_cli.
• The Thread border router openthread/ot_br.
• The Thread radio co-processor openthread/ot_rcp.
API Reference For manipulating the Thread network, the OpenThread api shall be used. The OpenThread api
docs can be found at the OpenThread official website.
ESP-IDF provides extra apis for launching and managing the OpenThread stack, binding to network interfaces and
border routing features.
Header File
• components/openthread/include/esp_openthread.h
Functions
esp_err_t esp_openthread_init(const esp_openthread_platform_config_t *init_config)
Initializes the full OpenThread stack.
Note: Thie function will not return unless error happens when running the OpenThread stack.
Returns
• ESP_OK on success
• ESP_ERR_NO_MEM if allocation has failed
• ESP_FAIL on other failures
esp_err_t esp_openthread_deinit(void)
This function performs OpenThread stack and platform driver deinitialization.
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if not initialized
otInstance *esp_openthread_get_instance(void)
This function acquires the underlying OpenThread instance.
Header File
• components/openthread/include/esp_openthread_types.h
Structures
struct esp_openthread_mainloop_context_t
This structure represents a context for a select() based mainloop.
Public Members
fd_set read_fds
The read file descriptors
fd_set write_fds
The write file descriptors
fd_set error_fds
The error file descriptors
int max_fd
The max file descriptor
struct esp_openthread_uart_config_t
The uart port config for OpenThread.
Public Members
uart_port_t port
UART port number
uart_config_t uart_config
UART configuration, see uart_config_t docs
int rx_pin
UART RX pin
int tx_pin
UART TX pin
struct esp_openthread_radio_config_t
The OpenThread radio configuration.
Public Members
esp_openthread_radio_mode_t radio_mode
The radio mode
esp_openthread_uart_config_t radio_uart_config
The uart configuration to RCP
struct esp_openthread_host_connection_config_t
The OpenThread host connection configuration.
Public Members
esp_openthread_host_connection_mode_t host_connection_mode
The host connection mode
esp_openthread_uart_config_t host_uart_config
The uart configuration to host
struct esp_openthread_port_config_t
The OpenThread port specific configuration.
Public Members
uint8_t netif_queue_size
The packet queue size for the network interface
uint8_t task_queue_size
The task queue size
struct esp_openthread_platform_config_t
The OpenThread platform configuration.
Public Members
esp_openthread_radio_config_t radio_config
The radio configuration
esp_openthread_host_connection_config_t host_config
The host connection configuration
esp_openthread_port_config_t port_config
The port configuration
Type Definitions
Enumerations
enum esp_openthread_event_t
OpenThread event declarations.
Values:
enumerator OPENTHREAD_EVENT_START
OpenThread stack start
enumerator OPENTHREAD_EVENT_STOP
OpenThread stack stop
enumerator OPENTHREAD_EVENT_IF_UP
OpenThread network interface up
enumerator OPENTHREAD_EVENT_IF_DOWN
OpenThread network interface down
enumerator OPENTHREAD_EVENT_GOT_IP6
OpenThread stack added IPv6 address
enumerator OPENTHREAD_EVENT_LOST_IP6
OpenThread stack removed IPv6 address
enumerator OPENTHREAD_EVENT_MULTICAST_GROUP_JOIN
OpenThread stack joined IPv6 multicast group
enumerator OPENTHREAD_EVENT_MULTICAST_GROUP_LEAVE
OpenThread stack left IPv6 multicast group
enumerator OPENTHREAD_EVENT_TREL_ADD_IP6
OpenThread stack added TREL IPv6 address
enumerator OPENTHREAD_EVENT_TREL_REMOVE_IP6
OpenThread stack removed TREL IPv6 address
enumerator OPENTHREAD_EVENT_TREL_MULTICAST_GROUP_JOIN
OpenThread stack joined TREL IPv6 multicast group
enum esp_openthread_radio_mode_t
The radio mode of OpenThread.
Values:
enumerator RADIO_MODE_NATIVE
Use the native 15.4 radio
enumerator RADIO_MODE_UART_RCP
UART connection to a 15.4 capable radio co-processor (RCP)
enumerator RADIO_MODE_SPI_RCP
SPI connection to a 15.4 capable radio co-processor (RCP)
enum esp_openthread_host_connection_mode_t
How OpenThread connects to the host.
Values:
enumerator HOST_CONNECTION_MODE_NONE
Disable host connection
enumerator HOST_CONNECTION_MODE_CLI_UART
CLI UART connection to the host
enumerator HOST_CONNECTION_MODE_RCP_UART
RCP UART connection to the host
Header File
• components/openthread/include/esp_openthread_lock.h
Functions
esp_err_t esp_openthread_lock_init(void)
This function initializes the OpenThread API lock.
Returns
• ESP_OK on success
• ESP_ERR_NO_MEM if allocation has failed
• ESP_ERR_INVALID_STATE if already initialized
void esp_openthread_lock_deinit(void)
This function deinitializes the OpenThread API lock.
bool esp_openthread_lock_acquire(TickType_t block_ticks)
This functions acquires the OpenThread API lock.
Note: Every OT APIs that takes an otInstance argument MUST be protected with this API lock except that
the call site is in OT callbacks.
Parameters block_ticks –[in] The maxinum number of RTOS ticks to wait for the lock.
Returns
• True on lock acquired
• False on failing to acquire the lock with the timeout.
void esp_openthread_lock_release(void)
This function releases the OpenThread API lock.
Header File
• components/openthread/include/esp_openthread_netif_glue.h
Functions
void *esp_openthread_netif_glue_init(const esp_openthread_platform_config_t *config)
This function initializes the OpenThread network interface glue.
Parameters config –[in] The platform configuration.
Returns
• glue pointer on success
• NULL on failure
void esp_openthread_netif_glue_deinit(void)
This function deinitializes the OpenThread network interface glue.
esp_netif_t *esp_openthread_get_netif(void)
This function acquires the OpenThread netif.
Returns The OpenThread netif or NULL if not initialzied.
Header File
• components/openthread/include/esp_openthread_border_router.h
Functions
void esp_openthread_set_backbone_netif(esp_netif_t *backbone_netif)
Sets the backbone interface used for border routing.
Note: Calling this function will make the device behave as an OpenThread border router. Kconfig option
CONFIG_OPENTHREAD_BORDER_ROUTER is required.
Returns
• ESP_OK on success
• ESP_ERR_NOT_SUPPORTED if feature not supported
esp_err_t esp_openthread_border_router_deinit(void)
Deinitializes the border router features of OpenThread.
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if not initialized
• ESP_FIAL on other failures
esp_netif_t *esp_openthread_get_backbone_netif(void)
Gets the backbone interface of OpenThread border router.
Returns The backbone interface or NULL if border router not initialized.
void esp_openthread_register_rcp_failure_handler(esp_openthread_rcp_failure_handler
handler)
Registers the callback for RCP failure.
void esp_openthread_rcp_deinit(void)
Deinitializes the conneciton to RCP.
Thread is an IPv6-based mesh networking technology for IoT. Code examples for the Thread API are provided in
the openthread directory of ESP-IDF examples.
2.5.4 ESP-NETIF
ESP-NETIF
ESP-NETIF architecture
| (A) USER CODE |
| |
.................| init settings events |
. +----------------------------------------+
. . | *
. . | *
--------+ +===========================+ * +---------------------
,→--+
| | new/config get/set | * | ␣
,→ |
| | |...*.....| init ␣
,→ |
| |---------------------------| * | ␣
,→ |
init | | |**** | ␣
,→ | (continues on next page)
--------+ | | +===========================+
communication | | NETWORK STACK
DRIVER | | ESP-NETIF
| | +------------------+
| | +---------------------------+.........| open/close |
| | | | | |
| -<--| l2tap_write |-----<---| write |
| | | | |
---->--| esp_vfs_l2tap_eth_filter |----->---| read |
| | | |
| (E) | +------------------+
+---------------------------+
USER CODE
ESP-NETIF L2 TAP
ESP-NETIF interaction
A) User code, boiler plate Overall application interaction with a specific IO driver for communication media and
configured TCP/IP network stack is abstracted using ESP-NETIF APIs and outlined as below:
A) Initialization code
1) Initializes IO driver
2) Creates a new instance of ESP-NETIF and configure with
• ESP-NETIF specific options (flags, behaviour, name)
• Network stack options (netif init and input functions, not publicly available)
B) Communication driver, IO driver, media driver Communication driver plays these two important roles in
relation with ESP-NETIF:
1) Event handlers: Define behaviour patterns of interaction with ESP-NETIF (for example: ethernet link-up ->
turn netif on)
2) Glue IO layer: Adapts the input/output functions to use ESP-NETIF transmit, receive and free receive buffer
• Installs driver_transmit to appropriate ESP-NETIF object, so that outgoing packets from network stack are
passed to the IO driver
• Calls esp_netif_receive() to pass incoming data to network stack
C) ESP-NETIF ESP-NETIF is an intermediary between an IO driver and a network stack, connecting packet data
path between these two. As that it provides a set of interfaces for attaching a driver to ESP-NETIF object (runtime)
and configuring a network stack (compile time). In addition to that a set of API is provided to control network
interface lifecycle and its TCP/IP properties. As an overview, the ESP-NETIF public interface could be divided into
these 6 groups:
1) Initialization APIs (to create and configure ESP-NETIF instance)
2) Input/Output API (for passing data between IO driver and network stack)
3) Event or Action API
• Used for network interface lifecycle management
• ESP-NETIF provides building blocks for designing event handlers
4) Setters and Getters for basic network interface properties
5) Network stack abstraction: enabling user interaction with TCP/IP stack
• Set interface up or down
• DHCP server and client API
• DNS API
6) Driver conversion utilities
D) Network stack Network stack has no public interaction with application code with regard to public interfaces
and shall be fully abstracted by ESP-NETIF API.
E) ESP-NETIF L2 TAP Interface The ESP-NETIF L2 TAP interface is ESP-IDF mechanism utilized to access
Data Link Layer (L2 per OSI/ISO) for frame reception and transmission from user application. Its typical usage in
embedded world might be implementation of non-IP related protocols such as PTP, Wake on LAN and others. Note
that only Ethernet (IEEE 802.3) is currently supported.
From user perspective, the ESP-NETIF L2 TAP interface is accessed using file descriptors of VFS which provides a
file-like interfacing (using functions like open(), read(), write(), etc). Refer to Virtual filesystem component
to learn more.
There is only one ESP-NETIF L2 TAP interface device (path name) available. However multiple file descriptors with
different configuration can be opened at a time since the ESP-NETIF L2 TAP interface can be understood as generic
entry point to Layer 2 infrastructure. Important is then specific configuration of particular file descriptor. It can be
configured to give an access to specific Network Interface identified by if_key (e.g. ETH_DEF) and to filter only
specific frames based on their type (e.g. Ethernet type in case of IEEE 802.3). Filtering only specific frames is crucial
since the ESP-NETIF L2 TAP needs to exist along with IP stack and so the IP related traffic (IP, ARP, etc.) should
not be passed directly to the user application. Even though such option is still configurable, it is not recommended in
standard use cases. Filtering is also advantageous from a perspective the user’s application gets access only to frame
types it is interested in and the remaining traffic is either passed to other L2 TAP file descriptors or to IP stack.
Initialization To be able to use the ESP-NETIF L2 TAP interface, it needs to be enabled in Kconfig by CON-
FIG_ESP_NETIF_L2_TAP first and then registered by esp_vfs_l2tap_intf_register() prior usage of
any VFS function.
open() Once the ESP-NETIF L2 TAP is registered, it can be opened at path name“/dev/net/tap”. The same path
name can be opened multiple times up to CONFIG_ESP_NETIF_L2_TAP_MAX_FDS and multiple file descriptors
with with different configuration may access the Data Link Layer frames.
The ESP-NETIF L2 TAP can be opened with O_NONBLOCK file status flag to the read() does not block. Note that
the write() may block in current implementation when accessing a Network interface since it is a shared resource
among multiple ESP-NETIF L2 TAP file descriptors and IP stack, and there is currently no queuing mechanism
deployed. The file status flag can be retrieved and modified using fcntl().
On success, open() returns the new file descriptor (a nonnegative integer). On error, -1 is returned and errno is
set to indicate the error.
ioctl() The newly opened ESP-NETIF L2 TAP file descriptor needs to be configured prior its usage since it is not
bounded to any specific Network Interface and no frame type filter is configured. The following configuration options
are available to do so:
• L2TAP_S_INTF_DEVICE - bounds the file descriptor to specific Network Interface which is iden-
tified by its if_key. ESP-NETIF Network Interface if_key is passed to ioctl() as the third
parameter. Note that default Network Interfaces if_key’s used in ESP-IDF can be found in
esp_netif/include/esp_netif_defaults.h.
• L2TAP_S_DEVICE_DRV_HNDL - is other way how to bound the file descriptor to specific Network Interface.
In this case the Network interface is identified directly by IO Driver handle (e.g. esp_eth_handle_t in
case of Ethernet). The IO Driver handle is passed to ioctl() as the third parameter.
• L2TAP_S_RCV_FILTER - sets the filter to frames with this type to be passed to the file descriptor. In case of
Ethernet frames, the frames are to be filtered based on Length/Ethernet type field. In case the filter value is set
less than or equal to 0x05DC, the Ethernet type field is considered to represent IEEE802.3 Length Field and all
frames with values in interval <0, 0x05DC> at that field are to be passed to the file descriptor. The IEEE802.2
logical link control (LLC) resolution is then expected to be performed by user’s application. In case the filter
value is set greater than 0x05DC, the Ethernet type field is considered to represent protocol identification and
only frames which are equal to the set value are to be passed to the file descriptor.
All above set configuration options have getter counterpart option to read the current settings.
Warning: The file descriptor needs to be firstly bounded to specific Network Interface by
L2TAP_S_INTF_DEVICE or L2TAP_S_DEVICE_DRV_HNDL to be L2TAP_S_RCV_FILTER option
available.
Note: VLAN tagged frames are currently not recognized. If user needs to process VLAN tagged frames, they need
set filter to be equal to VLAN tag (i.e. 0x8100 or 0x88A8) and process the VLAN tagged frames in user application.
Note: L2TAP_S_DEVICE_DRV_HNDL is particularly useful when user’s application does not require usage of
IP stack and so ESP-NETIF is not required to be initialized too. As a result, Network Interface cannot be identified
by its if_key and hence it needs to be identified directly by its IO Driver handle.
On success, ioctl() returns 0. On error, -1 is returned, and errno is set to indicate the error.
EBADF - not a valid file descriptor.
EACCES - option change is denied in this state (e.g. file descriptor has not be bounded to Network interface yet).
EINVAL - invalid configuration argument. Ethernet type filter is already used by other file descriptor on that same
Network interface.
ENODEV - no such Network Interface which is tried to be assigned to the file descriptor exists.
ENOSYS - unsupported operation, passed configuration option does not exists.
fcntl() fcntl() is used to manipulate with properties of opened ESP-NETIF L2 TAP file descriptor.
The following commands manipulate the status flags associated with file descriptor:
• F_GETFD - the function returns the file descriptor flags, the third argument is ignored.
• F_SETFD - sets the file descriptor flags to the value specified by the third argument. Zero is returned.
read() Opened and configured ESP-NETIF L2 TAP file descriptor can be accessed by read() to get inbound
frames. The read operation can be either blocking or non-blocking based on actual state of O_NONBLOCK file status
flag. When the file status flag is set blocking, the read operation waits until a frame is received and context is switched
to other task. When the file status flag is set non-blocking, the read operation returns immediately. In such case,
either a frame is returned if it was already queued or the function indicates the queue is empty. The number of
queued frames associated with one file descriptor is limited by CONFIG_ESP_NETIF_L2_TAP_RX_QUEUE_SIZE
Kconfig option. Once the number of queued frames reach configured threshold, the newly arriving frames are dropped
until the queue has enough room to accept incoming traffic (Tail Drop queue management).
On success, read() returns the number of bytes read. Zero is returned when size of the destination buffer is 0. On
error, -1 is returned, and errno is set to indicate the error.
EBADF - not a valid file descriptor.
EAGAIN - the file descriptor has been marked non-blocking (O_NONBLOCK), and the read would block.
write() A raw Data Link Layer frame can be sent to Network Interface via opened and configured ESP-NETIF L2
TAP file descriptor. User’s application is responsible to construct the whole frame except for fields which are added
automatically by the physical interface device. The following fields need to be constructed by the user’s application
in case of Ethernet link: source/destination MAC addresses, Ethernet type, actual protocol header and user data. See
below for more information about Ethernet frame structure.
+-------------------+-------------------+-------------+----------------------------
,→--- --+
| Destination MAC | Source MAC | Type/Length | Payload (protocol header/
,→data) ... |
+-------------------+-------------------+-------------+----------------------------
,→--- --+
6B 6B 2B 0-1486B
In other words, there is no additional frame processing performed by the ESP-NETIF L2 TAP interface. It only
checks the Ethernet type of the frame is the same as the filter configured in the file descriptor. If the Ethernet type is
different, an error is returned and the frame is not sent. Note that the write() may block in current implementation
when accessing a Network interface since it is a shared resource among multiple ESP-NETIF L2 TAP file descriptors
and IP stack, and there is currently no queuing mechanism deployed.
On success, write() returns the number of bytes written. Zero is returned when size of the input buffer is 0. On
error, -1 is returned, and errno is set to indicate the error.
EBADF - not a valid file descriptor.
EBADMSG - Ethernet type of the frame is different then file descriptor configured filter.
EIO - Network interface not available or busy.
close() Opened ESP-NETIF L2 TAP file descriptor can be closed by the close() to free its allocated resources.
The ESP-NETIF L2 TAP implementation of close() may block. On the other hand, it is thread safe and can be
called from different task than the file descriptor is actually used. If such situation occurs and one task is blocked
in I/O operation and another task tries to close the file descriptor, the first task is unblocked. The first’s task read
operation then ends with error.
On success, close() returns zero. On error, -1 is returned, and errno is set to indicate the error.
EBADF - not a valid file descriptor.
select() Select is used in a standard way, just CONFIG_VFS_SUPPORT_SELECT needs to be enabled to be the
select() function available.
ESP-NETIF programmer’s manual Please refer to the example section for basic initialization of default inter-
faces:
• WiFi Station: wifi/getting_started/station/main/station_example_main.c
• Ethernet: ethernet/basic/main/ethernet_example_main.c
• L2 TAP: protocols/l2tap/main/l2tap_main.c
• WiFi Access Point: wifi/getting_started/softAP/main/softap_example_main.c
For more specific cases please consult this guide: ESP-NETIF Custom I/O Driver.
WiFi default initialization The initialization code as well as registering event handlers for default interfaces, such
as softAP and station, are provided in separate APIs to facilitate simple startup code for most applications:
• esp_netif_create_default_wifi_sta()
• esp_netif_create_default_wifi_ap()
Please note that these functions return the esp_netif handle, i.e. a pointer to a network interface object allocated
and configured with default settings, which as a consequence, means that:
• The created object has to be destroyed if a network de-initialization is provided by an application using
esp_netif_destroy_default_wifi().
• These default interfaces must not be created multiple times, unless the created handle is deleted using
esp_netif_destroy().
• When using Wifi in AP+STA mode, both these interfaces has to be created.
API Reference
Header File
• components/esp_netif/include/esp_netif.h
Functions
esp_err_t esp_netif_init(void)
Initialize the underlying TCP/IP stack.
Note: This function should be called exactly once from application code, when the application starts up.
Returns
• ESP_OK on success
• ESP_FAIL if initializing failed
esp_err_t esp_netif_deinit(void)
Deinitialize the esp-netif component (and the underlying TCP/IP stack)
Returns
• ESP_ERR_INVALID_STATE if esp_netif not initialized
• ESP_ERR_NOT_SUPPORTED otherwise
• ESP_OK on success
• ESP_ERR_ESP_NETIF_DRIVER_ATTACH_FAILED if driver’s pot_attach callback
failed
esp_err_t esp_netif_receive(esp_netif_t *esp_netif, void *buffer, size_t len, void *eb)
Passes the raw packets from communication media to the appropriate TCP/IP stack.
This function is called from the configured (peripheral) driver layer. The data are then forwarded as frames to
the TCP/IP stack.
Parameters
• esp_netif –[in] Handle to esp-netif instance
• buffer –[in] Received data
• len –[in] Length of the data frame
• eb –[in] Pointer to internal buffer (used in Wi-Fi driver)
Returns
• ESP_OK
void esp_netif_action_start(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data)
Default building block for network interface action upon IO driver start event Creates network interface, if
AUTOUP enabled turns the interface on, if DHCPS enabled starts dhcp server.
Parameters
• esp_netif –[in] Handle to esp-netif instance
• base –
• event_id –
• data –
Parameters
• esp_netif –[in] Handle to esp-netif instance
• base –
• event_id –
• data –
Parameters
• esp_netif –[in] Handle to esp-netif instance
• base –
• event_id –
• data –
Parameters
• esp_netif –[in] Handle to esp-netif instance
• base –
• event_id –
• data –
Parameters
• esp_netif –[in] Handle to esp-netif instance
• base –
• event_id –
• data –
Parameters
• esp_netif –[in] Handle to esp-netif instance
• base –
• event_id –
• data –
Parameters
• esp_netif –[in] Handle to esp-netif instance
• base –
• event_id –
• data –
Parameters
• esp_netif –[in] Handle to esp-netif instance
• base –
• event_id –
• data –
Parameters
• esp_netif –[in] Handle to esp-netif instance
• base –
• event_id –
• data –
Parameters
• esp_netif –[in] Handle to esp-netif instance
• hostname –[in] New hostname for the interface. Maximum length 32 bytes.
Returns
• ESP_OK - success
• ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error
• ESP_ERR_ESP_NETIF_INVALID_PARAMS - parameter error
esp_err_t esp_netif_get_hostname(esp_netif_t *esp_netif, const char **hostname)
Get interface hostname.
Parameters
• esp_netif –[in] Handle to esp-netif instance
• hostname –[out] Returns a pointer to the hostname. May be NULL if no hostname
is set. If set non-NULL, pointer remains valid (and string may change if the hostname
changes).
Returns
• ESP_OK - success
• ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error
• ESP_ERR_ESP_NETIF_INVALID_PARAMS - parameter error
bool esp_netif_is_netif_up(esp_netif_t *esp_netif)
Test if supplied interface is up or down.
Parameters esp_netif –[in] Handle to esp-netif instance
Returns
• true - Interface is up
• false - Interface is down
esp_err_t esp_netif_get_ip_info(esp_netif_t *esp_netif, esp_netif_ip_info_t *ip_info)
Get interface’s IP address information.
If the interface is up, IP information is read directly from the TCP/IP stack. If the interface is down, IP
information is read from a copy kept in the ESP-NETIF instance
Parameters
• esp_netif –[in] Handle to esp-netif instance
• ip_info –[out] If successful, IP information will be returned in this argument.
Returns
• ESP_OK
• ESP_ERR_ESP_NETIF_INVALID_PARAMS
esp_err_t esp_netif_get_old_ip_info(esp_netif_t *esp_netif, esp_netif_ip_info_t *ip_info)
Get interface’s old IP information.
Returns an “old”IP address previously stored for the interface when the valid IP changed.
If the IP lost timer has expired (meaning the interface was down for longer than the configured interval) then
the old IP information will be zero.
Parameters
• esp_netif –[in] Handle to esp-netif instance
• ip_info –[out] If successful, IP information will be returned in this argument.
Returns
• ESP_OK
• ESP_ERR_ESP_NETIF_INVALID_PARAMS
esp_err_t esp_netif_set_ip_info(esp_netif_t *esp_netif, const esp_netif_ip_info_t *ip_info)
Set interface’s IP address information.
This function is mainly used to set a static IP on an interface.
If the interface is up, the new IP information is set directly in the TCP/IP stack.
The copy of IP information kept in the ESP-NETIF instance is also updated (this copy is returned if the IP is
queried while the interface is still down.)
Note: DHCP client/server must be stopped (if enabled for this interface) before setting new IP information.
Parameters
• esp_netif –[in] Handle to esp-netif instance
• ip_info –[in] IP information to set on the specified interface
Returns
• ESP_OK
• ESP_ERR_ESP_NETIF_INVALID_PARAMS
• ESP_ERR_ESP_NETIF_DHCP_NOT_STOPPED If DHCP server or client is still run-
ning
Note: This index could be used in setsockopt() to bind socket with multicast interface
Note: This name could be used in setsockopt() to bind socket with appropriate interface
Parameters
• esp_netif –[in] Handle to esp-netif instance
• name –[out] Interface name as specified in underlying TCP/IP stack. Note that the actual
name will be copied to the specified buffer, which must be allocated to hold maximum
interface name size (6 characters for lwIP)
Returns
• ESP_OK
• ESP_ERR_ESP_NETIF_INVALID_PARAMS
Note: The default event handlers for the SYSTEM_EVENT_STA_CONNECTED and SYS-
TEM_EVENT_ETH_CONNECTED events call this function.
Note: Calling action_netif_stop() will also stop the DHCP Client if it is running.
Parameters
• esp_netif –[in] Handle to esp-netif instance
• type –[in] Type of DNS Server to set: ESP_NETIF_DNS_MAIN,
ESP_NETIF_DNS_BACKUP, ESP_NETIF_DNS_FALLBACK
• dns –[in] DNS Server address to set
Returns
• ESP_OK on success
• ESP_ERR_ESP_NETIF_INVALID_PARAMS invalid params
Parameters
• esp_netif –[in] Handle to esp-netif instance
• if_ip6 –[out] IPv6 information will be returned in this argument if successful.
Returns
• ESP_OK
• ESP_FAIL If interface is down, does not have a global IPv6 address, or the global IPv6
address is not a preferred address.
int esp_netif_get_all_ip6(esp_netif_t *esp_netif, esp_ip6_addr_t if_ip6[])
Get all IPv6 addresses of the specified interface.
Parameters
• esp_netif –[in] Handle to esp-netif instance
• if_ip6 –[out] Array of IPv6 addresses will be copied to the argument
Returns number of returned IPv6 addresses
void esp_netif_set_ip4_addr(esp_ip4_addr_t *addr, uint8_t a, uint8_t b, uint8_t c, uint8_t d)
Sets IPv4 address to the specified octets.
Parameters
• addr –[out] IP address to be set
• a –the first octet (127 for IP 127.0.0.1)
• b–
• c–
• d–
char *esp_ip4addr_ntoa(const esp_ip4_addr_t *addr, char *buf, int buflen)
Converts numeric IP address into decimal dotted ASCII representation.
Parameters
• addr –ip address in network order to convert
• buf –target buffer where the string is stored
• buflen –length of buf
Returns either pointer to buf which now holds the ASCII representation of addr or NULL if buf
was too small
uint32_t esp_ip4addr_aton(const char *addr)
Ascii internet address interpretation routine The value returned is in network order.
Parameters addr –IP address in ascii representation (e.g. “127.0.0.1”)
Returns ip address in network order
esp_err_t esp_netif_str_to_ip4(const char *src, esp_ip4_addr_t *dst)
Converts Ascii internet IPv4 address into esp_ip4_addr_t.
Parameters
• src –[in] IPv4 address in ascii representation (e.g. “127.0.0.1”)
• dst –[out] Address of the target esp_ip4_addr_t structure to receive converted address
Returns
• ESP_OK on success
• ESP_FAIL if conversion failed
• ESP_ERR_INVALID_ARG if invalid parameter is passed into
esp_err_t esp_netif_str_to_ip6(const char *src, esp_ip6_addr_t *dst)
Converts Ascii internet IPv6 address into esp_ip4_addr_t Zeros in the IP address can be stripped or completely
ommited: “2001:db8:85a3:0:0:0:2:1”or “2001:db8::2:1”)
Parameters
• src –[in] IPv6 address in ascii representation (e.g. “ ”
2001:0db8:85a3:0000:0000:0000:0002:0001”)
• dst –[out] Address of the target esp_ip6_addr_t structure to receive converted address
Returns
• ESP_OK on success
Header File
• components/esp_netif/include/esp_netif_types.h
Structures
struct esp_netif_dns_info_t
DNS server info.
Public Members
esp_ip_addr_t ip
IPV4 address of DNS server
struct esp_netif_ip_info_t
Event structure for IP_EVENT_STA_GOT_IP, IP_EVENT_ETH_GOT_IP events
Public Members
esp_ip4_addr_t ip
Interface IPV4 address
esp_ip4_addr_t netmask
Interface IPV4 netmask
esp_ip4_addr_t gw
Interface IPV4 gateway address
struct esp_netif_ip6_info_t
IPV6 IP address information.
Public Members
esp_ip6_addr_t ip
Interface IPV6 address
struct ip_event_got_ip_t
Event structure for IP_EVENT_GOT_IP event.
Public Members
int if_index
Interface index for which the event is received (left for legacy compilation)
esp_netif_t *esp_netif
Pointer to corresponding esp-netif object
esp_netif_ip_info_t ip_info
IP address, netmask, gatway IP address
bool ip_changed
Whether the assigned IP has changed or not
struct ip_event_got_ip6_t
Event structure for IP_EVENT_GOT_IP6 event
Public Members
int if_index
Interface index for which the event is received (left for legacy compilation)
esp_netif_t *esp_netif
Pointer to corresponding esp-netif object
esp_netif_ip6_info_t ip6_info
IPv6 address of the interface
int ip_index
IPv6 address index
struct ip_event_add_ip6_t
Event structure for ADD_IP6 event
Public Members
esp_ip6_addr_t addr
The address to be added to the interface
bool preferred
The default preference of the address
struct ip_event_ap_staipassigned_t
Event structure for IP_EVENT_AP_STAIPASSIGNED event
Public Members
esp_netif_t *esp_netif
Pointer to the associated netif handle
esp_ip4_addr_t ip
IP address which was assigned to the station
uint8_t mac[6]
MAC address of the connected client
struct bridgeif_config
LwIP bridge configuration
Public Members
uint16_t max_fdb_dyn_entries
maximum number of entries in dynamic forwarding database
uint16_t max_fdb_sta_entries
maximum number of entries in static forwarding database
uint8_t max_ports
maximum number of ports the bridge can consist of
struct esp_netif_inherent_config
ESP-netif inherent config parameters.
Public Members
esp_netif_flags_t flags
flags that define esp-netif behavior
uint8_t mac[6]
initial mac address for this interface
uint32_t get_ip_event
event id to be raised when interface gets an IP
uint32_t lost_ip_event
event id to be raised when interface losts its IP
int route_prio
numeric priority of this interface to become a default routing if (if other netifs are up). A higher value
of route_prio indicates a higher priority
bridgeif_config_t *bridge_info
LwIP bridge configuration
struct esp_netif_driver_base_s
ESP-netif driver base handle.
Public Members
esp_netif_t *netif
netif handle
struct esp_netif_driver_ifconfig
Specific IO driver configuration.
Public Members
esp_netif_iodriver_handle handle
io-driver handle
struct esp_netif_config
Generic esp_netif configuration.
Public Members
Macros
ESP_ERR_ESP_NETIF_BASE
Definition of ESP-NETIF based errors.
ESP_ERR_ESP_NETIF_INVALID_PARAMS
ESP_ERR_ESP_NETIF_IF_NOT_READY
ESP_ERR_ESP_NETIF_DHCPC_START_FAILED
ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED
ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED
ESP_ERR_ESP_NETIF_NO_MEM
ESP_ERR_ESP_NETIF_DHCP_NOT_STOPPED
ESP_ERR_ESP_NETIF_DRIVER_ATTACH_FAILED
ESP_ERR_ESP_NETIF_INIT_FAILED
ESP_ERR_ESP_NETIF_DNS_NOT_CONFIGURED
ESP_ERR_ESP_NETIF_MLD6_FAILED
ESP_ERR_ESP_NETIF_IP6_ADDR_FAILED
ESP_NETIF_BR_FLOOD
Definition of ESP-NETIF bridge controll.
ESP_NETIF_BR_DROP
ESP_NETIF_BR_FDW_CPU
Type Definitions
typedef esp_err_t (*esp_netif_receive_t)(esp_netif_t *esp_netif, void *buffer, size_t len, void *eb)
ESP-NETIF Receive function type.
Enumerations
enum esp_netif_dns_type_t
Type of DNS server.
Values:
enumerator ESP_NETIF_DNS_MAIN
DNS main server address
enumerator ESP_NETIF_DNS_BACKUP
DNS backup server address (Wi-Fi STA and Ethernet only)
enumerator ESP_NETIF_DNS_FALLBACK
DNS fallback server address (Wi-Fi STA and Ethernet only)
enumerator ESP_NETIF_DNS_MAX
enum esp_netif_dhcp_status_t
Status of DHCP client or DHCP server.
Values:
enumerator ESP_NETIF_DHCP_INIT
DHCP client/server is in initial state (not yet started)
enumerator ESP_NETIF_DHCP_STARTED
DHCP client/server has been started
enumerator ESP_NETIF_DHCP_STOPPED
DHCP client/server has been stopped
enumerator ESP_NETIF_DHCP_STATUS_MAX
enum esp_netif_dhcp_option_mode_t
Mode for DHCP client or DHCP server option functions.
Values:
enumerator ESP_NETIF_OP_START
enumerator ESP_NETIF_OP_SET
Set option
enumerator ESP_NETIF_OP_GET
Get option
enumerator ESP_NETIF_OP_MAX
enum esp_netif_dhcp_option_id_t
Supported options for DHCP client or DHCP server.
Values:
enumerator ESP_NETIF_SUBNET_MASK
Network mask
enumerator ESP_NETIF_DOMAIN_NAME_SERVER
Domain name server
enumerator ESP_NETIF_ROUTER_SOLICITATION_ADDRESS
Solicitation router address
enumerator ESP_NETIF_REQUESTED_IP_ADDRESS
Request specific IP address
enumerator ESP_NETIF_IP_ADDRESS_LEASE_TIME
Request IP address lease time
enumerator ESP_NETIF_IP_REQUEST_RETRY_TIME
Request IP address retry counter
enumerator ESP_NETIF_VENDOR_CLASS_IDENTIFIER
Vendor Class Identifier of a DHCP client
enumerator ESP_NETIF_VENDOR_SPECIFIC_INFO
Vendor Specific Information of a DHCP server
enum ip_event_t
IP event declarations
Values:
enumerator IP_EVENT_STA_GOT_IP
station got IP from connected AP
enumerator IP_EVENT_STA_LOST_IP
station lost IP and the IP is reset to 0
enumerator IP_EVENT_AP_STAIPASSIGNED
soft-AP assign an IP to a connected station
enumerator IP_EVENT_GOT_IP6
station or ap or ethernet interface v6IP addr is preferred
enumerator IP_EVENT_ETH_GOT_IP
ethernet got IP from connected AP
enumerator IP_EVENT_ETH_LOST_IP
ethernet lost IP and the IP is reset to 0
enumerator IP_EVENT_PPP_GOT_IP
PPP interface got IP
enumerator IP_EVENT_PPP_LOST_IP
PPP interface lost IP
enum esp_netif_flags
Values:
enumerator ESP_NETIF_DHCP_CLIENT
enumerator ESP_NETIF_DHCP_SERVER
enumerator ESP_NETIF_FLAG_AUTOUP
enumerator ESP_NETIF_FLAG_GARP
enumerator ESP_NETIF_FLAG_EVENT_IP_MODIFIED
enumerator ESP_NETIF_FLAG_IS_PPP
enumerator ESP_NETIF_FLAG_IS_SLIP
enumerator ESP_NETIF_FLAG_IS_BRIDGE
enum esp_netif_ip_event_type
Values:
enumerator ESP_NETIF_IP_EVENT_GOT_IP
enumerator ESP_NETIF_IP_EVENT_LOST_IP
Header File
• components/esp_netif/include/esp_netif_ip_addr.h
Functions
esp_ip6_addr_type_t esp_netif_ip6_get_addr_type(esp_ip6_addr_t *ip6_addr)
Get the IPv6 address type.
Parameters ip6_addr –[in] IPv6 type
Returns IPv6 type in form of enum esp_ip6_addr_type_t
static inline void esp_netif_ip_addr_copy(esp_ip_addr_t *dest, const esp_ip_addr_t *src)
Copy IP addresses.
Parameters
• dest –[out] destination IP
• src –[in] source IP
Structures
struct esp_ip6_addr
IPv6 address.
Public Members
uint32_t addr[4]
IPv6 address
uint8_t zone
zone ID
struct esp_ip4_addr
IPv4 address.
Public Members
uint32_t addr
IPv4 address
struct _ip_addr
IP address.
Public Members
esp_ip6_addr_t ip6
IPv6 address type
esp_ip4_addr_t ip4
IPv4 address type
uint8_t type
ipaddress type
Macros
esp_netif_htonl(x)
esp_netif_ip4_makeu32(a, b, c, d)
ESP_IP6_ADDR_BLOCK1(ip6addr)
ESP_IP6_ADDR_BLOCK2(ip6addr)
ESP_IP6_ADDR_BLOCK3(ip6addr)
ESP_IP6_ADDR_BLOCK4(ip6addr)
ESP_IP6_ADDR_BLOCK5(ip6addr)
ESP_IP6_ADDR_BLOCK6(ip6addr)
ESP_IP6_ADDR_BLOCK7(ip6addr)
ESP_IP6_ADDR_BLOCK8(ip6addr)
IPSTR
esp_ip4_addr_get_byte(ipaddr, idx)
esp_ip4_addr1(ipaddr)
esp_ip4_addr2(ipaddr)
esp_ip4_addr3(ipaddr)
esp_ip4_addr4(ipaddr)
esp_ip4_addr1_16(ipaddr)
esp_ip4_addr2_16(ipaddr)
esp_ip4_addr3_16(ipaddr)
esp_ip4_addr4_16(ipaddr)
IP2STR(ipaddr)
IPV6STR
IPV62STR(ipaddr)
ESP_IPADDR_TYPE_V4
ESP_IPADDR_TYPE_V6
ESP_IPADDR_TYPE_ANY
ESP_IP4TOUINT32(a, b, c, d)
ESP_IP4TOADDR(a, b, c, d)
ESP_IP4ADDR_INIT(a, b, c, d)
ESP_IP6ADDR_INIT(a, b, c, d)
Type Definitions
Enumerations
enum esp_ip6_addr_type_t
Values:
enumerator ESP_IP6_ADDR_IS_UNKNOWN
enumerator ESP_IP6_ADDR_IS_GLOBAL
enumerator ESP_IP6_ADDR_IS_LINK_LOCAL
enumerator ESP_IP6_ADDR_IS_SITE_LOCAL
enumerator ESP_IP6_ADDR_IS_UNIQUE_LOCAL
enumerator ESP_IP6_ADDR_IS_IPV4_MAPPED_IPV6
Header File
• components/esp_netif/include/esp_vfs_l2tap.h
Functions
esp_err_t esp_vfs_l2tap_intf_register(l2tap_vfs_config_t *config)
Add L2 TAP virtual filesystem driver.
This function must be called prior usage of ESP-NETIF L2 TAP Interface
Parameters config –L2 TAP virtual filesystem driver configuration. Default base path
/dev/net/tap is used when this paramenter is NULL.
Returns esp_err_t
• ESP_OK on success
esp_err_t esp_vfs_l2tap_intf_unregister(const char *base_path)
Removes L2 TAP virtual filesystem driver.
Parameters base_path –Base path to the L2 TAP virtual filesystem driver. Default path
/dev/net/tap is used when this paramenter is NULL.
Returns esp_err_t
• ESP_OK on success
esp_err_t esp_vfs_l2tap_eth_filter(l2tap_iodriver_handle driver_handle, void *buff, size_t *size)
Filters received Ethernet L2 frames into L2 TAP infrastructure.
Parameters
• driver_handle –handle of driver at which the frame was received
• buff –received L2 frame
• size –input length of the L2 frame which is set to 0 when frame is filtered into L2 TAP
Returns esp_err_t
• ESP_OK is always returned
Structures
struct l2tap_vfs_config_t
L2Tap VFS config parameters.
Public Members
Macros
L2TAP_VFS_DEFAULT_PATH
L2TAP_VFS_CONFIG_DEFAULT()
Type Definitions
Enumerations
enum l2tap_ioctl_opt_t
Values:
enumerator L2TAP_S_RCV_FILTER
enumerator L2TAP_G_RCV_FILTER
enumerator L2TAP_S_INTF_DEVICE
enumerator L2TAP_G_INTF_DEVICE
enumerator L2TAP_S_DEVICE_DRV_HNDL
enumerator L2TAP_G_DEVICE_DRV_HNDL
Header File
• components/esp_wifi/include/esp_wifi_default.h
Functions
esp_err_t esp_netif_attach_wifi_station(esp_netif_t *esp_netif)
Attaches wifi station interface to supplied netif.
Parameters esp_netif –instance to attach the wifi station to
Returns
• ESP_OK on success
• ESP_FAIL if attach failed
esp_err_t esp_netif_attach_wifi_ap(esp_netif_t *esp_netif)
Attaches wifi soft AP interface to supplied netif.
Parameters esp_netif –instance to attach the wifi AP to
Returns
• ESP_OK on success
• ESP_FAIL if attach failed
esp_err_t esp_wifi_set_default_wifi_sta_handlers(void)
Sets default wifi event handlers for STA interface.
Returns
• ESP_OK on success, error returned from esp_event_handler_register if failed
esp_err_t esp_wifi_set_default_wifi_ap_handlers(void)
Sets default wifi event handlers for AP interface.
Returns
• ESP_OK on success, error returned from esp_event_handler_register if failed
esp_err_t esp_wifi_clear_default_wifi_driver_and_handlers(void *esp_netif)
Clears default wifi event handlers for supplied network interface.
Parameters esp_netif –instance of corresponding if object
Returns
• ESP_OK on success, error returned from esp_event_handler_register if failed
esp_netif_t *esp_netif_create_default_wifi_ap(void)
Creates default WIFI AP. In case of any init error this API aborts.
Note: The API creates esp_netif object with default WiFi access point config, attaches the netif to wifi and
registers default wifi handlers.
esp_netif_t *esp_netif_create_default_wifi_sta(void)
Creates default WIFI STA. In case of any init error this API aborts.
Note: The API creates esp_netif object with default WiFi station config, attaches the netif to wifi and registers
default wifi handlers.
Note: This API unregisters wifi handlers and detaches the created object from the wifi. (this function is a
no-operation if esp_netif is NULL)
Parameters
• wifi_if –[in] type of wifi interface
• esp_netif_config –inherent esp-netif configuration pointer
Returns pointer to esp-netif instance
This section outlines implementing a new I/O driver with esp-netif connection capabilities. By convention the I/O
driver has to register itself as an esp-netif driver and thus holds a dependency on esp-netif component and is responsible
for providing data path functions, post-attach callback and in most cases also default event handlers to define network
interface actions based on driver’s lifecycle transitions.
Packet input/output As shown in the diagram, the following three API functions for the packet data path must be
defined for connecting with esp-netif:
• esp_netif_transmit()
• esp_netif_free_rx_buffer()
• esp_netif_receive()
The first two functions for transmitting and freeing the rx buffer are provided as callbacks, i.e. they get called from
esp-netif (and its underlying TCP/IP stack) and I/O driver provides their implementation.
The receiving function on the other hand gets called from the I/O driver, so that the driver’s code simply calls
esp_netif_receive() on a new data received event.
Post attach callback A final part of the network interface initialization consists of attaching the esp-netif instance
to the I/O driver, by means of calling the following API:
It is assumed that the esp_netif_iodriver_handle is a pointer to driver’s object, a struct derived from
struct esp_netif_driver_base_s, so that the first member of I/O driver structure must be this base
structure with pointers to
• post-attach function callback
• related esp-netif instance
As a consequence the I/O driver has to create an instance of the struct per below:
} my_netif_driver_t;
Default handlers I/O drivers also typically provide default definitions of lifecycle behaviour of related network
interfaces based on state transitions of I/O drivers. For example driver start -> network start, etc. An example of
such a default handler is provided below:
{
driver_set_event_handler(driver->driver_impl, esp_netif_action_start, MY_DRV_
,→EVENT_START, esp_netif);
return ESP_OK;
}
Network stack connection The packet data path functions for transmitting and freeing the rx buffer (defined in
the I/O driver) are called from the esp-netif, specifically from its TCP/IP stack connecting layer. The following API
reference outlines these network stack interaction with the esp-netif.
Header File
• components/esp_netif/include/esp_netif_net_stack.h
Functions
esp_netif_t *esp_netif_get_handle_from_netif_impl(void *dev)
Returns esp-netif handle.
Parameters dev –[in] opaque ptr to network interface of specific TCP/IP stack
Returns handle to related esp-netif instance
void *esp_netif_get_netif_impl(esp_netif_t *esp_netif)
Returns network stack specific implementation handle (if supported)
Note that it is not supported to acquire PPP netif impl pointer and this function will return NULL for esp_netif
instances configured to PPP mode
Parameters esp_netif –[in] Handle to esp-netif instance
Returns handle to related network stack netif handle
esp_err_t esp_netif_transmit(esp_netif_t *esp_netif, void *data, size_t len)
Outputs packets from the TCP/IP stack to the media to be transmitted.
This function gets called from network stack to output packets to IO driver.
Parameters
• esp_netif –[in] Handle to esp-netif instance
• data –[in] Data to be transmitted
• len –[in] Length of the data frame
Returns ESP_OK on success, an error passed from the I/O driver otherwise
esp_err_t esp_netif_transmit_wrap(esp_netif_t *esp_netif, void *data, size_t len, void *netstack_buf)
Outputs packets from the TCP/IP stack to the media to be transmitted.
This function gets called from network stack to output packets to IO driver.
Parameters
• esp_netif –[in] Handle to esp-netif instance
• data –[in] Data to be transmitted
• len –[in] Length of the data frame
• netstack_buf –[in] net stack buffer
Returns ESP_OK on success, an error passed from the I/O driver otherwise
void esp_netif_free_rx_buffer(void *esp_netif, void *buffer)
Free the rx buffer allocated by the media driver.
This function gets called from network stack when the rx buffer to be freed in IO driver context, i.e. to
deallocate a buffer owned by io driver (when data packets were passed to higher levels to avoid copying)
Parameters
• esp_netif –[in] Handle to esp-netif instance
• buffer –[in] Rx buffer pointer
Code examples for TCP/IP socket APIs are provided in the protocols/sockets directory of ESP-IDF examples.
Documentation for Application layer network protocols (above the IP Network layer) are provided in Application
Protocols.
ADC Channels
The ESP32 integrates 2 SAR (Successive Approximation Register) ADCs, supporting a total of 18 measurement
channels (analog enabled pins).
These channels are supported:
ADC1:
• 8 channels: GPIO32 - GPIO39
ADC2:
• 10 channels: GPIO0, GPIO2, GPIO4, GPIO12 - GPIO15, GOIO25 - GPIO27
ADC Attenuation
Vref is the reference voltage used internally by ESP32 ADCs for measuring the input voltage. The ESP32 ADCs
can measure analog voltages from 0 V to Vref. Among different chips, the Vref varies, the median is 1.1 V. In order
to convert voltages larger than Vref, input voltages can be attenuated before being input to the ADCs. There are 4
available attenuation options, the higher the attenuation is, the higher the measurable input voltage could be.
ADC Conversion
An ADC conversion is to convert the input analog voltage to a digital value. The ADC conversion results provided
by the ADC driver APIs are raw data. Resolution of ESP32 ADC raw results under Single Read mode is 12-bit.
• adc1_get_raw()
• adc2_get_raw()
To calculate the voltage based on the ADC raw results, this formula can be used:
where:
For boards with eFuse ADC calibration bits, esp_adc_cal_raw_to_voltage() can be used to get the cal-
ibrated conversion results. These results stand for the actual voltage (in mV). No need to transform these data via
the formula (1). If ADC calibration APIs are used on boards without eFuse ADC calibration bits, warnings will be
generated. See ADC Calibration.
ADC Limitations
Note:
• Some of the ADC2 pins are used as strapping pins (GPIO 0, 2, 15) thus cannot be used freely. Such is the
case in the following official Development Kits:
• ESP32 DevKitC: GPIO 0 cannot be used due to external auto program circuits.
• ESP-WROVER-KIT: GPIO 0, 2, 4 and 15 cannot be used due to external connections for different purposes.
• Since the ADC2 module is also used by the Wi-Fi, only one of them could get the preemption when using
together, which means the adc2_get_raw() may get blocked until Wi-Fi stops, and vice versa.
Driver Usage
Both of the ADC units support single read mode, which is suitable for low-frequency sampling operations.
Note: ADC readings from a pin not connected to any signal are random.
ADC Single Read mode The ADC should be configured before reading is taken.
• For ADC1, configure desired precision and attenuation by calling functions adc1_config_width() and
adc1_config_channel_atten().
• For ADC2, configure the attenuation by adc2_config_channel_atten(). The reading width of
ADC2 is configured every time you take the reading.
Attenuation configuration is done per channel, see adc1_channel_t and adc2_channel_t, set as a parameter
of above functions.
Then it is possible to read ADC conversion result with adc1_get_raw() and adc2_get_raw(). Reading
width of ADC2 should be set as a parameter of adc2_get_raw() instead of in the configuration functions.
Single Read mode ADC example can be found in peripherals/adc/single_read directory of ESP-IDF examples.
It is also possible to read the internal hall effect sensor via ADC1 by calling dedicated function
hall_sensor_read(). Note that even the hall sensor is internal to ESP32, reading from it uses channels 0
and 3 of ADC1 (GPIO 36 and 39). Do not connect anything else to these pins and do not change their configuration.
Otherwise it may affect the measurement of low value signal from the sensor.
This API provides convenient way to configure ADC1 for reading from ULP. To do so, call function
adc1_ulp_enable() and then set precision and attenuation as discussed above.
There is another specific function adc_vref_to_gpio() used to route internal reference voltage to a GPIO pin.
It comes handy to calibrate ADC reading and this is discussed in section ADC Calibration.
Note: See ADC Limitations for the limitation of using ADC single read mode.
Minimizing Noise
The ESP32 ADC can be sensitive to noise leading to large discrepancies in ADC readings. Depending on the usage
scenario, users may connect a bypass capacitor (e.g. a 100 nF ceramic capacitor) to the ADC input pad in use, to
minimize noise. Besides, multisampling may also be used to further mitigate the effects of noise.
Fig. 6: Graph illustrating noise mitigation using capacitor and multisampling of 64 samples.
ADC Calibration
The esp_adc_cal/include/esp_adc_cal.h API provides functions to correct for differences in measured voltages caused
by variation of ADC reference voltages (Vref) between chips. Per design the ADC reference voltage is 1100 mV,
however the true reference voltage can range from 1000 mV to 1200 mV amongst different ESP32s.
Correcting ADC readings using this API involves characterizing one of the ADCs at a given attenuation to obtain
a characteristics curve (ADC-Voltage curve) that takes into account the difference in ADC reference voltage. The
characteristics curve is in the form of y = coeff_a * x + coeff_b and is used to convert ADC readings to
voltages in mV. Calculation of the characteristics curve is based on calibration values which can be stored in eFuse
or provided by the user.
Calibration Values Calibration values are used to generate characteristic curves that account for the variation of
ADC reference voltage of a particular ESP32 chip. There are currently 3 source(s) of calibration values on ESP32.
The availability of these calibration values will depend on the type and production date of the ESP32 chip/module.
• Two Point values represent each of the ADCs’readings at 150 mV and 850 mV. To obtain more accurate
calibration results these values should be measured by user and burned into eFuse BLOCK3.
• eFuse Vref represents the true ADC reference voltage. This value is measured and burned into eFuse BLOCK0
during factory calibration.
Fig. 7: Graph illustrating effect of differing reference voltages on the ADC voltage curve.
• Default Vref is an estimate of the ADC reference voltage provided by the user as a parameter during charac-
terization. If Two Point or eFuse Vref values are unavailable, Default Vref will be used.
Individual measurement and burning of the eFuse Vref has been applied to ESP32-D0WD and
ESP32-D0WDQ6 chips produced on/after the 1st week of 2018. Such chips may be recognized
by date codes on/later than 012018 (see Line 4 on figure below).
If you would like to purchase chips or modules with calibration, double check with distributor or
Espressif ([email protected]) directly.
If you are unable to check the date code (i.e. the chip may be enclosed inside a canned module,
etc.), you can still verify if eFuse Vref is present by running the espefuse.py tool with adc_info
parameter
For a chip with two point calibration the message will look similar to:
Application Extensions
#include "driver/adc.h"
#include "esp_adc_cal.h"
...
#include "driver/adc.h"
#include "esp_adc_cal.h"
...
uint32_t reading = adc1_get_raw(ADC1_CHANNEL_5);
uint32_t voltage = esp_adc_cal_raw_to_voltage(reading, adc_chars);
Routing ADC reference voltage to GPIO, so it can be manually measured (for Default Vref):
#include "driver/adc.h"
There are macros available to specify the GPIO number of a ADC channel, or vice versa. e.g.
1. ADC1_CHANNEL_0_GPIO_NUM is the GPIO number of ADC1 channel 0.
2. ADC1_GPIOn_CHANNEL is the ADC1 channel number of GPIO n.
API Reference
ADC driver
Header File
• components/driver/include/driver/adc.h
Functions
void adc_power_on(void)
Enable ADC power.
Deprecated:
Use adc_power_acquire and adc_power_release instead.
void adc_power_off(void)
Power off SAR ADC.
Deprecated:
Use adc_power_acquire and adc_power_release instead. This function will force power down for ADC.
This function is deprecated because forcing power ADC power off may disrupt operation of other com-
ponents which may be using the ADC.
void adc_power_acquire(void)
Increment the usage counter for ADC module. ADC will stay powered on while the counter is greater than 0.
Call adc_power_release when done using the ADC.
void adc_power_release(void)
Decrement the usage counter for ADC module. ADC will stay powered on while the counter is greater than 0.
Call this function when done using the ADC.
+----------+-------------+-----------------+
| | attenuation | suggested range |
| SoC | (dB) | (mV) |
+==========+=============+=================+
| | 0 | 100 ~ 950 |
| +-------------+-----------------+
| | 2.5 | 100 ~ 1250 |
| ESP32 +-------------+-----------------+
| | 6 | 150 ~ 1750 |
| +-------------+-----------------+
| | 11 | 150 ~ 2450 |
+----------+-------------+-----------------+
| | 0 | 0 ~ 750 |
| +-------------+-----------------+
| | 2.5 | 0 ~ 1050 |
| ESP32-S2 +-------------+-----------------+
| | 6 | 0 ~ 1300 |
| +-------------+-----------------+
| | 11 | 0 ~ 2500 |
+----------+-------------+-----------------+
For maximum accuracy, use the ADC calibration APIs and measure voltages within these recommended
ranges.
Note: For any given channel, this function must be called before the first time adc1_get_raw() is called
for that channel.
Note: This function can be called multiple times to configure multiple ADC channels simultaneously. You
may call adc1_get_raw() only after configuring a channel.
Parameters
• channel –ADC1 channel to configure
• atten –Attenuation level
Returns
• ESP_OK success
• ESP_ERR_INVALID_ARG Parameter error
Note: ESP32: When the power switch of SARADC1, SARADC2, HALL sensor and AMP sensor is
turned on, the input of GPIO36 and GPIO39 will be pulled down for about 80ns. When enabling power
for any of these peripherals, ignore input from GPIO36 and GPIO39. Please refer to section 3.11 of
‘ECO_and_Workarounds_for_Bugs_in_ESP32’for the description of this issue. As a workaround, call
adc_power_acquire() in the app. This will result in higher power consumption (by ~1mA), but will remove the
glitches on GPIO36 and GPIO39.
Note: Call adc1_config_width() before the first time this function is called.
Note: For any given channel, adc1_config_channel_atten(channel) must be called before the first time this
function is called. Configuring a new channel does not prevent a previously configured channel from being
read.
void adc1_ulp_enable(void)
Configure ADC1 to be usable by the ULP.
This function reconfigures ADC1 to be controlled by the ULP. Effect of this function can be reverted using
adc1_get_raw() function.
Note that adc1_config_channel_atten, adc1_config_width() functions need to be called to configure
ADC1 channels, before ADC1 is used by the ULP.
esp_err_t adc2_pad_get_io_num(adc2_channel_t channel, gpio_num_t *gpio_num)
Get the GPIO number of a specific ADC2 channel.
Parameters
• channel –Channel to get the GPIO number
• gpio_num –output buffer to hold the GPIO number
Returns
• ESP_OK if success
• ESP_ERR_INVALID_ARG if channel not valid
esp_err_t adc2_config_channel_atten(adc2_channel_t channel, adc_atten_t atten)
Configure the ADC2 channel, including setting attenuation.
The default ADC voltage is for attenuation 0 dB and listed in the table below. By setting higher attenuation it
is possible to read higher voltages.
Due to ADC characteristics, most accurate results are obtained within the “suggested range”shown in the
following table.
+----------+-------------+-----------------+
| | attenuation | suggested range |
| SoC | (dB) | (mV) |
+==========+=============+=================+
| | 0 | 100 ~ 950 |
| +-------------+-----------------+
| | 2.5 | 100 ~ 1250 |
| ESP32 +-------------+-----------------+
| | 6 | 150 ~ 1750 |
| +-------------+-----------------+
| | 11 | 150 ~ 2450 |
+----------+-------------+-----------------+
| | 0 | 0 ~ 750 |
| +-------------+-----------------+
| | 2.5 | 0 ~ 1050 |
| ESP32-S2 +-------------+-----------------+
| | 6 | 0 ~ 1300 |
| +-------------+-----------------+
| | 11 | 0 ~ 2500 |
+----------+-------------+-----------------+
For maximum accuracy, use the ADC calibration APIs and measure voltages within these recommended
ranges.
Note: This function also configures the input GPIO pin mux to connect it to the ADC2 channel. It must be
called before calling adc2_get_raw() for this channel.
Note: For any given channel, this function must be called before the first time adc2_get_raw() is called
for that channel.
Parameters
• channel –ADC2 channel to configure
Note: ESP32: When the power switch of SARADC1, SARADC2, HALL sensor and AMP sensor is
turned on, the input of GPIO36 and GPIO39 will be pulled down for about 80ns. When enabling power
for any of these peripherals, ignore input from GPIO36 and GPIO39. Please refer to section 3.11 of
‘ECO_and_Workarounds_for_Bugs_in_ESP32’for the description of this issue. As a workaround, call
adc_power_acquire() in the app. This will result in higher power consumption (by ~1mA), but will remove the
glitches on GPIO36 and GPIO39.
Note: ESP32: For a given channel, adc2_config_channel_atten() must be called before the first
time this function is called. If Wi-Fi is started via esp_wifi_start(), this function will always fail with
ESP_ERR_TIMEOUT.
Note: ESP32-S2: ADC2 support hardware arbiter. The arbiter is to improve the use efficiency of ADC2.
After the control right is robbed by the high priority, the low priority controller will read the invalid ADC2
data. Default priority: Wi-Fi > RTC > Digital;
Parameters
• channel –ADC2 channel to read
• width_bit –Bit capture width for ADC2
• raw_out –the variable to hold the output data.
Returns
• ESP_OK if success
• ESP_ERR_TIMEOUT ADC2 is being used by other controller and the request timed out.
• ESP_ERR_INVALID_STATE The controller status is invalid. Please try again.
Parameters
• adc_unit –[in] ADC unit index
• gpio –[in] GPIO number (Only ADC2’s channels IO are supported)
Returns
• ESP_OK: v_ref successfully routed to selected GPIO
• ESP_ERR_INVALID_ARG: Unsupported GPIO
Deprecated:
Use adc_vref_to_gpio instead.
Note: When the power switch of SARADC1, SARADC2, HALL sensor and AMP sensor is turned
on, the input of GPIO36 and GPIO39 will be pulled down for about 80ns. When enabling power
for any of these peripherals, ignore input from GPIO36 and GPIO39. Please refer to section 3.11 of
‘ECO_and_Workarounds_for_Bugs_in_ESP32’for the description of this issue.
Note: The Hall Sensor uses channels 0 and 3 of ADC1. Do not configure these channels for use as ADC
channels.
Note: The ADC1 module must be enabled by calling adc1_config_width() before calling hall_sensor_read().
ADC1 should be configured for 12 bit readings, as the hall sensor readings are low values and do not cover the
full range of the ADC.
Structures
struct adc_digi_init_config_s
ADC DMA driver configuration.
Public Members
uint32_t max_store_buf_size
Max length of the converted data that driver can store before they are processed.
uint32_t conv_num_each_intr
Bytes of data that can be converted in 1 interrupt.
uint32_t adc1_chan_mask
Channel list of ADC1 to be initialized.
uint32_t adc2_chan_mask
Channel list of ADC2 to be initialized.
struct adc_digi_configuration_t
ADC digital controller settings.
Public Members
bool conv_limit_en
To limit ADC conversion times. Conversion stops after finishing conv_limit_num times conversion.
uint32_t conv_limit_num
Set the upper limit of the number of ADC conversion triggers. Range: 1 ~ 255.
uint32_t pattern_num
Number of ADC channels that will be used.
adc_digi_pattern_config_t *adc_pattern
List of configs for each ADC channel that will be used.
uint32_t sample_freq_hz
The expected ADC sampling frequency in Hz. Range: 611Hz ~ 83333Hz Fs = Fd / interval / 2 Fs:
sampling frequency; Fd: digital controller frequency, no larger than 5M for better performance interval:
interval between 2 measurement trigger signal, the smallest interval should not be smaller than the ADC
measurement period, the largest interval should not be larger than 4095
adc_digi_convert_mode_t conv_mode
ADC DMA conversion mode, see adc_digi_convert_mode_t.
adc_digi_output_format_t format
ADC DMA conversion output format, see adc_digi_output_format_t.
Macros
ADC_ATTEN_0db
ADC rtc controller attenuation option.
ADC_ATTEN_2_5db
ADC_ATTEN_6db
ADC_ATTEN_11db
ADC_WIDTH_BIT_DEFAULT
The default (max) bit width of the ADC of current version. You can also get the maximum bitwidth by
SOC_ADC_RTC_MAX_BITWIDTH defined in soc_caps.h.
ADC_WIDTH_9Bit
ADC_WIDTH_10Bit
ADC_WIDTH_11Bit
ADC_WIDTH_12Bit
ADC_MAX_DELAY
Digital ADC DMA read max timeout value, it may make the adc_digi_read_bytes block forever if the
OS supports.
Type Definitions
Enumerations
enum adc1_channel_t
Values:
enumerator ADC1_CHANNEL_0
ADC1 channel 0 is GPIO36
enumerator ADC1_CHANNEL_1
ADC1 channel 1 is GPIO37
enumerator ADC1_CHANNEL_2
ADC1 channel 2 is GPIO38
enumerator ADC1_CHANNEL_3
ADC1 channel 3 is GPIO39
enumerator ADC1_CHANNEL_4
ADC1 channel 4 is GPIO32
enumerator ADC1_CHANNEL_5
ADC1 channel 5 is GPIO33
enumerator ADC1_CHANNEL_6
ADC1 channel 6 is GPIO34
enumerator ADC1_CHANNEL_7
ADC1 channel 7 is GPIO35
enumerator ADC1_CHANNEL_MAX
enum adc2_channel_t
Values:
enumerator ADC2_CHANNEL_0
ADC2 channel 0 is GPIO4 (ESP32), GPIO11 (ESP32-S2)
enumerator ADC2_CHANNEL_1
ADC2 channel 1 is GPIO0 (ESP32), GPIO12 (ESP32-S2)
enumerator ADC2_CHANNEL_2
ADC2 channel 2 is GPIO2 (ESP32), GPIO13 (ESP32-S2)
enumerator ADC2_CHANNEL_3
ADC2 channel 3 is GPIO15 (ESP32), GPIO14 (ESP32-S2)
enumerator ADC2_CHANNEL_4
ADC2 channel 4 is GPIO13 (ESP32), GPIO15 (ESP32-S2)
enumerator ADC2_CHANNEL_5
ADC2 channel 5 is GPIO12 (ESP32), GPIO16 (ESP32-S2)
enumerator ADC2_CHANNEL_6
ADC2 channel 6 is GPIO14 (ESP32), GPIO17 (ESP32-S2)
enumerator ADC2_CHANNEL_7
ADC2 channel 7 is GPIO27 (ESP32), GPIO18 (ESP32-S2)
enumerator ADC2_CHANNEL_8
ADC2 channel 8 is GPIO25 (ESP32), GPIO19 (ESP32-S2)
enumerator ADC2_CHANNEL_9
ADC2 channel 9 is GPIO26 (ESP32), GPIO20 (ESP32-S2)
enumerator ADC2_CHANNEL_MAX
enum adc_i2s_encode_t
ADC digital controller encode option.
Deprecated:
The ESP32-S2 doesn’t use I2S DMA. Call adc_digi_output_format_t instead.
Values:
enumerator ADC_ENCODE_12BIT
ADC to DMA data format, , [15:12]-channel [11:0]-12 bits ADC data
enumerator ADC_ENCODE_11BIT
ADC to DMA data format, [15]-unit, [14:11]-channel [10:0]-11 bits ADC data
enumerator ADC_ENCODE_MAX
Header File
• components/hal/include/hal/adc_types.h
Structures
struct adc_digi_pattern_config_t
ADC digital controller pattern configuration.
Public Members
uint8_t atten
Attenuation of this ADC channel.
uint8_t channel
ADC channel.
uint8_t unit
ADC unit.
uint8_t bit_width
ADC output bit width.
struct adc_digi_output_data_t
ADC digital controller (DMA mode) output data format. Used to analyze the acquired ADC (DMA) data.
Note: ESP32: Only type1 is valid. ADC2 does not support DMA mode.
Note: ESP32-S2: Member channel can be used to judge the validity of the ADC data, because the role of
the arbiter may get invalid ADC data.
Public Members
uint16_t data
ADC real output data info. Resolution: 12 bit.
ADC real output data info. Resolution: 11 bit.
uint16_t channel
ADC channel index info.
ADC channel index info. For ESP32-S2: If (channel < ADC_CHANNEL_MAX), The data is valid. If
(channel > ADC_CHANNEL_MAX), The data is invalid.
uint16_t unit
ADC unit index info. 0: ADC1; 1: ADC2.
uint16_t val
Raw data value
Enumerations
enum adc_unit_t
ADC unit.
Values:
enumerator ADC_UNIT_1
SAR ADC 1.
enumerator ADC_UNIT_2
SAR ADC 2.
enum adc_channel_t
ADC channels.
Values:
enumerator ADC_CHANNEL_0
ADC channel.
enumerator ADC_CHANNEL_1
ADC channel.
enumerator ADC_CHANNEL_2
ADC channel.
enumerator ADC_CHANNEL_3
ADC channel.
enumerator ADC_CHANNEL_4
ADC channel.
enumerator ADC_CHANNEL_5
ADC channel.
enumerator ADC_CHANNEL_6
ADC channel.
enumerator ADC_CHANNEL_7
ADC channel.
enumerator ADC_CHANNEL_8
ADC channel.
enumerator ADC_CHANNEL_9
ADC channel.
enum adc_atten_t
ADC attenuation parameter. Different parameters determine the range of the ADC. See
adc1_config_channel_atten.
Values:
enumerator ADC_ATTEN_DB_0
No input attenumation, ADC can measure up to approx. 800 mV.
enumerator ADC_ATTEN_DB_2_5
The input voltage of ADC will be attenuated extending the range of measurement by about 2.5 dB (1.33
x)
enumerator ADC_ATTEN_DB_6
The input voltage of ADC will be attenuated extending the range of measurement by about 6 dB (2 x)
enumerator ADC_ATTEN_DB_11
The input voltage of ADC will be attenuated extending the range of measurement by about 11 dB (3.55
x)
enum adc_bits_width_t
ADC resolution setting option.
Values:
enumerator ADC_WIDTH_BIT_9
ADC capture width is 9Bit.
enumerator ADC_WIDTH_BIT_10
ADC capture width is 10Bit.
enumerator ADC_WIDTH_BIT_11
ADC capture width is 11Bit.
enumerator ADC_WIDTH_BIT_12
ADC capture width is 12Bit.
enumerator ADC_WIDTH_MAX
enum adc_bitwidth_t
Values:
enumerator ADC_BITWIDTH_9
ADC output width is 9Bit.
enumerator ADC_BITWIDTH_10
ADC output width is 10Bit.
enumerator ADC_BITWIDTH_11
ADC output width is 11Bit.
enumerator ADC_BITWIDTH_12
ADC output width is 12Bit.
enumerator ADC_BITWIDTH_13
ADC output width is 13Bit.
enumerator ADC_BITWIDTH_DEFAULT
Default ADC output bits, max supported width will be selected.
enum adc_digi_convert_mode_t
ADC digital controller (DMA mode) work mode.
Values:
enumerator ADC_CONV_SINGLE_UNIT_1
Only use ADC1 for conversion.
enumerator ADC_CONV_SINGLE_UNIT_2
Only use ADC2 for conversion.
enumerator ADC_CONV_BOTH_UNIT
Use Both ADC1 and ADC2 for conversion simultaneously.
enumerator ADC_CONV_ALTER_UNIT
Use both ADC1 and ADC2 for conversion by turn. e.g. ADC1 -> ADC2 -> ADC1 -> ADC2 …..
enumerator ADC_CONV_UNIT_MAX
enum adc_digi_output_format_t
ADC digital controller (DMA mode) output data format option.
Values:
enumerator ADC_DIGI_FORMAT_12BIT
ADC to DMA data format, [15:12]-channel, [11: 0]-12 bits ADC data
(adc_digi_output_data_t). Note: For single convert mode.
enumerator ADC_DIGI_FORMAT_11BIT
ADC to DMA data format, [15]-adc unit, [14:11]-channel, [10: 0]-11 bits ADC data
(adc_digi_output_data_t). Note: For multi or alter convert mode.
enumerator ADC_DIGI_FORMAT_MAX
enumerator ADC_DIGI_OUTPUT_FORMAT_TYPE1
See adc_digi_output_data_t.type1
enumerator ADC_DIGI_OUTPUT_FORMAT_TYPE2
See adc_digi_output_data_t.type2
enum adc_i2s_source_t
ESP32 ADC DMA source selection.
Values:
enumerator ADC_I2S_DATA_SRC_IO_SIG
I2S data from GPIO matrix signal
enumerator ADC_I2S_DATA_SRC_ADC
I2S data from ADC
enumerator ADC_I2S_DATA_SRC_MAX
ADC Calibration
Header File
• components/esp_adc_cal/include/esp_adc_cal.h
Functions
esp_err_t esp_adc_cal_check_efuse(esp_adc_cal_value_t value_type)
Checks if ADC calibration values are burned into eFuse.
This function checks if ADC reference voltage or Two Point values have been burned to the eFuse of the
current ESP32
Note: For ESP32, Two Point values and eFuse Vref calibration can be enabled/disabled using menuconfig.
For ESP32s2, only Two Point values calibration and only ADC_WIDTH_BIT_13 is supported. The parameter
default_vref is unused.
Parameters
• adc_num –[in] ADC to characterize (ADC_UNIT_1 or ADC_UNIT_2)
• atten –[in] Attenuation to characterize
• bit_width –[in] Bit width configuration of ADC
• default_vref –[in] Default ADC reference voltage in mV (Only in ESP32, used if
eFuse values is not available)
• chars –[out] Pointer to empty structure used to store ADC characteristics
Returns
• ESP_ADC_CAL_VAL_EFUSE_VREF: eFuse Vref used for characterization
• ESP_ADC_CAL_VAL_EFUSE_TP: Two Point value used for characterization (only in
Linear Mode)
• ESP_ADC_CAL_VAL_DEFAULT_VREF: Default Vref used for characterization
Note: Characteristics structure must be initialized before this function is called (call
esp_adc_cal_characterize())
Parameters
• adc_reading –[in] ADC reading
• chars –[in] Pointer to initialized structure containing ADC characteristics
Returns Voltage in mV
Note: The Characteristics structure must be initialized before this function is called (call
esp_adc_cal_characterize())
Parameters
• channel –[in] ADC Channel to read
• chars –[in] Pointer to initialized ADC characteristics structure
• voltage –[out] Pointer to store converted voltage
Returns
• ESP_OK: ADC read and converted to mV
• ESP_ERR_INVALID_ARG: Error due to invalid arguments
• ESP_ERR_INVALID_STATE: Reading result is invalid. Try to read again.
Structures
struct esp_adc_cal_characteristics_t
Structure storing characteristics of an ADC.
Public Members
adc_unit_t adc_num
ADC unit
adc_atten_t atten
ADC attenuation
adc_bits_width_t bit_width
ADC bit width
uint32_t coeff_a
Gradient of ADC-Voltage curve
uint32_t coeff_b
Offset of ADC-Voltage curve
uint32_t vref
Vref used by lookup table
uint8_t version
ADC Calibration
Enumerations
enum esp_adc_cal_value_t
Type of calibration value used in characterization.
Values:
enumerator ESP_ADC_CAL_VAL_EFUSE_VREF
Characterization based on reference voltage stored in eFuse
enumerator ESP_ADC_CAL_VAL_EFUSE_TP
Characterization based on Two Point values stored in eFuse
enumerator ESP_ADC_CAL_VAL_DEFAULT_VREF
Characterization based on default reference voltage
enumerator ESP_ADC_CAL_VAL_EFUSE_TP_FIT
Characterization based on Two Point values and fitting curve coefficients stored in eFuse
enumerator ESP_ADC_CAL_VAL_MAX
enumerator ESP_ADC_CAL_VAL_NOT_SUPPORTED
Header File
• components/soc/esp32/include/soc/adc_channel.h
Macros
ADC1_GPIO36_CHANNEL
ADC1_CHANNEL_0_GPIO_NUM
ADC1_GPIO37_CHANNEL
ADC1_CHANNEL_1_GPIO_NUM
ADC1_GPIO38_CHANNEL
ADC1_CHANNEL_2_GPIO_NUM
ADC1_GPIO39_CHANNEL
ADC1_CHANNEL_3_GPIO_NUM
ADC1_GPIO32_CHANNEL
ADC1_CHANNEL_4_GPIO_NUM
ADC1_GPIO33_CHANNEL
ADC1_CHANNEL_5_GPIO_NUM
ADC1_GPIO34_CHANNEL
ADC1_CHANNEL_6_GPIO_NUM
ADC1_GPIO35_CHANNEL
ADC1_CHANNEL_7_GPIO_NUM
ADC2_GPIO4_CHANNEL
ADC2_CHANNEL_0_GPIO_NUM
ADC2_GPIO0_CHANNEL
ADC2_CHANNEL_1_GPIO_NUM
ADC2_GPIO2_CHANNEL
ADC2_CHANNEL_2_GPIO_NUM
ADC2_GPIO15_CHANNEL
ADC2_CHANNEL_3_GPIO_NUM
ADC2_GPIO13_CHANNEL
ADC2_CHANNEL_4_GPIO_NUM
ADC2_GPIO12_CHANNEL
ADC2_CHANNEL_5_GPIO_NUM
ADC2_GPIO14_CHANNEL
ADC2_CHANNEL_6_GPIO_NUM
ADC2_GPIO27_CHANNEL
ADC2_CHANNEL_7_GPIO_NUM
ADC2_GPIO25_CHANNEL
ADC2_CHANNEL_8_GPIO_NUM
ADC2_GPIO26_CHANNEL
ADC2_CHANNEL_9_GPIO_NUM
This section lists definitions of the ESP32’s supported root clocks and module clocks. These definitions are commonly
used in the driver configuration, to help user select a proper source clock for the peripheral.
Root Clocks
Root clocks generate reliable clock signals. These clock signals then pass through various gates, muxes, dividers, or
multipliers to become the clock sources for every functional module: the CPU core(s), WIFI, BT, the RTC, and the
peripherals.
ESP32’s root clocks are listed in soc_root_clk_t:
Module Clocks
ESP32’s available module clocks are listed in soc_module_clk_t. Each module clock has a unique ID. You
can get more information on each clock by checking the documented enum value.
API Reference
Header File
• components/soc/esp32/include/soc/clk_tree_defs.h
Macros
SOC_CLK_RC_FAST_FREQ_APPROX
Approximate RC_FAST_CLK frequency in Hz
SOC_CLK_RC_SLOW_FREQ_APPROX
Approximate RC_SLOW_CLK frequency in Hz
SOC_CLK_RC_FAST_D256_FREQ_APPROX
Approximate RC_FAST_D256_CLK frequency in Hz
SOC_CLK_XTAL32K_FREQ_APPROX
Approximate XTAL32K_CLK frequency in Hz
SOC_GPTIMER_CLKS
Array initializer for all supported clock sources of GPTimer.
The following code can be used to iterate all possible clocks:
SOC_LCD_CLKS
Array initializer for all supported clock sources of LCD.
SOC_RMT_CLKS
Array initializer for all supported clock sources of RMT.
SOC_MCPWM_TIMER_CLKS
Array initializer for all supported clock sources of MCPWM Timer.
SOC_MCPWM_CAPTURE_CLKS
Array initializer for all supported clock sources of MCPWM Capture Timer.
SOC_I2S_CLKS
Array initializer for all supported clock sources of.
Enumerations
enum soc_root_clk_t
Root clock.
Values:
enumerator SOC_ROOT_CLK_INT_RC_FAST
Internal 8MHz RC oscillator
enumerator SOC_ROOT_CLK_INT_RC_SLOW
Internal 150kHz RC oscillator
enumerator SOC_ROOT_CLK_EXT_XTAL
External 2~40MHz crystal
enumerator SOC_ROOT_CLK_EXT_XTAL32K
External 32kHz crystal/clock signal
enum soc_cpu_clk_src_t
CPU_CLK mux inputs, which are the supported clock sources for the CPU_CLK.
Note: Enum values are matched with the register field values on purpose
Values:
enumerator SOC_CPU_CLK_SRC_XTAL
Select XTAL_CLK as CPU_CLK source
enumerator SOC_CPU_CLK_SRC_PLL
Select PLL_CLK as CPU_CLK source (PLL_CLK is the output of 40MHz crystal oscillator frequency
multiplier, can be 480MHz or 320MHz)
enumerator SOC_CPU_CLK_SRC_RC_FAST
Select RC_FAST_CLK as CPU_CLK source
enumerator SOC_CPU_CLK_SRC_APLL
Select APLL_CLK as CPU_CLK source
enumerator SOC_CPU_CLK_SRC_INVALID
Invalid CPU_CLK source
enum soc_rtc_slow_clk_src_t
RTC_SLOW_CLK mux inputs, which are the supported clock sources for the RTC_SLOW_CLK.
Note: Enum values are matched with the register field values on purpose
Values:
enumerator SOC_RTC_SLOW_CLK_SRC_RC_SLOW
Select RC_SLOW_CLK as RTC_SLOW_CLK source
enumerator SOC_RTC_SLOW_CLK_SRC_XTAL32K
Select XTAL32K_CLK as RTC_SLOW_CLK source
enumerator SOC_RTC_SLOW_CLK_SRC_RC_FAST_D256
Select RC_FAST_D256_CLK (referred as FOSC_DIV or 8m_d256/8md256 in TRM and reg. descrip-
tion) as RTC_SLOW_CLK source
enumerator SOC_RTC_SLOW_CLK_SRC_INVALID
Invalid RTC_SLOW_CLK source
enum soc_rtc_fast_clk_src_t
RTC_FAST_CLK mux inputs, which are the supported clock sources for the RTC_FAST_CLK.
Note: Enum values are matched with the register field values on purpose
Values:
enumerator SOC_RTC_FAST_CLK_SRC_XTAL_D4
Select XTAL_D4_CLK (may referred as XTAL_CLK_DIV_4) as RTC_FAST_CLK source
enumerator SOC_RTC_FAST_CLK_SRC_XTAL_DIV
Alias name for SOC_RTC_FAST_CLK_SRC_XTAL_D4
enumerator SOC_RTC_FAST_CLK_SRC_RC_FAST
Select RC_FAST_CLK as RTC_FAST_CLK source
enumerator SOC_RTC_FAST_CLK_SRC_INVALID
Invalid RTC_FAST_CLK source
enum soc_module_clk_t
Supported clock sources for modules (CPU, peripherals, RTC, etc.)
Values:
enumerator SOC_MOD_CLK_CPU
CPU_CLK can be sourced from XTAL, PLL, RC_FAST, or APLL by configuring soc_cpu_clk_src_t
enumerator SOC_MOD_CLK_RTC_FAST
RTC_FAST_CLK can be sourced from XTAL_D4 or RC_FAST by configuring soc_rtc_fast_clk_src_t
enumerator SOC_MOD_CLK_RTC_SLOW
RTC_SLOW_CLK can be sourced from RC_SLOW, XTAL32K, or RC_FAST_D256 by configuring
soc_rtc_slow_clk_src_t
enumerator SOC_MOD_CLK_APB
APB_CLK is highly dependent on the CPU_CLK source
enumerator SOC_MOD_CLK_PLL_D2
PLL_D2_CLK is derived from PLL, it has a fixed divider of 2
enumerator SOC_MOD_CLK_XTAL32K
XTAL32K_CLK comes from the external 32kHz crystal, passing a clock gating to the peripherals
enumerator SOC_MOD_CLK_RC_FAST
RC_FAST_CLK comes from the internal 8MHz rc oscillator, passing a clock gating to the peripherals
enumerator SOC_MOD_CLK_RC_FAST_D256
RC_FAST_D256_CLK comes from the internal 8MHz rc oscillator, divided by 256, and passing a clock
gating to the peripherals
enumerator SOC_MOD_CLK_XTAL
XTAL_CLK comes from the external crystal (2~40MHz)
enumerator SOC_MOD_CLK_REF_TICK
REF_TICK is derived from APB, it has a fixed frequency of 1MHz even when APB frequency changes
enumerator SOC_MOD_CLK_APLL
APLL is sourced from PLL, and its frequency is configurable through APLL configuration registers
enum soc_periph_gptimer_clk_src_t
Type of GPTimer clock source.
Values:
enumerator GPTIMER_CLK_SRC_APB
Select APB as the source clock
enumerator GPTIMER_CLK_SRC_DEFAULT
Select APB as the default choice
enum soc_periph_tg_clk_src_legacy_t
Type of Timer Group clock source, reserved for the legacy timer group driver.
Values:
enumerator TIMER_SRC_CLK_APB
Timer group source clock is APB
enumerator TIMER_SRC_CLK_DEFAULT
Timer group source clock default choice is APB
enum soc_periph_lcd_clk_src_t
Type of LCD clock source.
Values:
enumerator LCD_CLK_SRC_PLL160M
Select PLL_D2 (default to 160MHz) as the source clock
enumerator LCD_CLK_SRC_APLL
Select APLL as the source clock
enumerator LCD_CLK_SRC_XTAL
Select XTAL as the source clock
enumerator LCD_CLK_SRC_DEFAULT
Select PLL_D2 (default to 160MHz) as the default choice
enum soc_periph_rmt_clk_src_t
Type of RMT clock source.
Values:
enumerator RMT_CLK_SRC_NONE
No clock source is selected
enumerator RMT_CLK_SRC_APB
Select APB as the source clock
enumerator RMT_CLK_SRC_REF_TICK
Select REF_TICK as the source clock
enumerator RMT_CLK_SRC_DEFAULT
Select APB as the default choice
enum soc_periph_rmt_clk_src_legacy_t
Type of RMT clock source, reserved for the legacy RMT driver.
Values:
enumerator RMT_BASECLK_APB
RMT source clock is APB CLK
enumerator RMT_BASECLK_REF
RMT source clock is REF_TICK
enumerator RMT_BASECLK_DEFAULT
RMT source clock default choice is APB
enum soc_periph_temperature_sensor_clk_src_t
Type of Temp Sensor clock source.
Values:
enumerator TEMPERATURE_SENSOR_SRC_NA
enum soc_periph_uart_clk_src_legacy_t
Type of UART clock source, reserved for the legacy UART driver.
Values:
enumerator UART_SCLK_APB
UART source clock is APB CLK
enumerator UART_SCLK_REF_TICK
UART source clock is REF_TICK
enumerator UART_SCLK_DEFAULT
UART source clock default choice is APB
enum soc_periph_mcpwm_timer_clk_src_t
Type of MCPWM timer clock source.
Values:
enumerator MCPWM_TIMER_CLK_SRC_PLL160M
Select PLL_D2 (160MHz) as the source clock
enumerator MCPWM_TIMER_CLK_SRC_DEFAULT
Select PLL_D2 as the default clock choice
enum soc_periph_mcpwm_capture_clk_src_t
Type of MCPWM capture clock source.
Values:
enumerator MCPWM_CAPTURE_CLK_SRC_APB
Select APB as the source clock
enumerator MCPWM_CAPTURE_CLK_SRC_DEFAULT
SElect APB as the default clock choice
enum soc_periph_i2s_clk_src_t
I2S clock source enum.
Values:
enumerator I2S_CLK_SRC_DEFAULT
Select PLL_D2 as the default source clock
enumerator I2S_CLK_SRC_PLL_160M
Select PLL_D2 as the source clock
enumerator I2S_CLK_SRC_APLL
Select APLL as the source clock
Overview
ESP32 has two 8-bit DAC (digital to analog converter) channels, connected to GPIO25 (Channel 1) and GPIO26
(Channel 2).
The DAC driver allows these channels to be set to arbitrary voltages.
The DAC channels can also be driven with DMA-style written sample data by the digital controller, via the I2S driver
when using the “built-in DAC mode”.
For other analog output options, see the Sigma-delta Modulation module and the LED Control module. Both these
modules produce high frequency PWM output, which can be hardware low-pass filtered in order to generate a lower
frequency analog output.
Application Example
Setting DAC channel 1 (GPIO25) voltage to approx 0.78 of VDD_A voltage (VDD * 200 / 255). For VDD_A 3.3V,
this is 2.59V.
#include <driver/dac.h>
...
dac_output_enable(DAC_CHANNEL_1);
dac_output_voltage(DAC_CHANNEL_1, 200);
API Reference
Header File
• components/driver/esp32/include/driver/dac.h
Functions
esp_err_t dac_i2s_enable(void)
Enable DAC output data from I2S.
Returns
• ESP_OK success
esp_err_t dac_i2s_disable(void)
Disable DAC output data from I2S.
Returns
• ESP_OK success
Header File
• components/driver/include/driver/dac_common.h
Functions
esp_err_t dac_pad_get_io_num(dac_channel_t channel, gpio_num_t *gpio_num)
Get the GPIO number of a specific DAC channel.
Parameters
• channel –Channel to get the gpio number
• gpio_num –output buffer to hold the gpio number
Returns
• ESP_OK if success
esp_err_t dac_output_voltage(dac_channel_t channel, uint8_t dac_value)
Set DAC output voltage. DAC output is 8-bit. Maximum (255) corresponds to VDD3P3_RTC.
Note: Need to configure DAC pad before calling this function. DAC channel 1 is attached to GPIO25, DAC
channel 2 is attached to GPIO26
Parameters
• channel –DAC channel
• dac_value –DAC output value
Returns
• ESP_OK success
Note: DAC channel 1 is attached to GPIO25, DAC channel 2 is attached to GPIO26 I2S left channel will be
mapped to DAC channel 2 I2S right channel will be mapped to DAC channel 1
esp_err_t dac_cw_generator_enable(void)
Enable cosine wave generator output.
Returns
• ESP_OK success
esp_err_t dac_cw_generator_disable(void)
Disable cosine wave generator output.
Returns
• ESP_OK success
esp_err_t dac_cw_generator_config(dac_cw_config_t *cw)
Config the cosine wave generator function in DAC module.
Parameters cw –Configuration.
Returns
• ESP_OK success
• ESP_ERR_INVALID_ARG The parameter is NULL.
GPIO Lookup Macros Some useful macros can be used to specified the GPIO number of a DAC channel, or vice
versa. e.g.
1. DAC_CHANNEL_1_GPIO_NUM is the GPIO number of channel 1 (GPIO25);
2. DAC_GPIO26_CHANNEL is the channel number of GPIO 26 (channel 2).
Header File
• components/soc/esp32/include/soc/dac_channel.h
Macros
DAC_GPIO25_CHANNEL
DAC_CHANNEL_1_GPIO_NUM
DAC_GPIO26_CHANNEL
DAC_CHANNEL_2_GPIO_NUM
Header File
• components/hal/include/hal/dac_types.h
Structures
struct dac_cw_config_t
Config the cosine wave generator function in DAC module.
Public Members
dac_channel_t en_ch
Enable the cosine wave generator of DAC channel.
dac_cw_scale_t scale
Set the amplitude of the cosine wave generator output.
dac_cw_phase_t phase
Set the phase of the cosine wave generator output.
uint32_t freq
Set frequency of cosine wave generator output. Range: 130(130Hz) ~ 55000(100KHz).
int8_t offset
Set the voltage value of the DC component of the cosine wave generator output. Note: Unreasonable
settings can cause waveform to be oversaturated. Range: -128 ~ 127.
Enumerations
enum dac_channel_t
Values:
enumerator DAC_CHANNEL_1
DAC channel 1 is GPIO25(ESP32) / GPIO17(ESP32S2)
enumerator DAC_CHANNEL_2
DAC channel 2 is GPIO26(ESP32) / GPIO18(ESP32S2)
enumerator DAC_CHANNEL_MAX
enum dac_cw_scale_t
The multiple of the amplitude of the cosine wave generator. The max amplitude is VDD3P3_RTC.
Values:
enumerator DAC_CW_SCALE_1
1/1. Default.
enumerator DAC_CW_SCALE_2
1/2.
enumerator DAC_CW_SCALE_4
1/4.
enumerator DAC_CW_SCALE_8
1/8.
enum dac_cw_phase_t
Set the phase of the cosine wave generator output.
Values:
enumerator DAC_CW_PHASE_0
Phase shift +0°
enumerator DAC_CW_PHASE_180
Phase shift +180°
Overview
The ESP32 chip features 34 physical GPIO pins (GPIO0 ~ GPIO19, GPIO21 ~ GPIO23, GPIO25 ~ GPIO27, and
GPIO32 ~ GPIO39). Each pin can be used as a general-purpose I/O, or be connected to an internal peripheral signal.
Through IO MUX, RTC IO MUX and the GPIO matrix, peripheral input signals can be from any IO pins, and
peripheral output signals can be routed to any IO pins. Together these modules provide highly configurable I/O. For
more details, see ESP32 Technical Reference Manual > IO MUX and GPIO Matrix (GPIO, IO_MUX) [PDF].
The table below provides more information on pin usage, and please note the comments in the table for GPIOs with
restrictions.
Note:
• Strapping pin: GPIO0, GPIO2, GPIO5, GPIO12 (MTDI), and GPIO15 (MTDO) are strapping pins. For more
infomation, please refer to ESP32 datasheet.
• SPI0/1: GPIO6-11 and GPIO16-17 are usually connected to the SPI flash and PSRAM integrated on the
module and therefore should not be used for other purposes.
• JTAG: GPIO12-15 are usually used for inline debug.
• GPI: GPIO34-39 can only be set as input mode and do not have software-enabled pullup or pulldown functions.
• TXD & RXD are usually used for flashing and debugging.
• ADC2: ADC2 pins cannot be used when Wi-Fi is used. So, if you are having trouble getting the value from
an ADC2 GPIO while using Wi-Fi, you may consider using an ADC1 GPIO instead, which should solve your
problem. For more details, please refer to ADC limitations.
There is also separate “RTC GPIO”support, which functions when GPIOs are routed to the “RTC”low-power
and analog subsystem. These pin functions can be used when:
• In Deep-sleep mode
• The Ultra Low Power co-processor is running
• Analog functions such as ADC/DAC/etc are in use.
Application Example
Header File
• components/driver/include/driver/gpio.h
Functions
Note: This function also configures the IOMUX for this pin to the GPIO function, and disconnects any other
peripheral output configured via GPIO Matrix.
Note: ESP32: Please do not use the interrupt of GPIO36 and GPIO39 when using ADC or Wi-Fi and
Bluetooth with sleep mode enabled. Please refer to the comments of adc1_get_raw. Please refer to Section
3.11 of ESP32 ECO and Workarounds for Bugs for the description of this issue. As a workaround, call
adc_power_acquire() in the app. This will result in higher power consumption (by ~1mA), but will remove the
glitches on GPIO36 and GPIO39.
Parameters gpio_num –GPIO number. If you want to enable an interrupt on e.g. GPIO16,
gpio_num should be GPIO_NUM_16 (16);
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Note: This function is allowed to be executed when Cache is disabled within ISR context, by enabling CON-
FIG_GPIO_CTRL_FUNC_IN_IRAM
Parameters gpio_num –GPIO number. If you want to disable the interrupt of e.g. GPIO16,
gpio_num should be GPIO_NUM_16 (16);
Returns
• ESP_OK success
• ESP_ERR_INVALID_ARG Parameter error
Note: This function is allowed to be executed when Cache is disabled within ISR context, by enabling CON-
FIG_GPIO_CTRL_FUNC_IN_IRAM
Parameters
• gpio_num –GPIO number. If you want to set the output level of e.g. GPIO16, gpio_num
should be GPIO_NUM_16 (16);
• level –Output level. 0: low ; 1: high
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG GPIO number error
Warning: If the pad is not configured for input (or input and output) the returned value is always 0.
Parameters gpio_num –GPIO number. If you want to get the logic level of e.g. pin GPIO16,
gpio_num should be GPIO_NUM_16 (16);
Returns
• 0 the GPIO input level is 0
• 1 the GPIO input level is 1
Note: ESP32: Only pins that support both input & output have integrated pull-up and pull-down resistors.
Input-only GPIOs 34-39 do not.
Parameters
• gpio_num –GPIO number. If you want to set pull up or down mode for e.g. GPIO16,
gpio_num should be GPIO_NUM_16 (16);
• pull –GPIO pull up/down mode.
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG : Parameter error
Parameters
• gpio_num –GPIO number, only support output GPIOs
• strength –Drive capability of the pad
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
esp_err_t gpio_get_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t *strength)
Get GPIO pad drive capability.
Parameters
• gpio_num –GPIO number, only support output GPIOs
• strength –Pointer to accept drive capability of the pad
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
esp_err_t gpio_hold_en(gpio_num_t gpio_num)
Enable gpio pad hold function.
The gpio pad hold function works in both input and output modes, but must be output-capable gpios. If pad
hold enabled: in output mode: the output level of the pad will be force locked and can not be changed. in input
mode: the input value read will not change, regardless the changes of input signal.
The state of digital gpio cannot be held during Deep-sleep, and it will resume the hold function when
the chip wakes up from Deep-sleep. If the digital gpio also needs to be held during Deep-sleep,
gpio_deep_sleep_hold_en should also be called.
Power down or call gpio_hold_dis will disable this function.
Parameters gpio_num –GPIO number, only support output-capable GPIOs
Returns
• ESP_OK Success
• ESP_ERR_NOT_SUPPORTED Not support pad hold function
esp_err_t gpio_hold_dis(gpio_num_t gpio_num)
Disable gpio pad hold function.
When the chip is woken up from Deep-sleep, the gpio will be set to the default mode, so, the gpio will output
the default level if this function is called. If you don’t want the level changes, the gpio should be configured
to a known state before this function is called. e.g. If you hold gpio18 high during Deep-sleep, after the chip
is woken up and gpio_hold_dis is called, gpio18 will output low level(because gpio18 is input mode by
default). If you don’t want this behavior, you should configure gpio18 as output mode and set it to hight level
before calling gpio_hold_dis.
Parameters gpio_num –GPIO number, only support output-capable GPIOs
Returns
• ESP_OK Success
• ESP_ERR_NOT_SUPPORTED Not support pad hold function
void gpio_deep_sleep_hold_en(void)
Enable all digital gpio pad hold function during Deep-sleep.
When the chip is in Deep-sleep mode, all digital gpio will hold the state before sleep, and when the chip is
woken up, the status of digital gpio will not be held. Note that the pad hold feature only works when the chip
is in Deep-sleep mode, when not in sleep mode, the digital gpio state can be changed even you have called this
function.
Power down or call gpio_hold_dis will disable this function, otherwise, the digital gpio hold feature works as
long as the chip enter Deep-sleep.
void gpio_deep_sleep_hold_dis(void)
Disable all digital gpio pad hold function during Deep-sleep.
Note: ESP32: Only pins that support both input & output have integrated pull-up and pull-down resistors.
Input-only GPIOs 34-39 do not.
Parameters
• gpio_num –GPIO number. If you want to set pull up or down mode for e.g. GPIO16,
gpio_num should be GPIO_NUM_16 (16);
• pull –GPIO pull up/down mode.
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG : Parameter error
Macros
GPIO_PIN_COUNT
GPIO_IS_VALID_GPIO(gpio_num)
Check whether it is a valid GPIO number.
GPIO_IS_VALID_OUTPUT_GPIO(gpio_num)
Check whether it can be a valid GPIO number of output mode.
Type Definitions
Header File
• components/hal/include/hal/gpio_types.h
Structures
struct gpio_config_t
Configuration parameters of GPIO pad for gpio_config function.
Public Members
uint64_t pin_bit_mask
GPIO pin: set with bit mask, each bit maps to a GPIO
gpio_mode_t mode
GPIO mode: set input/output mode
gpio_pullup_t pull_up_en
GPIO pull-up
gpio_pulldown_t pull_down_en
GPIO pull-down
gpio_int_type_t intr_type
GPIO interrupt type
Macros
GPIO_PIN_REG_0
GPIO_PIN_REG_1
GPIO_PIN_REG_2
GPIO_PIN_REG_3
GPIO_PIN_REG_4
GPIO_PIN_REG_5
GPIO_PIN_REG_6
GPIO_PIN_REG_7
GPIO_PIN_REG_8
GPIO_PIN_REG_9
GPIO_PIN_REG_10
GPIO_PIN_REG_11
GPIO_PIN_REG_12
GPIO_PIN_REG_13
GPIO_PIN_REG_14
GPIO_PIN_REG_15
GPIO_PIN_REG_16
GPIO_PIN_REG_17
GPIO_PIN_REG_18
GPIO_PIN_REG_19
GPIO_PIN_REG_20
GPIO_PIN_REG_21
GPIO_PIN_REG_22
GPIO_PIN_REG_23
GPIO_PIN_REG_24
GPIO_PIN_REG_25
GPIO_PIN_REG_26
GPIO_PIN_REG_27
GPIO_PIN_REG_28
GPIO_PIN_REG_29
GPIO_PIN_REG_30
GPIO_PIN_REG_31
GPIO_PIN_REG_32
GPIO_PIN_REG_33
GPIO_PIN_REG_34
GPIO_PIN_REG_35
GPIO_PIN_REG_36
GPIO_PIN_REG_37
GPIO_PIN_REG_38
GPIO_PIN_REG_39
GPIO_PIN_REG_40
GPIO_PIN_REG_41
GPIO_PIN_REG_42
GPIO_PIN_REG_43
GPIO_PIN_REG_44
GPIO_PIN_REG_45
GPIO_PIN_REG_46
GPIO_PIN_REG_47
GPIO_PIN_REG_48
Type Definitions
Enumerations
enum gpio_port_t
Values:
enumerator GPIO_PORT_0
enumerator GPIO_PORT_MAX
enum gpio_num_t
Values:
enumerator GPIO_NUM_NC
Use to signal not connected to S/W
enumerator GPIO_NUM_0
GPIO0, input and output
enumerator GPIO_NUM_1
GPIO1, input and output
enumerator GPIO_NUM_2
GPIO2, input and output
enumerator GPIO_NUM_3
GPIO3, input and output
enumerator GPIO_NUM_4
GPIO4, input and output
enumerator GPIO_NUM_5
GPIO5, input and output
enumerator GPIO_NUM_6
GPIO6, input and output
enumerator GPIO_NUM_7
GPIO7, input and output
enumerator GPIO_NUM_8
GPIO8, input and output
enumerator GPIO_NUM_9
GPIO9, input and output
enumerator GPIO_NUM_10
GPIO10, input and output
enumerator GPIO_NUM_11
GPIO11, input and output
enumerator GPIO_NUM_12
GPIO12, input and output
enumerator GPIO_NUM_13
GPIO13, input and output
enumerator GPIO_NUM_14
GPIO14, input and output
enumerator GPIO_NUM_15
GPIO15, input and output
enumerator GPIO_NUM_16
GPIO16, input and output
enumerator GPIO_NUM_17
GPIO17, input and output
enumerator GPIO_NUM_18
GPIO18, input and output
enumerator GPIO_NUM_19
GPIO19, input and output
enumerator GPIO_NUM_20
GPIO20, input and output
enumerator GPIO_NUM_21
GPIO21, input and output
enumerator GPIO_NUM_22
GPIO22, input and output
enumerator GPIO_NUM_23
GPIO23, input and output
enumerator GPIO_NUM_25
GPIO25, input and output
enumerator GPIO_NUM_26
GPIO26, input and output
enumerator GPIO_NUM_27
GPIO27, input and output
enumerator GPIO_NUM_28
GPIO28, input and output
enumerator GPIO_NUM_29
GPIO29, input and output
enumerator GPIO_NUM_30
GPIO30, input and output
enumerator GPIO_NUM_31
GPIO31, input and output
enumerator GPIO_NUM_32
GPIO32, input and output
enumerator GPIO_NUM_33
GPIO33, input and output
enumerator GPIO_NUM_34
GPIO34, input mode only
enumerator GPIO_NUM_35
GPIO35, input mode only
enumerator GPIO_NUM_36
GPIO36, input mode only
enumerator GPIO_NUM_37
GPIO37, input mode only
enumerator GPIO_NUM_38
GPIO38, input mode only
enumerator GPIO_NUM_39
GPIO39, input mode only
enumerator GPIO_NUM_MAX
enum gpio_int_type_t
Values:
enumerator GPIO_INTR_DISABLE
Disable GPIO interrupt
enumerator GPIO_INTR_POSEDGE
GPIO interrupt type : rising edge
enumerator GPIO_INTR_NEGEDGE
GPIO interrupt type : falling edge
enumerator GPIO_INTR_ANYEDGE
GPIO interrupt type : both rising and falling edge
enumerator GPIO_INTR_LOW_LEVEL
GPIO interrupt type : input low level trigger
enumerator GPIO_INTR_HIGH_LEVEL
GPIO interrupt type : input high level trigger
enumerator GPIO_INTR_MAX
enum gpio_mode_t
Values:
enumerator GPIO_MODE_DISABLE
GPIO mode : disable input and output
enumerator GPIO_MODE_INPUT
GPIO mode : input only
enumerator GPIO_MODE_OUTPUT
GPIO mode : output only mode
enumerator GPIO_MODE_OUTPUT_OD
GPIO mode : output only with open-drain mode
enumerator GPIO_MODE_INPUT_OUTPUT_OD
GPIO mode : output and input with open-drain mode
enumerator GPIO_MODE_INPUT_OUTPUT
GPIO mode : output and input mode
enum gpio_pullup_t
Values:
enumerator GPIO_PULLUP_DISABLE
Disable GPIO pull-up resistor
enumerator GPIO_PULLUP_ENABLE
Enable GPIO pull-up resistor
enum gpio_pulldown_t
Values:
enumerator GPIO_PULLDOWN_DISABLE
Disable GPIO pull-down resistor
enumerator GPIO_PULLDOWN_ENABLE
Enable GPIO pull-down resistor
enum gpio_pull_mode_t
Values:
enumerator GPIO_PULLUP_ONLY
Pad pull up
enumerator GPIO_PULLDOWN_ONLY
Pad pull down
enumerator GPIO_PULLUP_PULLDOWN
Pad pull up + pull down
enumerator GPIO_FLOATING
Pad floating
enum gpio_drive_cap_t
Values:
enumerator GPIO_DRIVE_CAP_0
Pad drive capability: weak
enumerator GPIO_DRIVE_CAP_1
Pad drive capability: stronger
enumerator GPIO_DRIVE_CAP_2
Pad drive capability: medium
enumerator GPIO_DRIVE_CAP_DEFAULT
Pad drive capability: medium
enumerator GPIO_DRIVE_CAP_3
Pad drive capability: strongest
enumerator GPIO_DRIVE_CAP_MAX
Header File
• components/driver/include/driver/rtc_io.h
Functions
bool rtc_gpio_is_valid_gpio(gpio_num_t gpio_num)
Determine if the specified GPIO is a valid RTC GPIO.
Parameters gpio_num –GPIO number
Returns true if GPIO is valid for RTC GPIO use. false otherwise.
int rtc_io_number_get(gpio_num_t gpio_num)
Get RTC IO index number by gpio number.
Parameters gpio_num –GPIO number
Returns >=0: Index of rtcio. -1 : The gpio is not rtcio.
Macros
RTC_GPIO_IS_VALID_GPIO(gpio_num)
Header File
• components/hal/include/hal/rtc_io_types.h
Enumerations
enum rtc_gpio_mode_t
RTCIO output/input mode type.
Values:
enumerator RTC_GPIO_MODE_INPUT_ONLY
Pad input
enumerator RTC_GPIO_MODE_OUTPUT_ONLY
Pad output
enumerator RTC_GPIO_MODE_INPUT_OUTPUT
Pad input + output
enumerator RTC_GPIO_MODE_DISABLED
Pad (output + input) disable
enumerator RTC_GPIO_MODE_OUTPUT_OD
Pad open-drain output
enumerator RTC_GPIO_MODE_INPUT_OUTPUT_OD
Pad input + open-drain output
Introduction
GPTimer (General Purpose Timer) is the driver of ESP32 Timer Group peripheral. The hardware timer features
high resolution and flexible alarm action. The behavior when the internal counter of a timer reaches a specific target
value is called a timer alarm. When a timer alarms, a user registered per-timer callback would be called.
Typically, a general purpose timer can be used in scenarios like:
• Free running as a wall clock, fetching a high-resolution timestamp at any time and any places
• Generate period alarms, trigger events periodically
• Generate one-shot alarm, respond in target time
Functional Overview
The following sections of this document cover the typical steps to install and operate a timer:
• Resource Allocation - covers which parameters should be set up to get a timer handle and how to recycle the
resources when GPTimer finishes working.
• Set and Get Count Value - covers how to force the timer counting from a start point and how to get the count
value at anytime.
• Set up Alarm Action - covers the parameters that should be set up to enable the alarm event.
• Register Event Callbacks - covers how to hook user specific code to the alarm event callback function.
• Enable and Disable Timer - covers how to enable and disable the timer.
• Start and Stop Timer - shows some typical use cases that start the timer with different alarm behavior.
• Power Management - describes how different source clock selections can affect power consumption.
• IRAM Safe - describes tips on how to make the timer interrupt and IO control functions work better along with
a disabled cache.
• Thread Safety - lists which APIs are guaranteed to be thread safe by the driver.
• Kconfig Options - lists the supported Kconfig options that can be used to make a different effect on driver
behavior.
Resource Allocation Different ESP chips might have different numbers of independent timer groups, and within
each group, there could also be several independent timers.1
A GPTimer instance is represented by gptimer_handle_t. The driver behind will manage all available hardware
resources in a pool, so that you do not need to care about which timer and which group it belongs to.
To install a timer instance, there is a configuration structure that needs to be given in advance: gpti-
mer_config_t:
• gptimer_config_t::clk_src selects the source clock for the timer. The available clocks are listed
in gptimer_clock_source_t, you can only pick one of them. For the effect on power consumption of
different clock source, please refer to Section Power Management.
• gptimer_config_t::direction sets the counting direction of the timer, supported directions are
listed in gptimer_count_direction_t, you can only pick one of them.
• gptimer_config_t::resolution_hz sets the resolution of the internal counter. Each count step is
equivalent to 1 / resolution_hz seconds.
• Optional gptimer_config_t::intr_shared sets whether or not mark the timer interrupt source as
a shared one. For the pros/cons of a shared interrupt, you can refer to Interrupt Handling.
With all the above configurations set in the structure, the structure can be passed to gptimer_new_timer()
which will instantiate the timer instance and return a handle of the timer.
The function can fail due to various errors such as insufficient memory, invalid arguments, etc. Specifically, when
there are no more free timers (i.e. all hardware resources have been used up), then ESP_ERR_NOT_FOUND will be
returned. The total number of available timers is represented by the SOC_TIMER_GROUP_TOTAL_TIMERS and
its value will depend on the ESP chip.
If a previously created GPTimer instance is no longer required, you should recycle the timer by calling gpti-
mer_del_timer(). This will allow the underlying HW timer to be used for other purposes. Before deleting a
GPTimer handle, please disable it by gptimer_disable() in advance or make sure it has not enabled yet by
gptimer_enable().
Manual > Chapter Timer Group (TIMG) [PDF]. The driver will not forbid you from applying for more timers, but it will return error when all
available hardware resources are used up. Please always check the return value when doing resource allocation (e.g. gptimer_new_timer()).
Set and Get Count Value When the GPTimer is created, the internal counter will be reset to zero by de-
fault. The counter value can be updated asynchronously by gptimer_set_raw_count(). The maximum
count value is dependent on the bit width of the hardware timer, which is also reflected by the SOC macro
SOC_TIMER_GROUP_COUNTER_BIT_WIDTH. When updating the raw count of an active timer, the timer will
immediately start counting from the new value.
Count value can be retrieved by gptimer_get_raw_count(), at any time.
Set up Alarm Action For most of the use cases of GPTimer, you should set up the alarm action before starting the
timer, except for the simple wall-clock scenario, where a free running timer is enough. To set up the alarm action,
you should configure several members of gptimer_alarm_config_t based on how you make use of the alarm
event:
• gptimer_alarm_config_t::alarm_count sets the target count value that will trig-
ger the alarm event. You should also take the counting direction into consideration when set-
ting the alarm value. Specially, gptimer_alarm_config_t::alarm_count and gpti-
mer_alarm_config_t::reload_count cannot be set to the same value when gpti-
mer_alarm_config_t::auto_reload_on_alarm is true, as keeping reload with a target
alarm count is meaningless.
• gptimer_alarm_config_t::reload_count sets the count value to be reloaded
when the alarm event happens. This configuration only takes effect when gpti-
mer_alarm_config_t::auto_reload_on_alarm is set to true.
• gptimer_alarm_config_t::auto_reload_on_alarm flag sets whether to enable
the auto-reload feature. If enabled, the hardware timer will reload the value of gpti-
mer_alarm_config_t::reload_count into counter immediately when an alarm event happens.
To make the alarm configurations take effect, you should call gptimer_set_alarm_action(). Especially, if
gptimer_alarm_config_t is set to NULL, the alarm function will be disabled.
Note: If an alarm value is set and the timer has already exceeded this value, the alarm will be triggered immediately.
Register Event Callbacks After the timer starts up, it can generate a specific event (e.g. the “Alarm Event”)
dynamically. If you have some functions that should be called when the event happens, please hook your function
to the interrupt service routine by calling gptimer_register_event_callbacks(). All supported event
callbacks are listed in gptimer_event_callbacks_t:
• gptimer_event_callbacks_t::on_alarm sets a callback function for alarm events. As this func-
tion is called within the ISR context, you must ensure that the function does not attempt to block (e.g., by
making sure that only FreeRTOS APIs with ISR suffix are called from within the function). The function
prototype is declared in gptimer_alarm_cb_t.
You can save your own context to gptimer_register_event_callbacks() as well, via the parameter
user_data. The user data will be directly passed to the callback function.
This function will lazy install the interrupt service for the timer but not enable it. So please call this function before
gptimer_enable(), otherwise the ESP_ERR_INVALID_STATE error will be returned. See Section Enable
and Disable Timer for more information.
Enable and Disable Timer Before doing IO control to the timer, you needs to enable the timer first, by calling
gptimer_enable(). This function will:
• Switch the timer driver state from init to enable.
Start and Stop Timer The basic IO operation of a timer is to start and stop. Calling gptimer_start()
can make the internal counter work, while calling gptimer_stop() can make the counter stop working. The
following illustrates how to start a timer with or without an alarm event.
{
BaseType_t high_task_awoken = pdFALSE;
QueueHandle_t queue = (QueueHandle_t)user_ctx;
// Retrieve the count value from event data
example_queue_element_t ele = {
.event_count = edata->count_value
};
// Optional: send the event data to other task by OS queue
// Do not introduce complex logics in callbacks
// Suggest dealing with event data in the main loop, instead of in this␣
,→callback
gptimer_alarm_config_t alarm_config = {
.reload_count = 0, // counter will reload with 0 on alarm event
.alarm_count = 1000000, // period = 1s @resolution 1MHz
.flags.auto_reload_on_alarm = true, // enable auto-reload
};
ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config));
gptimer_event_callbacks_t cbs = {
.on_alarm = example_timer_on_alarm_cb, // register user callback
};
ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue));
ESP_ERROR_CHECK(gptimer_enable(gptimer));
ESP_ERROR_CHECK(gptimer_start(gptimer));
typedef struct {
uint64_t event_count;
} example_queue_element_t;
{
BaseType_t high_task_awoken = pdFALSE;
QueueHandle_t queue = (QueueHandle_t)user_ctx;
// Stop timer the sooner the better
gptimer_stop(timer);
// Retrieve the count value from event data
example_queue_element_t ele = {
.event_count = edata->count_value
};
// Optional: send the event data to other task by OS queue
xQueueSendFromISR(queue, &ele, &high_task_awoken);
// return whether we need to yield at the end of ISR
return high_task_awoken == pdTRUE;
}
gptimer_alarm_config_t alarm_config = {
.alarm_count = 1 * 1000 * 1000, // alarm target = 1s @resolution 1MHz
};
ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config));
gptimer_event_callbacks_t cbs = {
.on_alarm = example_timer_on_alarm_cb, // register user callback
};
ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue));
ESP_ERROR_CHECK(gptimer_enable(gptimer));
ESP_ERROR_CHECK(gptimer_start(gptimer));
Dynamic Alarm Update Alarm value can be updated dynamically inside the ISR handler callback, by changing
gptimer_alarm_event_data_t::alarm_value. Then the alarm value will be updated after the callback
function returns.
typedef struct {
uint64_t event_count;
} example_queue_element_t;
{
BaseType_t high_task_awoken = pdFALSE;
QueueHandle_t queue = (QueueHandle_t)user_data;
// Retrieve the count value from event data
example_queue_element_t ele = {
.event_count = edata->count_value
};
// Optional: send the event data to other task by OS queue
xQueueSendFromISR(queue, &ele, &high_task_awoken);
// reconfigure alarm value
gptimer_alarm_config_t alarm_config = {
.alarm_count = edata->alarm_value + 1000000, // alarm in next 1s
};
gptimer_set_alarm_action(timer, &alarm_config);
// return whether we need to yield at the end of ISR
return high_task_awoken == pdTRUE;
}
(continues on next page)
gptimer_alarm_config_t alarm_config = {
.alarm_count = 1000000, // initial alarm target = 1s @resolution 1MHz
};
ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config));
gptimer_event_callbacks_t cbs = {
.on_alarm = example_timer_on_alarm_cb, // register user callback
};
ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue));
ESP_ERROR_CHECK(gptimer_enable(gptimer));
ESP_ERROR_CHECK(gptimer_start(gptimer, &alarm_config));
Power Management When power management is enabled (i.e. CONFIG_PM_ENABLE is on), the system will
adjust the APB frequency before going into Light-sleep mode, thus potentially changing the period of a GPTimer’s
counting step and leading to inaccurate time keeping.
However, the driver can prevent the system from changing APB frequency by acquiring a power management lock
of type ESP_PM_APB_FREQ_MAX. Whenever the driver creates a GPTimer instance that has selected GPTI-
MER_CLK_SRC_APB as its clock source, the driver will guarantee that the power management lock is acquired when
enabling the timer by gptimer_enable(). Likewise, the driver releases the lock when gptimer_disable()
is called for that timer.
If other gptimer clock sources are selected such as GPTIMER_CLK_SRC_XTAL, then the driver will not install
power management lock. The XTAL clock source is more suitable for a low power application as long as the source
clock can still provide sufficient resolution.
IRAM Safe By default, the GPTimer interrupt will be deferred when the cache is disabled because of writing
or erasing the flash. Thus the alarm interrupt will not get executed in time, which is not expected in a real-time
application.
There is a Kconfig option CONFIG_GPTIMER_ISR_IRAM_SAFE that will:
• Enable the interrupt being serviced even when the cache is disabled
• Place all functions that used by the ISR into IRAM2
• Place driver object into DRAM (in case it is mapped to PSRAM by accident)
This will allow the interrupt to run while the cache is disabled, but will come at the cost of increased IRAM con-
sumption.
There is another Kconfig option CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM that can put commonly used IO con-
trol functions into IRAM as well. So, these functions can also be executable when the cache is disabled. These IO
control functions are as follows:
• gptimer_start()
• gptimer_stop()
• gptimer_get_raw_count()
• gptimer_set_raw_count()
• gptimer_set_alarm_action()
Thread Safety The factory function gptimer_new_timer() is guaranteed to be thread safe by the driver,
which means, you can call it from different RTOS tasks without protection by extra locks.
The following functions are allowed to run under ISR context, as the driver uses a critical section to prevent them
being called concurrently in the task and ISR.
• gptimer_start()
2 gptimer_event_callbacks_t::on_alarm callback and the functions invoked by the callback should also be placed in IRAM,
please take care of them by yourself.
• gptimer_stop()
• gptimer_get_raw_count()
• gptimer_set_raw_count()
• gptimer_set_alarm_action()
Other functions that take gptimer_handle_t as the first positional parameter, are not treated as thread safe,
which means you should avoid calling them from multiple tasks.
Kconfig Options
• CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM controls where to place the GPTimer control functions (IRAM
or flash), see Section IRAM Safe for more information.
• CONFIG_GPTIMER_ISR_IRAM_SAFE controls whether the default ISR handler can work when the cache is
disabled, see Section IRAM Safe for more information.
• CONFIG_GPTIMER_ENABLE_DEBUG_LOG is used to enabled the debug log output. Enable this option will
increase the firmware binary size.
Application Examples
API Reference
Header File
• components/driver/include/driver/gptimer.h
Functions
esp_err_t gptimer_new_timer(const gptimer_config_t *config, gptimer_handle_t *ret_timer)
Create a new General Purpose Timer, and return the handle.
Parameters
• config –[in] GPTimer configuration
• ret_timer –[out] Returned timer handle
Returns
• ESP_OK: Create GPTimer successfully
• ESP_ERR_INVALID_ARG: Create GPTimer failed because of invalid argument
• ESP_ERR_NO_MEM: Create GPTimer failed because out of memory
• ESP_ERR_NOT_FOUND: Create GPTimer failed because all hardware timers are used
up and no more free one
• ESP_FAIL: Create GPTimer failed because of other error
esp_err_t gptimer_del_timer(gptimer_handle_t timer)
Delete the GPTimer handle.
Note: A timer can’t be in the enable state when this function is invoked. See also gptimer_disable()
for how to disable a timer.
Note: When updating the raw count of an active timer, the timer will immediately start counting from the
new value.
Note: This function is allowed to be executed when Cache is disabled, by enabling CON-
FIG_GPTIMER_CTRL_FUNC_IN_IRAM
Parameters
• timer –[in] Timer handle created by gptimer_new_timer()
• value –[in] Count value to be set
Returns
• ESP_OK: Set GPTimer raw count value successfully
• ESP_ERR_INVALID_ARG: Set GPTimer raw count value failed because of invalid ar-
gument
• ESP_FAIL: Set GPTimer raw count value failed because of other error
Note: With the raw count value and the resolution set in the gptimer_config_t, you can convert the
count value into seconds.
Note: This function is allowed to be executed when Cache is disabled, by enabling CON-
FIG_GPTIMER_CTRL_FUNC_IN_IRAM
Parameters
• timer –[in] Timer handle created by gptimer_new_timer()
• value –[out] Returned GPTimer count value
Returns
• ESP_OK: Get GPTimer raw count value successfully
• ESP_ERR_INVALID_ARG: Get GPTimer raw count value failed because of invalid ar-
gument
• ESP_FAIL: Get GPTimer raw count value failed because of other error
Note: User registered callbacks are expected to be runnable within ISR context
Note: This function should be called when the timer is in the init state (i.e. before calling gpti-
mer_enable())
Parameters
• timer –[in] Timer handle created by gptimer_new_timer()
• cbs –[in] Group of callback functions
• user_data –[in] User data, which will be passed to callback functions directly
Returns
• ESP_OK: Set event callbacks successfully
• ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument
• ESP_ERR_INVALID_STATE: Set event callbacks failed because the timer is not in init
state
• ESP_FAIL: Set event callbacks failed because of other error
Note: This function is allowed to run within ISR context, so that user can set new alarm action immediately
in the ISR callback.
Note: This function is allowed to be executed when Cache is disabled, by enabling CON-
FIG_GPTIMER_CTRL_FUNC_IN_IRAM
Parameters
• timer –[in] Timer handle created by gptimer_new_timer()
• config –[in] Alarm configuration, especially, set config to NULL means disabling the
alarm function
Returns
• ESP_OK: Set alarm action for GPTimer successfully
• ESP_ERR_INVALID_ARG: Set alarm action for GPTimer failed because of invalid ar-
gument
• ESP_FAIL: Set alarm action for GPTimer failed because of other error
Note: This function will transit the timer state from init to enable.
Note: This function will enable the interrupt service, if it’s lazy installed in gpti-
mer_register_event_callbacks().
Note: This function will acquire a PM lock, if a specific source clock (e.g. APB) is selected in the gpti-
mer_config_t, while CONFIG_PM_ENABLE is enabled.
Note: Enable a timer doesn’t mean to start it. See also gptimer_start() for how to make the timer
start counting.
Note: Disable a timer doesn’t mean to stop it. See also gptimer_stop() for how to make the timer
stop counting.
Note: This function should be called when the timer is in the enable state (i.e. after calling gpti-
mer_enable())
Note: This function should be called when the timer is in the enable state (i.e. after calling gpti-
mer_enable())
Structures
struct gptimer_alarm_event_data_t
GPTimer alarm event data.
Public Members
uint64_t count_value
Current count value
uint64_t alarm_value
Current alarm value
struct gptimer_event_callbacks_t
Group of supported GPTimer callbacks.
Note: When CONFIG_GPTIMER_ISR_IRAM_SAFE is enabled, the callback itself and functions callbed
by it should be placed in IRAM.
Public Members
gptimer_alarm_cb_t on_alarm
Timer alarm callback
struct gptimer_config_t
General Purpose Timer configuration.
Public Members
gptimer_clock_source_t clk_src
GPTimer clock source
gptimer_count_direction_t direction
Count direction
uint32_t resolution_hz
Counter resolution (working frequency) in Hz, hence, the step size of each count tick equals to (1 /
resolution_hz) seconds
uint32_t intr_shared
Set true, the timer interrupt number can be shared with other peripherals
struct gptimer_alarm_config_t
General Purpose Timer alarm configuration.
Public Members
uint64_t alarm_count
Alarm target count value
uint64_t reload_count
Alarm reload count value, effect only when auto_reload_on_alarm is set to true
uint32_t auto_reload_on_alarm
Reload the count value by hardware, immediately at the alarm event
Type Definitions
Header File
• components/hal/include/hal/timer_types.h
Type Definitions
Note: User should select the clock source based on the power and resolution requirement
Enumerations
enum gptimer_count_direction_t
GPTimer count direction.
Values:
enumerator GPTIMER_COUNT_DOWN
Decrease count value
enumerator GPTIMER_COUNT_UP
Increase count value
Overview
I2C is a serial, synchronous, half-duplex communication protocol that allows co-existence of multiple masters and
slaves on the same bus. The I2C bus consists of two lines: serial data line (SDA) and serial clock (SCL). Both lines
require pull-up resistors.
With such advantages as simplicity and low manufacturing cost, I2C is mostly used for communication of low-speed
peripheral devices over short distances (within one foot).
ESP32 has 2 I2C controller (also referred to as port), responsible for handling communications on the I2C bus. A
single I2C controller can operate as master or slave.
Driver Features
I2C driver governs communications of devices over the I2C bus. The driver supports the following features:
• Reading and writing bytes in Master mode
• Slave mode
• Reading and writing to registers which are in turn read/written by the master
Driver Usage
The following sections describe typical steps of configuring and operating the I2C driver:
1. Configuration - set the initialization parameters (master or slave mode, GPIO pins for SDA and SCL, clock
speed, etc.)
2. Install Driver- activate the driver on one of the two I2C controllers as a master or slave
3. Depending on whether you configure the driver for a master or slave, choose the appropriate item
a) Communication as Master - handle communications (master)
b) Communication as Slave - respond to messages from the master (slave)
4. Interrupt Handling - configure and service I2C interrupts
5. Customized Configuration - adjust default I2C communication parameters (timings, bit order, etc.)
6. Error Handling - how to recognize and handle driver configuration and communication errors
7. Delete Driver- release resources used by the I2C driver when communication ends
Configuration To establish I2C communication, start by configuring the driver. This is done by setting the param-
eters of the structure i2c_config_t:
• Set I2C mode of operation - master or slave from i2c_mode_t
• Configure communication pins
– Assign GPIO pins for SDA and SCL signals
– Set whether to enable ESP32’s internal pull-ups
• (Master only) Set I2C clock speed
• (Slave only) Configure the following
– Whether to enable 10 bit address mode
– Define slave address
After that, initialize the configuration for a given I2C port. For this, call the function i2c_param_config() and
pass to it the port number and the structure i2c_config_t.
Configuration example (master):
int i2c_master_port = 0;
i2c_config_t conf = {
.mode = I2C_MODE_MASTER,
.sda_io_num = I2C_MASTER_SDA_IO, // select GPIO specific to your␣
,→project
.sda_pullup_en = GPIO_PULLUP_ENABLE,
.scl_io_num = I2C_MASTER_SCL_IO, // select GPIO specific to your␣
,→project
.scl_pullup_en = GPIO_PULLUP_ENABLE,
.master.clk_speed = I2C_MASTER_FREQ_HZ, // select frequency specific to your␣
,→project
};
.sda_pullup_en = GPIO_PULLUP_ENABLE,
.scl_io_num = I2C_SLAVE_SCL_IO, // select GPIO specific to your␣
,→project
.scl_pullup_en = GPIO_PULLUP_ENABLE,
.mode = I2C_MODE_SLAVE,
.slave.addr_10bit_en = 0,
.slave.slave_addr = ESP_SLAVE_ADDR, // address of your project
};
At this stage, i2c_param_config() also sets a few other I2C configuration parameters to default values that are
defined by the I2C specification. For more details on the values and how to modify them, see Customized Configura-
tion.
Source Clock Configuration Clock sources allocator is added for supporting different clock sources. The clock
allocator will choose one clock source that meets all the requirements of frequency and capability (as requested in
i2c_config_t::clk_flags).
When i2c_config_t::clk_flags is 0, the clock allocator will select only according to the desired frequency.
If no special capabilities are needed, such as APB, you can configure the clock allocator to select the source clock only
according to the desired frequency. For this, set i2c_config_t::clk_flags to 0. For clock characteristics,
see the table below.
Note: A clock is not a valid option, if it doesn’t meet the requested capabilities, i.e. any bit of requested capabilities
(clk_flags) is 0 in the clock’s capabilities.
Note: The clock frequency of SCL in master mode should not be lager than max frequency for SCL mentioned in
the table above.
Note: The clock frequency of SCL will be influenced by the pull-up resistors and wire capacitance (or might slave
capacitance) together. Therefore, users need to choose correct pull-up resistors by themselves to make the frequency
accurate. It is recommended by I2C protocol that the pull-up resistors commonly range from 1KOhms to 10KOhms,
but different frequencies need different resistors.
Generally speaking, the higher frequency is selected, the smaller resistor should be used (but not less than 1KOhms).
This is because high resistor will decline the current, which will lengthen the rising time and reduce the frequency.
Usually, range 2KOhms to 5KOhms is what we recommend, but users also might need to make some adjustment
depends on their reality.
Install Driver After the I2C driver is configured, install it by calling the function i2c_driver_install()
with the following parameters:
• Port number, one of the two port numbers from i2c_port_t
• master or slave, selected from i2c_mode_t
• (Slave only) Size of buffers to allocate for sending and receiving data. As I2C is a master-centric bus, data
can only go from the slave to the master at the master’s request. Therefore, the slave will usually have a send
buffer where the slave application writes data. The data remains in the send buffer to be read by the master at
the master’s own discretion.
• Flags for allocating the interrupt (see ESP_INTR_FLAG_* values in
esp_hw_support/include/esp_intr_alloc.h)
Communication as Master After installing the I2C driver, ESP32 is ready to communicate with other I2C devices.
ESP32’s I2C controller operating as master is responsible for establishing communication with I2C slave devices
and sending commands to trigger a slave to action, for example, to take a measurement and send the readings back
to the master.
For better process organization, the driver provides a container, called a“command link”, that should be populated
with a sequence of commands and then passed to the I2C controller for execution.
Master Write The example below shows how to build a command link for an I2C master to send n bytes to a slave.
The following describes how a command link for a “master write”is set up and what comes inside:
1. Create a command link with i2c_cmd_link_create().
Then, populate it with the series of data to be sent to the slave:
a) Start bit - i2c_master_start()
b) Slave address - i2c_master_write_byte(). The single byte address is provided as an argument
of this function call.
c) Data - One or more bytes as an argument of i2c_master_write()
d) Stop bit - i2c_master_stop()
Both functions i2c_master_write_byte() and i2c_master_write() have an addi-
tional argument specifying whether the master should ensure that it has received the ACK bit.
2. Trigger the execution of the command link by I2C controller by calling i2c_master_cmd_begin().
Once the execution is triggered, the command link cannot be modified.
3. After the commands are transmitted, release the resources used by the command link by calling
i2c_cmd_link_delete().
Master Read The example below shows how to build a command link for an I2C master to read n bytes from a
slave.
Compared to writing data, the command link is populated in Step 4 not with i2c_master_write... func-
tions but with i2c_master_read_byte() and / or i2c_master_read(). Also, the last read in Step 5 is
configured so that the master does not provide the ACK bit.
Indicating Write or Read After sending a slave address (see Step 3 on both diagrams above), the master either
writes or reads from the slave.
The information on what the master will actually do is hidden in the least significant bit of the slave’s address.
For this reason, the command link sent by the master to write data to the slave contains the address
(ESP_SLAVE_ADDR << 1) | I2C_MASTER_WRITE and looks as follows:
Likewise, the command link to read from the slave looks as follows:
Communication as Slave After installing the I2C driver, ESP32 is ready to communicate with other I2C devices.
The API provides the following functions for slaves
• i2c_slave_read_buffer()
Whenever the master writes data to the slave, the slave will automatically store it in the receive
buffer. This allows the slave application to call the function i2c_slave_read_buffer() at
its own discretion. This function also has a parameter to specify block time if no data is in the
receive buffer. This will allow the slave application to wait with a specified timeout for data to
arrive to the buffer.
• i2c_slave_write_buffer()
The send buffer is used to store all the data that the slave wants to send to the mas-
ter in FIFO order. The data stays there until the master requests for it. The function
i2c_slave_write_buffer() has a parameter to specify block time if the send buffer is
full. This will allow the slave application to wait with a specified timeout for the adequate amount
of space to become available in the send buffer.
A code example showing how to use these functions can be found in peripherals/i2c.
Customized Configuration As mentioned at the end of Section Configuration, when the function
i2c_param_config() initializes the driver configuration for an I2C port, it also sets several I2C communication
parameters to default values defined in the I2C specification. Some other related parameters are pre-configured in
registers of the I2C controller.
All these parameters can be changed to user-defined values by calling dedicated functions given in the table be-
low. Please note that the timing values are defined in APB clock cycles. The frequency of APB is specified in
I2C_APB_CLK_FREQ.
Each of the above functions has a _get_ counterpart to check the currently set value. For example, to check the I2C
timeout value, call i2c_get_timeout().
To check the default parameter values which are set during the driver configuration process, please refer to the file
driver/i2c.c and look for defines with the suffix _DEFAULT.
You can also select different pins for SDA and SCL signals and alter the configuration of pull-ups with the function
i2c_set_pin(). If you want to modify already entered values, use the function i2c_param_config().
Note: ESP32’s internal pull-ups are in the range of tens of kOhm, which is, in most cases, insufficient for use as
I2C pull-ups. Users are advised to use external pull-ups with values described in the I2C specification.
Error Handling The majority of I2C driver functions either return ESP_OK on successful completion or a specific
error code on failure. It is a good practice to always check the returned values and implement error handling. The
driver also prints out log messages that contain error details, e.g., when checking the validity of entered configuration.
For details please refer to the file driver/i2c.c and look for defines with the suffix _ERR_STR.
Use dedicated interrupts to capture communication failures. For instance, if a slave stretches the clock for too long
while preparing the data to send back to master, the interrupt I2C_TIME_OUT_INT will be triggered. For detailed
information, see Interrupt Handling.
In case of a communication failure, you can reset the internal hardware buffers by calling the functions
i2c_reset_tx_fifo() and i2c_reset_rx_fifo() for the send and receive buffers respectively.
Delete Driver When the I2C communication is established with the function i2c_driver_install() and
is not required for some substantial amount of time, the driver may be deinitialized to release allocated resources by
calling i2c_driver_delete().
Before calling i2c_driver_delete() to remove i2c driver, please make sure that all threads have stopped using
the driver in any way, because this function does not guarantee thread safety.
Application Example
API Reference
Header File
• components/driver/include/driver/i2c.h
Functions
esp_err_t i2c_driver_install(i2c_port_t i2c_num, i2c_mode_t mode, size_t slv_rx_buf_len, size_t
slv_tx_buf_len, int intr_alloc_flags)
Install an I2C driver.
Note: Not all Espressif chips can support slave mode (e.g. ESP32C2)
Note: In master mode, if the cache is likely to be disabled(such as write flash) and the slave is time-sensitive,
ESP_INTR_FLAG_IRAM is suggested to be used. In this case, please use the memory allocated from internal
RAM in i2c read and write function, because we can not access the psram(if psram is enabled) in interrupt
handle function when cache is disabled.
Parameters
• i2c_num –I2C port number
• mode –I2C mode (either master or slave).
• slv_rx_buf_len –Receiving buffer size. Only slave mode will use this value, it is
ignored in master mode.
• slv_tx_buf_len –Sending buffer size. Only slave mode will use this value, it is ig-
nored in master mode.
• intr_alloc_flags –Flags used to allocate the interrupt. One or multiple (ORred)
ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info.
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
• ESP_FAIL Driver installation error
esp_err_t i2c_driver_delete(i2c_port_t i2c_num)
Delete I2C driver.
Note: This function does not guarantee thread safety. Please make sure that no thread will continuously hold
semaphores before calling the delete function.
Note: It is highly advised to not allocate this buffer on the stack. The size of the data used underneath may
increase in the future, resulting in a possible stack overflow as the macro I2C_LINK_RECOMMENDED_SIZE
would also return a bigger value. A better option is to use a buffer allocated statically or dynamically (with
malloc).
Parameters
• buffer –Buffer to use for commands allocations
• size –Size in bytes of the buffer
Returns Handle to the I2C command link or NULL if the buffer provided is too small, please use
I2C_LINK_RECOMMENDED_SIZE macro to get the recommended size for the buffer.
i2c_cmd_handle_t i2c_cmd_link_create(void)
Create and initialize an I2C commands list with a given buffer. After finishing the I2C transactions, it is
required to call i2c_cmd_link_delete() to release and return the resources. The required bytes will
be dynamically allocated.
Returns Handle to the I2C command link or NULL in case of insufficient dynamic memory.
void i2c_cmd_link_delete_static(i2c_cmd_handle_t cmd_handle)
Free the I2C commands list allocated statically with i2c_cmd_link_create_static.
Parameters cmd_handle –I2C commands list allocated statically. This handle should be cre-
ated thanks to i2c_cmd_link_create_static() function
void i2c_cmd_link_delete(i2c_cmd_handle_t cmd_handle)
Free the I2C commands list.
Parameters cmd_handle –I2C commands list. This handle should be created thanks to
i2c_cmd_link_create() function
bus. This function shall only be called in I2C master mode. Call i2c_master_cmd_begin() to send all
queued commands.
Parameters
• cmd_handle –I2C commands list
• data –Pointer where the received bytes will the stored. This buffer shall remain valid
until the transaction is finished.
• data_len –Size, in bytes, of the data buffer
• ack –ACK signal
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
• ESP_ERR_NO_MEM The static buffer used to create cmd_handler is too small
• ESP_FAIL No more memory left on the heap
esp_err_t i2c_master_stop(i2c_cmd_handle_t cmd_handle)
Queue a “STOP signal”to the given commands list. This function shall only be called in I2C master mode.
Call i2c_master_cmd_begin() to send all the queued commands.
Parameters cmd_handle –I2C commands list
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
• ESP_ERR_NO_MEM The static buffer used to create cmd_handler is too small
• ESP_FAIL No more memory left on the heap
esp_err_t i2c_master_cmd_begin(i2c_port_t i2c_num, i2c_cmd_handle_t cmd_handle, TickType_t
ticks_to_wait)
Send all the queued commands on the I2C bus, in master mode. The task will be blocked until all the commands
have been sent out. The I2C port is protected by mutex, so this function is thread-safe. This function shall only
be called in I2C master mode.
Parameters
• i2c_num –I2C port number
• cmd_handle –I2C commands list
• ticks_to_wait –Maximum ticks to wait before issuing a timeout.
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
• ESP_FAIL Sending command error, slave hasn’t ACK the transfer.
• ESP_ERR_INVALID_STATE I2C driver not installed or not in master mode.
• ESP_ERR_TIMEOUT Operation timeout because the bus is busy.
int i2c_slave_write_buffer(i2c_port_t i2c_num, const uint8_t *data, int size, TickType_t ticks_to_wait)
Write bytes to internal ringbuffer of the I2C slave data. When the TX fifo empty, the ISR will fill the hardware
FIFO with the internal ringbuffer’s data.
Parameters
• i2c_num –I2C port number
• data –Bytes to write into internal buffer
• size –Size, in bytes, of data buffer
• ticks_to_wait –Maximum ticks to wait.
Returns
• ESP_FAIL (-1) Parameter error
• Other (>=0) The number of data bytes pushed to the I2C slave buffer.
Parameters
• i2c_num –I2C port number
• data –Buffer to fill with ringbuffer’s bytes
• max_size –Maximum bytes to read
• ticks_to_wait –Maximum waiting ticks
Returns
• ESP_FAIL(-1) Parameter error
• Others(>=0) The number of data bytes read from I2C slave buffer.
Parameters
• i2c_num –I2C port number to filter
• cyc_num –the APB cycles need to be filtered (0<= cyc_num <=7). When the period of
a pulse is less than cyc_num * APB_cycle, the I2C controller will ignore this pulse.
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
• hold_time –clock number I2C used to hold the data after the falling-edge of SCL, it’
s a 10-bit value
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
esp_err_t i2c_get_data_timing(i2c_port_t i2c_num, int *sample_time, int *hold_time)
get I2C data signal timing
Parameters
• i2c_num –I2C port number
• sample_time –pointer to get sample time
• hold_time –pointer to get hold time
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
esp_err_t i2c_set_timeout(i2c_port_t i2c_num, int timeout)
set I2C timeout value
Parameters
• i2c_num –I2C port number
• timeout –timeout value for I2C bus (unit: APB 80Mhz clock cycle)
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
esp_err_t i2c_get_timeout(i2c_port_t i2c_num, int *timeout)
get I2C timeout value
Parameters
• i2c_num –I2C port number
• timeout –pointer to get timeout value
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
esp_err_t i2c_set_data_mode(i2c_port_t i2c_num, i2c_trans_mode_t tx_trans_mode, i2c_trans_mode_t
rx_trans_mode)
set I2C data transfer mode
Parameters
• i2c_num –I2C port number
• tx_trans_mode –I2C sending data mode
• rx_trans_mode –I2C receving data mode
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
esp_err_t i2c_get_data_mode(i2c_port_t i2c_num, i2c_trans_mode_t *tx_trans_mode, i2c_trans_mode_t
*rx_trans_mode)
get I2C data transfer mode
Parameters
• i2c_num –I2C port number
• tx_trans_mode –pointer to get I2C sending data mode
• rx_trans_mode –pointer to get I2C receiving data mode
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Structures
struct i2c_config_t
I2C initialization parameters.
Public Members
i2c_mode_t mode
I2C mode
int sda_io_num
GPIO number for I2C sda signal
int scl_io_num
GPIO number for I2C scl signal
bool sda_pullup_en
Internal GPIO pull mode for I2C sda signal
bool scl_pullup_en
Internal GPIO pull mode for I2C scl signal
uint32_t clk_speed
I2C clock frequency for master mode, (no higher than 1MHz for now)
uint8_t addr_10bit_en
I2C 10bit address mode enable for slave mode
uint16_t slave_addr
I2C address for slave mode
uint32_t maximum_speed
I2C expected clock speed from SCL.
uint32_t clk_flags
Bitwise of I2C_SCLK_SRC_FLAG_**FOR_DFS** for clk source choice
Macros
I2C_APB_CLK_FREQ
I2C source clock is APB clock, 80MHz
I2C_NUM_MAX
I2C port max
I2C_NUM_0
I2C port 0
I2C_NUM_1
I2C port 1
I2C_SCLK_SRC_FLAG_FOR_NOMAL
Any one clock source that is available for the specified frequency may be choosen
I2C_SCLK_SRC_FLAG_AWARE_DFS
For REF tick clock, it won’t change with APB.
I2C_SCLK_SRC_FLAG_LIGHT_SLEEP
For light sleep mode.
I2C_INTERNAL_STRUCT_SIZE
Minimum size, in bytes, of the internal private structure used to describe I2C commands link.
I2C_LINK_RECOMMENDED_SIZE(TRANSACTIONS)
The following macro is used to determine the recommended size of the buffer to pass to
i2c_cmd_link_create_static() function. It requires one parameter, TRANSACTIONS, de-
scribing the number of transactions intended to be performed on the I2C port. For example, if one wants
to perform a read on an I2C device register, TRANSACTIONS must be at least 2, because the commands
required are the following:
Type Definitions
Header File
• components/hal/include/hal/i2c_types.h
Macros
I2C_CLK_FREQ_MAX
Use the highest speed that is available for the clock source picked by clk_flags.
Type Definitions
Enumerations
enum i2c_mode_t
Values:
enumerator I2C_MODE_SLAVE
I2C slave mode
enumerator I2C_MODE_MASTER
I2C master mode
enumerator I2C_MODE_MAX
enum i2c_rw_t
Values:
enumerator I2C_MASTER_WRITE
I2C write data
enumerator I2C_MASTER_READ
I2C read data
enum i2c_trans_mode_t
Values:
enumerator I2C_DATA_MODE_MSB_FIRST
I2C data msb first
enumerator I2C_DATA_MODE_LSB_FIRST
I2C data lsb first
enumerator I2C_DATA_MODE_MAX
enum i2c_addr_mode_t
Values:
enumerator I2C_ADDR_BIT_7
I2C 7bit address for slave mode
enumerator I2C_ADDR_BIT_10
I2C 10bit address for slave mode
enumerator I2C_ADDR_BIT_MAX
enum i2c_ack_type_t
Values:
enumerator I2C_MASTER_ACK
I2C ack for each byte read
enumerator I2C_MASTER_NACK
I2C nack for each byte read
enumerator I2C_MASTER_LAST_NACK
I2C nack for the last byte
enumerator I2C_MASTER_ACK_MAX
enum i2c_sclk_t
I2C clock source, sorting from smallest to largest, place them in order. This can be expanded in the future use.
Values:
enumerator I2C_SCLK_DEFAULT
I2C source clock not selected
enumerator I2C_SCLK_APB
I2C source clock from APB, 80M
enumerator I2C_SCLK_MAX
Introduction
I2S (Inter-IC Sound) is a serial, synchronous communication protocol that is usually used for transmitting audio data
between two digital audio devices.
ESP32 contains two I2S peripheral(s). These peripherals can be configured to input and output sample data via the
I2S driver.
An I2S bus that communicate in Standard or TDM mode consists of the following lines:
• MCLK: Master clock line. It’s an optional signal depends on slave side, mainly used for offering a reference
clock to the I2S slave device.
• BCLK: Bit clock line. The bit clock for data line.
• WS: Word(Slot) select line. It is usually used to identify the vocal tract except PDM mode.
• DIN/DOUT: Serial data input/output line. (Data will loopback internally if din and dout are set to a same
GPIO)
And for the I2S bus that communicate in PDM mode, the lines are:
• CLK: PDM clock line.
• DIN/DOUT: Serial data input/output line.
Each I2S controller has the following features that can be configured by the I2S driver:
• Operation as system master or slave
• Capable of acting as transmitter or receiver
• DMA controller that allows for streaming sample data without requiring the CPU to copy each data sample
Each controller can operate in simplex communication mode. Thus, the two controllers can be combined to establish
full-duplex communication.
Note: The legacy driver can’t coexist with the new driver. Including i2s.h to use the legacy driver or the other
three headers to use the new driver. The legacy driver might be removed in future.
I2S Clock
Clock Source
• i2s_clock_src_t::I2S_CLK_SRC_DEFAULT: Default PLL clock.
• i2s_clock_src_t::I2S_CLK_SRC_PLL_160M: 160 MHz PLL clock.
• i2s_clock_src_t::I2S_CLK_SRC_APLL: Audio PLL clock, more precise than
I2S_CLK_SRC_PLL_160M in high sample rate applications. Its frequency is configurable according
to the sample rate, but if APLL has been occupied by emac or other channels already, the APLL frequency is
not allowed to change, the driver will try to work under this APLL frequency, if this APLL frequency can’t
meet the requirements of I2S, the clock configuration will fail.
Clock Terminology
• sample rate: The number of sampled data in one second per slot.
• sclk: Source clock frequency. It is the frequency of the clock source.
• mclk: Master clock frequency. bclk is generate from this clock, mclk is mostly needed in the case that
requires the MCLK signal as a reference clock to synchronize BCLK and WS between I2S master role and
slave role.
• bclk: Bit clock frequency. Every tick of this clock stands for one data bit on data pin. It means there
will be 8/16/24/32 bclk ticks in one slot, because the number of bclk ticks in one slot is equal to the
i2s_std_slot_config_t::slot_bit_width.
• lrck / ws: Left/Right clock or word select clock. For non-PDM mode, its frequency is equal to the sample rate.
Note: Normally mclk should be the multiple of sample rate and bclk at the same time. This
field i2s_std_clk_config_t::mclk_multiple means the multiple of mclk to the sample rate.
If slot_bit_width is set to I2S_SLOT_BIT_WIDTH_24BIT, to keep mclk a multiple to the bclk,
i2s_std_clk_config_t::mclk_multiple should be set to I2S_MCLK_MULTIPLE_384, otherwise
the ws will be inaccurate. But in the most other cases, I2S_MCLK_MULTIPLE_256 should be enough.
Standard Mode Standard mode always has left and right two sound channels which are called ‘slots’. These
slots can support 8/16/24/32 bits width sample data. And the communication format for the slots mainly includes
these following formats:
• Philip Format: Data signal have one bit shift comparing to the WS(word select) signal. And the duty of WS
signal is 50%.
slot_bit_width
data_bit_width
BCLK
WS
• MSB Format: Almost same as philip format, but its data have no shift.
slot_bit_width
data_bit_width
BCLK
WS
• PCM Short Format: Data have one bit shift and meanwhile WS signal becomes a pulse lasting one BCLK(Bit
Clock) cycle.
slot_bit_width
data_bit_width
BCLK
WS
PDM Mode (TX) PDM mode for tx channel can convert PCM data into PDM format which always has left and
right slots. PDM TX can only support 16 bits width sample data. PDM TX only needs CLK pin for clock signal
and DOUT pin for data signal (i.e. WS and SD signal in the following figure, the BCK signal is an internal bit sam-
pling clock, not needed between PDM devices). This mode allows user to configure the up-sampling parameters
i2s_pdm_tx_clk_config_t::up_sample_fp i2s_pdm_tx_clk_config_t::up_sample_fs.
The up-sampling rate can be calculated by up_sample_rate = fp / fs, there are up-sampling modes
in PDM TX:
• Fixed Clock Frequency: In this mode the up-sampling rate will change according to the sample rate. Setting
fp = 960 and fs = sample_rate / 100, then the clock frequency(Fpdm) on CLK pin will be fixed
to 128 * 48 KHz = 6.144 MHz, note that this frequency is not equal to the sample rate(Fpcm).
• Fixed Up-sampling Rate: In this mode the up-sampling rate is fixed to 2. Setting fp = 960 and fs =
480, then the clock frequency(Fpdm) on CLK pin will be 128 * sample_rate
CLK
PDM Mode (RX) PDM mode for rx channel can receive PDM format data and convert the data into
PCM format. PDM RX can only support 16 bits width sample data. PDM RX only need WS pin for
clock signal and DIN pin for data signal. This mode allows user to configure the down-sampling parameter
i2s_pdm_rx_clk_config_t::dn_sample_mode, there are two down-sampling modes in PDM RX:
ADC/DAC Mode ADC and DAC modes only exist on ESP32 and are only supported on I2S0. Actually, they are
two sub-modes of LCD/Camera mode. I2S0 can be routed directly to the internal analog-to-digital converter(ADC)
and digital-to-analog converter(DAC). In other words, ADC and DAC peripherals can read or write continuously via
I2S0 DMA. As they are not an actual communication mode, the I2S driver does not implement them.
Functional Overview
Power Management When the power management is enabled (i.e. CONFIG_PM_ENABLE is on), the system will
adjust or stop the source clock of I2S before going into light sleep, thus potentially changing the I2S signals and
leading to transmitting or receiving invalid data.
I2S driver can prevent the system from changing or stopping the source clock by acquiring a power
management lock. When the source clock is generated from APB, the lock type will be set to
esp_pm_lock_type_t::ESP_PM_APB_FREQ_MAX and when the source clock is APLL (if target support
APLL), it will be set to esp_pm_lock_type_t::ESP_PM_NO_LIGHT_SLEEP. Whenever user is reading or
writing via I2S (i.e. calling i2s_channel_read() or i2s_channel_write()), the driver will guarantee
that the power management lock is acquired. Likewise, the driver releases the lock after reading or writing finished.
Finite-State Machine There are three states for an I2S channel, they are registered, ready and running.
Their relationship is shown in the following diagram:
The <mode> in the diagram can be replaced by corresponding I2S communication mode like std for standard
two-slot mode, for other information of communication mode, please refer to I2S Communication Mode section.
Data Transport The data transport of I2S peripheral, including sending and receiving, is realized by DMA. Be-
fore transporting data, please call i2s_channel_enable() to enable the specific channel. When the sent or
received data reach the size of one DMA buffer, I2S_OUT_EOF or I2S_IN_SUC_EOF interrupt will be trig-
gered. Note that the DMA buffer size is not equal to i2s_std_slot_config_t::dma_frame_num, one
frame here means all the sampled data in one WS circle. Therefore, dma_buffer_size = dma_frame_num
* slot_num * slot_bit_width / 8. For the transmit case, users can input the data by calling
i2s_channel_write(). This function will help users to copy the data from the source buffer to the DMA
tx buffer and wait for the transmition finished. Then it’ll repeat until the sent bytes reach the given size. For the
receive case, the function i2s_channel_read() will wait for receiving the message queue which contains the
DMA buffer address, it will help users to copy the data from DMA rx buffer to the destination buffer.
Both i2s_channel_write() and i2s_channel_read() are blocking functions, they will keep waiting
until the whole source buffer are sent or the whole destination buffer loaded, unless they exceed the max blocking
time, then the error code ESP_ERR_TIMEOUT will return in this case. To send or receive data asynchronously,
IRAM Safe By default, the I2S interrupt will be deferred when the Cache is disabled for reasons like writing/erasing
Flash. Thus the EOF interrupt will not get executed in time, which is not expected in a real-time application.
There’s a Kconfig option CONFIG_I2S_ISR_IRAM_SAFE that will:
1. Enable the interrupt being serviced even when cache is disabled
2. Place driver object into DRAM (in case it’s linked to PSRAM by accident)
This will allow the interrupt to run while the cache is disabled but will come at the cost of increased IRAM consump-
tion.
Thread Safety All the public I2S APIs are guaranteed to be thread safe by the driver, which means, user can call
them from different RTOS tasks without protection by extra locks. Notice that I2S driver uses mutex lock to ensure
the thread safety, thus these APIs are not allowed to be used in ISR.
Kconfig Options
• CONFIG_I2S_ISR_IRAM_SAFE controls whether the default ISR handler can work when cache is disabled,
see IRAM Safe for more information.
• CONFIG_I2S_SUPPRESS_DEPRECATE_WARN controls whether to suppress the compiling warning message
while using the legacy I2S driver.
• CONFIG_I2S_ENABLE_DEBUG_LOG is used to enabled the debug log output. Enable this option will increase
the firmware binary size.
Application Example
The examples of the I2S driver can be found in the directory peripherals/i2s. Here are some simple usages of each
mode:
Standard TX/RX usage Different slot communication formats can be generated by following helper macros for
standard mode. As described above, there are three formats in standard mode, their helper macros are:
• I2S_STD_PHILIP_SLOT_DEFAULT_CONFIG
• I2S_STD_PCM_SLOT_DEFAULT_CONFIG
• I2S_STD_MSB_SLOT_DEFAULT_CONFIG
The clock config helper macro is:
• I2S_STD_CLK_DEFAULT_CONFIG
Please refer to Standard Mode for STD API information. And for more details, please refer to
driver/include/driver/i2s_std.h.
#include "driver/i2s_std.h"
#include "driver/gpio.h"
i2s_chan_handle_t tx_handle;
/* Get the default channel configuration by helper macro.
* This helper macro is defined in 'i2s_common.h' and shared by all the i2s␣
,→communication mode.
/* Setting the configurations, the slot configuration and clock configuration can␣
,→be generated by the macros
* These two helper macros is defined in 'i2s_std.h' which can only be used in STD␣
,→mode.
* They can help to specify the slot and clock configurations for initialization␣
,→or updating */
i2s_std_config_t std_cfg = {
.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(48000),
.slot_cfg = I2S_STD_MSB_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_
,→MODE_STEREO),
.gpio_cfg = {
.mclk = I2S_GPIO_UNUSED,
.bclk = GPIO_NUM_4,
.ws = GPIO_NUM_5,
.dout = GPIO_NUM_18,
.din = I2S_GPIO_UNUSED,
.invert_flags = {
.mclk_inv = false,
.bclk_inv = false,
.ws_inv = false,
},
},
};
/* Initialize the channel */
i2s_channel_init_std_mode(tx_handle, &std_cfg);
i2s_del_channel(tx_handle);
#include "driver/i2s_std.h"
#include "driver/gpio.h"
/* Setting the configurations, the slot configuration and clock configuration can␣
,→be generated by the macros
* These two helper macros is defined in 'i2s_std.h' which can only be used in STD␣
,→mode.
* They can help to specify the slot and clock configurations for initialization␣
,→or updating */
i2s_std_config_t std_cfg = {
.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(48000),
.slot_cfg = I2S_STD_MSB_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_
,→MODE_STEREO),
.gpio_cfg = {
.mclk = I2S_GPIO_UNUSED,
.bclk = GPIO_NUM_4,
.ws = GPIO_NUM_5,
.dout = I2S_GPIO_UNUSED,
.din = GPIO_NUM_19,
.invert_flags = {
.mclk_inv = false,
.bclk_inv = false,
.ws_inv = false,
},
},
};
/* Initialize the channel */
i2s_channel_init_std_mode(rx_handle, &std_cfg);
i2s_del_channel(rx_handle);
PDM TX usage For PDM mode in tx channel, the slot configuration helper macro is:
• I2S_PDM_TX_SLOT_DEFAULT_CONFIG
The clock configuration helper macro is:
• I2S_PDM_TX_CLK_DEFAULT_CONFIG
Please refer to PDM Mode for PDM TX API information. And for more details, please refer to
driver/include/driver/i2s_pdm.h.
#include "driver/i2s_pdm.h"
#include "driver/gpio.h"
.gpio_cfg = {
.clk = GPIO_NUM_5,
.dout = GPIO_NUM_18,
.invert_flags = {
.clk_inv = false,
},
},
};
i2s_channel_init_pdm_tx_mode(tx_handle, &pdm_tx_cfg);
...
PDM RX usage For PDM mode in RX channel, the slot configuration helper macro is:
• I2S_PDM_RX_SLOT_DEFAULT_CONFIG
The clock configuration helper macro is:
• I2S_PDM_RX_CLK_DEFAULT_CONFIG
Please refer to PDM Mode for PDM RX API information. And for more details, please refer to
driver/include/driver/i2s_pdm.h.
#include "driver/i2s_pdm.h"
#include "driver/gpio.h"
i2s_chan_handle_t rx_handle;
.gpio_cfg = {
.clk = GPIO_NUM_5,
.din = GPIO_NUM_19,
.invert_flags = {
.clk_inv = false,
},
},
};
i2s_channel_init_pdm_rx_mode(rx_handle, &pdm_rx_cfg);
...
Full-duplex Full-duplex mode will register tx and rx channel in an I2S port at the same time, and they will share
the BCLK and WS signal. Currently STD and TDM communication mode are able to adopt full-duplex mode in
following way, but PDM full-duplex is not supported because PDM TX and RX clock are not same.
Note that one handle can only stand for one channel, the slot and clock configurations for both tx and rx channel
should be set one by one.
Here is an example of how to allocate a pair of full-duplex channels:
#include "driver/i2s_std.h"
#include "driver/gpio.h"
i2s_chan_handle_t tx_handle;
i2s_chan_handle_t rx_handle;
/* Allocate for tx and rx channel at the same time, then they will work in full-
,→duplex mode */
/* Set the configurations for BOTH TWO channels, since tx and rx channel have to␣
,→be same in full-duplex mode */
i2s_std_config_t std_cfg = {
.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(32000),
.slot_cfg = I2S_STD_PHILIP_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_
,→SLOT_MODE_STEREO),
.gpio_cfg = {
.mclk = I2S_GPIO_UNUSED,
.bclk = GPIO_NUM_4,
.ws = GPIO_NUM_5,
.dout = GPIO_NUM_18,
.din = GPIO_NUM_19,
.invert_flags = {
.mclk_inv = false,
.bclk_inv = false,
.ws_inv = false,
},
},
};
i2s_init_channle(tx_handle, &std_cfg);
i2s_init_channle(rx_handle, &std_cfg);
i2s_channel_enable(tx_handle);
i2s_channel_enable(rx_handle);
...
Simplex Mode To allocate a channel handle in simplex mode, i2s_new_channel() should be called for each
channel. The clock and gpio pins of TX/RX channel on ESP32 are not separate, therefore TX and RX channel can’
t coexist on a same I2S port in simplex mode.
#include "driver/i2s_std.h"
#include "driver/gpio.h"
i2s_chan_handle_t tx_handle;
i2s_chan_handle_t rx_handle;
.gpio_cfg = {
.mclk = GPIO_NUM_0,
.bclk = GPIO_NUM_4,
.ws = GPIO_NUM_5,
.dout = GPIO_NUM_18,
.din = I2S_GPIO_UNUSED,
.invert_flags = {
.mclk_inv = false,
.bclk_inv = false,
.ws_inv = false,
},
},
};
/* Initialize the channel */
i2s_channel_init_std_mode(tx_handle, &std_tx_cfg);
i2s_channel_enable(tx_handle);
.gpio_cfg = {
.mclk = I2S_GPIO_UNUSED,
.bclk = GPIO_NUM_6,
.ws = GPIO_NUM_7,
.dout = I2S_GPIO_UNUSED,
.din = GPIO_NUM_19,
.invert_flags = {
.mclk_inv = false,
.bclk_inv = false,
.ws_inv = false,
},
},
};
i2s_channel_init_std_mode(rx_handle, &std_rx_cfg);
i2s_channel_enable(rx_handle);
Application Notes
How to Prevent Data Lost For the applications that need a high frequency sample rate, sometimes the massive
throughput of receiving data may cause data lost. Users can receive data lost event by registering isr callback function
to receive event queue:
{
// handle rx queue overflow event ...
return false;
}
i2s_event_callbacks_t cbs = {
.on_recv = NULL,
.on_recv_q_ovf = i2s_rx_queue_overflow_callback,
(continues on next page)
3. Determine the receiving buffer size. The receiving buffer that offered by user in i2s_channel_read should
be able to take all the data in all dma buffers, that means it should be bigger than the total size of all the dma
buffers:
For example, if there is an I2S application, and the known values are:
sample_rate = 144000 Hz
data_bit_width = 32 bits
slot_num = 2
polling_cycle = 10ms
Then the parameters dma_frame_num, dma_desc_num and recv_buf_size can be calculated according to
the given known values:
API Reference
Standard Mode
Header File
• components/driver/include/driver/i2s_std.h
Functions
esp_err_t i2s_channel_init_std_mode(i2s_chan_handle_t handle, const i2s_std_config_t *std_cfg)
Initialize i2s channel to standard mode.
Note: Only allowed to be called when the channel state is REGISTERED, (i.e., channel has been allocated,
but not initialized) and the state will be updated to READY if initialization success, otherwise the state will
return to REGISTERED.
Parameters
• handle –[in] I2S channel handler
• std_cfg –[in] Configurations for standard mode, including clock, slot
and gpio The clock configuration can be generated by the helper macro
I2S_STD_CLK_DEFAULT_CONFIG The slot configuration can be gener-
ated by the helper macro I2S_STD_PHILIP_SLOT_DEFAULT_CONFIG,
I2S_STD_PCM_SLOT_DEFAULT_CONFIG or I2S_STD_MSB_SLOT_DEFAULT_CONFIG
Returns
• ESP_OK Initialize successfully
• ESP_ERR_NO_MEM No memory for storing the channel information
• ESP_ERR_INVALID_ARG NULL pointer or invalid configuration
• ESP_ERR_INVALID_STATE This channel is not registered
esp_err_t i2s_channel_reconfig_std_clock(i2s_chan_handle_t handle, const i2s_std_clk_config_t
*clk_cfg)
Reconfigure the I2S clock for standard mode.
Note: Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but
not started this function won’t change the state. ‘i2s_channel_disable’should be called before calling this
function if i2s has started.
Note: The input channel handle has to be initialized to standard mode, i.e., ‘i2s_channel_init_std_mode’
has been called before reconfigring
Parameters
• handle –[in] I2S channel handler
• clk_cfg –[in] Standard mode clock configuration, can be generated by
I2S_STD_CLK_DEFAULT_CONFIG
Returns
• ESP_OK Set clock successfully
• ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode
• ESP_ERR_INVALID_STATE This channel is not initialized or not stopped
Note: Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but
not started this function won’t change the state. ‘i2s_channel_disable’should be called before calling this
function if i2s has started.
Note: The input channel handle has to be initialized to standard mode, i.e., ‘i2s_channel_init_std_mode’
has been called before reconfigring
Parameters
• handle –[in] I2S channel handler
Note: Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but
not started this function won’t change the state. ‘i2s_channel_disable’should be called before calling this
function if i2s has started.
Note: The input channel handle has to be initialized to standard mode, i.e., ‘i2s_channel_init_std_mode’
has been called before reconfigring
Parameters
• handle –[in] I2S channel handler
• gpio_cfg –[in] Standard mode gpio configuration, specified by user
Returns
• ESP_OK Set clock successfully
• ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode
• ESP_ERR_INVALID_STATE This channel is not initialized or not stopped
Structures
struct i2s_std_slot_config_t
I2S slot configuration for standard mode.
Public Members
i2s_data_bit_width_t data_bit_width
I2S sample data bit width (valid data bits per sample)
i2s_slot_bit_width_t slot_bit_width
I2S slot bit width (total bits per slot)
i2s_slot_mode_t slot_mode
Set mono or stereo mode with I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO
i2s_std_slot_mask_t slot_mask
Select the left, right or both slot
uint32_t ws_width
WS signal width (i.e. the number of bclk ticks that ws signal is high)
bool ws_pol
WS signal polarity, set true to enable high lever first
bool bit_shift
Set to enbale bit shift in Philip mode
bool msb_right
Set to place right channel data at the MSB in the FIFO
struct i2s_std_clk_config_t
I2S clock configuration for standard mode.
Public Members
uint32_t sample_rate_hz
I2S sample rate
i2s_clock_src_t clk_src
Choose clock source
i2s_mclk_multiple_t mclk_multiple
The multiple of mclk to the sample rate
struct i2s_std_gpio_config_t
I2S standard mode GPIO pins configuration.
Public Members
gpio_num_t mclk
MCK pin, output
gpio_num_t bclk
BCK pin, input in slave role, output in master role
gpio_num_t ws
WS pin, input in slave role, output in master role
gpio_num_t dout
DATA pin, output
gpio_num_t din
DATA pin, input
uint32_t mclk_inv
Set 1 to invert the mclk output
uint32_t bclk_inv
Set 1 to invert the bclk input/output
uint32_t ws_inv
Set 1 to invert the ws input/output
struct i2s_std_config_t
I2S standard mode major configuration that including clock/slot/gpio configuration.
Public Members
i2s_std_clk_config_t clk_cfg
Standard mode clock configuration, can be generated by macro I2S_STD_CLK_DEFAULT_CONFIG
i2s_std_slot_config_t slot_cfg
Standard mode slot configuration, can be generated by macros
I2S_STD_[mode]_SLOT_DEFAULT_CONFIG, [mode] can be replaced with PHILIP/MSB/PCM
i2s_std_gpio_config_t gpio_cfg
Standard mode gpio configuration, specified by user
Macros
I2S_STD_PHILIP_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo)
Philip format in 2 slots.
This file is specified for I2S standard communication mode Features:
• Philip/MSB/PCM are supported in standard mode
• Fixed to 2 slots
Parameters
• bits_per_sample –i2s data bit width
• mono_or_stereo –I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO
I2S_STD_PCM_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo)
PCM(short) format in 2 slots.
Parameters
• bits_per_sample –i2s data bit width
• mono_or_stereo –I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO
I2S_STD_MSB_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo)
MSB format in 2 slots.
Parameters
• bits_per_sample –i2s data bit width
• mono_or_stereo –I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO
I2S_STD_CLK_DEFAULT_CONFIG(rate)
i2s default standard clock configuration
Note: Please set the mclk_multiple to I2S_MCLK_MULTIPLE_384 while using 24 bits data width Other-
wise the sample rate might be imprecise since the bclk division is not a integer
Parameters
• rate –sample rate
PDM Mode
Header File
• components/driver/include/driver/i2s_pdm.h
Functions
esp_err_t i2s_channel_init_pdm_rx_mode(i2s_chan_handle_t handle, const i2s_pdm_rx_config_t
*pdm_rx_cfg)
Initialize i2s channel to PDM RX mode.
Note: Only allowed to be called when the channel state is REGISTERED, (i.e., channel has been allocated,
but not initialized) and the state will be updated to READY if initialization success, otherwise the state will
return to REGISTERED.
Parameters
• handle –[in] I2S rx channel handler
• pdm_rx_cfg –[in] Configurations for PDM RX mode, including clock,
slot and gpio The clock configuration can be generated by the helper macro
I2S_PDM_RX_CLK_DEFAULT_CONFIG The slot configuration can be generated by
the helper macro I2S_PDM_RX_SLOT_DEFAULT_CONFIG
Returns
• ESP_OK Initialize successfully
• ESP_ERR_NO_MEM No memory for storing the channel information
• ESP_ERR_INVALID_ARG NULL pointer or invalid configuration
• ESP_ERR_INVALID_STATE This channel is not registered
esp_err_t i2s_channel_reconfig_pdm_rx_clock(i2s_chan_handle_t handle, const
i2s_pdm_rx_clk_config_t *clk_cfg)
Reconfigure the I2S clock for PDM RX mode.
Note: Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but
not started this function won’t change the state. ‘i2s_channel_disable’should be called before calling this
function if i2s has started.
Note: The input channel handle has to be initialized to PDM RX mode, i.e.,
‘i2s_channel_init_pdm_rx_mode’has been called before reconfigring
Parameters
• handle –[in] I2S rx channel handler
Note: Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but
not started this function won’t change the state. ‘i2s_channel_disable’should be called before calling this
function if i2s has started.
Note: The input channel handle has to be initialized to PDM RX mode, i.e.,
‘i2s_channel_init_pdm_rx_mode’has been called before reconfigring
Parameters
• handle –[in] I2S rx channel handler
• slot_cfg –[in] PDM RX mode slot configuration, can be generated by
I2S_PDM_RX_SLOT_DEFAULT_CONFIG
Returns
• ESP_OK Set clock successfully
• ESP_ERR_NO_MEM No memory for DMA buffer
• ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode
• ESP_ERR_INVALID_STATE This channel is not initialized or not stopped
Note: Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but
not started this function won’t change the state. ‘i2s_channel_disable’should be called before calling this
function if i2s has started.
Note: The input channel handle has to be initialized to PDM RX mode, i.e.,
‘i2s_channel_init_pdm_rx_mode’has been called before reconfigring
Parameters
• handle –[in] I2S rx channel handler
• gpio_cfg –[in] PDM RX mode gpio configuration, specified by user
Returns
• ESP_OK Set clock successfully
• ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode
• ESP_ERR_INVALID_STATE This channel is not initialized or not stopped
Note: Only allowed to be called when the channel state is REGISTERED, (i.e., channel has been allocated,
but not initialized) and the state will be updated to READY if initialization success, otherwise the state will
return to REGISTERED.
Parameters
• handle –[in] I2S tx channel handler
• pdm_tx_cfg –[in] Configurations for PDM TX mode, including clock,
slot and gpio The clock configuration can be generated by the helper macro
I2S_PDM_TX_CLK_DEFAULT_CONFIG The slot configuration can be generated by
the helper macro I2S_PDM_TX_SLOT_DEFAULT_CONFIG
Returns
• ESP_OK Initialize successfully
• ESP_ERR_NO_MEM No memory for storing the channel information
• ESP_ERR_INVALID_ARG NULL pointer or invalid configuration
• ESP_ERR_INVALID_STATE This channel is not registered
Note: Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but
not started this function won’t change the state. ‘i2s_channel_disable’should be called before calling this
function if i2s has started.
Note: The input channel handle has to be initialized to PDM TX mode, i.e.,
‘i2s_channel_init_pdm_tx_mode’has been called before reconfigring
Parameters
• handle –[in] I2S tx channel handler
• clk_cfg –[in] PDM TX mode clock configuration, can be generated by
I2S_PDM_TX_CLK_DEFAULT_CONFIG
Returns
• ESP_OK Set clock successfully
• ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode
• ESP_ERR_INVALID_STATE This channel is not initialized or not stopped
Note: Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but
not started this function won’t change the state. ‘i2s_channel_disable’should be called before calling this
function if i2s has started.
Note: The input channel handle has to be initialized to PDM TX mode, i.e.,
‘i2s_channel_init_pdm_tx_mode’has been called before reconfigring
Parameters
• handle –[in] I2S tx channel handler
Note: Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but
not started this function won’t change the state. ‘i2s_channel_disable’should be called before calling this
function if i2s has started.
Note: The input channel handle has to be initialized to PDM TX mode, i.e.,
‘i2s_channel_init_pdm_tx_mode’has been called before reconfigring
Parameters
• handle –[in] I2S tx channel handler
• gpio_cfg –[in] PDM TX mode gpio configuration, specified by user
Returns
• ESP_OK Set clock successfully
• ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode
• ESP_ERR_INVALID_STATE This channel is not initialized or not stopped
Structures
struct i2s_pdm_rx_slot_config_t
I2S slot configuration for pdm rx mode.
Public Members
i2s_data_bit_width_t data_bit_width
I2S sample data bit width (valid data bits per sample), only support 16 bits for PDM mode
i2s_slot_bit_width_t slot_bit_width
I2S slot bit width (total bits per slot) , only support 16 bits for PDM mode
i2s_slot_mode_t slot_mode
Set mono or stereo mode with I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO
struct i2s_pdm_rx_clk_config_t
I2S clock configuration for pdm rx mode.
Public Members
uint32_t sample_rate_hz
I2S sample rate
i2s_clock_src_t clk_src
Choose clock source
i2s_mclk_multiple_t mclk_multiple
The multiple of mclk to the sample rate
i2s_pdm_dsr_t dn_sample_mode
Down-sampling rate mode
struct i2s_pdm_rx_gpio_config_t
I2S PDM tx mode GPIO pins configuration.
Public Members
gpio_num_t clk
PDM clk pin, output
gpio_num_t din
DATA pin, input
uint32_t clk_inv
Set 1 to invert the clk output
struct i2s_pdm_rx_config_t
I2S PDM RX mode major configuration that including clock/slot/gpio configuration.
Public Members
i2s_pdm_rx_clk_config_t clk_cfg
PDM RX clock configurations, can be genertated by macro I2S_PDM_RX_CLK_DEFAULT_CONFIG
i2s_pdm_rx_slot_config_t slot_cfg
PDM RX slot configurations, can be genertated by macro I2S_PDM_RX_SLOT_DEFAULT_CONFIG
i2s_pdm_rx_gpio_config_t gpio_cfg
PDM RX slot configurations, specified by user
struct i2s_pdm_tx_slot_config_t
I2S slot configuration for pdm tx mode.
Public Members
i2s_data_bit_width_t data_bit_width
I2S sample data bit width (valid data bits per sample), only support 16 bits for PDM mode
i2s_slot_bit_width_t slot_bit_width
I2S slot bit width (total bits per slot), only support 16 bits for PDM mode
i2s_slot_mode_t slot_mode
Set mono or stereo mode with I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO
uint32_t sd_prescale
Sigma-delta filter prescale
i2s_pdm_sig_scale_t sd_scale
Sigma-delta filter scaling value
i2s_pdm_sig_scale_t hp_scale
High pass filter scaling value
i2s_pdm_sig_scale_t lp_scale
Low pass filter scaling value
i2s_pdm_sig_scale_t sinc_scale
Sinc filter scaling value
struct i2s_pdm_tx_clk_config_t
I2S clock configuration for pdm tx mode.
Public Members
uint32_t sample_rate_hz
I2S sample rate
i2s_clock_src_t clk_src
Choose clock source
i2s_mclk_multiple_t mclk_multiple
The multiple of mclk to the sample rate
uint32_t up_sample_fp
Up-sampling param fp
uint32_t up_sample_fs
Up-sampling param fs
struct i2s_pdm_tx_gpio_config_t
I2S PDM tx mode GPIO pins configuration.
Public Members
gpio_num_t clk
PDM clk pin, output
gpio_num_t dout
DATA pin, output
uint32_t clk_inv
Set 1 to invert the clk output
struct i2s_pdm_tx_config_t
I2S PDM TX mode major configuration that including clock/slot/gpio configuration.
Public Members
i2s_pdm_tx_clk_config_t clk_cfg
PDM TX clock configurations, can be genertated by macro I2S_PDM_TX_CLK_DEFAULT_CONFIG
i2s_pdm_tx_slot_config_t slot_cfg
PDM TX slot configurations, can be genertated by macro I2S_PDM_TX_SLOT_DEFAULT_CONFIG
i2s_pdm_tx_gpio_config_t gpio_cfg
PDM TX gpio configurations, specified by user
Macros
I2S_PDM_RX_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo)
PDM format in 2 slots(RX)
This file is specified for I2S PDM communication mode Features:
• Only support PDM tx/rx mode
• Fixed to 2 slots
• Data bit width only support 16 bits
Parameters
• bits_per_sample –i2s data bit width, only support 16 bits for PDM mode
• mono_or_stereo –I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO
I2S_PDM_RX_CLK_DEFAULT_CONFIG(rate)
i2s default pdm rx clock configuration
Parameters
• rate –sample rate
I2S_PDM_TX_SLOT_DEFAULT_CONFIG(bits_per_sample, mono_or_stereo)
PDM style in 2 slots(TX)
Parameters
• bits_per_sample –i2s data bit width, only support 16 bits for PDM mode
• mono_or_stereo –I2S_SLOT_MODE_MONO or I2S_SLOT_MODE_STEREO
I2S_PDM_TX_CLK_DEFAULT_CONFIG(rate)
i2s default pdm tx clock configuration
Note: TX PDM can only be set to the following two up-sampling rate configurations: 1: fp = 960, fs =
sample_rate_hz / 100, in this case, Fpdm = 128*48000 2: fp = 960, fs = 480, in this case, Fpdm = 128*Fpcm
= 128*sample_rate_hz If the pdm receiver do not care the pdm serial clock, it’s recommended set Fpdm =
128*48000. Otherwise, the second configuration should be adopted.
Parameters
• rate –sample rate
I2S Driver
Header File
• components/driver/include/driver/i2s_common.h
Functions
esp_err_t i2s_new_channel(const i2s_chan_config_t *chan_cfg, i2s_chan_handle_t *ret_tx_handle,
i2s_chan_handle_t *ret_rx_handle)
Allocate new I2S channel(s)
Note: The new created I2S channel handle will be REGISTERED state after it is allocated successfully.
Note: When the port id in channel configuration is I2S_NUM_AUTO, driver will allocate I2S port auto-
matically on one of the i2s controller, otherwise driver will try to allocate the new channel on the selected
port.
Note: If both tx_handle and rx_handle are not NULL, it means this I2S controller will work at full-duplex
mode, the rx and tx channels will be allocated on a same I2S port in this case. Note that some configurations
of tx/rx channel are shared on ESP32 and ESP32S2, so please make sure they are working at same condition
and under same status(start/stop). Currently, full-duplex mode can’t guarantee tx/rx channels write/read
synchronously, they can only share the clock signals for now.
Note: If tx_handle OR rx_handle is NULL, it means this I2S controller will work at simplex mode. For
ESP32 and ESP32S2, the whole I2S controller (i.e. both rx and tx channel) will be occupied, even if only one
of rx or tx channel is registered. For the other targets, another channel on this controller will still available.
Parameters
• chan_cfg –[in] I2S controller channel configurations
• ret_tx_handle –[out] I2S channel handler used for managing the sending chan-
nel(optional)
• ret_rx_handle –[out] I2S channel handler used for managing the receiving chan-
nel(optional)
Returns
• ESP_OK Allocate new channel(s) success
• ESP_ERR_NOT_SUPPORTED The communication mode is not supported on the cur-
rent chip
Note: Only allowed to be called when the i2s channel is at REGISTERED or READY state (i.e., it should
stop before deleting it).
Note: Resource will be free automatically if all channels in one port are deleted
Note: Only allowed to be called when the channel state is READY, (i.e., channel has been initialized, but not
started) the channel will enter RUNNING state once it is enabled successfully.
Note: Enbale the channel can start the I2S communication on hardware. It will start outputting bclk and ws
signal. For mclk signal, it will start to output when initialization is finished
Note: Only allowed to be called when the channel state is READY / RUNNING, (i.e., channel has been
initialized) the channel will enter READY state once it is disabled successfully.
Note: Disable the channel can stop the I2S communication on hardware. It will stop bclk and ws signal but
not mclk signal
esp_err_t i2s_channel_write(i2s_chan_handle_t handle, const void *src, size_t size, size_t *bytes_written,
uint32_t timeout_ms)
I2S write data.
Note: Only allowed to be called when the channel state is RUNNING, (i.e., tx channel has been started and is
not writing now) but the RUNNING only stands for the software state, it doesn’t mean there is no the signal
transporting on line.
Parameters
• handle –[in] I2S channel handler
• src –[in] The pointer of sent data buffer
• size –[in] Max data buffer length
• bytes_written –[out] Byte number that actually be sent
• timeout_ms –[in] Max block time
Returns
• ESP_OK Write successfully
• ESP_ERR_INVALID_ARG NULL pointer or this handle is not tx handle
• ESP_ERR_TIMEOUT Writing timeout, no writing event received from ISR within
ticks_to_wait
• ESP_ERR_INVALID_STATE I2S is not ready to write
esp_err_t i2s_channel_read(i2s_chan_handle_t handle, void *dest, size_t size, size_t *bytes_read, uint32_t
timeout_ms)
I2S read data.
Note: Only allowed to be called when the channel state is RUNNING but the RUNNING only stands for the
software state, it doesn’t mean there is no the signal transporting on line.
Parameters
• handle –[in] I2S channel handler
• dest –[in] The pointer of receiving data buffer
• size –[in] Max data buffer length
• bytes_read –[out] Byte number that actually be read
• timeout_ms –[in] Max block time
Returns
• ESP_OK Read successfully
• ESP_ERR_INVALID_ARG NULL pointer or this handle is not rx handle
• ESP_ERR_TIMEOUT Reading timeout, no reading event received from ISR within
ticks_to_wait
• ESP_ERR_INVALID_STATE I2S is not ready to read
Note: Only allowed to be called when the channel state is REGISTARED / READY, (i.e., before channel
starts)
Note: User can deregister a previously registered callback by calling this function and setting the callback
member in the callbacks structure to NULL.
Note: When CONFIG_I2S_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should
be placed in IRAM. The variables used in the function should be in the SRAM as well. The user_data
should also reside in SRAM or internal RAM as well.
Parameters
• handle –[in] I2S channel handler
• callbacks –[in] Group of callback functions
• user_data –[in] User data, which will be passed to callback functions directly
Returns
• ESP_OK Set event callbacks successfully
• ESP_ERR_INVALID_ARG Set event callbacks failed because of invalid argument
• ESP_ERR_INVALID_STATE Set event callbacks failed because the current channel state
is not REGISTARED or READY
Structures
struct i2s_event_callbacks_t
Group of I2S callbacks.
Note: When CONFIG_I2S_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should
be placed in IRAM. The variables used in the function should be in the SRAM as well.
Public Members
i2s_isr_callback_t on_recv
Callback of data received event, only for rx channel The event data includes DMA buffer address and
size that just finished receiving data
i2s_isr_callback_t on_recv_q_ovf
Callback of receiving queue overflowed event, only for rx channel The event data includes buffer size that
has been overwritten
i2s_isr_callback_t on_sent
Callback of data sent event, only for tx channel The event data includes DMA buffer address and size
that just finished sending data
i2s_isr_callback_t on_send_q_ovf
Callback of sending queue overflowed evnet, only for tx channel The event data includes buffer size that
has been overwritten
struct i2s_chan_config_t
I2S controller channel configuration.
Public Members
i2s_port_t id
I2S port id
i2s_role_t role
I2S role, I2S_ROLE_MASTER or I2S_ROLE_SLAVE
uint32_t dma_desc_num
I2S DMA buffer number, it is also the number of DMA descriptor
uint32_t dma_frame_num
I2S frame number in one DMA buffer. One frame means one-time sample data in all slots
bool auto_clear
Set to auto clear DMA TX buffer, i2s will always send zero automatically if no data to send
struct i2s_chan_info_t
I2S channel information.
Public Members
i2s_port_t id
I2S port id
i2s_role_t role
I2S role, I2S_ROLE_MASTER or I2S_ROLE_SLAVE
i2s_dir_t dir
I2S channel direction
i2s_comm_mode_t mode
I2S channel communication mode
i2s_chan_handle_t pair_chan
I2S pair channel handle in duplex mode, always NULL in simplex mode
Macros
I2S_CHANNEL_DEFAULT_CONFIG(i2s_num, i2s_role)
get default I2S property
I2S_GPIO_UNUSED
Used in i2s_gpio_config_t for signals which are not used
I2S Types
Header File
• components/driver/include/driver/i2s_types.h
Structures
struct i2s_event_data_t
Event structure used in I2S event queue.
Public Members
void *data
The pointer of DMA buffer that just finished sending or receiving for on_recv and on_sent callback
NULL for on_recv_q_ovf and on_send_q_ovf callback
size_t size
The buffer size of DMA buffer when success to send or receive, also the buffer size that dropped when
queue overflow. It is related to the dma_frame_num and data_bit_width, typically it is fixed when
data_bit_width is not changed.
Type Definitions
Enumerations
enum i2s_port_t
I2S controller port number, the max port number is (SOC_I2S_NUM -1).
Values:
enumerator I2S_NUM_0
I2S controller port 0
enumerator I2S_NUM_1
I2S controller port 1
enumerator I2S_NUM_AUTO
Select whichever port is available
enum i2s_comm_mode_t
I2S controller communication mode.
Values:
enumerator I2S_COMM_MODE_STD
I2S controller using standard communication mode, support philip/MSB/PCM format
enumerator I2S_COMM_MODE_PDM
I2S controller using PDM communication mode, support PDM output or input
enumerator I2S_COMM_MODE_NONE
Unspecified I2S controller mode
enum i2s_mclk_multiple_t
The multiple of mclk to sample rate.
Values:
enumerator I2S_MCLK_MULTIPLE_128
mclk = sample_rate * 128
enumerator I2S_MCLK_MULTIPLE_256
mclk = sample_rate * 256
enumerator I2S_MCLK_MULTIPLE_384
mclk = sample_rate * 384
Header File
• components/hal/include/hal/i2s_types.h
Type Definitions
Enumerations
enum i2s_slot_mode_t
I2S channel slot mode.
Values:
enumerator I2S_SLOT_MODE_MONO
I2S channel slot format mono, transmit same data in all slots for tx mode, only receive the data in the first
slots for rx mode.
enumerator I2S_SLOT_MODE_STEREO
I2S channel slot format stereo, transmit different data in different slots for tx mode, receive the data in
all slots for rx mode.
enum i2s_dir_t
I2S channel direction.
Values:
enumerator I2S_DIR_RX
I2S channel direction RX
enumerator I2S_DIR_TX
I2S channel direction TX
enum i2s_role_t
I2S controller role.
Values:
enumerator I2S_ROLE_MASTER
I2S controller master role, bclk and ws signal will be set to output
enumerator I2S_ROLE_SLAVE
I2S controller slave role, bclk and ws signal will be set to input
enum i2s_data_bit_width_t
Available data bit width in one slot.
Values:
enumerator I2S_DATA_BIT_WIDTH_8BIT
I2S channel data bit-width: 8
enumerator I2S_DATA_BIT_WIDTH_16BIT
I2S channel data bit-width: 16
enumerator I2S_DATA_BIT_WIDTH_24BIT
I2S channel data bit-width: 24
enumerator I2S_DATA_BIT_WIDTH_32BIT
I2S channel data bit-width: 32
enum i2s_slot_bit_width_t
Total slot bit width in one slot.
Values:
enumerator I2S_SLOT_BIT_WIDTH_AUTO
I2S channel slot bit-width equals to data bit-width
enumerator I2S_SLOT_BIT_WIDTH_8BIT
I2S channel slot bit-width: 8
enumerator I2S_SLOT_BIT_WIDTH_16BIT
I2S channel slot bit-width: 16
enumerator I2S_SLOT_BIT_WIDTH_24BIT
I2S channel slot bit-width: 24
enumerator I2S_SLOT_BIT_WIDTH_32BIT
I2S channel slot bit-width: 32
enum i2s_pdm_dsr_t
I2S PDM RX down-sampling mode.
Values:
enumerator I2S_PDM_DSR_8S
downsampling number is 8 for PDM RX mode
enumerator I2S_PDM_DSR_16S
downsampling number is 16 for PDM RX mode
enumerator I2S_PDM_DSR_MAX
enum i2s_pdm_sig_scale_t
pdm tx singnal scaling mode
Values:
enumerator I2S_PDM_SIG_SCALING_DIV_2
I2S TX PDM signal scaling: /2
enumerator I2S_PDM_SIG_SCALING_MUL_1
I2S TX PDM signal scaling: x1
enumerator I2S_PDM_SIG_SCALING_MUL_2
I2S TX PDM signal scaling: x2
enumerator I2S_PDM_SIG_SCALING_MUL_4
I2S TX PDM signal scaling: x4
enum i2s_std_slot_mask_t
I2S slot select in standard mode.
Values:
enumerator I2S_STD_SLOT_ONLY_LEFT
I2S only transmits or receives left slot
enumerator I2S_STD_SLOT_ONLY_RIGHT
I2S only transmits or receives right slot
enumerator I2S_STD_SLOT_LEFT_RIGHT
I2S transmits or receives both left and right slot
2.6.8 LCD
Introduction
ESP chips can generate various kinds of timings that needed by common LCDs on the market, like SPI LCD, I80
LCD (a.k.a Intel 8080 parallel LCD), RGB LCD, I2C LCD, etc. The esp_lcd component is officially to support
those LCDs with a group of universal APIs across chips.
Functional Overview
In esp_lcd, an LCD panel is represented by esp_lcd_panel_handle_t, which plays the role of an abstract
frame buffer, regardless of the frame memory is allocated inside ESP chip or in external LCD controller. Based on
the location of the frame buffer, the LCD panel allocation functions are mainly grouped into the following categories:
• RGB LCD panel - is simply based on a group of specific synchronous signals indicating where to start and
stop a frame.
• Controller based LCD panel involves multiple steps to get a panel handle, like bus allocation, IO
device registration and controller driver install.
After we get the LCD handle, the remaining LCD operations are the same for different LCD interfaces and vendors.
Application Example
API Reference
Header File
• components/hal/include/hal/lcd_types.h
Type Definitions
Header File
• components/esp_lcd/include/esp_lcd_types.h
Type Definitions
Enumerations
enum esp_lcd_color_space_t
LCD color space type definition.
Values:
enumerator ESP_LCD_COLOR_SPACE_RGB
Color space: RGB
enumerator ESP_LCD_COLOR_SPACE_BGR
Color space: BGR
enumerator ESP_LCD_COLOR_SPACE_MONOCHROME
Color space: monochrome
Header File
• components/esp_lcd/include/esp_lcd_panel_io.h
Functions
esp_err_t esp_lcd_panel_io_rx_param(esp_lcd_panel_io_handle_t io, int lcd_cmd, void *param, size_t
param_size)
Transmit LCD command and receive corresponding parameters.
Note: Commands sent by this function are short, so they are sent using polling transactions. The
function does not return before the command tranfer is completed. If any queued transactions sent by
esp_lcd_panel_io_tx_color() are still pending when this function is called, this function will wait
until they are finished and the queue is empty before sending the command(s).
Parameters
• io –[in] LCD panel IO handle, which is created by other factory API like
esp_lcd_new_panel_io_spi()
• lcd_cmd –[in] The specific LCD command, set to -1 if no command needed
• param –[out] Buffer for the command data
• param_size –[in] Size of param buffer
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_ERR_NOT_SUPPORTED if read is not supported by transport
• ESP_OK on success
esp_err_t esp_lcd_panel_io_tx_param(esp_lcd_panel_io_handle_t io, int lcd_cmd, const void *param,
size_t param_size)
Transmit LCD command and corresponding parameters.
Note: Commands sent by this function are short, so they are sent using polling transactions. The
function does not return before the command tranfer is completed. If any queued transactions sent by
esp_lcd_panel_io_tx_color() are still pending when this function is called, this function will wait
until they are finished and the queue is empty before sending the command(s).
Parameters
• io –[in] LCD panel IO handle, which is created by other factory API like
esp_lcd_new_panel_io_spi()
Note: This function will package the command and RGB data into a transaction, and push into a queue. The
real transmission is performed in the background (DMA+interrupt). The caller should take care of the lifecycle
of the color buffer. Recycling of color buffer should be done in the callback on_color_trans_done().
Parameters
• io –[in] LCD panel IO handle, which is created by factory API like
esp_lcd_new_panel_io_spi()
• lcd_cmd –[in] The specific LCD command
• color –[in] Buffer that holds the RGB color data
• color_size –[in] Size of color in memory, in bytes
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_OK on success
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_ERR_NO_MEM if out of memory
• ESP_OK on success
esp_err_t esp_lcd_new_i80_bus(const esp_lcd_i80_bus_config_t *bus_config, esp_lcd_i80_bus_handle_t
*ret_bus)
Create Intel 8080 bus handle.
Parameters
• bus_config –[in] Bus configuration
• ret_bus –[out] Returned bus handle
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_ERR_NO_MEM if out of memory
• ESP_ERR_NOT_FOUND if no free bus is available
• ESP_OK on success
esp_err_t esp_lcd_del_i80_bus(esp_lcd_i80_bus_handle_t bus)
Destory Intel 8080 bus handle.
Parameters bus –[in] Intel 8080 bus handle, created by esp_lcd_new_i80_bus()
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_ERR_INVALID_STATE if there still be some device attached to the bus
• ESP_OK on success
esp_err_t esp_lcd_new_panel_io_i80(esp_lcd_i80_bus_handle_t bus, const
esp_lcd_panel_io_i80_config_t *io_config,
esp_lcd_panel_io_handle_t *ret_io)
Create LCD panel IO, for Intel 8080 interface.
Parameters
• bus –[in] Intel 8080 bus handle, created by esp_lcd_new_i80_bus()
• io_config –[in] IO configuration, for i80 interface
• ret_io –[out] Returned panel IO handle
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_ERR_NOT_SUPPORTED if some configuration can’t be satisfied, e.g. pixel clock
out of the range
• ESP_ERR_NO_MEM if out of memory
• ESP_OK on success
Structures
struct esp_lcd_panel_io_event_data_t
Type of LCD panel IO event data.
struct esp_lcd_panel_io_spi_config_t
Panel IO configuration structure, for SPI interface.
Public Members
int cs_gpio_num
GPIO used for CS line
int dc_gpio_num
GPIO used to select the D/C line, set this to -1 if the D/C line not controlled by manually pulling high/low
GPIO
int spi_mode
Traditional SPI mode (0~3)
size_t trans_queue_depth
Size of internal transaction queue
esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done
Callback invoked when color data transfer has finished
void *user_ctx
User private data, passed directly to on_color_trans_done’s user_ctx
int lcd_cmd_bits
Bit-width of LCD command
int lcd_param_bits
Bit-width of LCD parameter
struct esp_lcd_panel_io_i2c_config_t
Panel IO configuration structure, for I2C interface.
Public Members
uint32_t dev_addr
I2C device address
esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done
Callback invoked when color data transfer has finished
void *user_ctx
User private data, passed directly to on_color_trans_done’s user_ctx
size_t control_phase_bytes
I2C LCD panel will encode control information (e.g. D/C seclection) into control phase, in several bytes
int lcd_cmd_bits
Bit-width of LCD command
int lcd_param_bits
Bit-width of LCD parameter
struct esp_lcd_i80_bus_config_t
LCD Intel 8080 bus configuration structure.
Public Members
int dc_gpio_num
GPIO used for D/C line
int wr_gpio_num
GPIO used for WR line
lcd_clock_source_t clk_src
Clock source for the I80 LCD peripheral
int data_gpio_nums[(24)]
GPIOs used for data lines
size_t bus_width
Number of data lines, 8 or 16
size_t max_transfer_bytes
Maximum transfer size, this determines the length of internal DMA link
size_t psram_trans_align
DMA transfer alignment for data allocated from PSRAM
size_t sram_trans_align
DMA transfer alignment for data allocated from SRAM
struct esp_lcd_panel_io_i80_config_t
Panel IO configuration structure, for intel 8080 interface.
Public Members
int cs_gpio_num
GPIO used for CS line, set to -1 will declaim exclusively use of I80 bus
size_t trans_queue_depth
Transaction queue size, larger queue, higher throughput
esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done
Callback invoked when color data was tranferred done
void *user_ctx
User private data, passed directly to on_color_trans_done’s user_ctx
int lcd_cmd_bits
Bit-width of LCD command
int lcd_param_bits
Bit-width of LCD parameter
Type Definitions
Header File
• components/esp_lcd/include/esp_lcd_panel_ops.h
Functions
esp_err_t esp_lcd_panel_reset(esp_lcd_panel_handle_t panel)
Reset LCD panel.
Note: Panel reset must be called before attempting to initialize the panel using esp_lcd_panel_init().
Parameters panel –[in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
Returns
• ESP_OK on success
esp_err_t esp_lcd_panel_init(esp_lcd_panel_handle_t panel)
Initialize LCD panel.
Note: Before calling this function, make sure the LCD panel has finished the reset stage by
esp_lcd_panel_reset().
Parameters panel –[in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
Returns
• ESP_OK on success
Parameters
• panel –[in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
• mirror_x –[in] Whether the panel will be mirrored about the x axis
• mirror_y –[in] Whether the panel will be mirrored about the y axis
Returns
• ESP_OK on success
• ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel
Parameters
• panel –[in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
• swap_axes –[in] Whether to swap the x and y axis
Returns
• ESP_OK on success
• ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel
Note: Setting a gap is useful when positioning or centering a frame that is smaller than the LCD.
Parameters
• panel –[in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
• x_gap –[in] Extra gap on x axis, in pixels
• y_gap –[in] Extra gap on y axis, in pixels
Returns
• ESP_OK on success
Header File
• components/esp_lcd/include/esp_lcd_panel_rgb.h
Header File
• components/esp_lcd/include/esp_lcd_panel_vendor.h
Functions
esp_err_t esp_lcd_new_panel_st7789(const esp_lcd_panel_io_handle_t io, const
esp_lcd_panel_dev_config_t *panel_dev_config,
esp_lcd_panel_handle_t *ret_panel)
Create LCD panel for model ST7789.
Parameters
• io –[in] LCD panel IO handle
• panel_dev_config –[in] general panel device configuration
• ret_panel –[out] Returned LCD panel handle
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_ERR_NO_MEM if out of memory
• ESP_OK on success
esp_err_t esp_lcd_new_panel_nt35510(const esp_lcd_panel_io_handle_t io, const
esp_lcd_panel_dev_config_t *panel_dev_config,
esp_lcd_panel_handle_t *ret_panel)
Create LCD panel for model NT35510.
Parameters
• io –[in] LCD panel IO handle
• panel_dev_config –[in] general panel device configuration
• ret_panel –[out] Returned LCD panel handle
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_ERR_NO_MEM if out of memory
• ESP_OK on success
esp_err_t esp_lcd_new_panel_ssd1306(const esp_lcd_panel_io_handle_t io, const
esp_lcd_panel_dev_config_t *panel_dev_config,
esp_lcd_panel_handle_t *ret_panel)
Create LCD panel for model SSD1306.
Parameters
• io –[in] LCD panel IO handle
• panel_dev_config –[in] general panel device configuration
• ret_panel –[out] Returned LCD panel handle
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_ERR_NO_MEM if out of memory
• ESP_OK on success
Structures
struct esp_lcd_panel_dev_config_t
Configuration structure for panel device.
Public Members
int reset_gpio_num
GPIO used to reset the LCD panel, set to -1 if it’s not used
esp_lcd_color_space_t color_space
Set the color space used by the LCD panel
void *vendor_config
vendor specific configuration, optional, left as NULL if not used
Introduction
The LED control (LEDC) peripheral is primarily designed to control the intensity of LEDs, although it can also be
used to generate PWM signals for other purposes. It has 16 channels which can generate independent waveforms that
can be used, for example, to drive RGB LED devices.
LEDC channels are divided into two groups of 8 channels each. One group of LEDC channels operates in high
speed mode. This mode is implemented in hardware and offers automatic and glitch-free changing of the PWM duty
cycle. The other group of channels operate in low speed mode, the PWM duty cycle must be changed by the driver
in software. Each group of channels is also able to use different clock sources.
The PWM controller can automatically increase or decrease the duty cycle gradually, allowing for fades without any
processor interference.
Functionality Overview
Setting up a channel of the LEDC in either high or low speed mode is done in three steps:
1. Timer Configuration by specifying the PWM signal’s frequency and duty cycle resolution.
2. Channel Configuration by associating it with the timer and GPIO to output the PWM signal.
3. Change PWM Signal that drives the output in order to change LED’s intensity. This can be done under the
full control of software or with hardware fading functions.
As an optional step, it is also possible to set up an interrupt on fade end.
Timer Configuration Setting the timer is done by calling the function ledc_timer_config() and passing
the data structure ledc_timer_config_t that contains the following configuration settings:
The frequency and the duty resolution are interdependent. The higher the PWM frequency, the lower the duty
resolution which is available, and vice versa. This relationship might be important if you are planning to use this API
for purposes other than changing the intensity of LEDs. For more details, see Section Supported Range of Frequency
and Duty Resolutions.
The source clock can also limit the PWM frequency. The higher the source clock frequency, the higher the maximum
PWM frequency can be configured.
Note:
1. On ESP32, if RTCxM_CLK is chosen as the LEDC clock source, an internal calibration will be performed to
get the exact frequency of the clock. This ensures the accuracy of output PWM signal frequency.
Channel Configuration When the timer is set up, configure the desired channel (one out of ledc_channel_t).
This is done by calling the function ledc_channel_config().
Similar to the timer configuration, the channel setup function should be passed a structure
ledc_channel_config_t that contains the channel’s configuration parameters.
At this point, the channel should start operating and generating the PWM signal on the selected GPIO, as configured
in ledc_channel_config_t, with the frequency specified in the timer settings and the given duty cycle. The
channel operation (signal generation) can be suspended at any time by calling the function ledc_stop().
Change PWM Signal Once the channel starts operating and generating the PWM signal with the constant duty
cycle and frequency, there are a couple of ways to change this signal. When driving LEDs, primarily the duty cycle
is changed to vary the light intensity.
The following two sections describe how to change the duty cycle using software and hardware fading. If required,
the signal’s frequency can also be changed; it is covered in Section Change PWM Frequency.
Change PWM Duty Cycle Using Software To set the duty cycle, use the dedicated function
ledc_set_duty(). After that, call ledc_update_duty() to activate the changes. To check the
currently set value, use the corresponding _get_ function ledc_get_duty().
Another way to set the duty cycle, as well as some other channel parameters, is by calling
ledc_channel_config() covered in Section Channel Configuration.
The range of the duty cycle values passed to functions depends on selected duty_resolution and should be
from 0 to (2 ** duty_resolution) - 1. For example, if the selected duty resolution is 10, then the duty
cycle values can range from 0 to 1023. This provides the resolution of ~0.1%.
Change PWM Duty Cycle using Hardware The LEDC hardware provides the means to gradually transition from
one duty cycle value to another. To use this functionality, enable fading with ledc_fade_func_install()
and then configure it by calling one of the available fading functions:
• ledc_set_fade_with_time()
• ledc_set_fade_with_step()
• ledc_set_fade()
Start fading with ledc_fade_start(). A fade can be operated in blocking or non-blocking mode, please check
ledc_fade_mode_t for the difference between the two available fade modes. Note that with either fade mode,
the next fade or fixed-duty update will not take effect until the last fade finishes. Due to hardware limitations, there
is no way to stop a fade before it reaches its target duty.
To get a notification about the completion of a fade operation, a fade end callback function can be registered for each
channel by calling ledc_cb_register() after the fade service being installed.
If not required anymore, fading and an associated interrupt can be disabled with
ledc_fade_func_uninstall().
Change PWM Frequency The LEDC API provides several ways to change the PWM frequency “on the fly”:
• Set the frequency by calling ledc_set_freq(). There is a corresponding function ledc_get_freq()
to check the current frequency.
• Change the frequency and the duty resolution by calling ledc_bind_channel_timer() to bind some
other timer to the channel.
• Change the channel’s timer by calling ledc_channel_config().
More Control Over PWM There are several lower level timer-specific functions that can be used to change PWM
settings:
• ledc_timer_set()
• ledc_timer_rst()
• ledc_timer_pause()
• ledc_timer_resume()
The first two functions are called “behind the scenes”by ledc_channel_config() to provide a startup of a
timer after it is configured.
Use Interrupts When configuring an LEDC channel, one of the parameters selected within
ledc_channel_config_t is ledc_intr_type_t which triggers an interrupt on fade completion.
For registration of a handler to address this interrupt, call ledc_isr_register().
High speed mode enables a glitch-free changeover of timer settings. This means that if the timer settings are modified,
the changes will be applied automatically on the next overflow interrupt of the timer. In contrast, when updating the
low-speed timer, the change of settings should be explicitly triggered by software. The LEDC driver handles it in the
background, e.g., when ledc_timer_config() or ledc_timer_set() is called.
For additional details regarding speed modes, see ESP32 Technical Reference Manual > LED PWM Controller (LEDC)
[PDF].
The LED PWM Controller is designed primarily to drive LEDs. It provides a large flexibility of PWM duty cycle
settings. For instance, the PWM frequency of 5 kHz can have the maximum duty resolution of 13 bits. This means
that the duty can be set anywhere from 0 to 100% with a resolution of ~0.012% (2 ** 13 = 8192 discrete levels of the
LED intensity). Note, however, that these parameters depend on the clock signal clocking the LED PWM Controller
timer which in turn clocks the channel (see timer configuration and the ESP32 Technical Reference Manual > LED
PWM Controller (LEDC) [PDF]).
The LEDC can be used for generating signals at much higher frequencies that are sufficient enough to clock other
devices, e.g., a digital camera module. In this case, the maximum available frequency is 40 MHz with duty resolution
of 1 bit. This means that the duty cycle is fixed at 50% and cannot be adjusted.
The LEDC API is designed to report an error when trying to set a frequency and a duty resolution that exceed the
range of LEDC’s hardware. For example, an attempt to set the frequency to 20 MHz and the duty resolution to 3
bits will result in the following error reported on a serial monitor:
E (196) ledc: requested frequency and duty resolution cannot be achieved, try␣
,→reducing freq_hz or duty_resolution. div_param=128
In such a situation, either the duty resolution or the frequency must be reduced. For example, setting the duty
resolution to 2 will resolve this issue and will make it possible to set the duty cycle at 25% steps, i.e., at 25%, 50%
or 75%.
The LEDC driver will also capture and report attempts to configure frequency / duty resolution combinations that are
below the supported minimum, e.g.:
E (196) ledc: requested frequency and duty resolution cannot be achieved, try␣
,→increasing freq_hz or duty_resolution. div_param=128000000
The duty resolution is normally set using ledc_timer_bit_t. This enumeration covers the range from 10 to 15
bits. If a smaller duty resolution is required (from 10 down to 1), enter the equivalent numeric values directly.
Application Example
The LEDC change duty cycle and fading control example: peripherals/ledc/ledc_fade.
The LEDC basic example: peripherals/ledc/ledc_basic.
API Reference
Header File
• components/driver/include/driver/ledc.h
Functions
Note: Call this function to activate the LEDC updated parameters. After ledc_set_duty, we need to call this
function to update the settings. And the new LEDC parameters don’t take effect until the next PWM cycle.
Note: ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these
functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is
ledc_set_duty_and_update
Parameters
• speed_mode –Select the LEDC channel group with specified speed mode. Note that
not all targets support high speed mode.
• channel –LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from
ledc_channel_t
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Note: This function only routes the LEDC signal to GPIO through matrix, other LEDC resources initialization
are not involved. Please use ledc_channel_config() instead to fully configure a LEDC channel.
Parameters
• gpio_num –The LEDC output gpio
• speed_mode –Select the LEDC channel group with specified speed mode. Note that
not all targets support high speed mode.
• ledc_channel –LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from
ledc_channel_t
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Note: ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these
functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is
ledc_set_duty_and_update
Note: For ESP32, hardware does not support any duty change while a fade operation is running in progress
on that channel. Other duty operations will have to wait until the fade operation has finished.
Parameters
• speed_mode –Select the LEDC channel group with specified speed mode. Note that
not all targets support high speed mode.
• channel –LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from
ledc_channel_t
• duty –Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution) - 1]
• hpoint –Set the LEDC hpoint value(max: 0xfffff)
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Note: ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these
functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is
ledc_set_duty_and_update.
Note: For ESP32, hardware does not support any duty change while a fade operation is running in progress
on that channel. Other duty operations will have to wait until the fade operation has finished.
Parameters
• speed_mode –Select the LEDC channel group with specified speed mode. Note that
not all targets support high speed mode.
• channel –LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from
ledc_channel_t
• duty –Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution) - 1]
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Note: For ESP32, hardware does not support any duty change while a fade operation is running in progress
on that channel. Other duty operations will have to wait until the fade operation has finished.
Parameters
• speed_mode –Select the LEDC channel group with specified speed mode. Note that
not all targets support high speed mode.
• channel –LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from
ledc_channel_t
• duty –Set the start of the gradient duty, the range of duty setting is [0,
(2**duty_resolution) - 1]
• fade_direction –Set the direction of the gradient
• step_num –Set the number of the gradient
• duty_cycle_num –Set how many LEDC tick each time the gradient lasts
• duty_scale –Set gradient change amplitude
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Note: Call ledc_fade_func_install() once before calling this function. Call ledc_fade_start() after this to start
fading.
Note: ledc_set_fade_with_step, ledc_set_fade_with_time and ledc_fade_start are not thread-safe, do not call
these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API
is ledc_set_fade_step_and_start
Note: For ESP32, hardware does not support any duty change while a fade operation is running in progress
on that channel. Other duty operations will have to wait until the fade operation has finished.
Parameters
• speed_mode –Select the LEDC channel group with specified speed mode. Note that
not all targets support high speed mode. ,
Note: Call ledc_fade_func_install() once before calling this function. Call ledc_fade_start() after this to start
fading.
Note: ledc_set_fade_with_step, ledc_set_fade_with_time and ledc_fade_start are not thread-safe, do not call
these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API
is ledc_set_fade_step_and_start
Note: For ESP32, hardware does not support any duty change while a fade operation is running in progress
on that channel. Other duty operations will have to wait until the fade operation has finished.
Parameters
• speed_mode –Select the LEDC channel group with specified speed mode. Note that
not all targets support high speed mode. ,
• channel –LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from
ledc_channel_t
• target_duty –Target duty of fading [0, (2**duty_resolution) - 1]
• max_fade_time_ms –The maximum time of the fading ( ms ).
Returns
• ESP_ERR_INVALID_ARG Parameter error
• ESP_OK Success
• ESP_ERR_INVALID_STATE Fade function not installed.
• ESP_FAIL Fade function init error
Note: Call ledc_fade_func_install() once before calling this function. Call this API right after
ledc_set_fade_with_time or ledc_set_fade_with_step before to start fading.
Note: Starting fade operation with this API is not thread-safe, use with care.
Note: For ESP32, hardware does not support any duty change while a fade operation is running in progress
on that channel. Other duty operations will have to wait until the fade operation has finished.
Parameters
• speed_mode –Select the LEDC channel group with specified speed mode. Note that
not all targets support high speed mode.
• channel –LEDC channel number
• fade_mode –Whether to block until fading done. See ledc_types.h ledc_fade_mode_t
for more info. Note that this function will not return until fading to the target duty if
LEDC_FADE_WAIT_DONE mode is selected.
Returns
• ESP_OK Success
• ESP_ERR_INVALID_STATE Fade function not installed.
• ESP_ERR_INVALID_ARG Parameter error.
Note: For ESP32, hardware does not support any duty change while a fade operation is running in progress
on that channel. Other duty operations will have to wait until the fade operation has finished.
Parameters
• speed_mode –Select the LEDC channel group with specified speed mode. Note that
not all targets support high speed mode.
• channel –LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from
ledc_channel_t
• duty –Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution) - 1]
• hpoint –Set the LEDC hpoint value(max: 0xfffff)
Note: For ESP32, hardware does not support any duty change while a fade operation is running in progress
on that channel. Other duty operations will have to wait until the fade operation has finished.
Parameters
• speed_mode –Select the LEDC channel group with specified speed mode. Note that
not all targets support high speed mode.
Note: For ESP32, hardware does not support any duty change while a fade operation is running in progress
on that channel. Other duty operations will have to wait until the fade operation has finished.
Parameters
• speed_mode –Select the LEDC channel group with specified speed mode. Note that
not all targets support high speed mode.
• channel –LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from
ledc_channel_t
• target_duty –Target duty of fading [0, (2**duty_resolution) - 1]
• scale –Controls the increase or decrease step scale.
• cycle_num –increase or decrease the duty every cycle_num cycles
• fade_mode –choose blocking or non-blocking mode
Returns
• ESP_ERR_INVALID_ARG Parameter error
• ESP_OK Success
• ESP_ERR_INVALID_STATE Fade function not installed.
• ESP_FAIL Fade function init error
Note: The callback is called from an ISR, it must never attempt to block, and any FreeRTOS API called must
be ISR capable.
Parameters
• speed_mode –Select the LEDC channel group with specified speed mode. Note that
not all targets support high speed mode.
• channel –LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from
ledc_channel_t
• cbs –Group of LEDC callback functions
• user_arg –user registered data for the callback function
Returns
• ESP_ERR_INVALID_ARG Parameter error
• ESP_OK Success
Structures
struct ledc_channel_config_t
Configuration parameters of LEDC channel for ledc_channel_config function.
Public Members
int gpio_num
the LEDC output gpio_num, if you want to use gpio16, gpio_num = 16
ledc_mode_t speed_mode
LEDC speed speed_mode, high-speed mode or low-speed mode
ledc_channel_t channel
LEDC channel (0 - 7)
ledc_intr_type_t intr_type
configure interrupt, Fade interrupt enable or Fade interrupt disable
ledc_timer_t timer_sel
Select the timer source of channel (0 - 3)
uint32_t duty
LEDC channel duty, the range of duty setting is [0, (2**duty_resolution)]
int hpoint
LEDC channel hpoint value, the max value is 0xfffff
struct ledc_timer_config_t
Configuration parameters of LEDC Timer timer for ledc_timer_config function.
Public Members
ledc_mode_t speed_mode
LEDC speed speed_mode, high-speed mode or low-speed mode
ledc_timer_bit_t duty_resolution
LEDC channel duty resolution
ledc_timer_t timer_num
The timer source of channel (0 - 3)
uint32_t freq_hz
LEDC timer frequency (Hz)
ledc_clk_cfg_t clk_cfg
Configure LEDC source clock from ledc_clk_cfg_t. Note that LEDC_USE_RTC8M_CLK and
LEDC_USE_XTAL_CLK are non-timer-specific clock sources. You can not have one LEDC timer
uses RTC8M_CLK as the clock source and have another LEDC timer uses XTAL_CLK as its clock
source. All chips except esp32 and esp32s2 do not have timer-specific clock sources, which means clock
source for all timers must be the same one.
struct ledc_cb_param_t
LEDC callback parameter.
Public Members
ledc_cb_event_t event
Event name
uint32_t speed_mode
Speed mode of the LEDC channel group
uint32_t channel
LEDC channel (0 - LEDC_CHANNEL_MAX-1)
uint32_t duty
LEDC current duty of the channel, the range of duty is [0, (2**duty_resolution) - 1]
struct ledc_cbs_t
Group of supported LEDC callbacks.
Public Members
ledc_cb_t fade_cb
LEDC fade_end callback function
Macros
LEDC_APB_CLK_HZ
Frequency of one of the LEDC peripheral clock sources, APB_CLK.
Note: This macro should have no use in your application, we keep it here only for backward compatible
LEDC_REF_CLK_HZ
Frequency of one of the LEDC peripheral clock sources, REF_TICK.
Note: This macro should have no use in your application, we keep it here only for backward compatible
LEDC_ERR_DUTY
LEDC_ERR_VAL
Type Definitions
Enumerations
enum ledc_cb_event_t
LEDC callback event type.
Values:
enumerator LEDC_FADE_END_EVT
LEDC fade end event
Header File
• components/hal/include/hal/ledc_types.h
Enumerations
enum ledc_mode_t
Values:
enumerator LEDC_HIGH_SPEED_MODE
LEDC high speed speed_mode
enumerator LEDC_LOW_SPEED_MODE
LEDC low speed speed_mode
enumerator LEDC_SPEED_MODE_MAX
LEDC speed limit
enum ledc_intr_type_t
Values:
enumerator LEDC_INTR_DISABLE
Disable LEDC interrupt
enumerator LEDC_INTR_FADE_END
Enable LEDC interrupt
enumerator LEDC_INTR_MAX
enum ledc_duty_direction_t
Values:
enumerator LEDC_DUTY_DIR_DECREASE
LEDC duty decrease direction
enumerator LEDC_DUTY_DIR_INCREASE
LEDC duty increase direction
enumerator LEDC_DUTY_DIR_MAX
enum ledc_slow_clk_sel_t
Values:
enumerator LEDC_SLOW_CLK_RTC8M
LEDC low speed timer clock source is 8MHz RTC clock
enumerator LEDC_SLOW_CLK_APB
LEDC low speed timer clock source is 80MHz APB clock
enum ledc_clk_cfg_t
In theory, the following enumeration shall be placed in LEDC driver’s header. However, as the next enu-
meration, ledc_clk_src_t, makes the use of some of these values and to avoid mutual inclusion of the
headers, we must define it here.
Values:
enumerator LEDC_AUTO_CLK
The driver will automatically select the source clock based on the giving resolution and duty parameter
when init the timer
enumerator LEDC_USE_APB_CLK
LEDC timer select APB clock as source clock
enumerator LEDC_USE_RTC8M_CLK
LEDC timer select RTC8M_CLK as source clock. Only for low speed channels and this parameter must
be the same for all low speed channels
enumerator LEDC_USE_REF_TICK
LEDC timer select REF_TICK clock as source clock
enum ledc_clk_src_t
Values:
enumerator LEDC_REF_TICK
LEDC timer clock divided from reference tick (1Mhz)
enumerator LEDC_APB_CLK
LEDC timer clock divided from APB clock (80Mhz)
enumerator LEDC_SCLK
Selecting this value for LEDC_TICK_SEL_TIMER let the hardware take its source clock from
LEDC_APB_CLK_SEL
enum ledc_timer_t
Values:
enumerator LEDC_TIMER_0
LEDC timer 0
enumerator LEDC_TIMER_1
LEDC timer 1
enumerator LEDC_TIMER_2
LEDC timer 2
enumerator LEDC_TIMER_3
LEDC timer 3
enumerator LEDC_TIMER_MAX
enum ledc_channel_t
Values:
enumerator LEDC_CHANNEL_0
LEDC channel 0
enumerator LEDC_CHANNEL_1
LEDC channel 1
enumerator LEDC_CHANNEL_2
LEDC channel 2
enumerator LEDC_CHANNEL_3
LEDC channel 3
enumerator LEDC_CHANNEL_4
LEDC channel 4
enumerator LEDC_CHANNEL_5
LEDC channel 5
enumerator LEDC_CHANNEL_6
LEDC channel 6
enumerator LEDC_CHANNEL_7
LEDC channel 7
enumerator LEDC_CHANNEL_MAX
enum ledc_timer_bit_t
Values:
enumerator LEDC_TIMER_1_BIT
LEDC PWM duty resolution of 1 bits
enumerator LEDC_TIMER_2_BIT
LEDC PWM duty resolution of 2 bits
enumerator LEDC_TIMER_3_BIT
LEDC PWM duty resolution of 3 bits
enumerator LEDC_TIMER_4_BIT
LEDC PWM duty resolution of 4 bits
enumerator LEDC_TIMER_5_BIT
LEDC PWM duty resolution of 5 bits
enumerator LEDC_TIMER_6_BIT
LEDC PWM duty resolution of 6 bits
enumerator LEDC_TIMER_7_BIT
LEDC PWM duty resolution of 7 bits
enumerator LEDC_TIMER_8_BIT
LEDC PWM duty resolution of 8 bits
enumerator LEDC_TIMER_9_BIT
LEDC PWM duty resolution of 9 bits
enumerator LEDC_TIMER_10_BIT
LEDC PWM duty resolution of 10 bits
enumerator LEDC_TIMER_11_BIT
LEDC PWM duty resolution of 11 bits
enumerator LEDC_TIMER_12_BIT
LEDC PWM duty resolution of 12 bits
enumerator LEDC_TIMER_13_BIT
LEDC PWM duty resolution of 13 bits
enumerator LEDC_TIMER_14_BIT
LEDC PWM duty resolution of 14 bits
enumerator LEDC_TIMER_15_BIT
LEDC PWM duty resolution of 15 bits
enumerator LEDC_TIMER_16_BIT
LEDC PWM duty resolution of 16 bits
enumerator LEDC_TIMER_17_BIT
LEDC PWM duty resolution of 17 bits
enumerator LEDC_TIMER_18_BIT
LEDC PWM duty resolution of 18 bits
enumerator LEDC_TIMER_19_BIT
LEDC PWM duty resolution of 19 bits
enumerator LEDC_TIMER_20_BIT
LEDC PWM duty resolution of 20 bits
enumerator LEDC_TIMER_BIT_MAX
enum ledc_fade_mode_t
Values:
enumerator LEDC_FADE_NO_WAIT
LEDC fade function will return immediately
enumerator LEDC_FADE_WAIT_DONE
LEDC fade function will block until fading to the target duty
enumerator LEDC_FADE_MAX
ESP32 has two MCPWM units which can be used to control different types of motors. Each unit has three pairs of
PWM outputs.
Further in documentation the outputs of a single unit are labeled PWMxA / PWMxB.
More detailed block diagram of the MCPWM unit is shown below. Each A/B pair may be clocked by any one of
the three timers Timer 0, 1 and 2. The same timer may be used to clock more than one pair of PWM outputs. Each
unit is also able to collect inputs such as SYNC SIGNALS, detect FAULT SIGNALS like motor overcurrent or
overvoltage, as well as obtain feedback with CAPTURE SIGNALS on e.g. a rotor position.
Description of this API starts with configuration of MCPWM’s Timer and Generator submodules to provide
the basic motor control functionality. Then it discusses more advanced submodules and functionalities of a Fault
Handler, signal Capture and Carrier.
Contents
Configure
The scope of configuration depends on the motor type, in particular how many outputs and inputs are required, and
what will be the sequence of signals to drive the motor.
In this case we will describe a simple configuration to control a brushed DC motor that is using only some of the
available MCPWM’s resources. An example circuit is shown below. It includes a H-Bridge to switch polarization
of a voltage applied to the motor (M) and to provide sufficient current to drive it.
Operate
To operate a motor connected to the MCPWM unit, e.g. turn it left or right, or vary the speed, we should apply some
control signals to the unit’s outputs. The outputs are organized into three pairs. Within a pair they are labeled“A”
and “B”and each driven by a submodule called an “Generator”. To provide a PWM signal, the Operator itself,
which contains two Generator, should be clocked by one of three available Timers. To make the API simpler, each
Timer is automatically associated by the API to drive an Operator of the same index, e.g. Timer 0 is associated with
Operator 0.
There are the following basic ways to control the outputs:
• We can drive particular signal steady high or steady low with function mcpwm_set_signal_high() or
mcpwm_set_signal_low(). This will make the motor to turn with a maximum speed or stop. Depending
on selected output A or B the motor will rotate either right or left.
• Another option is to drive the outputs with the PWM signal by calling mcpwm_start() or
mcpwm_stop(). The motor speed will be proportional to the PWM duty.
• To vary PWM’s duty call mcpwm_set_duty() and provide the duty value in %. Optionally, you
may call mcpwm_set_duty_in_us(), if you prefer to set the duty in microseconds. Checking of cur-
rently set value is possible by calling mcpwm_get_duty(). Phase of the PWM signal may be altered
by calling mcpwm_set_duty_type(). The duty is set individually for each A and B output using
mcpwm_generator_t in specific function calls. The duty value refers either to high or low output signal
duration. This is configured when calling mcpwm_init(), as discussed in section Configure, and selecting
one of options from mcpwm_duty_type_t.
Adjust
There are couple of ways to adjust a signal on the outputs and changing how the motor operates.
• Set specific PWM frequency by calling mcpwm_set_frequency(). This may be required to adjust to
electrical or mechanical characteristics of particular motor and driver. To check what frequency is set, use
function mcpwm_get_frequency().
• Introduce a dead time between outputs A and B when they are changing the state to reverse direction of the
motor rotation. This is to make up for on/off switching delay of the motor driver FETs. The dead time options
are defined in mcpwm_deadtime_type_t and enabled by calling mcpwm_deadtime_enable(). To
disable this functionality call mcpwm_deadtime_disable().
• Synchronize outputs of operator submodules, e.g. to get raising edge of PWM0A/B and PWM1A/B to start ex-
actly at the same time, or shift them between each other by a given phase. Synchronization is triggered by SYNC
SIGNALS shown on the block diagram of the MCPWM above, and defined in mcpwm_sync_signal_t.
To attach the signal to a GPIO call mcpwm_gpio_init(). You can then enable synchronization with func-
tion mcpwm_sync_configure(). As input parameters provide MCPWM unit, timer to synchronize, the
synchronization signal and a phase to delay the timer.
Note: Synchronization signals are referred to using two different enumerations. First one
mcpwm_io_signals_t is used together with function mcpwm_gpio_init() when selecting a GPIO
as the signal input source. The second one mcpwm_sync_signal_t is used when enabling or disabling
synchronization with mcpwm_sync_configure() or mcpwm_sync_disable().
• Vary the pattern of the A/B output signals by getting MCPWM counters to count up, down and up/down
(automatically changing the count direction). Respective configuration is done when calling mcpwm_init(),
as discussed in section Configure, and selecting one of counter types from mcpwm_counter_type_t. For
explanation of how A/B PWM output signals are generated, see ESP32 Technical Reference Manual > Motor
Control PWM (MCPWM) [PDF].
Synchronize
Each PWM timer has a synchronization input and a synchronization output. The synchronization input can be selected
from other timers’synchronization outputs or GPIO signals via the GPIO matrix. Timer’s synchronization signal
can be generated from either the input sync signal or when the count value reaches peak/zero. Thus, the PWM timers
can be chained together with their phase-locked. During synchronization, the PWM timer clock prescaler will reset
its counter in order to synchronize the PWM timer clock.
The functionality is enabled in following steps:
1. Make sure the PWM timer and operator are already configured so that sync will inherit its config (count mode,
freq and duty).
2. Enabling sync input of the timer by invoking mcpwm_sync_configure(), selecting desired signal input
from mcpwm_sync_signal_t, and setting the desired phase range from 0 to 999 which is mapped to
0%~99.9%. 0 means zero phase is applied and output is fired at the same time. And selecting desired counting
direction.
3. Enabling one of sync event source from another timer or from external GPIO input.
To sync with another timer:
Enabling sync output of another timer by invoking mcpwm_set_timer_sync_output() and selecting desired
event to generate sync output from mcpwm_timer_sync_trigger_t.
To sync with GPIO positive edge input (negative edge requires mcpwm_sync_invert_gpio_synchro()):
Configuring GPIOs to act as the sync signal inputs by calling functions mcpwm_gpio_init() or
mcpwm_set_pin(), which were described in section Configure.
It’s normal condition that chained sync signal may have tens or even hundreds of nanoseconds of delay between
each timer output due to hardware limitation. To sync two timers accurately it is required to have the third timer
occupied to produce sync event that can be consumed parallel by other two timer, so that those two timer will have
no delay between each other but have the same delay between the timer which provides events. Another solution is
introducing an external GPIO event source so that all three timers can be synced together with no delay.
If not required anymore, the capture functionality may be disabled with mcpwm_sync_disable().
Capture
One of requirements of BLDC (Brushless DC, see figure below) motor control is sensing of the rotor position. To
facilitate this task each MCPWM unit provides three sensing inputs together with dedicated hardware. The hardware
is able to detect the input signal’s edge and measure time between signals. As result the control software is simpler
and the CPU power may be used for other tasks.
The capture functionality may be used for other types of motors or tasks. The functionality is enabled in two steps:
1. Configuration of GPIOs to act as the capture signal inputs by calling functions mcpwm_gpio_init() or
mcpwm_set_pin(), that were described in section Configure.
2. Enabling of the functionality itself by invoking mcpwm_capture_enable_channel(), selecting desired
signal input from mcpwm_capture_channel_id_t, setting the signal edge, signal count prescaler and
user callback within mcpwm_capture_config_t
Within the second step above a 32-bit capture timer is enabled. The timer runs continuously driven by the APB
clock. The clock frequency is typically 80 MHz. On each capture event the capture timer’s value is stored in time-
stamp register that may be then checked by calling mcpwm_capture_signal_get_value(). The edge of
the last signal may be checked with mcpwm_capture_signal_get_edge(). Those data are also provided
inside callback function as event data cap_event_data_t
If not required anymore, the capture functionality may be disabled with
mcpwm_capture_disable_channel().
Capture prescale is different from other modules as it is applied to the input signal, not the timer source. Prescaler
has maintained its own level state with the initial value set to low and is detecting the positive edge of the input
signal to change its internal state. That means if two pairs of positive and negative edges are passed to input, the
prescaler’s internal state will change twice. ISR will report on this internal state change, not the input signal.
For example, setting prescale to 2 will generate ISR callback on each positive edge of input if both edge is se-
lected via mcpwm_capture_config_t. Or each 2 positive edges of input if only one edge is selected though
mcpwm_capture_config_t.
Fault Handler
Each unit of the MCPWM is able to sense external signals with information about failure of the motor, the motor
driver or any other device connected to the MCPWM. There are three fault inputs per unit that may be routed to user
selectable GPIOs. The MCPWM may be configured to perform one of four predefined actions on A/B outputs when
a fault signal is received:
• lock current state of the output
• set the output low
• set the output high
• toggle the output
The user should determine possible failure modes of the motor and what action should be performed on detection of
particular fault, e.g. drive all outputs low for a brushed motor, or lock current state for a stepper motor, etc. As result
of this action the motor should be put into a safe state to reduce likelihood of a damage caused by the fault.
The fault handler functionality is enabled in two steps:
1. Configuration of GPIOs to act as fault signal inputs. This is done in analogous way as described for
capture signals in section above. It includes setting the signal level to trigger the fault as defined in
mcpwm_fault_input_level_t.
2. Initialization of the fault handler by calling either mcpwm_fault_set_oneshot_mode() or
mcpwm_fault_set_cyc_mode(). These functions set the mode that MCPWM should operate once
fault signal becomes inactive. There are two modes possible:
• State of MCPWM unit will be locked until reset - mcpwm_fault_set_oneshot_mode().
• The MCPWM will resume operation once fault signal becoming inactive -
mcpwm_fault_set_cyc_mode().
The function call parameters include selection of one of three fault inputs defined
in mcpwm_fault_signal_t and specific action on outputs A and B defined in
mcpwm_action_on_pwmxa_t and mcpwm_action_on_pwmxb_t.
Particular fault signal may be disabled at the runtime by calling mcpwm_fault_deinit().
Carrier
The MCPWM has a carrier submodule used if galvanic isolation from the motor driver is required by passing the A/B
output signals through transformers. Any of A and B output signals may be at 100% duty and not changing whenever
motor is required to run steady at the full load. Coupling of non alternating signals with a transformer is problematic,
so the signals are modulated by the carrier submodule to create an AC waveform, to make the coupling possible.
To use the carrier submodule, it should be first initialized by calling mcpwm_carrier_init(). The carrier
parameters are defined in mcpwm_carrier_config_t structure invoked within the function call. Then the
carrier functionality may be enabled by calling mcpwm_carrier_enable().
The carrier parameters may be then altered at a runtime by calling dedicated functions to change in-
dividual fields of the mcpwm_carrier_config_t structure, like mcpwm_carrier_set_period(),
mcpwm_carrier_set_duty_cycle(), mcpwm_carrier_output_invert(), etc.
This includes enabling and setting duration of the first pulse of the career with
mcpwm_carrier_oneshot_mode_enable(). For more details, see ESP32 Technical Reference Man-
ual > Motor Control PWM (MCPWM) > PWM Carrier Submodule [PDF].
To disable carrier functionality call mcpwm_carrier_disable().
Interrupts
Resolution
The default resolution for MCPWM group and MCPWM timer are configured to 10MHz and 1MHz
in mcpwm_init(), which might be not enough for some applications. The driver also provides two
APIs that can be used to override the default resolution: mcpwm_group_set_resolution() and
mcpwm_timer_set_resolution().
Note that, these two APIs won’t update the frequency and duty automatically, to achieve that, one has to call
mcpwm_set_frequency() and mcpwm_set_duty() accordingly.
To get PWM pulse that is below 15Hz, please set the resolution to a lower value. For high frequency PWM with
limited step range, please set them with higher value.
Application Example
API Reference
Header File
• components/hal/include/hal/mcpwm_types.h
Type Definitions
Enumerations
enum mcpwm_timer_direction_t
MCPWM timer count direction.
Values:
enumerator MCPWM_TIMER_DIRECTION_UP
Counting direction: Increase
enumerator MCPWM_TIMER_DIRECTION_DOWN
Counting direction: Decrease
enum mcpwm_timer_event_t
MCPWM timer events.
Values:
enumerator MCPWM_TIMER_EVENT_EMPTY
MCPWM timer counts to zero (i.e. counter is empty)
enumerator MCPWM_TIMER_EVENT_FULL
MCPWM timer counts to peak (i.e. counter is full)
enumerator MCPWM_TIMER_EVENT_INVALID
MCPWM timer invalid event
enum mcpwm_timer_count_mode_t
MCPWM timer count modes.
Values:
enumerator MCPWM_TIMER_COUNT_MODE_PAUSE
MCPWM timer paused
enumerator MCPWM_TIMER_COUNT_MODE_UP
MCPWM timer counting up
enumerator MCPWM_TIMER_COUNT_MODE_DOWN
MCPWM timer counting down
enumerator MCPWM_TIMER_COUNT_MODE_UP_DOWN
MCPWM timer counting up and down
enum mcpwm_timer_start_stop_cmd_t
MCPWM timer commands, specify the way to start or stop the timer.
Values:
enumerator MCPWM_TIMER_STOP_EMPTY
MCPWM timer stops when next count reaches zero
enumerator MCPWM_TIMER_STOP_FULL
MCPWM timer stops when next count reaches peak
enumerator MCPWM_TIMER_START_NO_STOP
MCPWM timer starts couting, and don’t stop until received stop command
enumerator MCPWM_TIMER_START_STOP_EMPTY
MCPWM timer starts counting and stops when next count reaches zero
enumerator MCPWM_TIMER_START_STOP_FULL
MCPWM timer starts counting and stops when next count reaches peak
enum mcpwm_generator_action_t
MCPWM generator actions.
Values:
enumerator MCPWM_GEN_ACTION_KEEP
Generator action: Keep the same level
enumerator MCPWM_GEN_ACTION_LOW
Generator action: Force to low level
enumerator MCPWM_GEN_ACTION_HIGH
Generator action: Force to high level
enumerator MCPWM_GEN_ACTION_TOGGLE
Generator action: Toggle level
enum mcpwm_operator_brake_mode_t
MCPWM operator brake mode.
Values:
enumerator MCPWM_OPER_BRAKE_MODE_CBC
Brake mode: CBC (cycle by cycle)
enumerator MCPWM_OPER_BRAKE_MODE_OST
Brake mode, OST (one shot)
enumerator MCPWM_OPER_BRAKE_MODE_INVALID
MCPWM operator invalid brake mode
enum mcpwm_capture_edge_t
MCPWM capture edge.
Values:
enumerator MCPWM_CAP_EDGE_POS
Capture on the positive edge
enumerator MCPWM_CAP_EDGE_NEG
Capture on the negative edge
Header File
• components/driver/include/driver/mcpwm.h
Functions
esp_err_t mcpwm_gpio_init(mcpwm_unit_t mcpwm_num, mcpwm_io_signals_t io_signal, int gpio_num)
This function initializes each gpio signal for MCPWM.
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• io_signal –set MCPWM signals, each MCPWM unit has 6 output(MCPWMXA,
MCPWMXB) and 9 input(SYNC_X, FAULT_X, CAP_X) ‘X’is timer_num(0-2)
• gpio_num –set this to configure gpio for MCPWM, if you want to use gpio16, gpio_num
= 16
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
esp_err_t mcpwm_set_pin(mcpwm_unit_t mcpwm_num, const mcpwm_pin_config_t *mcpwm_pin)
Initialize MCPWM gpio structure.
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• mcpwm_pin –MCPWM pin structure
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Note: The default resolution configured for MCPWM group and timer are 160M / 16 = 10M and
10M / 10 = 1M The default resolution can be changed by calling mcpwm_group_set_resolution() and
mcpwm_timer_set_resolution(), before calling this function.
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• timer_num –set timer number(0-2) of MCPWM, each MCPWM unit has 3 timers.
• mcpwm_conf –configure structure mcpwm_config_t
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Note: This will override default resolution of group(=10,000,000). This WILL NOT automatically update
frequency and duty. Call mcpwm_set_frequency() and mcpwm_set_duty() manually to set them back.
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• resolution –set expected frequency resolution
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Note: This WILL override default resolution of timer(=1,000,000). This WILL NOT automatically update
frequency and duty. Call mcpwm_set_frequency() and mcpwm_set_duty() manually to set them back.
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• timer_num –set timer number(0-2) of MCPWM, each MCPWM unit has 3 timers
• resolution –set expected frequency resolution
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Note: Call this function every time after mcpwm_set_signal_high or mcpwm_set_signal_low to resume with
previously set duty cycle
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• timer_num –set timer number(0-2) of MCPWM, each MCPWM unit has 3 timers
• gen –set the generator(MCPWMXA/MCPWMXB), ‘x’is operator number selected
• duty_type –set active low or active high duty type
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Parameters
Set oneshot mode on fault detection, once fault occur in oneshot mode reset is required to resume MCPWM
signals.
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• timer_num –set timer number(0-2) of MCPWM, each MCPWM unit has 3 timers
• fault_sig –set the fault pin, which needs to be enabled for oneshot mode
• action_on_pwmxa –action to be taken on MCPWMXA when fault occurs, either no
change or high or low or toggle
• action_on_pwmxb –action to be taken on MCPWMXB when fault occurs, either no
change or high or low or toggle
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• timer_num –set timer number(0-2) of MCPWM, each MCPWM unit has 3 timers
• fault_sig –set the fault pin, which needs to be enabled for cyc mode
• action_on_pwmxa –action to be taken on MCPWMXA when fault occurs, either no
change or high or low or toggle
• action_on_pwmxb –action to be taken on MCPWMXB when fault occurs, either no
change or high or low or toggle
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
esp_err_t mcpwm_capture_disable_channel(mcpwm_unit_t mcpwm_num,
mcpwm_capture_channel_id_t cap_channel)
Disable capture channel.
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• cap_channel –capture channel, which needs to be disabled
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
uint32_t mcpwm_capture_signal_get_value(mcpwm_unit_t mcpwm_num, mcpwm_capture_signal_t
cap_sig)
Get capture value.
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• cap_sig –capture channel on which value is to be measured
Returns Captured value
uint32_t mcpwm_capture_signal_get_edge(mcpwm_unit_t mcpwm_num, mcpwm_capture_signal_t
cap_sig)
Get edge of capture signal.
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• cap_sig –capture channel of whose edge is to be determined
Returns Capture signal edge: 1 - positive edge, 2 - negtive edge
esp_err_t mcpwm_sync_configure(mcpwm_unit_t mcpwm_num, mcpwm_timer_t timer_num, const
mcpwm_sync_config_t *sync_conf)
Initialize sync submodule and sets the signal that will cause the timer be loaded with pre-defined value.
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• timer_num –set timer number(0-2) of MCPWM, each MCPWM unit has 3 timers
• sync_conf –sync configuration on this timer
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
esp_err_t mcpwm_sync_disable(mcpwm_unit_t mcpwm_num, mcpwm_timer_t timer_num)
Disable sync submodule on given timer.
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• timer_num –set timer number(0-2) of MCPWM, each MCPWM unit has 3 timers
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
esp_err_t mcpwm_set_timer_sync_output(mcpwm_unit_t mcpwm_num, mcpwm_timer_t timer_num,
mcpwm_timer_sync_trigger_t trigger)
Set sync output on given timer Configures what event triggers MCPWM timer to output a sync signal.
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• timer_num –set timer number(0-2) of MCPWM, each MCPWM unit has 3 timers
• trigger –set the trigger that will cause the timer to generate a software sync signal.
Specifically, MCPWM_SWSYNC_SOURCE_DISABLED will disable the timer from gen-
erating sync signal.
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
esp_err_t mcpwm_timer_trigger_soft_sync(mcpwm_unit_t mcpwm_num, mcpwm_timer_t timer_num)
Trigger a software sync event and sends it to a specific timer.
Note: This software sync event will have the same effect as hw one, except that:
• On esp32s3 the soft sync event can be routed to its output if MCPWM_SWSYNC_SOURCE_SYNCIN is
selected via mcpwm_set_timer_sync_output()
• On esp32 there is no such behavior and soft sync event will only take effect on this timer and can not be
propagated to others.
Parameters
• mcpwm_num –set MCPWM unit(0-1)
• timer_num –set timer number(0-2) of MCPWM, each MCPWM unit has 3 timers
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Function pointer error.
Structures
struct mcpwm_pin_config_t
pin number for MCPWM
Public Members
int mcpwm0a_out_num
MCPWM0A out pin
int mcpwm0b_out_num
MCPWM0A out pin
int mcpwm1a_out_num
MCPWM0A out pin
int mcpwm1b_out_num
MCPWM0A out pin
int mcpwm2a_out_num
MCPWM0A out pin
int mcpwm2b_out_num
MCPWM0A out pin
int mcpwm_sync0_in_num
SYNC0 in pin
int mcpwm_sync1_in_num
SYNC1 in pin
int mcpwm_sync2_in_num
SYNC2 in pin
int mcpwm_fault0_in_num
FAULT0 in pin
int mcpwm_fault1_in_num
FAULT1 in pin
int mcpwm_fault2_in_num
FAULT2 in pin
int mcpwm_cap0_in_num
CAP0 in pin
int mcpwm_cap1_in_num
CAP1 in pin
int mcpwm_cap2_in_num
CAP2 in pin
struct cap_event_data_t
event data that will be passed into ISR callback
Public Members
mcpwm_capture_on_edge_t cap_edge
Which signal edge is detected
uint32_t cap_value
Corresponding timestamp when event occurs. Clock rate = APB(usually 80M)
struct mcpwm_config_t
MCPWM config structure.
Public Members
uint32_t frequency
Set frequency of MCPWM in Hz
float cmpr_a
Set % duty cycle for operator a(MCPWMXA), i.e for 62.3% duty cycle, duty_a = 62.3
float cmpr_b
Set % duty cycle for operator b(MCPWMXB), i.e for 48% duty cycle, duty_b = 48.0
mcpwm_duty_type_t duty_mode
Set type of duty cycle
mcpwm_counter_type_t counter_mode
Set type of MCPWM counter
struct mcpwm_carrier_config_t
MCPWM carrier configuration structure.
Public Members
uint8_t carrier_period
Set carrier period = (carrier_period + 1)*800ns, carrier_period should be < 16
uint8_t carrier_duty
Set carrier duty cycle, carrier_duty should be less than 8 (increment every 12.5%)
uint8_t pulse_width_in_os
Set pulse width of first pulse in one shot mode = (carrier period)*(pulse_width_in_os + 1), should be less
then 16
mcpwm_carrier_out_ivt_t carrier_ivt_mode
Invert output of carrier
struct mcpwm_capture_config_t
MCPWM config capture structure.
Public Members
mcpwm_capture_on_edge_t cap_edge
Set capture edge
uint32_t cap_prescale
Prescale of capture signal, ranging from 1 to 256
cap_isr_cb_t capture_cb
User defined capture event callback, running under interrupt context
void *user_data
User defined ISR callback function args
struct mcpwm_sync_config_t
MCPWM config sync structure.
Public Members
mcpwm_sync_signal_t sync_sig
Set sync input signal that will cause timer to sync
uint32_t timer_val
Counter value to be set after sync, in 0 ~ 999, unit: 1 / 1000 * peak
mcpwm_timer_direction_t count_direction
Counting direction to be set after sync
Macros
MCPWM_OPR_A
Deprecated:
MCPWM_OPR_B
Deprecated:
MCPWM_OPR_MAX
Deprecated:
MCPWM_SELCT_SYNC0
MCPWM_SELCT_SYNC1
MCPWM_SELCT_SYNC2
MCPWM_NO_CHANGE_IN_MCPWMXA
Deprecated:
No change in MCPWMXA output
MCPWM_FORCE_MCPWMXA_LOW
Deprecated:
Make MCPWMXA output low
MCPWM_FORCE_MCPWMXA_HIGH
Deprecated:
Make MCPWMXA output high
MCPWM_TOG_MCPWMXA
Deprecated:
Make MCPWMXA output toggle
MCPWM_NO_CHANGE_IN_MCPWMXB
Deprecated:
No change in MCPWMXB output
MCPWM_FORCE_MCPWMXB_LOW
Deprecated:
Make MCPWMXB output low
MCPWM_FORCE_MCPWMXB_HIGH
Deprecated:
Make MCPWMXB output high
MCPWM_TOG_MCPWMXB
Deprecated:
Make MCPWMXB output toggle
Type Definitions
Deprecated:
Deprecated:
MCPWM select action to be taken on MCPWMXA when fault occurs
Deprecated:
MCPWM select action to be taken on MCPWMXB when fault occurs
Note: Since this an ISR callback so do not do anything that may block and call APIs that is designed to be
used within ISR(usually has ‘_ISR’postfix)
Param edata Capture event data, contains capture edge and capture value, fed by the driver
Param user_data User registered data, passed from mcpwm_capture_config_t
Return Whether a task switch is needed after the callback function returns, this is usually due to
the callback wakes up some high priority task.
Enumerations
enum mcpwm_io_signals_t
IO signals for the MCPWM.
Values:
enumerator MCPWM0A
PWM0A output pin
enumerator MCPWM0B
PWM0B output pin
enumerator MCPWM1A
PWM1A output pin
enumerator MCPWM1B
PWM1B output pin
enumerator MCPWM2A
PWM2A output pin
enumerator MCPWM2B
PWM2B output pin
enumerator MCPWM_SYNC_0
SYNC0 input pin
enumerator MCPWM_SYNC_1
SYNC1 input pin
enumerator MCPWM_SYNC_2
SYNC2 input pin
enumerator MCPWM_FAULT_0
FAULT0 input pin
enumerator MCPWM_FAULT_1
FAULT1 input pin
enumerator MCPWM_FAULT_2
FAULT2 input pin
enumerator MCPWM_CAP_0
CAP0 input pin
enumerator MCPWM_CAP_1
CAP1 input pin
enumerator MCPWM_CAP_2
CAP2 input pin
enum mcpwm_unit_t
Select MCPWM unit.
Values:
enumerator MCPWM_UNIT_0
MCPWM unit0 selected
enumerator MCPWM_UNIT_1
MCPWM unit1 selected
enumerator MCPWM_UNIT_MAX
Max number of MCPWM units
enum mcpwm_timer_t
Select MCPWM timer.
Values:
enumerator MCPWM_TIMER_0
Select MCPWM timer0
enumerator MCPWM_TIMER_1
Select MCPWM timer1
enumerator MCPWM_TIMER_2
Select MCPWM timer2
enumerator MCPWM_TIMER_MAX
Max number of timers in a unit
enum mcpwm_generator_t
Select MCPWM operator.
Values:
enumerator MCPWM_GEN_A
Select MCPWMXA, where ‘X’is operator number
enumerator MCPWM_GEN_B
Select MCPWMXB, where ‘X’is operator number
enumerator MCPWM_GEN_MAX
Num of generators to each operator of MCPWM
enum mcpwm_carrier_out_ivt_t
MCPWM carrier output inversion, high frequency carrier signal active with MCPWM signal is high.
Values:
enumerator MCPWM_CARRIER_OUT_IVT_DIS
Enable carrier output inversion
enumerator MCPWM_CARRIER_OUT_IVT_EN
Disable carrier output inversion
enum mcpwm_fault_signal_t
MCPWM select fault signal input.
Values:
enumerator MCPWM_SELECT_F0
Select F0 as input
enumerator MCPWM_SELECT_F1
Select F1 as input
enumerator MCPWM_SELECT_F2
Select F2 as input
enum mcpwm_sync_signal_t
MCPWM select sync signal input.
Values:
enumerator MCPWM_SELECT_NO_INPUT
No sync input selected
enumerator MCPWM_SELECT_TIMER0_SYNC
Select software sync signal from timer0 as input
enumerator MCPWM_SELECT_TIMER1_SYNC
Select software sync signal from timer1 as input
enumerator MCPWM_SELECT_TIMER2_SYNC
Select software sync signal from timer2 as input
enumerator MCPWM_SELECT_GPIO_SYNC0
Select GPIO SYNC0 as input
enumerator MCPWM_SELECT_GPIO_SYNC1
Select GPIO SYNC1 as input
enumerator MCPWM_SELECT_GPIO_SYNC2
Select GPIO SYNC2 as input
enum mcpwm_timer_sync_trigger_t
MCPWM timer sync event trigger.
Values:
enumerator MCPWM_SWSYNC_SOURCE_SYNCIN
the input sync signal will be routed to its sync output path
enumerator MCPWM_SWSYNC_SOURCE_TEZ
sync signal generated when timer counts to zero
enumerator MCPWM_SWSYNC_SOURCE_TEP
sync signal generated when timer counts to peak
enumerator MCPWM_SWSYNC_SOURCE_DISABLED
timer does not generate sync signals
enum mcpwm_fault_input_level_t
MCPWM select triggering level of fault signal.
Values:
enumerator MCPWM_LOW_LEVEL_TGR
Fault condition occurs when fault input signal goes from high to low
enumerator MCPWM_HIGH_LEVEL_TGR
Fault condition occurs when fault input signal goes low to high
enum mcpwm_capture_on_edge_t
MCPWM select capture starts from which edge.
Values:
enumerator MCPWM_NEG_EDGE
Capture the negative edge
enumerator MCPWM_POS_EDGE
Capture the positive edge
enumerator MCPWM_BOTH_EDGE
Capture both edges
enum mcpwm_counter_type_t
Select type of MCPWM counter.
Values:
enumerator MCPWM_FREEZE_COUNTER
Counter freeze
enumerator MCPWM_UP_COUNTER
For asymmetric MCPWM
enumerator MCPWM_DOWN_COUNTER
For asymmetric MCPWM
enumerator MCPWM_UP_DOWN_COUNTER
For symmetric MCPWM, frequency is half of MCPWM frequency set
enumerator MCPWM_COUNTER_MAX
Maximum counter mode
enum mcpwm_duty_type_t
Select type of MCPWM duty cycle mode.
Values:
enumerator MCPWM_DUTY_MODE_0
Active high duty, i.e. duty cycle proportional to high time for asymmetric MCPWM
enumerator MCPWM_DUTY_MODE_1
Active low duty, i.e. duty cycle proportional to low time for asymmetric MCPWM, out of phase(inverted)
MCPWM
enumerator MCPWM_HAL_GENERATOR_MODE_FORCE_LOW
enumerator MCPWM_HAL_GENERATOR_MODE_FORCE_HIGH
enumerator MCPWM_DUTY_MODE_MAX
Num of duty cycle modes
enum mcpwm_deadtime_type_t
MCPWM deadtime types, used to generate deadtime, RED refers to rising edge delay and FED refers to falling
edge delay.
Values:
enumerator MCPWM_DEADTIME_BYPASS
Bypass the deadtime
enumerator MCPWM_BYPASS_RED
MCPWMXA Out = MCPWMXA In with no delay, MCPWMXB Out = MCPWMXA In with falling
edge delay
enumerator MCPWM_BYPASS_FED
MCPWMXA Out = MCPWMXA In with rising edge delay, MCPWMXB Out = MCPWMXB In with
no delay
enumerator MCPWM_ACTIVE_HIGH_MODE
MCPWMXA Out = MCPWMXA In with rising edge delay, MCPWMXB Out = MCPWMXA In with
falling edge delay
enumerator MCPWM_ACTIVE_LOW_MODE
MCPWMXA Out = MCPWMXA In with compliment of rising edge delay, MCPWMXB Out = MCP-
WMXA In with compliment of falling edge delay
enumerator MCPWM_ACTIVE_HIGH_COMPLIMENT_MODE
MCPWMXA Out = MCPWMXA In with rising edge delay, MCPWMXB = MCPWMXA In with com-
pliment of falling edge delay
enumerator MCPWM_ACTIVE_LOW_COMPLIMENT_MODE
MCPWMXA Out = MCPWMXA In with compliment of rising edge delay, MCPWMXB Out = MCP-
WMXA In with falling edge delay
enumerator MCPWM_ACTIVE_RED_FED_FROM_PWMXA
MCPWMXA Out = MCPWMXB Out = MCPWMXA In with rising edge delay as well as falling edge
delay
enumerator MCPWM_ACTIVE_RED_FED_FROM_PWMXB
MCPWMXA Out = MCPWMXB Out = MCPWMXB In with rising edge delay as well as falling edge
delay
enumerator MCPWM_DEADTIME_TYPE_MAX
Maximum number of supported dead time modes
enum mcpwm_output_action_t
MCPWM select action to be taken on the output when event happens.
Values:
enumerator MCPWM_ACTION_NO_CHANGE
No change in the output
enumerator MCPWM_ACTION_FORCE_LOW
Make output low
enumerator MCPWM_ACTION_FORCE_HIGH
Make output high
enumerator MCPWM_ACTION_TOGGLE
Make output toggle
enum mcpwm_capture_signal_t
MCPWM select capture signal input.
Values:
enumerator MCPWM_SELECT_CAP0
Select CAP0 as input
enumerator MCPWM_SELECT_CAP1
Select CAP1 as input
enumerator MCPWM_SELECT_CAP2
Select CAP2 as input
Introduction
The PCNT (Pulse Counter) module is designed to count the number of rising and/or falling edges of input signals.
The ESP32 contains multiple pulse counter units in the module.1 Each unit is in effect an independent counter with
multiple channels, where each channel can increment/decrement the counter on a rising/falling edge. Furthermore,
each channel can be configured separately.
PCNT channels can react to signals of edge type and level type, however for simple applications, detecting the edge
signal is usually sufficient. PCNT channels can be configured react to both pulse edges (i.e., rising and falling edge),
and can be configured to increase, decrease or do nothing to the unit’s counter on each edge. The level signal is the
so-called control signal, which is used to control the counting mode of the edge signals that are attached to the same
channel. By combining the usage of both edge and level signals, a PCNT unit can act as a quadrature decoder.
Besides that, PCNT unit is equipped with a separate glitch filter, which is helpful to remove noise from the signal.
Typically, a PCNT module can be used in scenarios like:
• Calculate periodic signal’s frequency by counting the pulse numbers within a time slice
• Decode quadrature signals into speed and direction
Functional Overview
Description of the PCNT functionality is divided into into the following sections:
• Resource Allocation - covers how to allocate PCNT units and channels with properly set of configurations. It
also covers how to recycle the resources when they finished working.
• Set Up Channel Actions - covers how to configure the PCNT channel to behave on different signal edges and
levels.
• Watch Points - describes how to configure PCNT watch points (i.e., tell PCNT unit to trigger an event when
the count reaches a certain value).
• Register Event Callbacks - describes how to hook user specific code to the watch point event callback function.
• Set Glitch Filter - describes how to enable and set the timing parameters for the internal glitch filter.
• Enable and Disable Unit - describes how to enable and disable the PCNT unit.
• Unit IO Control - describes IO control functions of PCNT unit, like enable glitch filter, start and stop unit, get
and clear count value.
• Power Management - describes what functionality will prevent the chip from going into low power mode.
• IRAM Safe - describes tips on how to make the PCNT interrupt and IO control functions work better along
with a disabled cache.
• Thread Safety - lists which APIs are guaranteed to be thread safe by the driver.
• Kconfig options - lists the supported Kconfig options that can be used to make a different effect on driver
behavior.
Resource Allocation The PCNT unit and channel are represented by pcnt_unit_handle_t and
pcnt_channel_handle_t respectively. All available units and channels are maintained by the driver in a re-
source pool, so the user doesn’t need to know the exact underlying instance ID.
1 Different ESP chip series might have different number of PCNT units and channels. Please refer to the [TRM] for details. The driver won’
t forbid you from applying for more PCNT units and channels, but it will return error when all available hardware resources are used up. Please
always check the return value when doing resource allocation (e.g. pcnt_new_unit()).
Install PCNT Unit To install a PCNT unit, there’s a configuration structure that needs to be given in advance:
pcnt_unit_config_t:
• pcnt_unit_config_t::low_limit and pcnt_unit_config_t::high_limit specify the
range for the internal counter. Counter will back to zero when it crosses either limit value.
Unit allocation and initialization is done by calling a function pcnt_new_unit() with pcnt_unit_config_t
as an input parameter. The function will return a PCNT unit handle only when it runs correctly. Specifi-
cally, when there are no more free PCNT units in the pool (i.e. unit resources have been used up), then this
function will return ESP_ERR_NOT_FOUND error. The total number of available PCNT units is recorded by
SOC_PCNT_UNITS_PER_GROUP for reference.
If a previously created PCNT unit is no longer needed, it’s recommended to recycle the resource by calling
pcnt_del_unit(). Which in return allows the underlying unit hardware to be used for other purposes. Be-
fore deleting a PCNT unit, one should ensure the following prerequisites:
• The unit is in the init state, in other words, the unit is either disabled by pcnt_unit_disable() or not
enabled yet.
• The attached PCNT channels are all removed by pcnt_del_channel().
pcnt_unit_config_t unit_config = {
.high_limit = EXAMPLE_PCNT_HIGH_LIMIT,
.low_limit = EXAMPLE_PCNT_LOW_LIMIT,
};
pcnt_unit_handle_t pcnt_unit = NULL;
ESP_ERROR_CHECK(pcnt_new_unit(&unit_config, &pcnt_unit));
Install PCNT Channel To install a PCNT channel, users must initialize a pcnt_chan_config_t structure
in advance, and then call pcnt_new_channel(). The configuration fields of the pcnt_chan_config_t
structure are described below:
• pcnt_chan_config_t::edge_gpio_num and pcnt_chan_config_t::level_gpio_num
specify the GPIO numbers used by edge type signal and level type signal. Please note, either of them can
be assigned to -1 if it’s not actually used, and thus it will become a virtual IO. For some simple pulse count-
ing applications where one of the level/edge signals signals is fixed (i.e., never changes), users can reclaim a
GPIO by setting the signal as a virtual IO on channel allocation. Setting the level/edge signal as a virtual IO
will cause that signal to be internally routed to a fixed High/Low logic level, thus allowing users to save a GPIO
for other purposes.
• pcnt_chan_config_t::virt_edge_io_level and pcnt_chan_config_t::virt_level_io_level
specify the virtual IO level for edge and level input signal, to ensure a deterministic state for such control
signal. Please note, they are only valid when either pcnt_chan_config_t::edge_gpio_num or
pcnt_chan_config_t::level_gpio_num is assigned to -1.
• pcnt_chan_config_t::invert_edge_input and pcnt_chan_config_t::invert_level_input
are used to decide whether to invert the input signals before they going into PCNT hardware. The invert is
done by GPIO matrix instead of PCNT hardware.
• pcnt_chan_config_t::io_loop_back is for debug only, which enables both the GPIO’s input and
output paths. This can help to simulate the pulse signals by function gpio_set_level() on the same
GPIO.
Channel allocating and initialization is done by calling a function pcnt_new_channel() with the above
pcnt_chan_config_t input parameter plus a PCNT unit handle returned from pcnt_new_unit(). This
function will return a PCNT channel handle if it runs correctly. Specifically, when there are no more free
PCNT channel within the unit (i.e. channel resources have been used up), then this function will return
ESP_ERR_NOT_FOUND error. The total number of available PCNT channels within the unit is recorded by
SOC_PCNT_CHANNELS_PER_UNIT for reference. Note that, when install a PCNT channel for a specific unit,
one should ensure the unit is in the init state, otherwise this function will return ESP_ERR_INVALID_STATE
error.
If a previously created PCNT channel is no longer needed, it’s recommended to recycle the resources by calling
pcnt_del_channel(). Which in return allows the underlying channel hardware to be used for other purposes.
#define EXAMPLE_CHAN_GPIO_A 0
#define EXAMPLE_CHAN_GPIO_B 2
pcnt_chan_config_t chan_config = {
.edge_gpio_num = EXAMPLE_CHAN_GPIO_A,
.level_gpio_num = EXAMPLE_CHAN_GPIO_B,
};
pcnt_channel_handle_t pcnt_chan = NULL;
ESP_ERROR_CHECK(pcnt_new_channel(pcnt_unit, &chan_config, &pcnt_chan));
Set Up Channel Actions The PCNT will increase/decrease/hold its internal count value when the input pulse signal
toggles. User can set different actions for edge signal and/or level signal.
• pcnt_channel_set_edge_action() function is to set specific actions for rising and falling edge of
the signal attached to the pcnt_chan_config_t::edge_gpio_num. Supported actions are listed in
pcnt_channel_edge_action_t.
• pcnt_channel_set_level_action() function is to set specific actions for high and low
level of the signal attached to the pcnt_chan_config_t::level_gpio_num. Supported ac-
tions are listed in pcnt_channel_level_action_t. This function is not mandatory if the
pcnt_chan_config_t::level_gpio_num is set to -1 when allocating PCNT channel by
pcnt_new_channel().
// decrease the counter on rising edge, increase the counter on falling edge
ESP_ERROR_CHECK(pcnt_channel_set_edge_action(pcnt_chan, PCNT_CHANNEL_EDGE_ACTION_
,→DECREASE, PCNT_CHANNEL_EDGE_ACTION_INCREASE));
// keep the counting mode when the control signal is high level, and reverse the␣
,→counting mode when the control signal is low level
ESP_ERROR_CHECK(pcnt_channel_set_level_action(pcnt_chan, PCNT_CHANNEL_LEVEL_ACTION_
,→KEEP, PCNT_CHANNEL_LEVEL_ACTION_INVERSE));
Watch Points Each PCNT unit can be configured to watch several different values that you’re in-
terested in. The value to be watched is also called Watch Point. The watch point itself can’
t exceed the range set in pcnt_unit_config_t by pcnt_unit_config_t::low_limit and
pcnt_unit_config_t::high_limit. When the counter reaches either watch point, a watch
event will be triggered and notify user by interrupt if any watch event callback has ever registered in
pcnt_unit_register_event_callbacks(). See Register Event Callbacks for how to register event call-
backs.
The watch point can be added and removed by pcnt_unit_add_watch_point() and
pcnt_unit_remove_watch_point(). The commonly used watch points are: zero cross, max-
imum / minimum count and other threshold values. The number of available watch point is limited,
pcnt_unit_add_watch_point() will return error ESP_ERR_NOT_FOUND if it can’t find any free
hardware resource to save the watch point. User can’t add the same watch point for multiple times, otherwise it
will return error ESP_ERR_INVALID_STATE.
It is recommended to remove the unused watch point by pcnt_unit_remove_watch_point() to recycle the
watch point resources.
Register Event Callbacks When PCNT unit reaches any enabled watch point, specific event will be generated and
notify the CPU by interrupt. If you have some function that want to get executed when event happens, you should
{
BaseType_t high_task_wakeup;
QueueHandle_t queue = (QueueHandle_t)user_ctx;
// send watch point to queue, from this interrupt callback
xQueueSendFromISR(queue, &(edata->watch_point_value), &high_task_wakeup);
// return whether a high priority task has been waken up by this function
return (high_task_wakeup == pdTRUE);
}
pcnt_event_callbacks_t cbs = {
.on_reach = example_pcnt_on_reach,
};
QueueHandle_t queue = xQueueCreate(10, sizeof(int));
ESP_ERROR_CHECK(pcnt_unit_register_event_callbacks(pcnt_unit, &cbs, queue));
Set Glitch Filter The PCNT unit features filters to ignore possible short glitches in the signals. The parameters
that can be configured for the glitch filter are listed in pcnt_glitch_filter_config_t:
• pcnt_glitch_filter_config_t::max_glitch_ns sets the maximum glitch width, in nano sec-
onds. If a signal pulse’s width is smaller than this value, then it will be treated as noise and won’t in-
crease/decrease the internal counter.
User can enable the glitch filter for PCNT unit by calling pcnt_unit_set_glitch_filter() with
the filter configuration provided above. Particularly, user can disable the glitch filter later by calling
pcnt_unit_set_glitch_filter() with a NULL filter configuration.
This function should be called when the the unit is in the init state. Otherwise, it will return
ESP_ERR_INVALID_STATE error.
Note: The glitch filter is clocked from APB. For the counter not to miss any pulses, the maximum glitch width
should be longer than one APB_CLK cycle (usually 12.5 ns if APB equals 80MHz). As the APB frequency would
be changed after DFS (Dynamic Frequency Scaling) enabled, which means the filter won’t work as expect in that
case. So the driver will install a PM lock for PCNT unit during the first time user enables the glitch filter. For more
information related to power management strategy used in PCNT driver, please see Power Management.
pcnt_glitch_filter_config_t filter_config = {
.max_glitch_ns = 1000,
};
ESP_ERROR_CHECK(pcnt_unit_set_glitch_filter(pcnt_unit, &filter_config));
Enable and Disable Unit Before doing IO control to the PCNT unit, user needs to enable it first, by calling
pcnt_unit_enable(). Internally, this function will:
• switch the PCNT driver state from init to enable.
• enable the interrupt service if it has been lazy installed in pcnt_unit_register_event_callbacks().
• acquire a proper power management lock if it has been lazy installed in
pcnt_unit_set_glitch_filter(). See also Power management for more information.
On the contrary, calling pcnt_unit_disable() will do the opposite, that is, put the PCNT driver back to the
init state, disable the interrupts service and release the power management lock.
Unit IO Control
Start/Stop and Clear Calling pcnt_unit_start() will make the PCNT unit start to work, increase
or decrease counter according to pulse signals. On the contrary, calling pcnt_unit_stop() will stop
the PCNT unit but retain current count value. Instead, clearing counter can only be done by calling
pcnt_unit_clear_count().
Note, pcnt_unit_start() and pcnt_unit_stop() should be called when the unit has been enabled by
pcnt_unit_enable(). Otherwise, it will return ESP_ERR_INVALID_STATE error.
Get Count Value User can check current count value at any time by calling pcnt_unit_get_count().
Note: The returned count value is a signed integer, where the sign can be used to reflect the direction. The internal
counter will overflow when it reaches high or low limit, but this function doesn’t compensate for that loss.
int pulse_count = 0;
ESP_ERROR_CHECK(pcnt_unit_get_count(pcnt_unit, &pulse_count));
Power Management When power management is enabled (i.e. CONFIG_PM_ENABLE is on), the system will
adjust the APB frequency before going into light sleep, thus potentially changing the behavior of PCNT glitch filter
and leading to valid signal being treated as noise.
However, the driver can prevent the system from changing APB frequency by acquiring a power
management lock of type ESP_PM_APB_FREQ_MAX. Whenever user enables the glitch filter by
pcnt_unit_set_glitch_filter(), the driver will guarantee that the power management lock is ac-
quired after the PCNT unit is enabled by pcnt_unit_enable(). Likewise, the driver releases the lock after
pcnt_unit_disable() is called.
IRAM Safe By default, the PCNT interrupt will be deferred when the Cache is disabled for reasons like writ-
ing/erasing Flash. Thus the alarm interrupt will not get executed in time, which is not expected in a real-time appli-
cation.
There’s a Kconfig option CONFIG_PCNT_ISR_IRAM_SAFE that will:
1. Enable the interrupt being serviced even when cache is disabled
2. Place all functions that used by the ISR into IRAM2
2 pcnt_event_callbacks_t::on_reach callback and the functions invoked by itself should also be placed in IRAM, users need to
3. Place driver object into DRAM (in case it’s mapped to PSRAM by accident)
This will allow the interrupt to run while the cache is disabled but will come at the cost of increased IRAM consump-
tion.
There’s another Kconfig option CONFIG_PCNT_CTRL_FUNC_IN_IRAM that can put commonly used IO control
functions into IRAM as well. So that these functions can also be executable when the cache is disabled. These IO
control functions are as follows:
• pcnt_unit_start()
• pcnt_unit_stop()
• pcnt_unit_clear_count()
• pcnt_unit_get_count()
Thread Safety The factory function pcnt_new_unit() and pcnt_new_channel() are guaranteed to be
thread safe by the driver, which means, user can call them from different RTOS tasks without protection by extra
locks. The following functions are allowed to run under ISR context, the driver uses a critical section to prevent them
being called concurrently in both task and ISR.
• pcnt_unit_start()
• pcnt_unit_stop()
• pcnt_unit_clear_count()
• pcnt_unit_get_count()
Other functions that take the pcnt_unit_handle_t and pcnt_channel_handle_t as the first positional
parameter, are not treated as thread safe. Which means the user should avoid calling them from multiple tasks.
Kconfig Options
• CONFIG_PCNT_CTRL_FUNC_IN_IRAM controls where to place the PCNT control functions (IRAM or
Flash), see IRAM Safe for more information.
• CONFIG_PCNT_ISR_IRAM_SAFE controls whether the default ISR handler can work when cache is disabled,
see IRAM Safe for more information.
• CONFIG_PCNT_ENABLE_DEBUG_LOG is used to enabled the debug log output. Enable this option will
increase the firmware binary size.
Application Examples
API Reference
Header File
• components/driver/include/driver/pulse_cnt.h
Functions
esp_err_t pcnt_new_unit(const pcnt_unit_config_t *config, pcnt_unit_handle_t *ret_unit)
Create a new PCNT unit, and return the handle.
Note: The newly created PCNT unit is put in the init state.
Parameters
• config –[in] PCNT unit configuration
• ret_unit –[out] Returned PCNT unit handle
Returns
Note: A PCNT unit can’t be in the enable state when this function is invoked. See also
pcnt_unit_disable() for how to disable a unit.
Note: The glitch filter module is clocked from APB, and APB frequency can be changed during DFS, which
in return make the filter out of action. So this function will lazy-install a PM lock internally when the power
management is enabled. With this lock, the APB frequency won’t be changed. The PM lock can be uninstalled
in pcnt_del_unit().
Note: This function should be called when the PCNT unit is in the init state (i.e. before calling
pcnt_unit_enable())
Parameters
• unit –[in] PCNT unit handle created by pcnt_new_unit()
• config –[in] PCNT filter configuration, set config to NULL means disabling the filter
function
Returns
• ESP_OK: Set glitch filter successfully
• ESP_ERR_INVALID_ARG: Set glitch filter failed because of invalid argument (e.g.
glitch width is too big)
• ESP_ERR_INVALID_STATE: Set glitch filter failed because the unit is not in the init
state
• ESP_FAIL: Set glitch filter failed because of other error
Note: This function will transit the unit state from init to enable.
Note: This function will enable the interrupt service, if it’s lazy installed in
pcnt_unit_register_event_callbacks().
Note: This function will acquire the PM lock if it’s lazy installed in
pcnt_unit_set_glitch_filter().
Note: Enable a PCNT unit doesn’t mean to start it. See also pcnt_unit_start() for how to start the
PCNT counter.
Note: Disable a PCNT unit doesn’t mean to stop it. See also pcnt_unit_stop() for how to stop the
PCNT counter.
Note: This function should be called when the unit is in the enable state (i.e. after calling
pcnt_unit_enable())
Note: This function will be placed into IRAM if CONFIG_PCNT_CTRL_FUNC_IN_IRAM is on, so that
it’s allowed to be executed when Cache is disabled
Returns
• ESP_OK: Start PCNT unit successfully
• ESP_ERR_INVALID_ARG: Start PCNT unit failed because of invalid argument
• ESP_ERR_INVALID_STATE: Start PCNT unit failed because the unit is not enabled yet
• ESP_FAIL: Start PCNT unit failed because of other error
Note: This function should be called when the unit is in the enable state (i.e. after calling
pcnt_unit_enable())
Note: The stop operation won’t clear the counter. Also see pcnt_unit_clear_count() for how to
clear pulse count value.
Note: It’s recommended to call this function after adding a watch point by
pcnt_unit_add_watch_point(), so that the newly added watch point is effective immediately.
Note: This function will be placed into IRAM if CONFIG_PCNT_CTRL_FUNC_IN_IRAM, so that it’s
allowed to be executed when Cache is disabled
Note: This function will be placed into IRAM if CONFIG_PCNT_CTRL_FUNC_IN_IRAM, so that it’s
allowed to be executed when Cache is disabled
Parameters
• unit –[in] PCNT unit handle created by pcnt_new_unit()
• value –[out] Returned count value
Returns
• ESP_OK: Get PCNT pulse count successfully
• ESP_ERR_INVALID_ARG: Get PCNT pulse count failed because of invalid argument
• ESP_FAIL: Get PCNT pulse count failed because of other error
Note: User registered callbacks are expected to be runnable within ISR context
Note: This function is only allowed to be called when the unit is in the init state (i.e. before calling
pcnt_unit_enable())
Parameters
• unit –[in] PCNT unit handle created by pcnt_new_unit()
• cbs –[in] Group of callback functions
• user_data –[in] User data, which will be passed to callback functions directly
Returns
• ESP_OK: Set event callbacks successfully
• ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument
• ESP_ERR_INVALID_STATE: Set event callbacks failed because the unit is not in init
state
• ESP_FAIL: Set event callbacks failed because of other error
Parameters
• unit –[in] PCNT unit handle created by pcnt_new_unit()
• watch_point –[in] Watch point value
Returns
• ESP_OK: Remove watch point successfully
• ESP_ERR_INVALID_ARG: Remove watch point failed because of invalid argument
• ESP_ERR_INVALID_STATE: Remove watch point failed because the watch point was
not added by pcnt_unit_add_watch_point() yet
• ESP_FAIL: Remove watch point failed because of other error
esp_err_t pcnt_new_channel(pcnt_unit_handle_t unit, const pcnt_chan_config_t *config,
pcnt_channel_handle_t *ret_chan)
Create PCNT channel for specific unit, each PCNT has several channels associated with it.
Note: This function should be called when the unit is in init state (i.e. before calling
pcnt_unit_enable())
Parameters
• unit –[in] PCNT unit handle created by pcnt_new_unit()
• config –[in] PCNT channel configuration
• ret_chan –[out] Returned channel handle
Returns
• ESP_OK: Create PCNT channel successfully
• ESP_ERR_INVALID_ARG: Create PCNT channel failed because of invalid argument
• ESP_ERR_NO_MEM: Create PCNT channel failed because of insufficient memory
• ESP_ERR_NOT_FOUND: Create PCNT channel failed because all PCNT channels are
used up and no more free one
• ESP_ERR_INVALID_STATE: Create PCNT channel failed because the unit is not in the
init state
• ESP_FAIL: Create PCNT channel failed because of other error
Structures
struct pcnt_watch_event_data_t
PCNT watch event data.
Public Members
int watch_point_value
Watch point value that triggered the event
pcnt_unit_zero_cross_mode_t zero_cross_mode
Zero cross mode
struct pcnt_event_callbacks_t
Group of supported PCNT callbacks.
Note: When CONFIG_PCNT_ISR_IRAM_SAFE is enabled, the callback itself and functions callbed by it
should be placed in IRAM.
Public Members
pcnt_watch_cb_t on_reach
Called when PCNT unit counter reaches any watch point
struct pcnt_unit_config_t
PCNT unit configuration.
Public Members
int low_limit
Low limitation of the count unit, should be lower than 0
int high_limit
High limitation of the count unit, should be higher than 0
struct pcnt_chan_config_t
PCNT channel configuration.
Public Members
int edge_gpio_num
GPIO number used by the edge signal, input mode with pull up enabled. Set to -1 if unused
int level_gpio_num
GPIO number used by the level signal, input mode with pull up enabled. Set to -1 if unused
uint32_t invert_edge_input
Invert the input edge signal
uint32_t invert_level_input
Invert the input level signal
uint32_t virt_edge_io_level
Virtual edge IO level, 0: low, 1: high. Only valid when edge_gpio_num is set to -1
uint32_t virt_level_io_level
Virtual level IO level, 0: low, 1: high. Only valid when level_gpio_num is set to -1
uint32_t io_loop_back
For debug/test, the signal output from the GPIO will be fed to the input path as well
struct pcnt_glitch_filter_config_t
PCNT glitch filter configuration.
Public Members
uint32_t max_glitch_ns
Pulse width smaller than this threshold will be treated as glitch and ignored, in the unit of ns
Type Definitions
Note: The callback function is invoked from an ISR context, so it should meet the restrictions of not calling
any blocking APIs when implementing the callback. e.g. must use ISR version of FreeRTOS APIs.
Header File
• components/hal/include/hal/pcnt_types.h
Enumerations
enum pcnt_channel_level_action_t
PCNT channel action on control level.
Values:
enumerator PCNT_CHANNEL_LEVEL_ACTION_KEEP
Keep current count mode
enumerator PCNT_CHANNEL_LEVEL_ACTION_INVERSE
Invert current count mode (increase -> decrease, decrease -> increase)
enumerator PCNT_CHANNEL_LEVEL_ACTION_HOLD
Hold current count value
enum pcnt_channel_edge_action_t
PCNT channel action on signal edge.
Values:
enumerator PCNT_CHANNEL_EDGE_ACTION_HOLD
Hold current count value
enumerator PCNT_CHANNEL_EDGE_ACTION_INCREASE
Increase count value
enumerator PCNT_CHANNEL_EDGE_ACTION_DECREASE
Decrease count value
enum pcnt_unit_zero_cross_mode_t
PCNT unit zero cross mode.
Values:
enumerator PCNT_UNIT_ZERO_CROSS_POS_ZERO
start from positive value, end to zero, i.e. +N->0
enumerator PCNT_UNIT_ZERO_CROSS_NEG_ZERO
start from negative value, end to zero, i.e. -N->0
enumerator PCNT_UNIT_ZERO_CROSS_NEG_POS
start from negative value, end to positive value, i.e. -N->+M
enumerator PCNT_UNIT_ZERO_CROSS_POS_NEG
start from positive value, end to negative value, i.e. +N->-M
Introduction
The RMT (Remote Control Transceiver) peripheral was designed to act as an infrared transceiver. However, due
to the flexibility of its data format, the functionality of RMT can be extended to a versatile and general purpose
transceiver. From the perspective of network layering, the RMT hardware contains both physical and data link layer.
The physical layer defines the communication media and bit signal representation. The data link layer defines the
format of an RMT frame. The minimal data unit in the frame is called RMT symbol, which is represented by
rmt_symbol_word_t in the driver.
ESP32 contains multiple channels in the RMT peripheral.1 Each channel can be configured as either transmitter or
receiver, independently.
Typically, the RMT peripheral can be used in the following scenarios:
• Transmit or receive infrared signals, with any IR protocols, e.g. NEC
• General purpose sequence generator
• Transmit signals in a hardware controlled loop, with finite or infinite number of times
• Multi-channel simultaneous transmission
• Modulate the carrier to the output signal or demodulate the carrier from the input signal
Layout of RMT Symbols The RMT hardware defines data in its own pattern –the RMT symbol. Each symbol
consists of two pairs of two values. The first value in a pair describes the signal duration in RMT ticks and is 15 bits
long. The second provides the signal level (high or low) and is contained in a single bit, as shown below:
RMT Transmitter Overview The data path and control path of an RMT TX channel is illustrated in the figure
below:
The driver will encode user’s data into RMT data format, then the RMT transmitter can generate the waveforms
according to the encoding artifacts. It is also possible to modulate a high frequency carrier signal before being routed
to a GPIO pad.
RMT Receiver Overview The data path and control path of an RMT RX channel is illustrated in the figure below:
The RMT receiver can sample incoming signals into RMT data format, and store the data in memory. It’s feasible to
tell the receiver the basic characteristics of the incoming signal, so that the signal’s stop condition can be recognized,
and signal glitches and noise can be filtered out. The RMT peripheral also supports demodulating the high frequency
carrier from the base signal.
1 Different ESP chip series might have different number of RMT channels. Please refer to the [TRM] for details. The driver won’t forbid
you from applying for more RMT channels, but it will return error when there’s no hardware resources available. Please always check the return
value when doing Resource Allocation.
Functional Overview
Resource Allocation Both RMT TX and RX channels are represented by rmt_channel_handle_t in the
driver. The available channels are managed in a resource pool, which will hand out a free channel on request.
Install RMT TX Channel To install an RMT TX channel, there’s a configuration structure that needs to be given
in advance: rmt_tx_channel_config_t:
• rmt_tx_channel_config_t::gpio_num sets the GPIO number used by the transmitter.
• rmt_tx_channel_config_t::clk_src selects the source clock for the RMT channel. The available
clocks are listed in rmt_clock_source_t. Note that, the selected clock will also be used by other chan-
nels, which means user should ensure this configuration is same when allocating other channels, regardless of
TX or RX. For the effect on power consumption of different clock source, please refer to Power Management
section.
• rmt_tx_channel_config_t::resolution_hz sets the resolution of the internal tick counter. The
timing parameter of RMT signal is calculated based on this tick.
• rmt_tx_channel_config_t::mem_block_symbols sets the size of the dedicated memory block
or DMA buffer that is used to store RMT encoding artifacts.
• rmt_tx_channel_config_t::trans_queue_depth sets the depth of internal transaction queue,
the deeper the queue, the more transactions can be prepared in the backlog.
• rmt_tx_channel_config_t::invert_out is used to decide whether to invert the RMT signal be-
fore sending it to the GPIO pad.
• rmt_tx_channel_config_t::with_dma is used to indicate if the channel needs a DMA back-
end. A channel with DMA attached can offload the CPU by a lot. However, DMA backend is not avail-
able on all ESP chips, please refer to [TRM] before you enable this option. Or you might encounter
ESP_ERR_NOT_SUPPORTED error.
• rmt_tx_channel_config_t::io_loop_back is for debugging purposes only. It enables both the
GPIO’s input and output ability through the GPIO matrix peripheral. Meanwhile, if both TX and RX channels
are bound to the same GPIO, then monitoring of the data transmission line can be realized.
Once the rmt_tx_channel_config_t structure is populated with mandatory parameters, users can call
rmt_new_tx_channel() to allocate and initialize a TX channel. This function will return an RMT channel
handle if it runs correctly. Specifically, when there are no more free channels in the RMT resource pool, this func-
tion will return ESP_ERR_NOT_FOUND error. If some feature (e.g. DMA backend) is not supported by hardware,
it will return ESP_ERR_NOT_SUPPORTED error.
rmt_channel_handle_t tx_chan = NULL;
rmt_tx_channel_config_t tx_chan_config = {
.clk_src = RMT_CLK_SRC_DEFAULT, // select source clock
(continues on next page)
Install RMT RX Channel To install an RMT RX channel, there’s a configuration structure that needs to be given
in advance: rmt_rx_channel_config_t:
• rmt_rx_channel_config_t::gpio_num sets the GPIO number used by the receiver.
• rmt_rx_channel_config_t::clk_src selects the source clock for the RMT channel. The available
clocks are listed in rmt_clock_source_t. Note that, the selected clock will also be used by other chan-
nels, which means user should ensure this configuration is same when allocating other channels, regardless of
TX or RX. For the effect on power consumption of different clock source, please refer to Power Management
section.
• rmt_rx_channel_config_t::resolution_hz sets the resolution of the internal tick counter. The
timing parameter of RMT signal is calculated based on this tick.
• rmt_rx_channel_config_t::mem_block_symbols sets the size of the dedicated memory block
or DMA buffer that used to store RMT encoding artifacts.
• rmt_rx_channel_config_t::invert_in is used to decide whether to invert the input signals before
they going into RMT receiver. The inversion is done by GPIO matrix instead of by the RMT peripheral.
• rmt_rx_channel_config_t::with_dma is used to indicate if the channel needs a DMA back-
end. A channel with DMA attached can offload the CPU by a lot. However, DMA backend is not avail-
able on all ESP chips, please refer to [TRM] before you enable this option. Or you might encounter
ESP_ERR_NOT_SUPPORTED error.
• rmt_rx_channel_config_t::io_loop_back is for debugging purposes only. It enables both the
GPIO’s input and output ability through the GPIO matrix peripheral. Meanwhile, if both TX and RX channels
are bound to the same GPIO, then monitoring of the data transmission line can be realized.
Once the rmt_rx_channel_config_t structure is populated with mandatory parameters, users can call
rmt_new_rx_channel() to allocate and initialize a RX channel. This function will return an RMT channel
handle if it runs correctly. Specifically, when there are no more free channels in the RMT resource pool, this func-
tion will return ESP_ERR_NOT_FOUND error. If some feature (e.g. DMA backend) is not supported by hardware,
it will return ESP_ERR_NOT_SUPPORTED error.
rmt_channel_handle_t rx_chan = NULL;
rmt_rx_channel_config_t rx_chan_config = {
.clk_src = RMT_CLK_SRC_DEFAULT, // select source clock
.resolution_hz = 1 * 1000 * 1000, // 1MHz tick resolution, i.e. 1 tick = 1us
.mem_block_symbols = 64, // memory block size, 64 * 4 = 256Bytes
.gpio_num = 2, // GPIO number
.flags.invert_in = false, // don't invert input signal
.flags.with_dma = false, // don't need DMA backend
};
ESP_ERROR_CHECK(rmt_new_rx_channel(&rx_chan_config, &rx_chan));
Uninstall RMT Channel If a previously installed RMT channel is no longer needed, it’s recommended to recycle
the resources by calling rmt_del_channel(), which in return allows the underlying hardware to be usable for
other purposes.
Carrier Modulation and Demodulation The RMT transmitter can generate a carrier wave and modulate it onto
the base signal. Compared to the base signal, the carrier frequency is usually high. In addition, user can only set the
frequency and duty cycle for the carrier. The RMT receiver can demodulate the carrier from the incoming signal.
Note that, carrier modulation and demodulation is not supported on all ESP chips, please refer to [TRM] before
configuring the carrier, or you might encounter a ESP_ERR_NOT_SUPPORTED error.
Carrier related configurations lie in rmt_carrier_config_t:
• rmt_carrier_config_t::frequency_hz sets the carrier frequency, in Hz.
• rmt_carrier_config_t::duty_cycle sets the carrier duty cycle.
• rmt_carrier_config_t::polarity_active_low sets the carrier polarity, i.e. on which level the
carrier is applied.
• rmt_carrier_config_t::always_on sets whether to output the carrier even when the data trans-
mission has finished. This configuration is only valid for TX channel.
Note: For RX channel, we shouldn’t set the carrier frequency exactly to the theoretical value. It’s recommended
to leave a tolerance for the carrier frequency. For example, in the snippet below, we set the frequency to 25KHz,
instead of the 38KHz that configured on the TX side. The reason is that reflection and refraction will occur when a
signal travels through the air, leading to the a distortion on the receiver side.
rmt_carrier_config_t tx_carrier_cfg = {
.duty_cycle = 0.33, // duty cycle 33%
.frequency_hz = 38000, // 38KHz
.flags.polarity_active_low = false, // carrier should modulated to high level
};
// modulate carrier to TX channel
ESP_ERROR_CHECK(rmt_apply_carrier(tx_chan, &tx_carrier_cfg));
rmt_carrier_config_t rx_carrier_cfg = {
.duty_cycle = 0.33, // duty cycle 33%
.frequency_hz = 25000, // 25KHz carrier, should be smaller than␣
,→transmitter's carrier frequency
Register Event Callbacks When an RMT channel finishes transmitting or receiving, a specific event will
be generated and notify the CPU by interrupt. If you have some function that needs to be called
when those events occurred, you can hook your function to the ISR (Interrupt Service Routine) by calling
rmt_tx_register_event_callbacks() and rmt_rx_register_event_callbacks() for TX
and RX channel respectively. Since the registered callback functions are called in the interrupt context, user should
ensure the callback function doesn’t attempt to block (e.g. by making sure that only FreeRTOS APIs with ISR
suffix are called from within the function). The callback function has a boolean return value, to tell the caller whether
a high priority task is woke up by it.
TX channel supported event callbacks are listed in the rmt_tx_event_callbacks_t:
• rmt_tx_event_callbacks_t::on_trans_done sets a callback function for trans done event. The
function prototype is declared in rmt_tx_done_callback_t.
RX channel supported event callbacks are listed in the rmt_rx_event_callbacks_t:
• rmt_rx_event_callbacks_t::on_recv_done sets a callback function for receive complete event.
The function prototype is declared in rmt_rx_done_callback_t.
User can save own context in rmt_tx_register_event_callbacks() and
rmt_rx_register_event_callbacks() as well, via the parameter user_data. The user data
will be directly passed to each callback function.
In the callback function, users can fetch the event specific data that is filled by the driver in the edata. Note that
the edata pointer is only valid for the duration of the callback.
The TX done event data is defined in rmt_tx_done_event_data_t:
Enable and Disable channel rmt_enable() must be called in advanced before transmitting or receiving RMT
symbols. For transmitters, enabling a channel will enable a specific interrupt and prepare the hardware to dispatch
transactions. For RX channels, enabling a channel will enable an interrupt, but the receiver is not started dur-
ing this time, as it has no idea about the characteristics of the incoming signals. The receiver will be started in
rmt_receive().
rmt_disable() does the opposite work by disabling the interrupt and clearing pending status. The transmitter
and receiver will be disabled as well.
ESP_ERROR_CHECK(rmt_enable(tx_chan));
ESP_ERROR_CHECK(rmt_enable(rx_chan));
Initiate TX Transaction RMT is a special communication peripheral as it’s unable to transmit raw byte streams
like SPI and I2C. RMT can only send data in its own format rmt_symbol_word_t. However, the hardware
doesn’t help to convert the user data into RMT symbols, this can only be done in software —by the so-called RMT
Encoder. The encoder is responsible for encoding user data into RMT symbols and then write to RMT memory
block or DMA buffer. For how to create an RMT encoder, please refer to RMT Encoder.
Once we got an encoder, we can initiate a TX transaction by calling rmt_transmit(). This function takes several
positional parameters like channel handle, encoder handle, payload buffer. Besides that, we also need to provide a
transmission specific configuration in rmt_transmit_config_t:
• rmt_transmit_config_t::loop_count sets the number of transmission loop. After the trans-
mitter finished one round of transmission, it can restart the same transmission again if this value is
not set to zero. As the loop is controlled by hardware, the RMT channel can be used to gen-
erate many periodic sequences at the cost of a very little CPU intervention. Specially, setting
rmt_transmit_config_t::loop_count to -1 means an infinite loop transmission. In this situa-
tion, the channel won’t stop until manually call of rmt_disable(). And the trans done event won’t be
generated as well. If rmt_transmit_config_t::loop_count is set to a positive number, the trans
done event won’t be generated until target number of loop transmission have finished. Note that, the loop
transmit feature is not supported on all ESP chips, please refer to [TRM] before you configure this option. Or
you might encounter ESP_ERR_NOT_SUPPORTED error.
• rmt_transmit_config_t::eot_level sets the output level when the transmitter finishes working or
stops working by calling rmt_disable().
Internally, rmt_transmit() will construct a transaction descriptor and send to a job queue, which will be dis-
patched in the ISR. So it is possible that the transaction is not started yet when rmt_transmit() returns. To
ensure all pending transaction to complete, user can use rmt_tx_wait_all_done().
Multiple Channels Simultaneous Transmission In some real-time control applications, we don’t want any time
drift in between when startup multiple TX channels. For example, to make two robotic arms move simultaneously.
The RMT driver can help to manage this by creating a so-called Sync Manager. The sync manager is represented by
rmt_sync_manager_handle_t in the driver. The procedure of RMT sync transmission is shown as follows:
Install RMT Sync Manager To create a sync manager, user needs to tell which channels are going to be managed
in the rmt_sync_manager_config_t:
• rmt_sync_manager_config_t::tx_channel_array points to the array of TX channels to be
managed.
• rmt_sync_manager_config_t::array_size sets the number of channels to be managed.
rmt_new_sync_manager() can return a manager handle on success. This function could also fail due to various
errors such as invalid arguments, etc. Specially, when the sync manager has been installed before, and there’re no
hardware resources to create another manager, this function will report ESP_ERR_NOT_FOUND error. In addition,
if the sync manager is not supported by the hardware, it will report ESP_ERR_NOT_SUPPORTED error. Please
refer to [TRM] before using the sync manager feature.
Start Transmission Simultaneously For any managed TX channel, it won’t start the machine until all the chan-
nels in the rmt_sync_manager_config_t::tx_channel_array are called with rmt_transmit().
Before that, the channel is just put in a waiting state. Different channel usually take different time to finish the job if
the transaction is different, which results in a loss of sync. So user needs to call rmt_sync_reset() to pull the
channels back to the starting line again before restarting a simultaneous transmission.
Calling rmt_del_sync_manager() can recycle the sync manager and enable the channels to initiate transactions
independently afterwards.
};
ESP_ERROR_CHECK(rmt_new_tx_channel(&tx_chan_config, &tx_channels[i]));
}
// install sync manager
rmt_sync_manager_handle_t synchro = NULL;
rmt_sync_manager_config_t synchro_config = {
.tx_channel_array = tx_channels,
.array_size = sizeof(tx_channels) / sizeof(tx_channels[0]),
};
ESP_ERROR_CHECK(rmt_new_sync_manager(&synchro_config, &synchro));
Initiate RX Transaction As also discussed in the Enable and Disable channel, the RX channel still doesn’t get
ready to receive RMT symbols even user calls rmt_enable(). User needs to specify the basic characteristics of
the incoming signals in rmt_receive_config_t:
• rmt_receive_config_t::signal_range_min_ns specifies the minimal valid pulse duration (ei-
ther high or low level). A pulse whose width is smaller than this value will be treated as glitch and ignored by
the hardware.
• rmt_receive_config_t::signal_range_max_ns specifies the maximum valid pulse duration
(either high or low level). A pulse whose width is bigger than this value will be treated as Stop Signal, and the
receiver will generate receive complete event immediately.
The RMT receiver will start the RX machine after user calls rmt_receive() with the provided configuration
above. Note that, this configuration is transaction specific, which means, to start a new round of reception, user needs
to sets the rmt_receive_config_t again. The receiver saves the incoming signals into its internal memory
block or DMA buffer, in the format of rmt_symbol_word_t.
Due to the limited size of memory block, the RMT receiver can only save short frames whose length is not longer
than the memory block capacity. Long frames will be truncated by the hardware, and the driver will report an error
message: hw buffer too small, received symbols truncated.
The copy destination should be provided in the buffer parameter of rmt_receive() function. If this buffer
size is not sufficient, the receiver can continue to work but later incoming symbols will be dropped and report an error
message: user buffer too small, received symbols truncated. Please take care of the lifecycle
of the buffer parameter, user shouldn’t recycle the buffer before the receiver finished or stopped working.
The receiver will be stopped by the driver when it finishes working (i.e. received a signal whose
duration is bigger than rmt_receive_config_t::signal_range_max_ns). User needs to call
rmt_receive() again to restart the receiver, is necessary. User can get the received data in the
rmt_rx_event_callbacks_t::on_recv_done callback. See also Register Event Callbacks for more in-
formation.
{
BaseType_t high_task_wakeup = pdFALSE;
TaskHandle_t task_to_notify = (TaskHandle_t)user_data;
// send the received RMT symbols to the parser task
(continues on next page)
};
// ready to receive
ESP_ERROR_CHECK(rmt_receive(rx_channel, raw_symbols, sizeof(raw_symbols), &receive_
,→config));
RMT Encoder An RMT encoder is part of the RMT TX transaction, whose responsibility is to generate and write
the correct RMT symbols into hardware memory (or DMA buffer) at specific time. There’re some special restrictions
for an encoding function:
• An encoding function might be called for several times within a single transaction. This is because the target
RMT memory block can’t accommodate all the artifacts at once. We have to use the memory in a ping-pong
way, thus the encoding session is divided into multiple parts. This requires the encoder to be stateful.
• The encoding function is running in the ISR context. To speed up the encoding session, it’s high recommend
to put the encoding function into IRAM. This can also avoid the cache miss during encoding.
To help get started with RMT driver faster, some commonly used encoders are provided out-of-the box. They can
either work alone or chained together into a new encoder. See also Composite Pattern for the principle behind. The
driver has defined the encoder interface in rmt_encoder_t, it contains the following functions:
• rmt_encoder_t::encode is the fundamental function of an encoder. This is where the encoding session
happens. Please note, the rmt_encoder_t::encode function might be called for multiple times within
a single transaction. The encode function should return the state of current encoding session. The supported
states are listed in the rmt_encode_state_t. If the result contains RMT_ENCODING_COMPLETE, it
means the current encoder has finished work. If the result contains RMT_ENCODING_MEM_FULL, we need
to yield from current session, as there’s no space to save more encoding artifacts.
• rmt_encoder_t::reset should reset the encoder state back to initial. The RMT encoder is stateful, if
RMT transmitter stopped manually without its corresponding encoder being reset, then the following encoding
session can be wrong. This function is also called implicitly in rmt_disable().
• rmt_encoder_t::del function should free the resources allocated by the encoder.
Copy Encoder A copy encoder is created by calling rmt_new_copy_encoder(). Copy encoder’s main
functionality is to copy the RMT symbols from user space into the driver layer. It’s usually used to encode const
data (i.e. data won’t change at runtime after initialization), for example, the leading code in the IR protocol.
Bytes Encoder A bytes encoder is created by calling rmt_new_bytes_encoder(). Bytes encoder’s main
functionality is to convert the user space byte stream into RMT symbols dynamically. It’s usually used to encode
dynamic data, for example, the address and command fields in the IR protocol.
A configuration structure rmt_bytes_encoder_config_t should be provided in advance before calling
rmt_new_bytes_encoder():
• rmt_bytes_encoder_config_t::bit0 and rmt_bytes_encoder_config_t::bit1 are
necessary to tell to the encoder how to represent bit zero and bit one in the format of rmt_symbol_word_t.
• rmt_bytes_encoder_config_t::msb_first sets the encoding order for of byte. If it is set to true,
the encoder will encode the Most Significant Bit first. Otherwise, it will encode the Least Significant Bit
first.
Besides the primitive encoders provided by the driver, user can implement his own encoder by chaining the existing
encoders together. A common encoder chain is shown as follows:
Customize RMT Encoder for NEC Protocol In this section, we will demonstrate on how to write an NEC en-
coder. The NEC IR protocol uses pulse distance encoding of the message bits. Each pulse burst is 562.5µs in length,
logical bits are transmitted as follows. It is worth mentioning, the bytes of data bits are sent least significant bit first.
• Logical 0: a 562.5µs pulse burst followed by a 562.5µs space, with a total transmit time of 1.125ms
• Logical 1: a 562.5µs pulse burst followed by a 1.6875ms space, with a total transmit time of 2.25ms
When a key is pressed on the remote controller, the message transmitted consists of the following, in order:
int state; // record the current encoding state (i.e. we're in which encoding␣
,→phase)
} rmt_ir_nec_encoder_t;
,→state)
{
rmt_ir_nec_encoder_t *nec_encoder = __containerof(encoder, rmt_ir_nec_encoder_
,→t, base);
rmt_encode_state_t session_state = 0;
rmt_encode_state_t state = 0;
size_t encoded_symbols = 0;
ir_nec_scan_code_t *scan_code = (ir_nec_scan_code_t *)primary_data;
rmt_encoder_handle_t copy_encoder = nec_encoder->copy_encoder;
rmt_encoder_handle_t bytes_encoder = nec_encoder->bytes_encoder;
switch (nec_encoder->state) {
case 0: // send leading code
encoded_symbols += copy_encoder->encode(copy_encoder, channel, &nec_
,→encoder->nec_leading_symbol,
sizeof(rmt_symbol_word_t), &
,→session_state);
}
if (session_state & RMT_ENCODING_MEM_FULL) {
state |= RMT_ENCODING_MEM_FULL;
goto out; // yield if there's no free space to put other encoding␣
,→artifacts
}
// fall-through
case 1: // send address
encoded_symbols += bytes_encoder->encode(bytes_encoder, channel, &scan_
,→code->address, sizeof(uint16_t), &session_state);
}
// fall-through
case 2: // send command
encoded_symbols += bytes_encoder->encode(bytes_encoder, channel, &scan_
,→code->command, sizeof(uint16_t), &session_state);
}
if (session_state & RMT_ENCODING_MEM_FULL) {
state |= RMT_ENCODING_MEM_FULL;
goto out; // yield if there's no free space to put other encoding␣
,→artifacts
}
// fall-through
case 3: // send ending code
encoded_symbols += copy_encoder->encode(copy_encoder, channel, &nec_
,→encoder->nec_ending_symbol,
sizeof(rmt_symbol_word_t), &
,→session_state);
}
if (session_state & RMT_ENCODING_MEM_FULL) {
state |= RMT_ENCODING_MEM_FULL;
goto out; // yield if there's no free space to put other encoding␣
,→artifacts
}
}
out:
*ret_state = state;
return encoded_symbols;
}
A full sample code can be found in peripherals/rmt/ir_nec_transceiver. In the above snippet, we use a
switch-case plus several goto statements to implement a state machine . With this pattern, user can construct
a lot more complex IR protocols.
Power Management When power management is enabled (i.e. CONFIG_PM_ENABLE is on), the system will
adjust the APB frequency before going into light sleep, thus potentially changing the resolution of RMT internal
counter.
However, the driver can prevent the system from changing APB frequency by acquiring a power management lock of
type ESP_PM_APB_FREQ_MAX. Whenever user creates an RMT channel that has selected RMT_CLK_SRC_APB
as the clock source, the driver will guarantee that the power management lock is acquired after the channel enabled
by rmt_enable(). Likewise, the driver releases the lock after rmt_disable() is called for the same channel.
This also reveals that the rmt_enable() and rmt_disable() should appear in pairs.
If the channel clock source is selected to others like RMT_CLK_SRC_XTAL, then the driver won’t install power
management lock for it, which is more suitable for a low power application as long as the source clock can still provide
sufficient resolution.
IRAM Safe By default, the RMT interrupt will be deferred when the Cache is disabled for reasons like writ-
ing/erasing the main Flash. Thus the transaction done interrupt will not get executed in time, which is not expected
in a real-time application. What’s worse, when the RMT transaction relies on ping-pong interrupt to successively
encode or copy RMT symbols, such delayed response can lead to an unpredictable result.
There’s a Kconfig option CONFIG_RMT_ISR_IRAM_SAFE that will:
1. Enable the interrupt being serviced even when cache is disabled
2. Place all functions that used by the ISR into IRAM2
3. Place driver object into DRAM (in case it’s mapped to PSRAM by accident)
This Kconfig option will allow the interrupt to run while the cache is disabled but will come at the cost of increased
IRAM consumption.
Kconfig Options
• CONFIG_RMT_ISR_IRAM_SAFE controls whether the default ISR handler can work when cache is disabled,
see also IRAM Safe for more information.
• CONFIG_RMT_ENABLE_DEBUG_LOG is used to enabled the debug log at the cost of increased firmware
binary size.
Application Examples
API Reference
Header File
• components/driver/include/driver/rmt_tx.h
Functions
esp_err_t rmt_new_tx_channel(const rmt_tx_channel_config_t *config, rmt_channel_handle_t *ret_chan)
Create a RMT TX channel.
Parameters
• config –[in] TX channel configurations
• ret_chan –[out] Returned generic RMT channel handle
Returns
• ESP_OK: Create RMT TX channel successfully
• ESP_ERR_INVALID_ARG: Create RMT TX channel failed because of invalid argument
• ESP_ERR_NO_MEM: Create RMT TX channel failed because out of memory
• ESP_ERR_NOT_FOUND: Create RMT TX channel failed because all RMT channels are
used up and no more free one
2 Callback function (e.g. rmt_tx_event_callbacks_t::on_trans_done) and the functions invoked by itself should also reside in
Note: This function will construct a transaction descriptor and push to a queue. The transaction will not start
immediately until it’s dispatched in the ISR. If there’re too many transactions pending in the queue, this
function will block until the queue has free space.
Note: The data to be transmitted will be encoded into RMT symbols by the specific encoder.
Parameters
• tx_channel –[in] RMT TX channel that created by rmt_new_tx_channel()
• encoder –[in] RMT encoder that created by various factory APIs like
rmt_new_bytes_encoder()
• payload –[in] The raw data to be encoded into RMT symbols
• payload_bytes –[in] Size of the payload in bytes
• config –[in] Transmission specific configuration
Returns
• ESP_OK: Transmit data successfully
• ESP_ERR_INVALID_ARG: Transmit data failed because of invalid argument
• ESP_ERR_INVALID_STATE: Transmit data failed because channel is not enabled
• ESP_ERR_NOT_SUPPORTED: Transmit data failed because some feature is not sup-
ported by hardware, e.g. unsupported loop count
• ESP_FAIL: Transmit data failed because of other error
Note: This function will block forever if the pending transaction can’t be finished within a limited time (e.g.
an infinite loop transaction). See also rmt_disable() for how to terminate a working channel.
Parameters
• tx_channel –[in] RMT TX channel that created by rmt_new_tx_channel()
• timeout_ms –[in] Wait timeout, in ms. Specially, -1 means to wait forever.
Returns
• ESP_OK: Flush transactions successfully
• ESP_ERR_INVALID_ARG: Flush transactions failed because of invalid argument
• ESP_ERR_TIMEOUT: Flush transactions failed because of timeout
• ESP_FAIL: Flush transactions failed because of other error
Note: User can deregister a previously registered callback by calling this function and setting the callback
member in the cbs structure to NULL.
Note: When CONFIG_RMT_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it
should be placed in IRAM. The variables used in the function should be in the SRAM as well. The user_data
should also reside in SRAM.
Parameters
• tx_channel –[in] RMT generic channel that created by rmt_new_tx_channel()
• cbs –[in] Group of callback functions
• user_data –[in] User data, which will be passed to callback functions directly
Returns
• ESP_OK: Set event callbacks successfully
• ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument
• ESP_FAIL: Set event callbacks failed because of other error
Note: All the channels to be managed should be enabled by rmt_enable() before put them into sync
manager.
Parameters
• config –[in] Synchronization manager configuration
• ret_synchro –[out] Returned synchronization manager handle
Returns
• ESP_OK: Create sync manager successfully
• ESP_ERR_INVALID_ARG: Create sync manager failed because of invalid argument
• ESP_ERR_NOT_SUPPORTED: Create sync manager failed because it is not supported
by hardware
• ESP_ERR_INVALID_STATE: Create sync manager failed because not all channels are
enabled
• ESP_ERR_NO_MEM: Create sync manager failed because out of memory
• ESP_ERR_NOT_FOUND: Create sync manager failed because all sync controllers are
used up and no more free one
• ESP_FAIL: Create sync manager failed because of other error
Structures
struct rmt_tx_event_callbacks_t
Group of RMT TX callbacks.
Note: When CONFIG_RMT_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it
should be placed in IRAM. The variables used in the function should be in the SRAM as well.
Public Members
rmt_tx_done_callback_t on_trans_done
Event callback, invoked when transmission is finished
struct rmt_tx_channel_config_t
RMT TX channel specific configuration.
Public Members
int gpio_num
GPIO number used by RMT TX channel. Set to -1 if unused
rmt_clock_source_t clk_src
Clock source of RMT TX channel, channels in the same group must use the same clock source
uint32_t resolution_hz
Channel clock resolution, in Hz
size_t mem_block_symbols
Size of memory block, in number of rmt_symbol_word_t, must be an even
size_t trans_queue_depth
Depth of internal transfer queue, increase this value can support more transfers pending in the background
uint32_t invert_out
Whether to invert the RMT channel signal before output to GPIO pad
uint32_t with_dma
If set, the driver will allocate an RMT channel with DMA capability
uint32_t io_loop_back
For debug/test, the signal output from the GPIO will be fed to the input path as well
struct rmt_transmit_config_t
RMT transmit specific configuration.
Public Members
int loop_count
Specify the times of transmission in a loop, -1 means transmitting in an infinite loop
uint32_t eot_level
Set the output level for the “End Of Transmission”
struct rmt_sync_manager_config_t
Synchronous manager configuration.
Public Members
size_t array_size
Size of the tx_channel_array
Header File
• components/driver/include/driver/rmt_rx.h
Functions
esp_err_t rmt_new_rx_channel(const rmt_rx_channel_config_t *config, rmt_channel_handle_t *ret_chan)
Create a RMT RX channel.
Parameters
• config –[in] RX channel configurations
• ret_chan –[out] Returned generic RMT channel handle
Returns
• ESP_OK: Create RMT RX channel successfully
• ESP_ERR_INVALID_ARG: Create RMT RX channel failed because of invalid argument
• ESP_ERR_NO_MEM: Create RMT RX channel failed because out of memory
• ESP_ERR_NOT_FOUND: Create RMT RX channel failed because all RMT channels
are used up and no more free one
• ESP_ERR_NOT_SUPPORTED: Create RMT RX channel failed because some feature
is not supported by hardware, e.g. DMA feature is not supported by hardware
• ESP_FAIL: Create RMT RX channel failed because of other error
esp_err_t rmt_receive(rmt_channel_handle_t rx_channel, void *buffer, size_t buffer_size, const
rmt_receive_config_t *config)
Initiate a receive job for RMT RX channel.
Note: This function is non-blocking, it initiates a new receive job and then returns.
User should check the received data from the on_recv_done callback that registered by
rmt_rx_register_event_callbacks().
Parameters
• rx_channel –[in] RMT RX channel that created by rmt_new_rx_channel()
• buffer –[in] The buffer to store the received RMT symbols
• buffer_size –[in] size of the buffer, in bytes
• config –[in] Receive specific configurations
Returns
• ESP_OK: Initiate receive job successfully
• ESP_ERR_INVALID_ARG: Initiate receive job failed because of invalid argument
• ESP_ERR_INVALID_STATE: Initiate receive job failed because channel is not enabled
• ESP_FAIL: Initiate receive job failed because of other error
Note: User can deregister a previously registered callback by calling this function and setting the callback
member in the cbs structure to NULL.
Note: When CONFIG_RMT_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it
should be placed in IRAM. The variables used in the function should be in the SRAM as well. The user_data
should also reside in SRAM.
Parameters
• rx_channel –[in] RMT generic channel that created by rmt_new_rx_channel()
• cbs –[in] Group of callback functions
• user_data –[in] User data, which will be passed to callback functions directly
Returns
• ESP_OK: Set event callbacks successfully
• ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument
• ESP_FAIL: Set event callbacks failed because of other error
Structures
struct rmt_rx_event_callbacks_t
Group of RMT RX callbacks.
Note: When CONFIG_RMT_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it
should be placed in IRAM. The variables used in the function should be in the SRAM as well.
Public Members
rmt_rx_done_callback_t on_recv_done
Event callback, invoked when one RMT channel receiving transaction completes
struct rmt_rx_channel_config_t
RMT RX channel specific configuration.
Public Members
int gpio_num
GPIO number used by RMT RX channel. Set to -1 if unused
rmt_clock_source_t clk_src
Clock source of RMT RX channel, channels in the same group must use the same clock source
uint32_t resolution_hz
Channel clock resolution, in Hz
size_t mem_block_symbols
Size of memory block, in number of rmt_symbol_word_t, must be an even
uint32_t invert_in
Whether to invert the incoming RMT channel signal
uint32_t with_dma
If set, the driver will allocate an RMT channel with DMA capability
uint32_t io_loop_back
For debug/test, the signal output from the GPIO will be fed to the input path as well
struct rmt_receive_config_t
RMT receive specific configuration.
Public Members
uint32_t signal_range_min_ns
A pulse whose width is smaller than this threshold will be treated as glitch and ignored
uint32_t signal_range_max_ns
RMT will stop receiving if one symbol level has kept more than signal_range_max_ns
Header File
• components/driver/include/driver/rmt_common.h
Functions
esp_err_t rmt_del_channel(rmt_channel_handle_t channel)
Delete an RMT channel.
Parameters channel –[in] RMT generic channel that created by rmt_new_tx_channel()
or rmt_new_rx_channel()
Returns
• ESP_OK: Delete RMT channel successfully
• ESP_ERR_INVALID_ARG: Delete RMT channel failed because of invalid argument
• ESP_ERR_INVALID_STATE: Delete RMT channel failed because it is still in working
• ESP_FAIL: Delete RMT channel failed because of other error
esp_err_t rmt_apply_carrier(rmt_channel_handle_t channel, const rmt_carrier_config_t *config)
Apply modulation feature for TX channel or demodulation feature for RX channel.
Parameters
• channel –[in] RMT generic channel that created by rmt_new_tx_channel() or
rmt_new_rx_channel()
• config –[in] Carrier configuration. Specially, a NULL config means to disable the car-
rier modulation or demodulation feature
Returns
• ESP_OK: Apply carrier configuration successfully
• ESP_ERR_INVALID_ARG: Apply carrier configuration failed because of invalid argu-
ment
• ESP_FAIL: Apply carrier configuration failed because of other error
esp_err_t rmt_enable(rmt_channel_handle_t channel)
Enable the RMT channel.
Note: This function will acquire a PM lock that might be installed during channel allocation
Note: This function will release a PM lock that might be installed during channel allocation
Structures
struct rmt_carrier_config_t
RMT carrier wave configuration (for either modulation or demodulation)
Public Members
uint32_t frequency_hz
Carrier wave frequency, in Hz, 0 means disabling the carrier
float duty_cycle
Carrier wave duty cycle (0~100%)
uint32_t polarity_active_low
Specify the polarity of carrier, by default it’s modulated to base signal’s high level
uint32_t always_on
If set, the carrier can always exist even there’s not transfer undergoing
Header File
• components/driver/include/driver/rmt_encoder.h
Functions
esp_err_t rmt_new_bytes_encoder(const rmt_bytes_encoder_config_t *config, rmt_encoder_handle_t
*ret_encoder)
Create RMT bytes encoder, which can encode byte stream into RMT symbols.
Parameters
• config –[in] Bytes encoder configuration
• ret_encoder –[out] Returned encoder handle
Returns
• ESP_OK: Create RMT bytes encoder successfully
• ESP_ERR_INVALID_ARG: Create RMT bytes encoder failed because of invalid argu-
ment
• ESP_ERR_NO_MEM: Create RMT bytes encoder failed because out of memory
• ESP_FAIL: Create RMT bytes encoder failed because of other error
esp_err_t rmt_new_copy_encoder(const rmt_copy_encoder_config_t *config, rmt_encoder_handle_t
*ret_encoder)
Create RMT copy encoder, which copies the given RMT symbols into RMT memory.
Parameters
• config –[in] Copy encoder configuration
• ret_encoder –[out] Returned encoder handle
Returns
• ESP_OK: Create RMT copy encoder successfully
• ESP_ERR_INVALID_ARG: Create RMT copy encoder failed because of invalid argu-
ment
• ESP_ERR_NO_MEM: Create RMT copy encoder failed because out of memory
• ESP_FAIL: Create RMT copy encoder failed because of other error
esp_err_t rmt_del_encoder(rmt_encoder_handle_t encoder)
Delete RMT encoder.
Parameters encoder –[in] RMT encoder handle, created by e.g
rmt_new_bytes_encoder()
Returns
Structures
struct rmt_encoder_t
Interface of RMT encoder.
Public Members
Note: The encoding function will also be called from an ISR context, thus the function must not call
any blocking API.
Note: It’s recommended to put this function implementation in the IRAM, to achieve a high perfor-
mance and less interrupt latency.
struct rmt_bytes_encoder_config_t
Bytes encoder configuration.
Public Members
rmt_symbol_word_t bit0
How to represent BIT0 in RMT symbol
rmt_symbol_word_t bit1
How to represent BIT1 in RMT symbol
uint32_t msb_first
Whether to encode MSB bit first
struct rmt_copy_encoder_config_t
Copy encoder configuration.
Type Definitions
Enumerations
enum rmt_encode_state_t
RMT encoding state.
Values:
enumerator RMT_ENCODING_COMPLETE
The encoding session is finished, the caller can continue with subsequent encoding
enumerator RMT_ENCODING_MEM_FULL
The encoding artifact memory is full, the caller should return from current encoding session
Header File
• components/driver/include/driver/rmt_types.h
Structures
struct rmt_tx_done_event_data_t
Type of RMT TX done event data.
Public Members
size_t num_symbols
The number of transmitted RMT symbols (only one round is counted if it’s a loop transmission)
struct rmt_rx_done_event_data_t
Type of RMT RX done event data.
Public Members
rmt_symbol_word_t *received_symbols
Point to the received RMT symbols
size_t num_symbols
The number of received RMT symbols
Type Definitions
Header File
• components/hal/include/hal/rmt_types.h
Unions
union rmt_symbol_word_t
#include <rmt_types.h> The layout of RMT symbol stored in memory, which is decided by the hardware design.
Public Members
Type Definitions
Note: User should select the clock source based on the power and resolution requirement
Espressif hardware products are designed for multiple use cases which may require different pull states on pins. For
this reason, the pull state of particular pins on certain products will need to be adjusted to provide the pull-ups required
in the SD bus.
SD pull-up requirements apply to cases where ESP32 uses the SPI or SDMMC controller to communicate with SD
cards. When an SD card is operating in SPI mode or 1-bit SD mode, the CMD and DATA (DAT0 - DAT3) lines
of the SD bus must be pulled up by 10 kOhm resistors. SD cards and SDIO devices should also have pull-ups on all
above-mentioned lines (regardless of whether these lines are connected to the host) in order to prevent them from
entering a wrong state.
By default, the MTDI bootstrapping pin is incompatible with the DAT2 line pull-up if the flash voltage is 3.3 V. For
more information, see MTDI Strapping Pin below.
This document has the following structure:
• Overview of compatibility between the default pull states on pins of Espressif’s products and the states required
by the SD bus
• Solutions - ideas on how to resolve compatibility issues
• Related information - other relevant information
Overview of Compatibility
This section provides an overview of compatibility issues that might occur when using SDIO (secure digital input
output). Since the SD bus needs to be connected to pull-ups, these issues should be resolved regardless of whether
they are related to master (host) or slave (device). Each issue has links to its respective solution. A solution for a host
and device may differ.
Modules
• ESP32-WROOM-32 Series, including ESP32-WROOM-32, ESP32-WROOM-32D, ESP32-WROOM-32U,
and ESP32-SOLO-1
– No Pull-ups
– Conflicts Between Bootstrap and SDIO on DAT2
• ESP32-WROVER Series, including ESP32-WROVER and ESP32-WROVER-I
– No Pull-ups
• ESP32-WROVER-B Series, including ESP32-WROVER-B and ESP32-WROVER-IB
– No Pull-ups
– Conflicts Between Bootstrap and SDIO on DAT2
Development Boards
• ESP32-PICO-KIT, including PICO-KIT v4.1, v4.0, and v3
– No Pull-ups
– Conflicts Between Bootstrap and SDIO on DAT2
– Download Mode Not Working (minor issue)
• ESP32-DevKitC, including ESP32-DevKitC v4 and v2
– No Pull-ups
– Conflicts Between Bootstrap and SDIO on DAT2
– Download Mode Not Working (minor issue)
• ESP-WROVER-KIT
– Required pull-ups are provided
– Pull-up Conflicts on GPIO13 (v4.1, v3, v2, and v1)
– Conflicts Between Bootstrap and SDIO on DAT2 (v4.1, v2, and v1)
– Download Mode Not Working (minor issue) (v2, v1)
You can determine the version of your ESP23-WROVER-KIT by checking which module is
mounted on it:
– ESP32-WROVER-B on v4.1
– ESP32-WROVER on v3
– ESP32-WROOM-32 on v1 and v2
• ESP32-LyraTD-MSC
– Required pull-ups are provided
– Conflicts Between Bootstrap and SDIO on DAT2
• ESP32-LyraT
– Required pull-ups are provided
– Pull-up Conflicts on GPIO13
Non-Espressif Hosts Please make sure that your SDIO host provides necessary pull-ups for all SD bus signals.
Solutions
No Pull-ups If you use a development board without pull-ups, you can do the following:
• If your host and slave device are on separate boards, replace one of them with a board that has pull-ups. For
the list of Espressif’s development boards with pull-ups, go to Development Boards.
• Attach external pull-ups by connecting each pin which requires a pull-up to VDD via a 10 kOhm resistor.
Pull-up Conflicts on GPIO13 If DAT3 of your device is not properly pulled up, you have the following options:
• Use 1-bit SD mode and tie the device’s DAT3 to VDD
• Use SPI mode
• Perform one of the following actions on the GPIO13 pin:
– Remove the pull-down resistors
– Attach a pull-up resistor of less than 5 kOhm (2 kOhm suggested)
– Pull it up or drive it high either by using the host or with 3.3 V on VDD in 1-bit SD mode
Conflicts Between Bootstrap and SDIO on DAT2 There is a conflict between the boot strapping requirements
of the ESP32 and the SDIO protocol. For details, see MTDI Strapping Pin.
To resolve the conflict, you have the following options:
1. (Recommended) Burn the flash voltage selection eFuses. This will permanently configure the internal regulator’
s output voltage to 3.3 V, and GPIO12 will not be used as a bootstrapping pin. After that, connect a pull-up
resistor to GPIO12.
Warning: Burning eFuses is irreversible! The issue list above might be out of date, so please make sure that
the module you are burning has a 3.3 V flash chip by checking the information on https://www.espressif.com/.
If you burn the 3.3 V eFuses on a module with a 1.8 V flash chip, the module will stop functioning.
If you are sure that you need to irreversibly burn eFuses, go to your ESP-IDF directory and run the following com-
mand:
This command will burn the XPD_SDIO_TIEH, XPD_SDIO_FORCE, and XPD_SDIO_REG eFuses. After all the
three eFuses are burned to value 1, the internal VDD_SDIO flash voltage regulator will be permanently set to 3.3 V.
You will see the following log if the burning succeeds:
espefuse.py v2.6
Connecting....
``components/esptool_py/esptool/espefuse.py summary``
No Pull-up on GPIO12 Your module is compatible with the SDIO protocol. Just connect GPIO12 to VDD via a
10 kOhm resistor.
Download Mode Not Working (minor issue) When the GPIO2 pin is pulled high in accordance with the SD
pull-up requirements, you cannot enter Download mode because GPIO2 is a bootstrapping pin which in this case
must be pulled low.
There are the following solutions:
• For boards that require shorting the GPIO0 and GPIO2 pins with a jumper, put the jumper in place, and the
auto-reset circuit will pull GPIO2 low along with GPIO0 before entering Download mode.
• For boards with components attached to their GPIO2 pin (such as pull-down resistors and/or LEDs), check the
schematic of your development board for anything connected to GPIO2.
– LEDs would not affect operation in most cases.
– Pull-down resistors can interfere with DAT0 signals and must be removed.
If the above solutions do not work for you, please determine if it is the host or slave device that has pull-ups affecting
their GPIO2, then locate these pull-ups and remove them.
Related Information
MTDI Strapping Pin MTDI (GPIO12) is used as a bootstrapping pin to select the output voltage of an internal
regulator (VDD_SDIO) which powers the flash chip. This pin has an internal pull-down, so, if left unconnected, it
will read low level at startup, which will lead to selecting the default 3.3 V operation.
All ESP32-WROVER modules, excluding ESP32-WROVER-B, use 1.8 V flash and have internal pull-ups on
GPIO12. Other modules that use 3.3 V flash have no pull-ups on the GPIO12 pin, and this pin is slightly pulled
down internally.
When adding a pull-up to this pin for SD card operation, consider the following:
• For boards that do not use the internal regulator (VDD_SDIO) to power flash, GPIO12 can be pulled high.
• For boards using 1.8 V flash chips, GPIO12 needs to be pulled high at reset. This is fully compatible with the
SD card operation.
• On boards using the internal regulator and a 3.3 V flash chip, GPIO12 must be pulled low at reset. This is
incompatible with the SD card operation. For reference information on compatibility of Espressif’s boards
with the SD card operation, see Overview of Compatibility.
Internal Pull-ups and Strapping Requirements Using external resistors is always preferable. However, Espres-
sif’s products have internal weak pull-up and pull-down resistors which can be enabled and used instead of external
ones. Please keep in mind that this solution cannot guarantee reliable SDIO communication.
With that said, the information about these internal pull-ups and strapping requirements can still be useful. Espressif
hardware products have different weak internal pull-ups / pull-downs connected to CMD and DATA pins. The table
below shows the default pull-up and pull-down states of the CMD and DATA pins.
Table 6: Default pull-up and pull-down states of the CMD and DATA pins
GPIO number Pin Name Startup State Strapping Requirement
15 CMD WPU
2 DAT0 WPD Low for Download mode
4 DAT1 WPD
12 DAT2 PU for 1.8 V flash; WPD High for 1.8 V flash; Low
for 3.3 V flash for 3.3 V flash
13 DAT3 WPU
Overview
ESP32’s SDMMC host peripheral has two slots. Each slot can be used independently to connect to an SD card,
SDIO device or eMMC chip.
• Slot 0 (SDMMC_HOST_SLOT_0) is an 8-bit slot. It uses HS1_* signals in the PIN MUX.
• Slot 1 (SDMMC_HOST_SLOT_1) is a 4-bit slot. It uses HS2_* signals in the PIN MUX.
The slots are connected to ESP32 GPIOs using IO MUX. Pin mappings of these slots are given in the table below.
The Card Detect and Write Protect signals can be routed to arbitrary pins using the GPIO matrix. To re-
serve the pins, set the cd and wp members of the sdmmc_slot_config_t structure before calling sd-
mmc_host_init_slot(). Please note that it is not advised to specify a Card Detect pin when working with
SDIO cards, because the card detect signal in ESP32 can also trigger SDIO slave interrupt.
Warning: Pins used by Slot 0 (HS1_*) are also used to connect the SPI flash chip in ESP32-WROOM and
ESP32-WROVER modules. These pins cannot be shared between an SD card and SPI flash. If you need to use
Slot 0, connect SPI flash to different pins and set eFuses accordingly.
• High Speed (40 MHz), 1/4-line (with SD cards), and 1/4/8-line (with 3.3 V eMMC)
• High Speed DDR (40 MHz), 4-line (with 3.3 V eMMC)
Speed modes not supported at present:
• High Speed DDR mode, 8-line eMMC
• UHS-I 1.8 V modes, 4-line SD cards
Of all the functions listed below, only the following ones will be used directly by most applications:
• sdmmc_host_init()
• sdmmc_host_init_slot()
• sdmmc_host_deinit()
Other functions, such as the ones given below, will be called by the SD/MMC protocol layer via function pointers in
the sdmmc_host_t structure:
• sdmmc_host_set_bus_width()
• sdmmc_host_set_card_clk()
• sdmmc_host_do_transaction()
With the default initializers for sdmmc_host_t and sdmmc_slot_config_t (SDMMC_HOST_DEFAULT and
SDMMC_SLOT_CONFIG_DEFAULT), SDMMC Host driver will attempt to use the widest bus supported by the card
(4 lines for SD, 8 lines for eMMC) and the frequency of 20 MHz.
In the designs where communication at 40 MHz frequency can be achieved, it is possible to increase the bus frequency
by changing the max_freq_khz field of sdmmc_host_t:
sdmmc_host_t host = SDMMC_HOST_DEFAULT();
host.max_freq_khz = SDMMC_FREQ_HIGHSPEED;
To configure the bus width, set the width field of sdmmc_slot_config_t. For example, to set 1-line mode:
sdmmc_slot_config_t slot = SDMMC_SLOT_CONFIG_DEFAULT();
slot.width = 1;
See also
See SD/SDIO/MMC Driver for the higher level driver which implements the protocol layer.
See SD SPI Host Driver for a similar driver which uses the SPI controller and is limited to SD protocol’s SPI mode.
See SD Pull-up Requirements for pullup support and compatibilities of modules and development kits.
API Reference
Header File
• components/driver/include/driver/sdmmc_host.h
Functions
esp_err_t sdmmc_host_init(void)
Initialize SDMMC host peripheral.
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if sdmmc_host_init was already called
• ESP_ERR_NO_MEM if memory can not be allocated
esp_err_t sdmmc_host_init_slot(int slot, const sdmmc_slot_config_t *slot_config)
Initialize given slot of SDMMC peripheral.
On the ESP32, SDMMC peripheral has two slots:
• Slot 0: 8-bit wide, maps to HS1_* signals in PIN MUX
• Slot 1: 4-bit wide, maps to HS2_* signals in PIN MUX
Card detect and write protect signals can be routed to arbitrary GPIOs using GPIO matrix.
Parameters
• slot –slot number (SDMMC_HOST_SLOT_0 or SDMMC_HOST_SLOT_1)
• slot_config –additional configuration for the slot
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if host has not been initialized using sdmmc_host_init
Parameters
• slot –slot number (SDMMC_HOST_SLOT_0 or SDMMC_HOST_SLOT_1)
• width –bus width (1, 4, or 8 for slot 0; 1 or 4 for slot 1)
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if slot number or width is not valid
Parameters
• slot –slot number (SDMMC_HOST_SLOT_0 or SDMMC_HOST_SLOT_1)
• freq_khz –card clock frequency, in kHz
Returns
• ESP_OK on success
• other error codes may be returned in the future
Note: This function is not thread safe w.r.t. init/deinit functions, and bus width/clock speed configuration
functions. Multiple tasks can call sdmmc_host_do_transaction as long as other sdmmc_host_* functions are
not called.
Parameters
• slot –slot number (SDMMC_HOST_SLOT_0 or SDMMC_HOST_SLOT_1)
• cmdinfo –pointer to structure describing command and data to transfer
Returns
• ESP_OK on success
• ESP_ERR_TIMEOUT if response or data transfer has timed out
• ESP_ERR_INVALID_CRC if response or data transfer CRC check has failed
• ESP_ERR_INVALID_RESPONSE if the card has sent an invalid response
• ESP_ERR_INVALID_SIZE if the size of data transfer is not valid in SD protocol
• ESP_ERR_INVALID_ARG if the data buffer is not in DMA capable memory
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if sdmmc_host_init function has not been called
Structures
struct sdmmc_slot_config_t
Extra configuration for SDMMC peripheral slot
Public Members
gpio_num_t gpio_cd
GPIO number of card detect signal.
gpio_num_t cd
GPIO number of card detect signal; shorter name.
gpio_num_t gpio_wp
GPIO number of write protect signal.
gpio_num_t wp
GPIO number of write protect signal; shorter name.
uint8_t width
Bus width used by the slot (might be less than the max width supported)
uint32_t flags
Features used by this slot.
Macros
SDMMC_HOST_SLOT_0
SDMMC slot 0.
SDMMC_HOST_SLOT_1
SDMMC slot 1.
SDMMC_HOST_DEFAULT()
Default sdmmc_host_t structure initializer for SDMMC peripheral.
Uses SDMMC peripheral, with 4-bit mode enabled, and max frequency set to 20MHz
SDMMC_SLOT_FLAG_INTERNAL_PULLUP
Enable internal pullups on enabled pins. The internal pullups are insufficient however, please make sure external
pullups are connected on the bus. This is for debug / example purpose only.
SDMMC_SLOT_NO_CD
indicates that card detect line is not used
SDMMC_SLOT_NO_WP
indicates that write protect line is not used
SDMMC_SLOT_WIDTH_DEFAULT
use the maximum possible width for the slot
SDMMC_SLOT_CONFIG_DEFAULT()
Macro defining default configuration of SDMMC host slot
Overview
The SD SPI host driver allows communicating with one or more SD cards by the SPI Master driver which makes use
of the SPI host. Each card is accessed through an SD SPI device represented by an sdspi_dev_handle_t spi_handle re-
turned when attaching the device to an SPI bus by calling sdspi_host_init_device. The bus should be already initialized
before (by spi_bus_initialize).
This driver’s naming pattern was adopted from the SDMMC Host driver due to their similarity. Likewise, the APIs
of both drivers are also very similar.
SD SPI driver (access the SD card in SPI mode) offers lower throughput but makes pin selection more flexible. With
the help of the GPIO matrix, an SPI peripheral’s signals can be routed to any ESP32 pin. Otherwise, if SDMMC
host driver is used (See SDMMC Host) to access the card in SD 1-bit/4-bit mode, higher throughput can be reached
but it requires routing the signals through their dedicated IO_MUX pins only.
With the help of SPI Master driver based on, the SPI bus can be shared among SD cards and other SPI devices. The
SPI Master driver will handle exclusive access from different tasks.
The SD SPI driver uses software-controlled CS signal.
How to Use
Other Details
Only the following driver’s API functions are normally used by most applications:
• sdspi_host_init()
• sdspi_host_init_device()
• sdspi_host_remove_device()
• sdspi_host_deinit()
Other functions are mostly used by the protocol level SD/SDIO/MMC driver via function pointers in the sd-
mmc_host_t structure. For more details, see the SD/SDIO/MMC Driver.
Note: SD over SPI does not support speeds above SDMMC_FREQ_DEFAULT due to the limitations of the SPI
driver.
Warning: If you want to share the SPI bus among SD card and other SPI devices, there are some restrictions,
see Sharing the SPI bus among SD card and other SPI devices.
Related Docs
Sharing the SPI bus among SD card and other SPI devices The SD card has a SPI mode, which allows it to be
communicated to as a SPI device. But there are some restrictions that we need to pay attention to.
Pin loading of other devices When adding more devices onto the same bus, the overall pin loading increases. The
loading consists of AC loading (pin capacitor) and DC loading (pull-ups).
AC loading SD cards, which are designed for high-speed communications, have small pin capacitors (AC loading)
to work until 50MHz. However, the other attached devices will increase the pin’s AC loading.
Heavy AC loading of a pin may prevent the pin from being toggled quickly. By using an oscilloscope, you will see
the edges of the pin become smoother and not ideal any more (the gradient of the edge is smaller). The setup timing
requirements of an SD card may be violoated when the card is connected to such bus. Even worse, the clock from
the host may not be recognized by the SD card and other SPI devices on the same bus.
This issue may be more obvious if other attached devices are not designed to work at the same frequency as the SD
card, because they may have larger pin capacitors.
To see if your pin AC loading is too heavy, you can try the following tests:
(Terminology: launch edge: at which clock edge the data start to toggle; latch edge: at which clock edge the data is
supposed to be sampled by the receiver, for SD cad, it’s the rising edge.)
1. Use an oscilloscope to see the clock and compare the data line to the clock. - If you see the clock is not fast
enough (for example, the rising/falling edge is longer than 1/4 of the clock cycle), it means the clock is skewed
too much. - If you see the data line unstable before the latch edge of the clock, it means the load of the data
line is too large.
You may also observed the corresponding phenomenon (data delayed largely from launching edge of clock)
with logic analyzers. But it’s not as obvious as with an oscilloscope.
2. Try to use slower clock frequency.
If the lower frequency can work while the higher frequency can’t, it’s an indication of the AC loading on
the pins is too large.
If the AC loading of the pins is too large, you can either use other faster devices (with lower pin load) or slow down
the clock speed.
DC loading The pull-ups required by SD cards are usually around 10 kOhm to 50 kOhm, which may be too strong
for some other SPI devices.
Check the specification of your device about its DC output current , it should be larger than 700uA, otherwise the
device output may not be read correctly.
Initialization sequence
Note: If you see any problem in the following steps, please make sure the timing is correct first. You can try to
slow down the clock speed (SDMMC_FREQ_PROBING = 400 KHz for SD card) to avoid the influence of pin AC
loading (see above section).
When using ab SD card with other SPI devices on the same SPI bus, due to the restrictions of the SD card startup
flow, the following initialization sequence should be followed: (See also storage/sd_card)
1. Initialize the SPI bus properly by spi_bus_initialize.
2. Tie the CS lines of all other devices than the SD card to high. This is to avoid conflicts to the SD card in the
following step.
You can do this by either:
1. Attach devices to the SPI bus by calling spi_bus_add_device. This function will initialize the GPIO that
is used as CS to the idle level: high.
2. Initialize GPIO on the CS pin that needs to be tied up before actually adding a new device.
3. Rely on the internal/external pull-up (not recommended) to pull-up all the CS pins when the GPIOs of
ESP are not initialized yet. You need to check carefull the pull-up is strong enough and there are no other
pull-downs that will influence the pull-up (For example, internal pull-down should be enabled).
3. Mount the card to the filesystem by calling esp_vfs_fat_sdspi_mount.
This step will put the SD card into the SPI mode, which SHOULD be done before all other SPI communications
on the same bus. Otherwise the card will stay in the SD mode, in which mode it may randomly respond to any
SPI communications on the bus, even when its CS line is not addressed.
If you want to test this behavior, please also note that, once the card is put into SPI mode, it will not return to
SD mode before next power cycle, i.e. powered down and powered up again.
4. Now you can talk to other SPI devices freely!
API Reference
Header File
• components/driver/include/driver/sdspi_host.h
Functions
esp_err_t sdspi_host_init(void)
Initialize SD SPI driver.
Returns
• ESP_OK on success
• other error codes may be returned in future versions
esp_err_t sdspi_host_init_device(const sdspi_device_config_t *dev_config, sdspi_dev_handle_t
*out_handle)
Attach and initialize an SD SPI device on the specific SPI bus.
Note: Initialize the SPI bus by spi_bus_initialize() before calling this function.
Note: The SDIO over sdspi needs an extra interrupt line. Call gpio_install_isr_service() before
this function.
Parameters
• dev_config –pointer to device configuration structure
• out_handle –Output of the handle to the sdspi device.
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if sdspi_host_init_device has invalid arguments
• ESP_ERR_NO_MEM if memory can not be allocated
• other errors from the underlying spi_master and gpio drivers
Note: This function is not thread safe w.r.t. init/deinit functions, and bus width/clock speed configuration
functions. Multiple tasks can call sdspi_host_do_transaction as long as other sdspi_host_* functions are not
called.
Parameters
• handle –Handle of the sdspi device
• cmdinfo –pointer to structure describing command and data to transfer
Returns
• ESP_OK on success
• ESP_ERR_TIMEOUT if response or data transfer has timed out
• ESP_ERR_INVALID_CRC if response or data transfer CRC check has failed
• ESP_ERR_INVALID_RESPONSE if the card has sent an invalid response
Parameters
• host –Handle of the sdspi device
• freq_khz –card clock frequency, in kHz
Returns
• ESP_OK on success
• other error codes may be returned in the future
esp_err_t sdspi_host_deinit(void)
Release resources allocated using sdspi_host_init.
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if sdspi_host_init function has not been called
Structures
struct sdspi_device_config_t
Extra configuration for SD SPI device.
Public Members
spi_host_device_t host_id
SPI host to use, SPIx_HOST (see spi_types.h).
gpio_num_t gpio_cs
GPIO number of CS signal.
gpio_num_t gpio_cd
GPIO number of card detect signal.
gpio_num_t gpio_wp
GPIO number of write protect signal.
gpio_num_t gpio_int
GPIO number of interrupt line (input) for SDIO card.
Macros
SDSPI_DEFAULT_HOST
SDSPI_DEFAULT_DMA
SDSPI_HOST_DEFAULT()
Default sdmmc_host_t structure initializer for SD over SPI driver.
Uses SPI mode and max frequency set to 20MHz
‘slot’should be set to an sdspi device initialized by sdspi_host_init_device().
SDSPI_SLOT_NO_CD
indicates that card detect line is not used
SDSPI_SLOT_NO_WP
indicates that write protect line is not used
SDSPI_SLOT_NO_INT
indicates that interrupt line is not used
SDSPI_DEVICE_CONFIG_DEFAULT()
Macro defining default configuration of SD SPI device.
Type Definitions
Overview
The ESP32 SDIO Card peripherals (Host, Slave) shares two sets of pins as below table. The first set is
usually occupied by SPI0 bus which is responsible for the SPI flash holding the code to run. This means
SDIO slave driver can only runs on the second set of pins while SDIO host is not using it.
The SDIO slave can run under 3 modes: SPI, 1-bit SD and 4-bit SD modes, which is detected automat-
ically by the hardware. According to the SDIO specification, CMD and DAT0-3 lines should be pulled
up no matter in 1-bit, 4-bit or SPI mode.
Connections
Pin Name Corresponding pins in SPI mode Slot1 Slot2
GPIO Number
CLK SCLK 6 14
CMD MOSI 11 15
DAT0 MISO 7 2
DAT1 Interrupt 8 4
DAT2 N.C. (pullup) 9 12
DAT3 #CS 10 13
• 1-bit SD mode: Connect CLK, CMD, DAT0, DAT1 pins and the ground.
• 4-bit SD mode: Connect all pins and the ground.
• SPI mode: Connect SCLK, MOSI, MISO, Interrupt, #CS pins and the ground.
Note: Please check if CMD and DATA lines D0-D3 of the card are properly pulled up by 10 KOhm resistors. This
should be ensured even in 1-bit mode or SPI mode. Most official modules don’t offer these pullups internally. If
you are using official development boards, check Overview of Compatibility to see whether your development boards
have such pullups.
Note: Most official modules have conflicts on strapping pins with the SDIO slave function. If you are using a ESP32
module with 3.3 V flash inside, you have to burn the EFUSE when you are developing on the module for the first
time. See Overview of Compatibility to see how to make your modules compatible with the SDIO.
Here is a list for modules/kits with 3.3 V flash:
• Modules: ESP32-PICO-D4, ESP32-WROOM-32 series (including ESP32-SOLO-1), ESP32-WROVER-B
and ESP32-WROVER-IB
• Kits: ESP32-PICO-KIT, ESP32-DevKitC (till v4), ESP32-WROVER-KIT (v4.1 (also known as ESP32-
WROVER-KIT-VB), v2, v1 (also known as DevKitJ v1))
You can tell the version of your ESP23-WROVER-KIT version from the module on it: v4.1 are with ESP32-
WROVER-B modules, v3 are with ESP32-WROVER modules, while v2 and v1 are with ESP32-WROOM-32
modules.
Note: Register names in ESP32 Technical Reference Manual > SDIO Slave Controller [PDF] are oriented from the
point of view of the host, i.e. ‘rx’registers refer to sending, while ‘tx’registers refer to receiving. We’re not
using tx or rx in the driver to avoid ambiguities.
• FIFO: specific address in Function 1 that can be access by CMD53 to read/write large amount of data. The
address is related to the length requested to read from/write to the slave in a single transfer: requested length =
0x1F800-address.
• Ownership: When the driver takes ownership of a buffer, it means the driver can randomly read/write the
buffer (usually via DMA). The application should not read/write the buffer until the ownership is returned to
the application. If the application reads from a buffer owned by a receiving driver, the data read can be random;
if the application writes to a buffer owned by a sending driver, the data sent may be corrupted.
• Requested length: The length requested in one transfer determined by the FIFO address.
• Transfer length: The length requested in one transfer determined by the CMD53 byte/block count field.
Note: Requested length is different from the transfer length. ESP32 slave DMA base on the requested length rather
than the transfer length. The transfer length should be no shorter than the requested length, and the rest part will be
filled with 0 (sending) or discard (receiving).
• Receiving buffer size: The buffer size is pre-defined between the host and the slave before communication
starts. Slave application has to set the buffer size during initialization by the recv_buffer_size member
of sdio_slave_config_t.
• Interrupts: the esp32 slave support interrupts in two directions: from host to slave (called slave interrupts below)
and from slave to host (called host interrupts below). See more in Interrupts.
Communication with ESP SDIO Slave The host should initialize the ESP32 SDIO slave according to the standard
SDIO initialization process (Sector 3.1.2 of SDIO Simplified Specification), which is described briefly in ESP SDIO
Slave Initialization.
Furthermore, there’s an ESP32-specific upper-level communication protocol upon the CMD52/CMD53 to Func
1. Please refer to ESP SDIO Slave Protocol. There is also a component ESP Serial Slave Link for ESP32 master to
communicate with ESP32 SDIO slave, see example peripherals/sdio when programming your host.
Interrupts There are interrupts from host to slave, and from slave to host to help communicating conveniently.
Slave Interrupts The host can interrupt the slave by writing any one bit in the register 0x08D. Once any bit
of the register is set, an interrupt is raised and the SDIO slave driver calls the callback function defined in the
slave_intr_cb member in the sdio_slave_config_t structure.
Note: The callback function is called in the ISR, do not use any delay, loop or spinlock in the callback.
There’s another set of functions can be used. You can call sdio_slave_wait_int to wait for an interrupt
within a certain time, or call sdio_slave_clear_int to clear interrupts from host. The callback function can
work with the wait functions perfectly.
Host Interrupts The slave can interrupt the host by an interrupt line (at certain time) which is level sensitive. When
the host see the interrupt line pulled down, it may read the slave interrupt status register, to see the interrupt source.
Host can clear interrupt bits, or choose to disable a interrupt source. The interrupt line will hold active until all the
sources are cleared or disabled.
There are several dedicated interrupt sources as well as general purpose sources. see sdio_slave_hostint_t
for more information.
Shared Registers There are 52 8-bit R/W shared registers to share information between host and slave. The slave
can write or read the registers at any time by sdio_slave_read_reg and sdio_slave_write_reg. The
host can access (R/W) the register by CMD52 or CMD53.
Receiving FIFO When the host is going to send the slave some packets, it has to check whether the slave is ready
to receive by reading the buffer number of slave.
To allow the host sending data to the slave, the application has to load buffers to the slave driver by the following
steps:
1. Register the buffer by calling sdio_slave_recv_register_buf, and get the handle of the registered
buffer. The driver will allocate memory for the linked-list descriptor needed to link the buffer onto the hard-
ware. The size of these buffers should equal to the Receiving buffer size.
2. Load buffers onto the driver by passing the buffer handle to sdio_slave_recv_load_buf.
3. Get the received data by calling sdio_slave_recv or sdio_slave_recv_packet. If non-blocking
call is needed, set wait=0.
The difference between two APIs is that, sdio_slave_recv_packet gives more information about
packet, which can consist of several buffers. When ESP_ERR_NOT_FINISHED is returned by this API,
you should call this API iteratively until the return value is ESP_OK. All the continuous buffers returned with
ESP_ERR_NOT_FINISHED, together with the last buffer returned with ESP_OK, belong to one packet from
the host. Call sdio_slave_recv_get_buf to get the address of the received data, and the actual length
received in each buffer. The packet length is the sum of received length of all the buffers in the packet.
If the host never send data longer than the Receiving buffer size, or you don’t care about the packet boundary
(e.g. the data is only a byte stream), you can call the simpler version sdio_slave_recv instead.
4. Pass the handle of processed buffer back to the driver by sdio_recv_load_buf again.
Note: To avoid overhead from copying data, the driver itself doesn’t have any buffer inside, the application is
responsible to offer new buffers in time. The DMA will automatically store received data to the buffer.
Sending FIFO Each time the slave has data to send, it raises an interrupt and the host will request for the packet
length. There are two sending modes:
• Stream Mode: when a buffer is loaded to the driver, the buffer length will be counted into the packet length
requested by host in the incoming communications. Regardless previous packets are sent or not. This means
the host can get data of several buffers in one transfer.
• Packet Mode: the packet length is updated packet by packet, and only when previous packet is sent. This
means that the host can only get data of one buffer in one transfer.
Note: To avoid overhead from copying data, the driver itself doesn’t have any buffer inside. Namely, the DMA
takes data directly from the buffer provided by the application. The application should not touch the buffer until the
sending is finished.
The sending mode can be set in the sending_mode member of sdio_slave_config_t, and the buffer num-
bers can be set in the send_queue_size. All the buffers are restricted to be no larger than 4092 bytes. Though
in the stream mode several buffers can be sent in one transfer, each buffer is still counted as one in the queue.
The application can call sdio_slave_transmit to send packets. In this case the function returns when the
transfer is successfully done, so the queue is not fully used. When higher effeciency is required, the application can
use the following functions instead:
1. Pass buffer information (address, length, as well as an arg indicating the buffer) to
sdio_slave_send_queue. If non-blocking call is needed, set wait=0. If the wait is not
portMAX_DELAY (wait until success), application has to check the result to know whether the data is put in
to the queue or discard.
2. Call sdio_slave_send_get_finished to get and deal with a finished transfer. A buffer should be keep
unmodified until returned from sdio_slave_send_get_finished. This means the buffer is actually
sent to the host, rather than just staying in the queue.
There are several ways to use the arg in the queue parameter:
1. Directly point arg to a dynamic-allocated buffer, and use the arg to free it when transfer finished.
2. Wrap transfer informations in a transfer structure, and point arg to the structure. You can use the structure
to do more things like:
typedef struct {
uint8_t* buffer;
size_t size;
int id;
}sdio_transfer_t;
3. Working with the receiving part of this driver, point arg to the receive buffer handle of this buffer. So that
we can directly use the buffer to receive data when it’s sent:
uint8_t buffer[256]={1,2,3,4,5,6,7,8};
sdio_slave_buf_handle_t handle = sdio_slave_recv_register_buf(buffer);
sdio_slave_send_queue(buffer, 8, handle, portMAX_DELAY);
Application Example
API Reference
Header File
• components/hal/include/hal/sdio_slave_types.h
Enumerations
enum sdio_slave_hostint_t
Mask of interrupts sending to the host.
Values:
enumerator SDIO_SLAVE_HOSTINT_BIT0
General purpose interrupt bit 0.
enumerator SDIO_SLAVE_HOSTINT_BIT1
enumerator SDIO_SLAVE_HOSTINT_BIT2
enumerator SDIO_SLAVE_HOSTINT_BIT3
enumerator SDIO_SLAVE_HOSTINT_BIT4
enumerator SDIO_SLAVE_HOSTINT_BIT5
enumerator SDIO_SLAVE_HOSTINT_BIT6
enumerator SDIO_SLAVE_HOSTINT_BIT7
enumerator SDIO_SLAVE_HOSTINT_SEND_NEW_PACKET
New packet available.
enum sdio_slave_timing_t
Timing of SDIO slave.
Values:
enumerator SDIO_SLAVE_TIMING_PSEND_PSAMPLE
Send at posedge, and sample at posedge. Default value for HS mode. Normally there’s no problem
using this to work in DS mode.
enumerator SDIO_SLAVE_TIMING_NSEND_PSAMPLE
Send at negedge, and sample at posedge. Default value for DS mode and below.
enumerator SDIO_SLAVE_TIMING_PSEND_NSAMPLE
Send at posedge, and sample at negedge.
enumerator SDIO_SLAVE_TIMING_NSEND_NSAMPLE
Send at negedge, and sample at negedge.
enum sdio_slave_sending_mode_t
Configuration of SDIO slave mode.
Values:
enumerator SDIO_SLAVE_SEND_STREAM
Stream mode, all packets to send will be combined as one if possible.
enumerator SDIO_SLAVE_SEND_PACKET
Packet mode, one packets will be sent one after another (only increase packet_len if last packet sent).
Header File
• components/driver/include/driver/sdio_slave.h
Functions
esp_err_t sdio_slave_initialize(sdio_slave_config_t *config)
Initialize the sdio slave driver
Parameters config –Configuration of the sdio slave driver.
Returns
• ESP_ERR_NOT_FOUND if no free interrupt found.
• ESP_ERR_INVALID_STATE if already initialized.
• ESP_ERR_NO_MEM if fail due to memory allocation failed.
• ESP_OK if success
void sdio_slave_deinit(void)
De-initialize the sdio slave driver to release the resources.
esp_err_t sdio_slave_start(void)
Start hardware for sending and receiving, as well as set the IOREADY1 to 1.
Note: The driver will continue sending from previous data and PKT_LEN counting, keep data received as
well as start receiving from current TOKEN1 counting. See sdio_slave_reset.
Returns
• ESP_ERR_INVALID_STATE if already started.
• ESP_OK otherwise.
void sdio_slave_stop(void)
Stop hardware from sending and receiving, also set IOREADY1 to 0.
Note: this will not clear the data already in the driver, and also not reset the PKT_LEN and TOKEN1
counting. Call sdio_slave_reset to do that.
esp_err_t sdio_slave_reset(void)
Clear the data still in the driver, as well as reset the PKT_LEN and TOKEN1 counting.
Returns always return ESP_OK.
sdio_slave_buf_handle_t sdio_slave_recv_register_buf(uint8_t *start)
Register buffer used for receiving. All buffers should be registered before used, and then can be used (again)
in the driver by the handle returned.
Note: The driver will use and only use the amount of space specified in the recv_buffer_size member
set in the sdio_slave_config_t. All buffers should be larger than that. The buffer is used by the DMA,
so it should be DMA capable and 32-bit aligned.
Note: Call sdio_slave_load_buf with the handle to re-load the buffer onto the link list, and re-
ceive with the same buffer again. The address and length of the buffer got here is the same as got from
sdio_slave_get_buffer.
Parameters
• handle_ret –Handle of the buffer holding received data. Use this handle in
sdio_slave_recv_load_buf() to receive in the same buffer again.
• wait –Time to wait before data received.
Returns
• ESP_ERR_INVALID_ARG if handle_ret is NULL
• ESP_ERR_TIMEOUT if timeout before receiving new data
• ESP_ERR_NOT_FINISHED if returned buffer is not the end of a packet from the host,
should call this API again until the end of a packet
• ESP_OK if success
Note: Call sdio_slave_load_buf with the handle to re-load the buffer onto the link list, and re-
ceive with the same buffer again. The address and length of the buffer got here is the same as got from
sdio_slave_get_buffer.
Parameters
• handle_ret –Handle to the buffer holding received data. Use this handle in
sdio_slave_recv_load_buf to receive in the same buffer again.
• out_addr –[out] Output of the start address, set to NULL if not needed.
• out_len –[out] Actual length of the data in the buffer, set to NULL if not needed.
• wait –Time to wait before data received.
Returns
• ESP_ERR_INVALID_ARG if handle_ret is NULL
• ESP_ERR_TIMEOUT if timeout before receiving new data
• ESP_OK if success
Parameters
• pos –register address, 0-11, 14-15, 18-19, 24-27 and 32-63, other address are reserved.
• reg –the value to write.
Returns ESP_ERR_INVALID_ARG if address wrong, otherwise ESP_OK.
sdio_slave_hostint_t sdio_slave_get_host_intena(void)
Get the interrupt enable for host.
Returns the interrupt mask.
void sdio_slave_set_host_intena(sdio_slave_hostint_t mask)
Set the interrupt enable for host.
Parameters mask –Enable mask for host interrupt.
esp_err_t sdio_slave_send_host_int(uint8_t pos)
Interrupt the host by general purpose interrupt.
Parameters pos –Interrupt num, 0-7.
Returns
• ESP_ERR_INVALID_ARG if interrupt num error
• ESP_OK otherwise
Parameters
• pos –Interrupt source number to wait for. is set.
• wait –Time to wait before interrupt triggered.
Returns ESP_OK if success, ESP_ERR_TIMEOUT if timeout.
Structures
struct sdio_slave_config_t
Configuration of SDIO slave.
Public Members
sdio_slave_timing_t timing
timing of sdio_slave. see sdio_slave_timing_t.
sdio_slave_sending_mode_t sending_mode
mode of sdio_slave. SDIO_SLAVE_MODE_STREAM if the data needs to be sent as much as possible;
SDIO_SLAVE_MODE_PACKET if the data should be sent in packets.
int send_queue_size
max buffers that can be queued before sending.
size_t recv_buffer_size
If buffer_size is too small, it costs more CPU time to handle larger number of buffers. If buffer_size is
too large, the space larger than the transaction length is left blank but still counts a buffer, and the buffers
are easily run out. Should be set according to length of data really transferred. All data that do not fully
fill a buffer is still counted as one buffer. E.g. 10 bytes data costs 2 buffers if the size is 8 bytes per
buffer. Buffer size of the slave pre-defined between host and slave before communication. All receive
buffer given to the driver should be larger than this.
sdio_event_cb_t event_cb
when the host interrupts slave, this callback will be called with interrupt number (0-7).
uint32_t flags
Features to be enabled for the slave, combinations of SDIO_SLAVE_FLAG_*.
Macros
SDIO_SLAVE_RECV_MAX_BUFFER
SDIO_SLAVE_FLAG_DAT2_DISABLED
It is required by the SD specification that all 4 data lines should be used and pulled up even in 1-bit mode or
SPI mode. However, as a feature, the user can specify this flag to make use of DAT2 pin in 1-bit mode. Note
that the host cannot read CCCR registers to know we don’t support 4-bit mode anymore, please do this at
your own risk.
SDIO_SLAVE_FLAG_HOST_INTR_DISABLED
The DAT1 line is used as the interrupt line in SDIO protocol. However, as a feature, the user can specify this
flag to make use of DAT1 pin of the slave in 1-bit mode. Note that the host has to do polling to the interrupt
registers to know whether there are interrupts from the slave. And it cannot read CCCR registers to know we
don’t support 4-bit mode anymore, please do this at your own risk.
SDIO_SLAVE_FLAG_INTERNAL_PULLUP
Enable internal pullups for enabled pins. It is required by the SD specification that all the 4 data lines should
be pulled up even in 1-bit mode or SPI mode. Note that the internal pull-ups are not sufficient for stable
communication, please do connect external pull-ups on the bus. This is only for example and debug use.
Type Definitions
Introduction
ESP32 has a second-order sigma-delta modulation module. This driver configures the channels of the sigma-delta
module.
Functionality Overview
There are 8 independent sigma-delta modulation channels identified with sigmadelta_channel_t. Each chan-
nel is capable to output the binary, hardware generated signal with the sigma-delta modulation.
Selected channel should be set up by providing configuration parameters in sigmadelta_config_t and then
applying this configuration with sigmadelta_config().
Another option is to call individual functions, that will configure all required parameters one by one:
• Prescaler of the sigma-delta generator - sigmadelta_set_prescale()
• Duty of the output signal - sigmadelta_set_duty()
• GPIO pin to output modulated signal - sigmadelta_set_pin()
The range of the ‘duty’input parameter of sigmadelta_set_duty() is from -128 to 127 (eight bit
signed integer). If zero value is set, then the output signal’s duty will be about 50%, see description of sig-
madelta_set_duty().
Typically, if the sigma-delta signal is connected to an LED, you don’t have to add any filter between them (because
our eyes are a low pass filter naturally). However, if you want to check the real voltage or watch the analog waveform,
you need to design an analog low pass filter. Also, it is recommended to use an active filter instead of a passive filter
to gain better isolation and not lose too much voltage.
For example, you can take the following Sallen-Key topology Low Pass Filter as a reference.
Application Example
API Reference
Header File
• components/driver/include/driver/sigmadelta.h
Functions
esp_err_t sigmadelta_config(const sigmadelta_config_t *config)
Configure Sigma-delta channel.
Parameters config –Pointer of Sigma-delta channel configuration struct
Returns
• ESP_OK Success
• ESP_ERR_INVALID_STATE sigmadelta driver already initialized
• ESP_ERR_INVALID_ARG Parameter error
esp_err_t sigmadelta_set_duty(sigmadelta_channel_t channel, int8_t duty)
Set Sigma-delta channel duty.
Parameters
• channel –Sigma-delta channel number
• duty –Sigma-delta duty of one channel, the value ranges from -128 to 127, recommended
range is -90 ~ 90. The waveform is more like a random one in this range.
Returns
• ESP_OK Success
• ESP_ERR_INVALID_STATE sigmadelta driver has not been initialized
• ESP_ERR_INVALID_ARG Parameter error
Structures
struct sigmadelta_config_t
Sigma-delta configure struct.
Public Members
sigmadelta_channel_t channel
Sigma-delta channel number
int8_t sigmadelta_duty
Sigma-delta duty, duty ranges from -128 to 127.
uint8_t sigmadelta_prescale
Sigma-delta prescale, prescale ranges from 0 to 255.
gpio_num_t sigmadelta_gpio
Sigma-delta output io number, refer to gpio.h for more details.
Header File
• components/hal/include/hal/sigmadelta_types.h
Enumerations
enum sigmadelta_port_t
SIGMADELTA port number, the max port number is (SIGMADELTA_NUM_MAX -1).
Values:
enumerator SIGMADELTA_PORT_0
SIGMADELTA port 0
enumerator SIGMADELTA_PORT_MAX
SIGMADELTA port max
enum sigmadelta_channel_t
Sigma-delta channel list.
Values:
enumerator SIGMADELTA_CHANNEL_0
Sigma-delta channel 0
enumerator SIGMADELTA_CHANNEL_1
Sigma-delta channel 1
enumerator SIGMADELTA_CHANNEL_2
Sigma-delta channel 2
enumerator SIGMADELTA_CHANNEL_3
Sigma-delta channel 3
enumerator SIGMADELTA_CHANNEL_4
Sigma-delta channel 4
enumerator SIGMADELTA_CHANNEL_5
Sigma-delta channel 5
enumerator SIGMADELTA_CHANNEL_6
Sigma-delta channel 6
enumerator SIGMADELTA_CHANNEL_7
Sigma-delta channel 7
enumerator SIGMADELTA_CHANNEL_MAX
Sigma-delta channel max
SPI Master driver is a program that controls ESP32’s SPI peripherals while they function as masters.
Terminology
The terms used in relation to the SPI master driver are given in the table below.
Term Definition
Host The SPI controller peripheral inside ESP32 that initiates SPI transmissions over the bus, and acts as an SPI
Master.
De- SPI slave device. An SPI bus may be connected to one or more Devices. Each Device shares the MOSI,
vice MISO and SCLK signals but is only active on the bus when the Host asserts the Device’s individual CS
line.
Bus A signal bus, common to all Devices connected to one Host. In general, a bus includes the following lines:
MISO, MOSI, SCLK, one or more CS lines, and, optionally, QUADWP and QUADHD. So Devices are
connected to the same lines, with the exception that each Device has its own CS line. Several Devices can
also share one CS line if connected in the daisy-chain manner.
MOSIMaster Out, Slave In, a.k.a. D. Data transmission from a Host to Device. Also data0 signal in Octal/OPI
mode.
MISOMaster In, Slave Out, a.k.a. Q. Data transmission from a Device to Host. Also data1 signal in Octal/OPI
mode.
SCLKSerial Clock. Oscillating signal generated by a Host that keeps the transmission of data bits in sync.
CS Chip Select. Allows a Host to select individual Device(s) connected to the bus in order to send or receive
data.
QUADWP Write Protect signal. Used for 4-bit (qio/qout) transactions. Also for data2 signal in Octal/OPI mode.
QUADHD Hold signal. Used for 4-bit (qio/qout) transactions. Also for data3 signal in Octal/OPI mode.
DATA4Data4 signal in Octal/OPI mode.
DATA5Data5 signal in Octal/OPI mode.
DATA6Data6 signal in Octal/OPI mode.
DATA7Data7 signal in Octal/OPI mode.
As- The action of activating a line.
ser-
tion
De- The action of returning the line back to inactive (back to idle) status.
assertion
Trans-One instance of a Host asserting a CS line, transferring data to and from a Device, and de-asserting the CS
ac- line. Transactions are atomic, which means they can never be interrupted by another transaction.
tion
LaunchEdge of the clock at which the source register launches the signal onto the line.
edge
Latch Edge of the clock at which the destination register latches in the signal.
edge
Driver Features
The SPI master driver governs communications of Hosts with Devices. The driver supports the following features:
• Multi-threaded environments
• Transparent handling of DMA transfers while reading and writing data
• Automatic time-division multiplexing of data coming from different Devices on the same signal bus, see SPI
Bus Lock.
Warning: The SPI master driver has the concept of multiple Devices connected to a single bus (sharing a single
ESP32 SPI peripheral). As long as each Device is accessed by only one task, the driver is thread safe. However,
if multiple tasks try to access the same SPI Device, the driver is not thread-safe. In this case, it is recommended
to either:
• Refactor your application so that each SPI peripheral is only accessed by a single task at a time.
• Add a mutex lock around the shared Device using xSemaphoreCreateMutex.
SPI Features
SPI Master
SPI Bus Lock To realize the multiplexing of different devices from different drivers, including SPI Master, SPI
Flash, etc., an SPI bus lock is applied on each SPI bus. Drivers can attach their devices onto the bus with the arbitration
of the lock.
Each bus lock is initialized with a BG (background) service registered. All devices that request transactions on the
bus should wait until the BG is successfully disabled.
• For SPI1 bus, the BG is the cache. The bus lock will disable the cache before device operations start, and
enable it again after device releases the lock. No devices on SPI1 is allowed to use ISR, since it is meaningless
for the task to yield to other tasks when the cache is disabled.
There are quite a few limitations when using SPI Master driver on the SPI1 bus. See Notes on Using the SPI
Master driver on SPI1 Bus.
• For other buses, the driver may register its ISR as the BG. When a device task requests for exclusive use of
the bus, the bus lock will block the task and try to disable ISR. After ISR is successfully disabled, the bus lock
will then unblock the device task and allow it to exclusively use the bus. When the task releases the lock, the
lock will also try to resume ISR if there are pending transactions in ISR.
SPI Transactions
An SPI bus transaction consists of five phases which can be found in the table below. Any of these phases can be
skipped.
Phase Description
Com- In this phase, a command (0-16 bit) is written to the bus by the Host.
mand
Ad- In this phase, an address (0-64 bit) is transmitted over the bus by the Host.
dress
Write Host sends data to a Device. This data follows the optional command and address phases and is indis-
tinguishable from them at the electrical level.
Dummy This phase is configurable and is used to meet the timing requirements.
Read Device sends data to its Host.
The attributes of a transaction are determined by the bus configuration structure spi_bus_config_t, de-
vice configuration structure spi_device_interface_config_t, and transaction configuration structure
spi_transaction_t.
An SPI Host can send full-duplex transactions, during which the read and write phases occur simultaneously. The
total transaction length is determined by the sum of the following members:
• spi_device_interface_config_t::command_bits
• spi_device_interface_config_t::address_bits
• spi_transaction_t::length
While the member spi_transaction_t::rxlength only determines the length of data received into the
buffer.
In half-duplex transactions, the read and write phases are not simultaneous (one direction at a time).
The lengths of the write and read phases are determined by spi_transaction_t::length and
spi_transaction_t::rxlength respectively.
The command and address phases are optional, as not every SPI device requires a command and/or address. This is
reflected in the Device’s configuration: if spi_device_interface_config_t::command_bits and/or
spi_device_interface_config_t::address_bits are set to zero, no command or address phase will
occur.
The read and write phases can also be optional, as not every transaction requires both writing and reading data. If
spi_transaction_t::rx_buffer is NULL and SPI_TRANS_USE_RXDATA is not set, the read phase is
skipped. If spi_transaction_t::tx_buffer is NULL and SPI_TRANS_USE_TXDATA is not set, the
write phase is skipped.
The driver supports two types of transactions: the interrupt transactions and polling transactions. The programmer
can choose to use a different transaction type per Device. If your Device requires both transaction types, see Notes
on Sending Mixed Transactions to the Same Device.
Interrupt Transactions Interrupt transactions will block the transaction routine until the transaction completes,
thus allowing the CPU to run other tasks.
An application task can queue multiple transactions, and the driver will automatically handle them one-by-one in the
interrupt service routine (ISR). It allows the task to switch to other procedures until all the transactions complete.
Polling Transactions Polling transactions do not use interrupts. The routine keeps polling the SPI Host’s status
bit until the transaction is finished.
All the tasks that use interrupt transactions can be blocked by the queue. At this point, they will need to wait for the
ISR to run twice before the transaction is finished. Polling transactions save time otherwise spent on queue handling
and context switching, which results in smaller transaction duration. The disadvantage is that the CPU is busy while
these transactions are in progress.
The spi_device_polling_end() routine needs an overhead of at least 1 us to unblock other tasks when
the transaction is finished. It is strongly recommended to wrap a series of polling transactions using the functions
spi_device_acquire_bus() and spi_device_release_bus() to avoid the overhead. For more in-
formation, see Bus Acquiring.
Transaction Line Mode Supported line modes for ESP32 are listed as follows, to make use of these modes, set
the member flags in the struct spi_transaction_t as shown in the Transaction Flag column. If you want to
check if corresponding IO pins are set or not, set the member flags in the spi_bus_config_t as shown in the
Bus IO setting Flag column.
Command and Address Phases During the command and address phases, the members
spi_transaction_t::cmd and spi_transaction_t::addr are sent to the bus, nothing is read at this
time. The default lengths of the command and address phases are set in spi_device_interface_config_t
by calling spi_bus_add_device(). If the flags SPI_TRANS_VARIABLE_CMD and
SPI_TRANS_VARIABLE_ADDR in the member spi_transaction_t::flags are not set, the driver
automatically sets the length of these phases to default values during Device initialization.
If the lengths of the command and address phases need to be variable, declare the
struct spi_transaction_ext_t, set the flags SPI_TRANS_VARIABLE_CMD and/or
SPI_TRANS_VARIABLE_ADDR in the member spi_transaction_ext_t::base and configure the rest
of base as usual. Then the length of each phase will be equal to spi_transaction_ext_t::command_bits
and spi_transaction_ext_t::address_bits set in the struct spi_transaction_ext_t.
If the command and address phase need to be as the same number of lines as data phase, you need to
set SPI_TRANS_MULTILINE_CMD and/or SPI_TRANS_MULTILINE_ADDR to the flags member in the struct
spi_transaction_t. Also see Transaction Line Mode.
Write and Read Phases Normally, the data that needs to be transferred to or from a Device will be read
from or written to a chunk of memory indicated by the members spi_transaction_t::rx_buffer and
spi_transaction_t::tx_buffer. If DMA is enabled for transfers, the buffers are required to be:
1. Allocated in DMA-capable internal memory. If external PSRAM is enabled, this means using pvPortMal-
locCaps(size, MALLOC_CAP_DMA).
2. 32-bit aligned (staring from a 32-bit boundary and having a length of multiples of 4 bytes).
If these requirements are not satisfied, the transaction efficiency will be affected due to the allocation and copying of
temporary buffers.
If using more than one data lines to transmit, please set SPI_DEVICE_HALFDUPLEX flag for the member flags in the
struct spi_device_interface_config_t. And the member flags in the struct spi_transaction_t
should be set as described in Transaction Line Mode.
Note: Half-duplex transactions with both read and write phases are not supported when using DMA. For details and
workarounds, see Known Issues.
Bus Acquiring Sometimes you might want to send SPI transactions exclusively and continuously so that it
takes as little time as possible. For this, you can use bus acquiring, which helps to suspend transactions (both
polling or interrupt) to other devices until the bus is released. To acquire and release a bus, use the functions
spi_device_acquire_bus() and spi_device_release_bus().
Driver Usage
• Initialize an SPI bus by calling the function spi_bus_initialize(). Make sure to set the correct I/O
pins in the struct spi_bus_config_t. Set the signals that are not needed to -1.
• Register a Device connected to the bus with the driver by calling the function spi_bus_add_device().
Make sure to configure any timing requirements the device might need with the parameter dev_config.
You should now have obtained the Device’s handle which will be used when sending a transaction to it.
• To interact with the Device, fill one or more spi_transaction_t structs with any transaction parameters
required. Then send the structs either using a polling transaction or an interrupt transaction:
– Interrupt Either queue all transactions by calling the function spi_device_queue_trans() and,
at a later time, query the result using the function spi_device_get_trans_result(), or
handle all requests synchronously by feeding them into spi_device_transmit().
– Polling Call the function spi_device_polling_transmit() to send polling transactions.
Alternatively, if you want to insert something in between, send the transactions by using
spi_device_polling_start() and spi_device_polling_end().
• (Optional) To perform back-to-back transactions with a Device, call the function
spi_device_acquire_bus() before sending transactions and spi_device_release_bus()
after the transactions have been sent.
• (Optional) To unload the driver for a certain Device, call spi_bus_remove_device() with the Device
handle as an argument.
• (Optional) To remove the driver for a bus, make sure no more drivers are attached and call
spi_bus_free().
The example code for the SPI master driver can be found in the peripherals/spi_master directory of ESP-IDF exam-
ples.
Transactions with Data Not Exceeding 32 Bits When the transaction data size is equal to or
less than 32 bits, it will be sub-optimal to allocate a buffer for the data. The data can be di-
rectly stored in the transaction struct instead. For transmitted data, it can be achieved by using the
spi_transaction_t::tx_data member and setting the SPI_TRANS_USE_TXDATA flag on the transmis-
sion. For received data, use spi_transaction_t::rx_data and set SPI_TRANS_USE_RXDATA. In both
cases, do not touch the spi_transaction_t::tx_buffer or spi_transaction_t::rx_buffer
members, because they use the same memory locations as spi_transaction_t::tx_data and
spi_transaction_t::rx_data.
Transactions with Integers Other Than uint8_t An SPI Host reads and writes data into memory byte by byte.
By default, data is sent with the most significant bit (MSB) first, as LSB first used in rare cases. If a value less than 8
bits needs to be sent, the bits should be written into memory in the MSB first manner.
For example, if 0b00010 needs to be sent, it should be written into a uint8_t variable, and the length for reading
should be set to 5 bits. The Device will still receive 8 bits with 3 additional “random”bits, so the reading must be
performed correctly.
On top of that, ESP32 is a little-endian chip, which means that the least significant byte of uint16_t and
uint32_t variables is stored at the smallest address. Hence, if uint16_t is stored in memory, bits [7:0] are
sent first, followed by bits [15:8].
For cases when the data to be transmitted has the size differing from uint8_t arrays, the following macros can be
used to transform data to the format that can be sent by the SPI driver directly:
• SPI_SWAP_DATA_TX for data to be transmitted
• SPI_SWAP_DATA_RX for data received
Notes on Sending Mixed Transactions to the Same Device To reduce coding complexity, send only one type of
transactions (interrupt or polling) to one Device. However, you still can send both interrupt and polling transactions
alternately. The notes below explain how to do this.
The polling transactions should be initiated only after all the polling and interrupt transactions are finished.
Since an unfinished polling transaction blocks other transactions, please do not forget to call the function
spi_device_polling_end() after spi_device_polling_start() to allow other transactions or to
allow other Devices to use the bus. Remember that if there is no need to switch to other tasks during your polling
transaction, you can initiate a transaction with spi_device_polling_transmit() so that it will be ended
automatically.
In-flight polling transactions are disturbed by the ISR operation to accommodate interrupt
transactions. Always make sure that all the interrupt transactions sent to the ISR are fin-
ished before you call spi_device_polling_start(). To do that, you can keep calling
spi_device_get_trans_result() until all the transactions are returned.
To have better control of the calling sequence of functions, send mixed transactions to the same Device only within
a single task.
To use SPI Master driver on SPI1 bus, you have to take care of two problems:
1. The code and data, required at the meanwhile the driver is operating SPI1 bus, should be in the internal memory.
SPI1 bus is shared among devices and the cache for data (code) in the Flash as well as the PSRAM. The cache
should be disabled during the other drivers are operating the SPI1 bus. Hence the data (code) in the flash as
well as the PSRAM cannot be fetched at the meanwhile the driver acquires the SPI1 bus by:
• Explicit bus acquiring between spi_device_acquire_bus() and
spi_device_release_bus().
• Implicit bus acquiring between spi_device_polling_start() and
spi_device_polling_end() (or inside spi_device_polling_transmit()).
During the time above, all other tasks and most ISRs will be disabled (see IRAM-Safe Interrupt Handlers).
Application code and data used by current task should be placed in internal memory (DRAM or IRAM), or
already in the ROM. Access to external memory (flash code, const data in the flash, and static/heap data in the
PSRAM) will cause a Cache disabled but cached memory region accessed exception. For differences between
IRAM, DRAM, and flash cache, please refer to the application memory layout documentation.
To place functions into the IRAM, you can either:
1. Add IRAM_ATTR (include “esp_attr.h”) to the function like:
IRAM_ATTR void foo(void) { }
Please note that when a function is inlined, it will follow its caller’s segment, and the attribute will not
take effect. You may need to use NOLINE_ATTR to avoid this.
2. Use the noflash placement in the linker.lf. See more in Linker Script Generation. Please note that, some
code may be transformed into lookup table in the const data by the compiler, so noflash_text is not safe.
Please do take care that the optimization level may affect the compiler behavior of inline, or transforming some
code into lookup table in the const data, etc.
To place data into the DRAM, you can either:
1. Add DRAM_ATTR (include “esp_attr.h”) to the data definition like:
DRAM_ATTR int g_foo = 3;
2. Use the noflash placement in the linker.lf. See more in Linker Script Generation.
Please also see the example peripherals/spi_master/hd_eeprom.
GPIO Matrix and IO_MUX Most of ESP32’s peripheral signals have direct connection to their dedicated
IO_MUX pins. However, the signals can also be routed to any other available pins using the less direct GPIO matrix.
If at least one signal is routed through the GPIO matrix, then all signals will be routed through it.
The GPIO matrix introduces flexibility of routing but also brings the following disadvantages:
• Increases the input delay of the MISO signal, which makes MISO setup time violations more likely. If SPI
needs to operate at high speeds, use dedicated IO_MUX pins.
• Allows signals with clock frequencies only up to 40 MHz, as opposed to 80 MHz if IO_MUX pins are used.
Note: For more details about the influence of the MISO input delay on the maximum clock frequency, see Timing
Considerations.
* Only the first Device attached to the bus can use the CS0 pin.
Transaction Duration Transaction duration includes setting up SPI peripheral registers, copying data to FIFOs or
setting up DMA links, and the time for SPI transaction.
Interrupt transactions allow appending extra overhead to accommodate the cost of FreeRTOS queues and the time
needed for switching between tasks and the ISR.
For interrupt transactions, the CPU can switch to other tasks when a transaction is in progress. This saves the CPU
time but increases the transaction duration. See Interrupt Transactions. For polling transactions, it does not block
the task but allows to do polling when the transaction is in progress. For more information, see Polling Transactions.
If DMA is enabled, setting up the linked list requires about 2 us per transaction. When a master is transferring data,
it automatically reads the data from the linked list. If DMA is not enabled, the CPU has to write and read each byte
from the FIFO by itself. Usually, this is faster than 2 us, but the transaction length is limited to 64 bytes for both
write and read.
Typical transaction duration for one byte of data are given below.
• Interrupt Transaction via DMA: 28 µs.
• Interrupt Transaction via CPU: 25 µs.
• Polling Transaction via DMA: 10 µs.
• Polling Transaction via CPU: 8 µs.
SPI Clock Frequency Transferring each byte takes eight times the clock period 8/fspi.
If the clock frequency is too high, the use of some functions might be limited. See Timing Considerations.
Cache Miss The default config puts only the ISR into the IRAM. Other SPI related functions, including the driver
itself and the callback, might suffer from cache misses and will need to wait until the code is read from flash. Select
CONFIG_SPI_MASTER_IN_IRAM to put the whole SPI driver into IRAM and put the entire callback(s) and its callee
functions into IRAM to prevent cache misses.
For an interrupt transaction, the overall cost is 20+8n/Fspi[MHz] [us] for n bytes transferred in one transaction.
Hence, the transferring speed is: n/(20+8n/Fspi). An example of transferring speed at 8 MHz clock speed is given
in the following table.
When a transaction length is short, the cost of transaction interval is high. If possible, try to squash several short
transactions into one transaction to achieve a higher transfer speed.
Please note that the ISR is disabled during flash operation by default. To keep sending transactions during
flash operations, enable CONFIG_SPI_MASTER_ISR_IN_IRAM and set ESP_INTR_FLAG_IRAM in the member
spi_bus_config_t::intr_flags. In this case, all the transactions queued before starting flash operations
will be handled by the ISR in parallel. Also note that the callback of each Device and their callee functions should
be in IRAM, or your callback will crash due to cache miss. For more details, see IRAM-Safe Interrupt Handlers.
Timing Considerations
As shown in the figure below, there is a delay on the MISO line after the SCLK launch edge and before the signal is
latched by the internal register. As a result, the MISO pin setup time is the limiting factor for the SPI clock speed.
When the delay is too long, the setup slack is < 0, which means the setup timing requirement is violated and the
reading might be incorrect.
SCLK a d
input delay
MISO delayed c
Dummy bit workaround: Dummy clocks, during which the Host does not read data, can be inserted before the read
phase begins. The Device still sees the dummy clocks and sends out data, but the Host does not read until the read
phase comes. This compensates for the lack of the MISO setup time required by the Host and allows the Host to do
reading at a higher frequency.
In the ideal case, if the Device is so fast that the input delay is shorter than an APB clock cycle - 12.5 ns - the
maximum frequency at which the Host can read (or read and write) in different conditions is as follows:
If the Host only writes data, the dummy bit workaround and the frequency check can be disabled by setting the bit
SPI_DEVICE_NO_DUMMY in the member spi_device_interface_config_t::flags. When disabled,
the output frequency can be 80MHz, even if the GPIO matrix is used.
spi_device_interface_config_t::flags
The SPI master driver still works even if the spi_device_interface_config_t::input_delay_ns in
the structure spi_device_interface_config_t is set to 0. However, setting an accurate value helps to:
• Calculate the frequency limit for full-duplex transactions
• Compensate the timing correctly with dummy bits for half-duplex transactions
You can approximate the maximum data valid time after the launch edge of SPI clocks by checking the statistics in
the AC characteristics chapter of your Device’s specification or measure the time using an oscilloscope or logic
analyzer.
Please note that the actual PCB layout design and excessive loads may increase the input delay. It means that non-
optimal wiring and/or a load capacitor on the bus will most likely lead to input delay values exceeding the values
given in the Device specification or measured while the bus is floating.
Some typical delay values are shown in the following table. (These data are retrieved when the slave device is on a
different physical chip)
The MISO path delay (valid time) consists of a slave’s input delay plus master’s GPIO matrix delay. This delay
determines the frequency limit above which full-duplex transfers will not work as well as the dummy bits used in the
half-duplex transactions. The frequency limit is:
Freq limit [MHz] = 80 / (floor(MISO delay[ns]/12.5) + 1)
The figure below shows the relationship between frequency limit and input delay. Two extra APB clock cycle periods
should be added to the MISO delay if the master uses the GPIO matrix.
Corresponding frequency limits for different Devices with different input delay times are shown in the table below.
Master Input delay (ns) MISO path delay (ns) Freq. limit (MHz)
IO_MUX (0ns) 0 0 80
50 50 16
75 75 11.43
GPIO (25ns) 0 25 26.67
50 75 11.43
75 100 8.89
Known Issues
1. Half-duplex transactions are not compatible with DMA when both writing and reading phases are used.
If such transactions are required, you have to use one of the alternative solutions:
1. Use full-duplex transactions instead.
2. Disable DMA by setting the bus initialization function’s last parameter to 0 as follows:
ret=spi_bus_initialize(VSPI_HOST, &buscfg, 0);
This can prohibit you from transmitting and receiving data longer than 64 bytes. 3. Try using the
command and address fields to replace the write phase.
2. Full-duplex transactions are not compatible with the dummy bit workaround, hence the frequency is limited.
See dummy bit speed-up workaround.
3. dummy_bits in spi_device_interface_config_t and spi_transaction_ext_t are not
available when SPI read and write phases are both enabled (regardless of full duplex or half duplex mode).
4. cs_ena_pretrans is not compatible with the command and address phases of full-duplex transactions.
Application Example
The code example for using the SPI master half duplex mode to read/write a AT93C46D EEPROM (8-bit mode)
can be found in the peripherals/spi_master/hd_eeprom directory of ESP-IDF examples.
Header File
• components/hal/include/hal/spi_types.h
Structures
struct spi_line_mode_t
Line mode of SPI transaction phases: CMD, ADDR, DOUT/DIN.
Public Members
uint8_t cmd_lines
The line width of command phase, e.g. 2-line-cmd-phase.
uint8_t addr_lines
The line width of address phase, e.g. 1-line-addr-phase.
uint8_t data_lines
The line width of data phase, e.g. 4-line-data-phase.
Enumerations
enum spi_host_device_t
Enum with the three SPI peripherals that are software-accessible in it.
Values:
enumerator SPI1_HOST
SPI1.
enumerator SPI2_HOST
SPI2.
enumerator SPI3_HOST
SPI3.
enumerator SPI_HOST_MAX
invalid host value
enum spi_clock_source_t
Values:
enumerator SPI_CLK_APB
Select APB as the source clock.
enumerator SPI_CLK_XTAL
Select XTAL as the source clock.
enum spi_event_t
SPI Events.
Values:
enumerator SPI_EV_BUF_TX
The buffer has sent data to master.
enumerator SPI_EV_BUF_RX
The buffer has received data from master.
enumerator SPI_EV_SEND_DMA_READY
Slave has loaded its TX data buffer to the hardware (DMA).
enumerator SPI_EV_SEND
Master has received certain number of the data, the number is determined by Master.
enumerator SPI_EV_RECV_DMA_READY
Slave has loaded its RX data buffer to the hardware (DMA).
enumerator SPI_EV_RECV
Slave has received certain number of data from master, the number is determined by Master.
enumerator SPI_EV_CMD9
Received CMD9 from master.
enumerator SPI_EV_CMDA
Received CMDA from master.
enumerator SPI_EV_TRANS
A transaction has done.
Header File
• components/driver/include/driver/spi_common.h
Functions
esp_err_t spi_bus_initialize(spi_host_device_t host_id, const spi_bus_config_t *bus_config,
spi_dma_chan_t dma_chan)
Initialize a SPI bus.
Warning: If a DMA channel is selected, any transmit and receive buffer used should be allocated in
DMA-capable memory.
Warning: The ISR of SPI is always executed on the core which calls this function. Never starve the ISR
on this core or the SPI transactions will not be handled.
Parameters
• host_id –SPI peripheral that controls this bus
• bus_config –Pointer to a spi_bus_config_t struct specifying how the host should be
initialized
• dma_chan –- Selecting a DMA channel for an SPI bus allows transactions on the bus
with size only limited by the amount of internal memory.
– Selecting SPI_DMA_DISABLED limits the size of transactions.
– Set to SPI_DMA_DISABLED if only the SPI flash uses this bus.
– Set to SPI_DMA_CH_AUTO to let the driver to allocate the DMA channel.
Returns
• ESP_ERR_INVALID_ARG if configuration is invalid
• ESP_ERR_INVALID_STATE if host already is in use
• ESP_ERR_NOT_FOUND if there is no available DMA channel
• ESP_ERR_NO_MEM if out of memory
• ESP_OK on success
esp_err_t spi_bus_free(spi_host_device_t host_id)
Free a SPI bus.
Warning: In order for this to succeed, all devices have to be removed first.
Structures
struct spi_bus_config_t
This is a configuration structure for a SPI bus.
You can use this structure to specify the GPIO pins of the bus. Normally, the driver will use the GPIO matrix
to route the signals. An exception is made when all signals either can be routed through the IO_MUX or are
-1. In that case, the IO_MUX is used, allowing for >40MHz speeds.
Note: Be advised that the slave driver does not use the quadwp/quadhd lines and fields in spi_bus_config_t
refering to these lines will be ignored and can thus safely be left uninitialized.
Public Members
int mosi_io_num
GPIO pin for Master Out Slave In (=spi_d) signal, or -1 if not used.
int data0_io_num
GPIO pin for spi data0 signal in quad/octal mode, or -1 if not used.
int miso_io_num
GPIO pin for Master In Slave Out (=spi_q) signal, or -1 if not used.
int data1_io_num
GPIO pin for spi data1 signal in quad/octal mode, or -1 if not used.
int sclk_io_num
GPIO pin for SPI Clock signal, or -1 if not used.
int quadwp_io_num
GPIO pin for WP (Write Protect) signal, or -1 if not used.
int data2_io_num
GPIO pin for spi data2 signal in quad/octal mode, or -1 if not used.
int quadhd_io_num
GPIO pin for HD (Hold) signal, or -1 if not used.
int data3_io_num
GPIO pin for spi data3 signal in quad/octal mode, or -1 if not used.
int data4_io_num
GPIO pin for spi data4 signal in octal mode, or -1 if not used.
int data5_io_num
GPIO pin for spi data5 signal in octal mode, or -1 if not used.
int data6_io_num
GPIO pin for spi data6 signal in octal mode, or -1 if not used.
int data7_io_num
GPIO pin for spi data7 signal in octal mode, or -1 if not used.
int max_transfer_sz
Maximum transfer size, in bytes. Defaults to 4092 if 0 when DMA enabled, or to
SOC_SPI_MAXIMUM_BUFFER_SIZE if DMA is disabled.
uint32_t flags
Abilities of bus to be checked by the driver. Or-ed value of SPICOMMON_BUSFLAG_* flags.
int intr_flags
Interrupt flag for the bus to set the priority, and IRAM attribute, see esp_intr_alloc.h. Note that
the EDGE, INTRDISABLED attribute are ignored by the driver. Note that if ESP_INTR_FLAG_IRAM
is set, ALL the callbacks of the driver, and their callee functions, should be put in the IRAM.
Macros
SPI_MAX_DMA_LEN
SPI_SWAP_DATA_TX(DATA, LEN)
Transform unsigned integer of length <= 32 bits to the format which can be sent by the SPI driver directly.
E.g. to send 9 bits of data, you can:
Parameters
• DATA –Data to be rearranged, can be uint8_t, uint16_t or uint32_t.
• LEN –Length of data received, since the SPI peripheral writes from the MSB, this helps
to shift the data to the LSB.
SPICOMMON_BUSFLAG_SLAVE
Initialize I/O in slave mode.
SPICOMMON_BUSFLAG_MASTER
Initialize I/O in master mode.
SPICOMMON_BUSFLAG_IOMUX_PINS
Check using iomux pins. Or indicates the pins are configured through the IO mux rather than GPIO matrix.
SPICOMMON_BUSFLAG_GPIO_PINS
Force the signals to be routed through GPIO matrix. Or indicates the pins are routed through the GPIO matrix.
SPICOMMON_BUSFLAG_SCLK
Check existing of SCLK pin. Or indicates CLK line initialized.
SPICOMMON_BUSFLAG_MISO
Check existing of MISO pin. Or indicates MISO line initialized.
SPICOMMON_BUSFLAG_MOSI
Check existing of MOSI pin. Or indicates MOSI line initialized.
SPICOMMON_BUSFLAG_DUAL
Check MOSI and MISO pins can output. Or indicates bus able to work under DIO mode.
SPICOMMON_BUSFLAG_WPHD
Check existing of WP and HD pins. Or indicates WP & HD pins initialized.
SPICOMMON_BUSFLAG_QUAD
Check existing of MOSI/MISO/WP/HD pins as output. Or indicates bus able to work under QIO mode.
SPICOMMON_BUSFLAG_IO4_IO7
Check existing of IO4~IO7 pins. Or indicates IO4~IO7 pins initialized.
SPICOMMON_BUSFLAG_OCTAL
Check existing of MOSI/MISO/WP/HD/SPIIO4/SPIIO5/SPIIO6/SPIIO7 pins as output. Or indicates bus
able to work under octal mode.
SPICOMMON_BUSFLAG_NATIVE_PINS
Type Definitions
Enumerations
enum spi_common_dma_t
SPI DMA channels.
Values:
enumerator SPI_DMA_DISABLED
Do not enable DMA for SPI.
enumerator SPI_DMA_CH1
Enable DMA, select DMA Channel 1.
enumerator SPI_DMA_CH2
Enable DMA, select DMA Channel 2.
enumerator SPI_DMA_CH_AUTO
Enable DMA, channel is automatically selected by driver.
Header File
• components/driver/include/driver/spi_master.h
Functions
esp_err_t spi_bus_add_device(spi_host_device_t host_id, const spi_device_interface_config_t *dev_config,
spi_device_handle_t *handle)
Allocate a device on a SPI bus.
This initializes the internal structures for a device, plus allocates a CS pin on the indicated SPI master peripheral
and routes it to the indicated GPIO. All SPI master devices have three CS pins and can thus control up to three
devices.
Note: While in general, speeds up to 80MHz on the dedicated SPI pins and 40MHz on GPIO-matrix-routed
pins are supported, full-duplex transfers routed over the GPIO matrix only support speeds up to 26MHz.
Parameters
• host_id –SPI peripheral to allocate device on
• dev_config –SPI interface protocol config for the device
• handle –Pointer to variable to hold the device handle
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_ERR_NOT_FOUND if host doesn’t have any free CS slots
• ESP_ERR_NO_MEM if out of memory
• ESP_OK on success
esp_err_t spi_bus_remove_device(spi_device_handle_t handle)
Remove a device from the SPI bus.
Parameters handle –Device handle to free
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_ERR_INVALID_STATE if device already is freed
• ESP_OK on success
esp_err_t spi_device_queue_trans(spi_device_handle_t handle, spi_transaction_t *trans_desc,
TickType_t ticks_to_wait)
Queue a SPI transaction for interrupt transaction execution. Get the result by
spi_device_get_trans_result.
Note: Normally a device cannot start (queue) polling and interrupt transactions simultaneously.
Parameters
• handle –Device handle obtained using spi_host_add_dev
• trans_desc –Description of transaction to execute
• ticks_to_wait –Ticks to wait until there’s room in the queue; use port-
MAX_DELAY to never time out.
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid. This can happen if
SPI_TRANS_CS_KEEP_ACTIVE flag is specified while the bus was not acquired
(spi_device_acquire_bus() should be called first)
• ESP_ERR_TIMEOUT if there was no room in the queue before ticks_to_wait expired
• ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed
• ESP_ERR_INVALID_STATE if previous transactions are not finished
• ESP_OK on success
Note: This function is not thread safe when multiple tasks access the same SPI device. Normally a device
cannot start (queue) polling and interrupt transactions simutanuously.
Parameters
• handle –Device handle obtained using spi_host_add_dev
• trans_desc –Description of transaction to execute
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_OK on success
Note: Normally a device cannot start (queue) polling and interrupt transactions simutanuously. Moreover, a
device cannot start a new polling transaction if another polling transaction is not finished.
Parameters
• handle –Device handle obtained using spi_host_add_dev
• trans_desc –Description of transaction to execute
• ticks_to_wait –Ticks to wait until there’s room in the queue; currently only port-
MAX_DELAY is supported.
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid. This can happen if
SPI_TRANS_CS_KEEP_ACTIVE flag is specified while the bus was not acquired
(spi_device_acquire_bus() should be called first)
• ESP_ERR_TIMEOUT if the device cannot get control of the bus before
ticks_to_wait expired
• ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed
• ESP_ERR_INVALID_STATE if previous transactions are not finished
• ESP_OK on success
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_ERR_TIMEOUT if the transaction cannot finish before ticks_to_wait expired
• ESP_OK on success
esp_err_t spi_device_polling_transmit(spi_device_handle_t handle, spi_transaction_t *trans_desc)
Send a polling transaction, wait for it to complete, and return the result.
This function is the equivalent of calling spi_device_polling_start() followed by spi_device_polling_end(). Do
not use this when there is still a transaction that hasn’t been finalized.
Note: This function is not thread safe when multiple tasks access the same SPI device. Normally a device
cannot start (queue) polling and interrupt transactions simutanuously.
Parameters
• handle –Device handle obtained using spi_host_add_dev
• trans_desc –Description of transaction to execute
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_OK on success
Note: The function will wait until all the existing transactions have been sent.
Parameters
• device –The device to occupy the bus.
• wait –Time to wait before the the bus is occupied by the device. Currently MUST set to
portMAX_DELAY.
Returns
• ESP_ERR_INVALID_ARG : wait is not set to portMAX_DELAY.
• ESP_OK : Success.
Note: If **dummy_o* is not zero, it means dummy bits should be applied in half duplex mode, and full
duplex mode may not work.
Parameters
• gpio_is_used –True if using GPIO matrix, or False if iomux pins are used.
• input_delay_ns –Input delay from SCLK launch edge to MISO data valid.
• eff_clk –Effective clock frequency (in Hz) from spi_get_actual_clock().
• dummy_o –Address of dummy bits used output. Set to NULL if not needed.
• cycles_remain_o –Address of cycles remaining (after dummy bits are used) output.
– -1 If too many cycles remaining, suggest to compensate half a clock.
– 0 If no remaining cycles or dummy bits are not used.
– positive value: cycles suggest to compensate.
Structures
struct spi_device_interface_config_t
This is a configuration for a SPI slave device that is connected to one of the SPI buses.
Public Members
uint8_t command_bits
Default amount of bits in command phase (0-16), used when SPI_TRANS_VARIABLE_CMD is not
used, otherwise ignored.
uint8_t address_bits
Default amount of bits in address phase (0-64), used when SPI_TRANS_VARIABLE_ADDR is not
used, otherwise ignored.
uint8_t dummy_bits
Amount of dummy bits to insert between address and data phase.
uint8_t mode
SPI mode, representing a pair of (CPOL, CPHA) configuration:
• 0: (0, 0)
• 1: (0, 1)
• 2: (1, 0)
• 3: (1, 1)
uint16_t duty_cycle_pos
Duty cycle of positive clock, in 1/256th increments (128 = 50%/50% duty). Setting this to 0 (=not setting
it) is equivalent to setting this to 128.
uint16_t cs_ena_pretrans
Amount of SPI bit-cycles the cs should be activated before the transmission (0-16). This only works on
half-duplex transactions.
uint8_t cs_ena_posttrans
Amount of SPI bit-cycles the cs should stay active after the transmission (0-16)
int clock_speed_hz
Clock speed, divisors of 80MHz, in Hz. See SPI_MASTER_FREQ_*.
int input_delay_ns
Maximum data valid time of slave. The time required between SCLK and MISO valid, including the
possible clock delay from slave to master. The driver uses this value to give an extra delay before the
MISO is ready on the line. Leave at 0 unless you know you need a delay. For better timing performance
at high frequency (over 8MHz), it’s suggest to have the right value.
int spics_io_num
CS GPIO pin for this device, or -1 if not used.
uint32_t flags
Bitwise OR of SPI_DEVICE_* flags.
int queue_size
Transaction queue size. This sets how many transactions can be ‘in the air’(queued using
spi_device_queue_trans but not yet finished using spi_device_get_trans_result) at the same time.
transaction_cb_t pre_cb
Callback to be called before a transmission is started.
This callback is called within interrupt context should be in IRAM for best performance, see “Trans-
ferring Speed”section in the SPI Master documentation for full details. If not, the callback may crash
during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM.
transaction_cb_t post_cb
Callback to be called after a transmission has completed.
This callback is called within interrupt context should be in IRAM for best performance, see “Trans-
ferring Speed”section in the SPI Master documentation for full details. If not, the callback may crash
during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM.
struct spi_transaction_t
This structure describes one SPI transaction. The descriptor should not be modified until the transaction fin-
ishes.
Public Members
uint32_t flags
Bitwise OR of SPI_TRANS_* flags.
uint16_t cmd
Command data, of which the length is set in the command_bits of spi_device_interface_config_t.
NOTE: this field, used to be “command”in ESP-IDF 2.1 and before, is re-written to be used in
a new way in ESP-IDF 3.0.
Example: write 0x0123 and command_bits=12 to send command 0x12, 0x3_ (in previous version, you
may have to write 0x3_12).
uint64_t addr
Address data, of which the length is set in the address_bits of spi_device_interface_config_t.
NOTE: this field, used to be “address”in ESP-IDF 2.1 and before, is re-written to be used in a
new way in ESP-IDF3.0.
Example: write 0x123400 and address_bits=24 to send address of 0x12, 0x34, 0x00 (in previous version,
you may have to write 0x12340000).
size_t length
Total data length, in bits.
size_t rxlength
Total data length received, should be not greater than length in full-duplex mode (0 defaults this to the
value of length).
void *user
User-defined variable. Can be used to store eg transaction ID.
uint8_t tx_data[4]
If SPI_TRANS_USE_TXDATA is set, data set here is sent directly from this variable.
void *rx_buffer
Pointer to receive buffer, or NULL for no MISO phase. Written by 4 bytes-unit if DMA is used.
uint8_t rx_data[4]
If SPI_TRANS_USE_RXDATA is set, data is received directly to this variable.
struct spi_transaction_ext_t
This struct is for SPI transactions which may change their address and command length. Please do set the flags
in base to SPI_TRANS_VARIABLE_CMD_ADR to use the bit length here.
Public Members
uint8_t command_bits
The command length in this transaction, in bits.
uint8_t address_bits
The address length in this transaction, in bits.
uint8_t dummy_bits
The dummy length in this transaction, in bits.
Macros
SPI_MASTER_FREQ_8M
SPI master clock is divided by 80MHz apb clock. Below defines are example frequencies, and are accurate. Be
free to specify a random frequency, it will be rounded to closest frequency (to macros below if above 8MHz).
8MHz
SPI_MASTER_FREQ_9M
8.89MHz
SPI_MASTER_FREQ_10M
10MHz
SPI_MASTER_FREQ_11M
11.43MHz
SPI_MASTER_FREQ_13M
13.33MHz
SPI_MASTER_FREQ_16M
16MHz
SPI_MASTER_FREQ_20M
20MHz
SPI_MASTER_FREQ_26M
26.67MHz
SPI_MASTER_FREQ_40M
40MHz
SPI_MASTER_FREQ_80M
80MHz
SPI_DEVICE_TXBIT_LSBFIRST
Transmit command/address/data LSB first instead of the default MSB first.
SPI_DEVICE_RXBIT_LSBFIRST
Receive data LSB first instead of the default MSB first.
SPI_DEVICE_BIT_LSBFIRST
Transmit and receive LSB first.
SPI_DEVICE_3WIRE
Use MOSI (=spid) for both sending and receiving data.
SPI_DEVICE_POSITIVE_CS
Make CS positive during a transaction instead of negative.
SPI_DEVICE_HALFDUPLEX
Transmit data before receiving it, instead of simultaneously.
SPI_DEVICE_CLK_AS_CS
Output clock on CS line if CS is active.
SPI_DEVICE_NO_DUMMY
There are timing issue when reading at high frequency (the frequency is related to whether iomux pins are used,
valid time after slave sees the clock).
• In half-duplex mode, the driver automatically inserts dummy bits before reading phase to fix the timing
issue. Set this flag to disable this feature.
• In full-duplex mode, however, the hardware cannot use dummy bits, so there is no way to prevent data
being read from getting corrupted. Set this flag to confirm that you’re going to work with output only,
or read without dummy bits at your own risk.
SPI_DEVICE_DDRCLK
SPI_TRANS_MODE_DIO
Transmit/receive data in 2-bit mode.
SPI_TRANS_MODE_QIO
Transmit/receive data in 4-bit mode.
SPI_TRANS_USE_RXDATA
Receive into rx_data member of spi_transaction_t instead into memory at rx_buffer.
SPI_TRANS_USE_TXDATA
Transmit tx_data member of spi_transaction_t instead of data at tx_buffer. Do not set tx_buffer when using
this.
SPI_TRANS_MODE_DIOQIO_ADDR
Also transmit address in mode selected by SPI_MODE_DIO/SPI_MODE_QIO.
SPI_TRANS_VARIABLE_CMD
Use the command_bits in spi_transaction_ext_t rather than default value in
spi_device_interface_config_t.
SPI_TRANS_VARIABLE_ADDR
Use the address_bits in spi_transaction_ext_t rather than default value in
spi_device_interface_config_t.
SPI_TRANS_VARIABLE_DUMMY
Use the dummy_bits in spi_transaction_ext_t rather than default value in
spi_device_interface_config_t.
SPI_TRANS_CS_KEEP_ACTIVE
Keep CS active after data transfer.
SPI_TRANS_MULTILINE_CMD
The data lines used at command phase is the same as data phase (otherwise, only one data line is used at
command phase)
SPI_TRANS_MODE_OCT
Transmit/receive data in 8-bit mode.
SPI_TRANS_MULTILINE_ADDR
The data lines used at address phase is the same as data phase (otherwise, only one data line is used at address
phase)
Type Definitions
SPI Slave driver is a program that controls ESP32’s SPI peripherals while they function as slaves.
ESP32 integrates two general purpose SPI controllers which can be used as slave nodes driven by an off-chip SPI
master.
• SPI2, sometimes referred to as HSPI
• SPI3, sometimes referred to as VSPI
SPI2 and SPI3 have independent signal buses with the same respective names.
Terminology
The terms used in relation to the SPI slave driver are given in the table below.
Term Definition
Host The SPI controller peripheral external to ESP32 that initiates SPI transmissions
over the bus, and acts as an SPI Master.
Device SPI slave device (general purpose SPI controller). Each Device shares the
MOSI, MISO and SCLK signals but is only active on the bus when the Host
asserts the Device’s individual CS line.
Bus A signal bus, common to all Devices connected to one Host. In general, a bus
includes the following lines: MISO, MOSI, SCLK, one or more CS lines, and,
optionally, QUADWP and QUADHD. So Devices are connected to the same
lines, with the exception that each Device has its own CS line. Several Devices
can also share one CS line if connected in the daisy-chain manner.
MISO Master In, Slave Out, a.k.a. Q. Data transmission from a Device to Host.
MOSI Master Out, Slave In, a.k.a. D. Data transmission from a Host to Device.
SCLK Serial Clock. Oscillating signal generated by a Host that keeps the transmission
of data bits in sync.
CS Chip Select. Allows a Host to select individual Device(s) connected to the bus
in order to send or receive data.
QUADWP Write Protect signal. Only used for 4-bit (qio/qout) transactions.
QUADHD Hold signal. Only used for 4-bit (qio/qout) transactions.
Assertion The action of activating a line. The opposite action of returning the line back
to inactive (back to idle) is called de-assertion.
Transaction One instance of a Host asserting a CS line, transferring data to and from a
Device, and de-asserting the CS line. Transactions are atomic, which means
they can never be interrupted by another transaction.
Launch Edge Edge of the clock at which the source register launches the signal onto the line.
Latch Edge Edge of the clock at which the destination register latches in the signal.
Driver Features
The SPI slave driver allows using the SPI peripherals as full-duplex Devices. The driver can send/receive transactions
up to 64 bytes in length, or utilize DMA to send/receive longer transactions. However, there are some known issues
related to DMA.
SPI Transactions
A full-duplex SPI transaction begins when the Host asserts the CS line and starts sending out clock pulses on the
SCLK line. Every clock pulse, a data bit is shifted from the Host to the Device on the MOSI line and back on the
MISO line at the same time. At the end of the transaction, the Host de-asserts the CS line.
The attributes of a transaction are determined by the configuration structure for an SPI peripheral
acting as a slave device spi_slave_interface_config_t, and transaction configuration structure
spi_slave_transaction_t.
As not every transaction requires both writing and reading data, you have a choice to config-
ure the spi_transaction_t structure for TX only, RX only, or TX and RX transactions. If
spi_slave_transaction_t::rx_buffer is set to NULL, the read phase will be skipped. If
spi_slave_transaction_t::tx_buffer is set to NULL, the write phase will be skipped.
Note: A Host should not start a transaction before its Device is ready for receiving data. It is recommended to use
another GPIO pin for a handshake signal to sync the Devices. For more details, see Transaction Interval.
Driver Usage
• Initialize an SPI peripheral as a Device by calling the function cpp:func:spi_slave_initialize. Make sure to set
the correct I/O pins in the struct bus_config. Set the unused signals to -1.
If transactions will be longer than 32 bytes, allow a DMA channel 1 or 2 by setting the parameter dma_chan to 1
or 2 respectively. Otherwise, set dma_chan to 0.
• Before initiating transactions, fill one or more spi_slave_transaction_t structs with the transaction
parameters required. Either queue all transactions by calling the function spi_slave_queue_trans()
and, at a later time, query the result by using the function spi_slave_get_trans_result(), or handle
all requests individually by feeding them into spi_slave_transmit(). The latter two functions will be
blocked until the Host has initiated and finished a transaction, causing the queued data to be sent and received.
• (Optional) To unload the SPI slave driver, call spi_slave_free().
Normally, the data that needs to be transferred to or from a Device is read or written to
a chunk of memory indicated by the spi_slave_transaction_t::rx_buffer and
spi_slave_transaction_t::tx_buffer. The SPI driver can be configured to use DMA for transfers,
in which case these buffers must be allocated in DMA-capable memory using pvPortMallocCaps(size,
MALLOC_CAP_DMA).
The amount of data that the driver can read or write to the buffers is limited by
spi_slave_transaction_t::length. However, this member does not define the actual length
of an SPI transaction. A transaction’s length is determined by the clock and CS lines driven by the
Host. The actual length of the transmission can be read only after a transaction is finished from the member
spi_slave_transaction_t::trans_len.
If the length of the transmission is greater than the buffer length, only the initial number of bits speci-
fied in the spi_slave_transaction_t::length member will be sent and received. In this case,
spi_slave_transaction_t::trans_len is set to spi_slave_transaction_t::length
instead of the actual transaction length. To meet the actual transaction length require-
ments, set spi_slave_transaction_t::length to a value greater than the maximum
spi_slave_transaction_t::trans_len expected. If the transmission length is shorter than the
buffer length, only the data equal to the length of the buffer will be transmitted.
Most of ESP32’s peripheral signals have direct connection to their dedicated IO_MUX pins. However, the signals
can also be routed to any other available pins using the less direct GPIO matrix.
If at least one signal is routed through the GPIO matrix, then all signals will be routed through it. The GPIO matrix
samples all signals at 80 MHz and transmits them between the GPIO and the peripheral.
If the driver is configured so that all SPI signals are either routed to their dedicated IO_MUX pins or are not connected
at all, the GPIO matrix will be bypassed.
The GPIO matrix introduces flexibility of routing but also increases the input delay of the MISO signal, which makes
MISO setup time violations more likely. If SPI needs to operate at high speeds, use dedicated IO_MUX pins.
Note: For more details about the influence of the MISO input delay on the maximum clock frequency, see Timing
Considerations.
• Only the first Device attached to the bus can use the CS0 pin.
Transaction Interval The ESP32 SPI slave peripherals are designed as general purpose Devices controlled by a
CPU. As opposed to dedicated slaves, CPU-based SPI Devices have a limited number of pre-defined registers. All
transactions must be handled by the CPU, which means that the transfers and responses are not real-time, and there
might be noticeable latency.
As a solution, a Device’s response rate can be doubled by using the functions spi_slave_queue_trans()
and then spi_slave_get_trans_result() instead of using spi_slave_transmit().
You can also configure a GPIO pin through which the Device will signal to the Host when it is ready for a new
transaction. A code example of this can be found in peripherals/spi_slave.
SCLK Frequency Requirements The SPI slaves are designed to operate at up to 10 MHz. The data cannot be
recognized or received correctly if the clock is too fast or does not have a 50% duty cycle.
On top of that, there are additional requirements for the data to meet the timing constraints:
• Read (MOSI): The Device can read data correctly only if the data is already set at the launch edge. Although
it is usually the case for most masters.
• Write (MISO): The output delay of the MISO signal needs to be shorter than half of a clock cycle period so
that the MISO line is stable before the next latch edge. Given that the clock is balanced, the output delay
and frequency limitations in different cases are given below.
Note: 1. If the frequency reaches the maximum limitation, random errors may occur. 2. The clock
uncertainty between the Host and the Device (12.5 ns) is included. 3. The output delay is measured
under ideal circumstances (no load). If the MISO pin is heavily loaded, the output delay will be longer,
and the maximum allowed frequency will be lower.
Exception: The frequency is allowed to be higher if the master has more tolerance for the MISO setup
time, e.g., latch data at the next edge, or configurable latching time.
1. If DMA is enabled, the rx buffer should be word-aligned (starting from a 32-bit boundary and having a length
of multiples of 4 bytes). Otherwise, DMA may write incorrectly or not in a boundary aligned manner. The
driver reports an error if this condition is not satisfied.
Also, a Host should write lengths that are multiples of 4 bytes. The data with inappropriate lengths will be
discarded.
2. Furthermore, DMA requires SPI modes 1 and 3. For SPI modes 0 and 2, the MISO signal has to be launched
half a clock cycle earlier to meet the timing. The new timing is as follows:
CS
SCLK a b
delay setup hold
MISO (normal) 7 c 6 d 5 4 3
SCLK e f
delay setup hold
MISO (DMA) 7 g 6 h 5 4 3
If DMA is enabled, a Device’s launch edge is half of an SPI clock cycle ahead of the normal time, shifting to the
Master’s actual latch edge. In this case, if the GPIO matrix is bypassed, the hold time for data sampling is 68.75 ns
and no longer a half of an SPI clock cycle. If the GPIO matrix is used, the hold time will increase to 93.75 ns. The
Host should sample the data immediately at the latch edge or communicate in SPI modes 1 or 3. If your Host cannot
meet these timing requirements, initialize your Device without DMA.
Application Example
The code example for Device/Host communication can be found in the peripherals/spi_slave directory of ESP-IDF
examples.
API Reference
Header File
• components/driver/include/driver/spi_slave.h
Functions
esp_err_t spi_slave_initialize(spi_host_device_t host, const spi_bus_config_t *bus_config, const
spi_slave_interface_config_t *slave_config, spi_dma_chan_t dma_chan)
Initialize a SPI bus as a slave interface.
Warning: If a DMA channel is selected, any transmit and receive buffer used should be allocated in
DMA-capable memory.
Warning: The ISR of SPI is always executed on the core which calls this function. Never starve the ISR
on this core or the SPI transactions will not be handled.
Parameters
• host –SPI peripheral to use as a SPI slave interface
• bus_config –Pointer to a spi_bus_config_t struct specifying how the host should be
initialized
• slave_config –Pointer to a spi_slave_interface_config_t struct specifying the details
for the slave interface
• dma_chan –- Selecting a DMA channel for an SPI bus allows transactions on the bus
with size only limited by the amount of internal memory.
– Selecting SPI_DMA_DISABLED limits the size of transactions.
– Set to SPI_DMA_DISABLED if only the SPI flash uses this bus.
– Set to SPI_DMA_CH_AUTO to let the driver to allocate the DMA channel.
Returns
• ESP_ERR_INVALID_ARG if configuration is invalid
• ESP_ERR_INVALID_STATE if host already is in use
Parameters
• host –SPI peripheral to that is acting as a slave
• trans_desc –Pointer to variable able to contain a pointer to the description of the
transaction that is executed. Not const because we may want to write status back into the
transaction description.
• ticks_to_wait –Ticks to wait until there’s a returned item; use portMAX_DELAY
to never time out.
Returns
• ESP_ERR_INVALID_ARG if parameter is invalid
• ESP_OK on success
Structures
struct spi_slave_interface_config_t
This is a configuration for a SPI host acting as a slave device.
Public Members
int spics_io_num
CS GPIO pin for this device.
uint32_t flags
Bitwise OR of SPI_SLAVE_* flags.
int queue_size
Transaction queue size. This sets how many transactions can be ‘in the air’(queued using
spi_slave_queue_trans but not yet finished using spi_slave_get_trans_result) at the same time.
uint8_t mode
SPI mode, representing a pair of (CPOL, CPHA) configuration:
• 0: (0, 0)
• 1: (0, 1)
• 2: (1, 0)
• 3: (1, 1)
slave_transaction_cb_t post_setup_cb
Callback called after the SPI registers are loaded with new data.
This callback is called within interrupt context should be in IRAM for best performance, see “Trans-
ferring Speed”section in the SPI Master documentation for full details. If not, the callback may crash
during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM.
slave_transaction_cb_t post_trans_cb
Callback called after a transaction is done.
This callback is called within interrupt context should be in IRAM for best performance, see “Trans-
ferring Speed”section in the SPI Master documentation for full details. If not, the callback may crash
during flash operation when the driver is initialized with ESP_INTR_FLAG_IRAM.
struct spi_slave_transaction_t
This structure describes one SPI transaction
Public Members
size_t length
Total data length, in bits.
size_t trans_len
Transaction data length, in bits.
void *rx_buffer
Pointer to receive buffer, or NULL for no MISO phase. When the DMA is anabled, must start at WORD
boundary (rx_buffer%4==0), and has length of a multiple of 4 bytes.
void *user
User-defined variable. Can be used to store eg transaction ID.
Macros
SPI_SLAVE_TXBIT_LSBFIRST
Transmit command/address/data LSB first instead of the default MSB first.
SPI_SLAVE_RXBIT_LSBFIRST
Receive data LSB first instead of the default MSB first.
SPI_SLAVE_BIT_LSBFIRST
Transmit and receive LSB first.
Type Definitions
Overview
The ESP32-WROOM-32SE has integrated Microchip’s ATECC608A cryptoauth chip in the module. ATECC608A
is secure element which would generate and store ECC private key in the hardware.The ECC private key can be used
to enhance security to connect to IoT cloud services with use of X.509 based mutual authentication. The application
example demonstrates ECDSA sign and verify functions using ECC private key stored in ATECC608A
Application Example
ATECC608A can be used for TLS connections using ESP-TLS. To configure ESP-TLS for using secure element
please refer ATECC608A with ESP-TLS in ESP-TLS documentation.
Introduction
A touch sensor system is built on a substrate which carries electrodes and relevant connections under a protective flat
surface. When a user touches the surface, the capacitance variation is used to evaluate if the touch was valid.
Touch sensor on ESP32 can support up to 10 capacitive touch pads / GPIOs.
The sensing pads can be arranged in different combinations (e.g., matrix, slider), so that a larger area or more points
can be detected. The touch pad sensing process is under the control of a hardware-implemented finite-state machine
(FSM) which is initiated by software or a dedicated hardware timer.
For design, operation, and control registers of a touch sensor, see ESP32 Technical Reference Manual > On-Chip
Sensors and Analog Signal Processing [PDF].
In-depth design details of touch sensors and firmware development guidelines for ESP32 are available in Touch Sensor
Application Note.
For more information about testing touch sensors in various configurations, please check the Guide for ESP32-Sense-
Kit.
Functionality Overview
Description of API is broken down into groups of functions to provide a quick overview of the following features:
• Initialization of touch pad driver
• Configuration of touch pad GPIO pins
• Taking measurements
• Adjusting parameters of measurements
• Filtering measurements
• Touch detection methods
• Setting up interrupts to report touch detection
• Waking up from Sleep mode on interrupt
For detailed description of a particular function, please go to Section API Reference. Practical implementation of this
API is covered in Section Application Examples.
Initialization Before using a touch pad, you need to initialize the touch pad driver by calling the function
touch_pad_init(). This function sets several .._DEFAULT driver parameters listed in API Reference under
Macros. It also removes the information about which pads have been touched before, if any, and disables interrupts.
If the driver is not required anymore, deinitialize it by calling touch_pad_deinit().
Configuration Enabling the touch sensor functionality for a particular GPIO is done with
touch_pad_config().
Use the function touch_pad_set_fsm_mode() to select if touch pad measurement (operated by FSM)
should be started automatically by a hardware timer, or by software. If software mode is selected, use
touch_pad_sw_start() to start the FSM.
Touch State Measurements The following two functions come in handy to read raw or filtered measurements
from the sensor:
• touch_pad_read_raw_data()
• touch_pad_read_filtered()
They can also be used, for example, to evaluate a particular touch pad design by checking the range of sensor readings
when a pad is touched or released. This information can be then used to establish a touch threshold.
Note: Before using touch_pad_read_filtered(), you need to initialize and configure the filter by calling
specific filter functions described in Section Filtering of Measurements.
For the demonstration of how to read the touch pad data, check the application example peripher-
als/touch_sensor/touch_sensor_v1/touch_pad_read.
Method of Measurements The touch sensor will count the number of charge/discharge cycles over a fixed
period of time (specified by touch_pad_set_measurement_clock_cycles()). The count result is
the raw data that read from touch_pad_read_raw_data(). After finishing one measurement, the touch
sensor will sleep until the next measurement start, this interval between two measurements can be set by
touch_pad_set_measurement_interval().
Note: If the specified clock cycles for measurement is too samll, the result may be inaccurate, but increasing clock
cycles will increase the power consumption as well. Additionally, the response of the touch sensor will slow down if
the total time of the inverval and measurement is too long.
Optimization of Measurements A touch sensor has several configurable parameters to match the characteristics
of a particular touch pad design. For instance, to sense smaller capacity changes, it is possible to narrow down the
reference voltage range within which the touch pads are charged / discharged. The high and low reference voltages
are set using the function touch_pad_set_voltage().
Besides the ability to discern smaller capacity changes, a positive side effect is reduction of power consumption for
low power applications. A likely negative effect is an increase in measurement noise. If the dynamic range of obtained
readings is still satisfactory, then further reduction of power consumption might be done by reducing the measurement
time with touch_pad_set_measurement_clock_cycles().
The following list summarizes available measurement parameters and corresponding ‘set’functions:
• Touch pad charge / discharge parameters:
– voltage range: touch_pad_set_voltage()
– speed (slope): touch_pad_set_cnt_mode()
• Clock cycles of one measurement: touch_pad_set_measurement_clock_cycles()
Relationship between the voltage range (high / low reference voltages), speed (slope), and measurement time is shown
in the figure below.
The last chart Output represents the touch sensor reading, i.e., the count of pulses collected within the measurement
time.
All functions are provided in pairs to set a specific parameter and to get the current parameter’s value, e.g.,
touch_pad_set_voltage() and touch_pad_get_voltage().
Filtering of Measurements If measurements are noisy, you can filter them with provided API functions. Before
using the filter, please start it by calling touch_pad_filter_start().
The filter type is IIR (infinite impulse response), and it has a configurable period that can be set with the function
touch_pad_set_filter_period().
You can stop the filter with touch_pad_filter_stop(). If not required anymore, the filter can be deleted by
invoking touch_pad_filter_delete().
Touch Detection Touch detection is implemented in ESP32’s hardware based on the user-configured threshold
and raw measurements executed by FSM. Use the functions touch_pad_get_status() to check which pads
have been touched and touch_pad_clear_status() to clear the touch status information.
Hardware touch detection can also be wired to interrupts. This is described in the next section.
If measurements are noisy and capacity changes are small, hardware touch detection might be unreliable. To resolve
this issue, instead of using hardware detection / provided interrupts, implement measurement filtering and perform
touch detection in your own application. For sample implementation of both methods of touch detection, see pe-
ripherals/touch_sensor/touch_sensor_v1/touch_pad_interrupt.
Touch Triggered Interrupts Before enabling an interrupt on a touch detection, you should establish a touch de-
tection threshold. Use the functions described in Touch State Measurements to read and display sensor measurements
when a pad is touched and released. Apply a filter if measurements are noisy and relative capacity changes are small.
Depending on your application and environment conditions, test the influence of temperature and power supply volt-
age changes on measured values.
Once a detection threshold is established, it can be set during initialization with touch_pad_config() or at the
runtime with touch_pad_set_thresh().
In the next step, configure how interrupts are triggered. They can be triggered below or above the threshold, which is
set with the function touch_pad_set_trigger_mode().
Finally, configure and manage interrupt calls using the following functions:
• touch_pad_isr_register() / touch_pad_isr_deregister()
• touch_pad_intr_enable() / touch_pad_intr_disable()
When interrupts are operational, you can obtain the information from which particular pad an interrupt came by
invoking touch_pad_get_status() and clear the pad status with touch_pad_clear_status().
Note: Interrupts on touch detection operate on raw / unfiltered measurements checked against user established
threshold and are implemented in hardware. Enabling the software filtering API (see Filtering of Measurements) does
Wakeup from Sleep Mode If touch pad interrupts are used to wake up the chip from a sleep mode, you can select
a certain configuration of pads (SET1 or both SET1 and SET2) that should be touched to trigger the interrupt and
cause the subsequent wakeup. To do so, use the function touch_pad_set_trigger_source().
Configuration of required bit patterns of pads may be managed for each ‘SET’with:
• touch_pad_set_group_mask() / touch_pad_get_group_mask()
• touch_pad_clear_group_mask()
Application Examples
API Reference
Header File
• components/driver/esp32/include/driver/touch_sensor.h
Functions
esp_err_t touch_pad_config(touch_pad_t touch_num, uint16_t threshold)
Configure touch pad interrupt threshold.
Note: If FSM mode is set to TOUCH_FSM_MODE_TIMER, this function will be blocked for one measure-
ment cycle and wait for data to be valid.
Parameters
• touch_num –touch pad index
• threshold –interrupt threshold,
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG if argument wrong
• ESP_FAIL if touch pad not initialized
esp_err_t touch_pad_read(touch_pad_t touch_num, uint16_t *touch_value)
get touch sensor counter value. Each touch sensor has a counter to count the number of charge/discharge
cycles. When the pad is not ‘touched’, we can get a number of the counter. When the pad is ‘touched’,
the value in counter will get smaller because of the larger equivalent capacitance.
Note: This API requests hardware measurement once. If IIR filter mode is enabled, please use
‘touch_pad_read_raw_data’interface instead.
Parameters
• touch_num –touch pad index
• touch_value –pointer to accept touch sensor value
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Touch pad parameter error
• ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of
“touch_value”is 0.
Note: touch_pad_filter_start has to be called before calling touch_pad_read_filtered. This function can be
called from ISR
Parameters
• touch_num –touch pad index
• touch_value –pointer to accept touch sensor value
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Touch pad parameter error
• ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of
“touch_value”is 0.
• ESP_FAIL Touch pad not initialized
Note: touch_pad_filter_start has to be called before calling touch_pad_read_raw_data. This function can be
called from ISR
Parameters
• touch_num –touch pad index
• touch_value –pointer to accept touch sensor value
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Touch pad parameter error
• ESP_ERR_INVALID_STATE This touch pad hardware connection is error, the value of
“touch_value”is 0.
• ESP_FAIL Touch pad not initialized
Parameters read_cb –Pointer to filtered callback function. If the argument passed in is NULL,
the callback will stop.
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG set error
Note: This function will specify the clock cycles of each measurement and the clock is sourced from
SOC_MOD_CLK_RTC_FAST, its default frequency is SOC_CLK_RC_FAST_FREQ_APPROX The touch
sensor will record the charge and discharge times during these clock cycles as the final result (raw value)
Note: The touch sensor will sleep between two mesurements This function is to set the inter-
val cycle And the interval is clocked from SOC_MOD_CLK_RTC_SLOW, its default frequency is
SOC_CLK_RC_SLOW_FREQ_APPROX
Note: The touch sensor will count the number of charge/discharge cycles over a fixed period of time (specified
as the second parameter). That means the number of cycles (raw value) will decrease as the capacity of the
touch pad is increasing.
Note: The greater the duty cycle of the measurement time, the more system power is consumed.
Parameters
• sleep_cycle –The touch sensor will sleep after each measurement. sleep_cycle
decide the interval between each measurement. t_sleep = sleep_cycle /
SOC_CLK_RC_SLOW_FREQ_APPROX. The approximate frequency value of
RTC_SLOW_CLK can be obtained using rtc_clk_slow_freq_get_hz function.
• meas_cycle –The duration of the touch sensor measurement. t_meas = meas_cycle
/ SOC_CLK_RC_FAST_FREQ_APPROX, the maximum measure time is 0xffff /
SOC_CLK_RC_FAST_FREQ_APPROX
Returns
• ESP_OK on success
Returns
• ESP_OK on success
esp_err_t touch_pad_intr_disable(void)
To disable touch pad interrupt.
Returns
• ESP_OK on success
esp_err_t touch_pad_intr_clear(void)
To clear touch pad interrupt.
Returns
• ESP_OK on success
esp_err_t touch_pad_set_filter_period(uint32_t new_period_ms)
set touch pad filter calibration period, in ms. Need to call touch_pad_filter_start before all touch filter APIs
Parameters new_period_ms –filter period, in ms
Returns
• ESP_OK Success
• ESP_ERR_INVALID_STATE driver state error
• ESP_ERR_INVALID_ARG parameter error
esp_err_t touch_pad_get_filter_period(uint32_t *p_period_ms)
get touch pad filter calibration period, in ms Need to call touch_pad_filter_start before all touch filter APIs
Parameters p_period_ms –pointer to accept period
Returns
• ESP_OK Success
• ESP_ERR_INVALID_STATE driver state error
• ESP_ERR_INVALID_ARG parameter error
esp_err_t touch_pad_filter_start(uint32_t filter_period_ms)
start touch pad filter function This API will start a filter to process the noise in order to prevent false triggering
when detecting slight change of capacitance. Need to call touch_pad_filter_start before all touch filter APIs
Note: This filter uses FreeRTOS timer, which is dispatched from a task with priority 1 by default on CPU
0. So if some application task with higher priority takes a lot of CPU0 time, then the quality of data obtained
from this filter will be affected. You can adjust FreeRTOS timer task priority in menuconfig.
esp_err_t touch_pad_filter_stop(void)
stop touch pad filter function Need to call touch_pad_filter_start before all touch filter APIs
Returns
• ESP_OK Success
• ESP_ERR_INVALID_STATE driver state error
esp_err_t touch_pad_filter_delete(void)
delete touch pad filter driver and release the memory Need to call touch_pad_filter_start before all touch filter
APIs
Returns
• ESP_OK Success
Type Definitions
Param raw_value The latest raw data(touch sensor counter value) that points to all chan-
nels(raw_value[0..TOUCH_PAD_MAX-1]).
Param filtered_value The latest IIR filtered data(calculated from raw data) that points to all chan-
nels(filtered_value[0..TOUCH_PAD_MAX-1]).
Header File
• components/driver/include/driver/touch_sensor_common.h
Functions
esp_err_t touch_pad_init(void)
Initialize touch module.
Note: If default parameter don’t match the usage scenario, it can be changed after this function.
Returns
• ESP_OK Success
• ESP_ERR_NO_MEM Touch pad init error
• ESP_ERR_NOT_SUPPORTED Touch pad is providing current to external XTAL
esp_err_t touch_pad_deinit(void)
Un-install touch pad driver.
Note: After this function is called, other touch functions are prohibited from being called.
Returns
• ESP_OK Success
• ESP_FAIL Touch pad driver not initialized
Note: The higher the charge and discharge current, the greater the immunity of the touch channel, but it will
increase the system power consumption.
Parameters
• touch_num –touch pad index
• slope –touch pad charge/discharge speed
• opt –the initial voltage
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if argument is wrong
• ESP_OK on success
• ESP_ERR_INVALID_STATE if a handler matching both fn and arg isn’t registered
esp_err_t touch_pad_get_wakeup_status(touch_pad_t *pad_num)
Get the touch pad which caused wakeup from deep sleep.
Parameters pad_num –pointer to touch pad which caused wakeup
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG parameter is NULL
esp_err_t touch_pad_set_fsm_mode(touch_fsm_mode_t mode)
Set touch sensor FSM mode, the test action can be triggered by the timer, as well as by the software.
Parameters mode –FSM mode
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if argument is wrong
esp_err_t touch_pad_get_fsm_mode(touch_fsm_mode_t *mode)
Get touch sensor FSM mode.
Parameters mode –pointer to accept FSM mode
Returns
• ESP_OK on success
esp_err_t touch_pad_clear_status(void)
To clear the touch sensor channel active status.
Note: The FSM automatically updates the touch sensor status. It is generally not necessary to call this API
to clear the status.
Returns
• ESP_OK on success
uint32_t touch_pad_get_status(void)
Get the touch sensor channel active status mask. The bit position represents the channel number. The 0/1
status of the bit represents the trigger status.
Returns
• The touch sensor status. e.g. Touch1 trigger status is status_mask & (BIT1).
bool touch_pad_meas_is_done(void)
Check touch sensor measurement status.
Returns
• True measurement is under way
• False measurement done
GPIO Lookup Macros Some useful macros can be used to specified the GPIO number of a touch pad channel,
or vice versa. e.g.
1. TOUCH_PAD_NUM5_GPIO_NUM is the GPIO number of channel 5 (12);
2. TOUCH_PAD_GPIO4_CHANNEL is the channel number of GPIO 4 (channel 0).
Header File
• components/soc/esp32/include/soc/touch_sensor_channel.h
Macros
TOUCH_PAD_GPIO4_CHANNEL
TOUCH_PAD_NUM0_GPIO_NUM
TOUCH_PAD_GPIO0_CHANNEL
TOUCH_PAD_NUM1_GPIO_NUM
TOUCH_PAD_GPIO2_CHANNEL
TOUCH_PAD_NUM2_GPIO_NUM
TOUCH_PAD_GPIO15_CHANNEL
TOUCH_PAD_NUM3_GPIO_NUM
TOUCH_PAD_GPIO13_CHANNEL
TOUCH_PAD_NUM4_GPIO_NUM
TOUCH_PAD_GPIO12_CHANNEL
TOUCH_PAD_NUM5_GPIO_NUM
TOUCH_PAD_GPIO14_CHANNEL
TOUCH_PAD_NUM6_GPIO_NUM
TOUCH_PAD_GPIO27_CHANNEL
TOUCH_PAD_NUM7_GPIO_NUM
TOUCH_PAD_GPIO33_CHANNEL
TOUCH_PAD_NUM8_GPIO_NUM
TOUCH_PAD_GPIO32_CHANNEL
TOUCH_PAD_NUM9_GPIO_NUM
Header File
• components/hal/include/hal/touch_sensor_types.h
Macros
TOUCH_PAD_BIT_MASK_ALL
TOUCH_PAD_SLOPE_DEFAULT
TOUCH_PAD_TIE_OPT_DEFAULT
TOUCH_PAD_BIT_MASK_MAX
TOUCH_PAD_HIGH_VOLTAGE_THRESHOLD
TOUCH_PAD_LOW_VOLTAGE_THRESHOLD
TOUCH_PAD_ATTEN_VOLTAGE_THRESHOLD
TOUCH_PAD_IDLE_CH_CONNECT_DEFAULT
TOUCH_PAD_THRESHOLD_MAX
If set touch threshold max value, The touch sensor can’t be in touched status
TOUCH_PAD_SLEEP_CYCLE_DEFAULT
The timer frequency is RTC_SLOW_CLK (can be 150k or 32k depending on the options), max value is 0xffff
TOUCH_PAD_MEASURE_CYCLE_DEFAULT
The timer frequency is 8Mhz, the max value is 0x7fff
TOUCH_FSM_MODE_DEFAULT
The touch FSM my be started by the software or timer
TOUCH_TRIGGER_MODE_DEFAULT
Interrupts can be triggered if sensor value gets below or above threshold
TOUCH_TRIGGER_SOURCE_DEFAULT
The wakeup trigger source can be SET1 or both SET1 and SET2
Enumerations
enum touch_pad_t
Touch pad channel
Values:
enumerator TOUCH_PAD_NUM0
Touch pad channel 0 is GPIO4(ESP32)
enumerator TOUCH_PAD_NUM1
Touch pad channel 1 is GPIO0(ESP32) / GPIO1(ESP32-S2)
enumerator TOUCH_PAD_NUM2
Touch pad channel 2 is GPIO2(ESP32) / GPIO2(ESP32-S2)
enumerator TOUCH_PAD_NUM3
Touch pad channel 3 is GPIO15(ESP32) / GPIO3(ESP32-S2)
enumerator TOUCH_PAD_NUM4
Touch pad channel 4 is GPIO13(ESP32) / GPIO4(ESP32-S2)
enumerator TOUCH_PAD_NUM5
Touch pad channel 5 is GPIO12(ESP32) / GPIO5(ESP32-S2)
enumerator TOUCH_PAD_NUM6
Touch pad channel 6 is GPIO14(ESP32) / GPIO6(ESP32-S2)
enumerator TOUCH_PAD_NUM7
Touch pad channel 7 is GPIO27(ESP32) / GPIO7(ESP32-S2)
enumerator TOUCH_PAD_NUM8
Touch pad channel 8 is GPIO33(ESP32) / GPIO8(ESP32-S2)
enumerator TOUCH_PAD_NUM9
Touch pad channel 9 is GPIO32(ESP32) / GPIO9(ESP32-S2)
enumerator TOUCH_PAD_MAX
enum touch_high_volt_t
Touch sensor high reference voltage
Values:
enumerator TOUCH_HVOLT_KEEP
Touch sensor high reference voltage, no change
enumerator TOUCH_HVOLT_2V4
Touch sensor high reference voltage, 2.4V
enumerator TOUCH_HVOLT_2V5
Touch sensor high reference voltage, 2.5V
enumerator TOUCH_HVOLT_2V6
Touch sensor high reference voltage, 2.6V
enumerator TOUCH_HVOLT_2V7
Touch sensor high reference voltage, 2.7V
enumerator TOUCH_HVOLT_MAX
enum touch_low_volt_t
Touch sensor low reference voltage
Values:
enumerator TOUCH_LVOLT_KEEP
Touch sensor low reference voltage, no change
enumerator TOUCH_LVOLT_0V5
Touch sensor low reference voltage, 0.5V
enumerator TOUCH_LVOLT_0V6
Touch sensor low reference voltage, 0.6V
enumerator TOUCH_LVOLT_0V7
Touch sensor low reference voltage, 0.7V
enumerator TOUCH_LVOLT_0V8
Touch sensor low reference voltage, 0.8V
enumerator TOUCH_LVOLT_MAX
enum touch_volt_atten_t
Touch sensor high reference voltage attenuation
Values:
enumerator TOUCH_HVOLT_ATTEN_KEEP
Touch sensor high reference voltage attenuation, no change
enumerator TOUCH_HVOLT_ATTEN_1V5
Touch sensor high reference voltage attenuation, 1.5V attenuation
enumerator TOUCH_HVOLT_ATTEN_1V
Touch sensor high reference voltage attenuation, 1.0V attenuation
enumerator TOUCH_HVOLT_ATTEN_0V5
Touch sensor high reference voltage attenuation, 0.5V attenuation
enumerator TOUCH_HVOLT_ATTEN_0V
Touch sensor high reference voltage attenuation, 0V attenuation
enumerator TOUCH_HVOLT_ATTEN_MAX
enum touch_cnt_slope_t
Touch sensor charge/discharge speed
Values:
enumerator TOUCH_PAD_SLOPE_0
Touch sensor charge / discharge speed, always zero
enumerator TOUCH_PAD_SLOPE_1
Touch sensor charge / discharge speed, slowest
enumerator TOUCH_PAD_SLOPE_2
Touch sensor charge / discharge speed
enumerator TOUCH_PAD_SLOPE_3
Touch sensor charge / discharge speed
enumerator TOUCH_PAD_SLOPE_4
Touch sensor charge / discharge speed
enumerator TOUCH_PAD_SLOPE_5
Touch sensor charge / discharge speed
enumerator TOUCH_PAD_SLOPE_6
Touch sensor charge / discharge speed
enumerator TOUCH_PAD_SLOPE_7
Touch sensor charge / discharge speed, fast
enumerator TOUCH_PAD_SLOPE_MAX
enum touch_tie_opt_t
Touch sensor initial charge level
Values:
enumerator TOUCH_PAD_TIE_OPT_LOW
Initial level of charging voltage, low level
enumerator TOUCH_PAD_TIE_OPT_HIGH
Initial level of charging voltage, high level
enumerator TOUCH_PAD_TIE_OPT_MAX
enum touch_fsm_mode_t
Touch sensor FSM mode
Values:
enumerator TOUCH_FSM_MODE_TIMER
To start touch FSM by timer
enumerator TOUCH_FSM_MODE_SW
To start touch FSM by software trigger
enumerator TOUCH_FSM_MODE_MAX
enum touch_trigger_mode_t
Values:
enumerator TOUCH_TRIGGER_BELOW
Touch interrupt will happen if counter value is less than threshold.
enumerator TOUCH_TRIGGER_ABOVE
Touch interrupt will happen if counter value is larger than threshold.
enumerator TOUCH_TRIGGER_MAX
enum touch_trigger_src_t
Values:
enumerator TOUCH_TRIGGER_SOURCE_BOTH
wakeup interrupt is generated if both SET1 and SET2 are “touched”
enumerator TOUCH_TRIGGER_SOURCE_SET1
wakeup interrupt is generated if SET1 is “touched”
enumerator TOUCH_TRIGGER_SOURCE_MAX
Overview
The Two-Wire Automotive Interface (TWAI) is a real-time serial communication protocol suited for automotive and
industrial applications. It is compatible with ISO11898-1 Classical frames, thus can support Standard Frame Format
(11-bit ID) and Extended Frame Format (29-bit ID). The ESP32’s peripherals contains a TWAI controller that can
be configured to communicate on a TWAI bus via an external transceiver.
Warning: The TWAI controller is not compatible with ISO11898-1 FD Format frames, and will interpret such
frames as errors.
Sections
The TWAI is a multi-master, multi-cast, asynchronous, serial communication protocol. TWAI also supports error
detection and signalling, and inbuilt message prioritization.
Multi-master: Any node on the bus can initiate the transfer of a message.
Multi-cast: When a node transmits a message, all nodes on the bus will receive the message (i.e., broadcast) thus
ensuring data consistency across all nodes. However, some nodes can selectively choose which messages to accept
via the use of acceptance filtering (multi-cast).
Asynchronous: The bus does not contain a clock signal. All nodes on the bus operate at the same bit rate and
synchronize using the edges of the bits transmitted on the bus.
Error Detection and Signalling: Every node will constantly monitor the bus. When any node detects an error, it
will signal the detection by transmitting an error frame. Other nodes will receive the error frame and transmit their
own error frames in response. This will result in an error detection being propagated to all nodes on the bus.
Message Priorities: Messages contain an ID field. If two or more nodes attempt to transmit simultaneously, the
node transmitting the message with the lower ID value will win arbitration of the bus. All other nodes will become
receivers ensuring that there is at most one transmitter at any time.
TWAI Messages TWAI Messages are split into Data Frames and Remote Frames. Data Frames are used to deliver
a data payload to other nodes, whereas a Remote Frame is used to request a Data Frame from other nodes (other nodes
can optionally respond with a Data Frame). Data and Remote Frames have two frame formats known as Extended
Frame and Standard Frame which contain a 29-bit ID and an 11-bit ID respectively. A TWAI message consists of
the following fields:
• 29-bit or 11-bit ID: Determines the priority of the message (lower value has higher priority).
• Data Length Code (DLC) between 0 to 8: Indicates the size (in bytes) of the data payload for a Data Frame,
or the amount of data to request for a Remote Frame.
• Up to 8 bytes of data for a Data Frame (should match DLC).
Error States and Counters The TWAI protocol implements a feature known as “fault confinement”where a
persistently erroneous node will eventually eliminate itself form the bus. This is implemented by requiring every
node to maintain two internal error counters known as the Transmit Error Counter (TEC) and the Receive Error
Counter (REC). The two error counters are incremented and decremented according to a set of rules (where the
counters increase on an error, and decrease on a successful message transmission/reception). The values of the
counters are used to determine a node’s error state, namely Error Active, Error Passive, and Bus-Off.
Error Active: A node is Error Active when both TEC and REC are less than 128 and indicates that the node is
operating normally. Error Active nodes are allowed to participate in bus communications, and will actively signal the
detection of any errors by automatically transmitting an Active Error Flag over the bus.
Error Passive: A node is Error Passive when either the TEC or REC becomes greater than or equal to 128.
Error Passive nodes are still able to take part in bus communications, but will instead transmit a Passive Error Flag
upon detection of an error.
Bus-Off: A node becomes Bus-Off when the TEC becomes greater than or equal to 256. A Bus-Off node is
unable influence the bus in any manner (essentially disconnected from the bus) thus eliminating itself from the bus.
A node will remain in the Bus-Off state until it undergoes bus-off recovery.
The TWAI controller does not contain a integrated transceiver. Therefore, to connect the TWAI controller to a TWAI
bus, an external transceiver is required. The type of external transceiver used should depend on the application’
s physical layer specification (e.g. using SN65HVD23x transceivers for ISO 11898-2 compatibility).
The TWAI controller’s interface consists of 4 signal lines known as TX, RX, BUS-OFF, and CLKOUT. These
four signal lines can be routed through the GPIO Matrix to the ESP32’s GPIO pads.
TX and RX: The TX and RX signal lines are required to interface with an external transceiver. Both signal lines
represent/interpret a dominant bit as a low logic level (0V), and a recessive bit as a high logic level (3.3V).
BUS-OFF: The BUS-OFF signal line is optional and is set to a low logic level (0V) whenever the TWAI controller
reaches a bus-off state. The BUS-OFF signal line is set to a high logic level (3.3V) otherwise.
CLKOUT: The CLKOUT signal line is optional and outputs a prescaled version of the controller’s source clock
(APB Clock).
Note: An external transceiver must internally loopback the TX to RX such that a change in logic level to the TX
signal line can be observed on the RX line. Failing to do so will cause the TWAI controller to interpret differences
in logic levels between the two signal lines as a loss in arbitration or a bit error.
Driver Configuration
Operating Modes The TWAI driver supports the following modes of operations:
Normal Mode: The normal operating mode allows the TWAI controller to take part in bus activities such as trans-
mitting and receiving messages/error frames. Acknowledgement from another node is required when transmitting a
message.
No Ack Mode: The No Acknowledgement mode is similar to normal mode, however acknowledgements are not
required for a message transmission to be considered successful. This mode is useful when self testing the TWAI
controller (loopback of transmissions).
Listen Only Mode: This mode will prevent the TWAI controller from influencing the bus. Therefore, transmission of
messages/acknowledgement/error frames will be disabled. However the TWAI controller will still be able to receive
messages but will not acknowledge the message. This mode is suited for bus monitor applications.
Alerts The TWAI driver contains an alert feature that is used to notify the application layer of certain TWAI con-
troller or TWAI bus events. Alerts are selectively enabled when the TWAI driver is installed, but can be reconfigured
during runtime by calling twai_reconfigure_alerts(). The application can then wait for any enabled alerts
to occur by calling twai_read_alerts(). The TWAI driver supports the following alerts:
Note: The TWAI controller’s error warning limit is used to preemptively warn the application of bus errors
before the error passive state is reached. By default, the TWAI driver sets the error warning limit to 96. The
TWAI_ALERT_ABOVE_ERR_WARN is raised when the TEC or REC becomes larger then or equal to the error
warning limit. The TWAI_ALERT_BELOW_ERR_WARN is raised when both TEC and REC return back to values
below 96.
Note: When enabling alerts, the TWAI_ALERT_AND_LOG flag can be used to cause the TWAI driver to
log any raised alerts to UART. However, alert logging is disabled and TWAI_ALERT_AND_LOG if the CON-
FIG_TWAI_ISR_IN_IRAM option is enabled (see Placing ISR into IRAM).
Note: The TWAI_ALERT_ALL and TWAI_ALERT_NONE macros can also be used to enable/disable all alerts
during configuration/reconfiguration.
Bit Timing The operating bit rate of the TWAI driver is configured using the twai_timing_config_t struc-
ture. The period of each bit is made up of multiple time quanta, and the period of a time quantum is determined
by a prescaled version of the TWAI controller’s source clock. A single bit contains the following segments in the
following order:
1. The Synchronization Segment consists of a single time quantum
2. Timing Segment 1 consists of 1 to 16 time quanta before sample point
3. Timing Segment 2 consists of 1 to 8 time quanta after sample point
The Baudrate Prescaler is used to determine the period of each time quantum by dividing the TWAI controller’s
source clock (80 MHz APB clock). On the ESP32, the brp can be any even number from 2 to 128.
If the ESP32 is a revision 2 or later chip, the brp will also support any multiple of 4 from 132 to 256, and can be
enabled by setting the CONFIG_ESP32_REV_MIN to revision 2 or higher.
The sample point of a bit is located on the intersection of Timing Segment 1 and 2. Enabling Triple Sampling will
cause 3 time quanta to be sampled per bit instead of 1 (extra samples are located at the tail end of Timing Segment
1).
The Synchronization Jump Width is used to determine the maximum number of time quanta a single bit time can
be lengthened/shortened for synchronization purposes. sjw can range from 1 to 4.
Note: Multiple combinations of brp, tseg_1, tseg_2, and sjw can achieve the same bit rate. Users should
tune these values to the physical characteristics of their bus by taking into account factors such as propagation delay,
node information processing time, and phase errors.
Bit timing macro initializers are also available for commonly used bit rates. The following macro initializers are
provided by the TWAI driver.
• TWAI_TIMING_CONFIG_1MBITS()
• TWAI_TIMING_CONFIG_800KBITS()
• TWAI_TIMING_CONFIG_500KBITS()
• TWAI_TIMING_CONFIG_250KBITS()
• TWAI_TIMING_CONFIG_125KBITS()
• TWAI_TIMING_CONFIG_100KBITS()
• TWAI_TIMING_CONFIG_50KBITS()
• TWAI_TIMING_CONFIG_25KBITS()
Revision 2 or later of the ESP32 also supports the following bit rates:
• TWAI_TIMING_CONFIG_20KBITS()
• TWAI_TIMING_CONFIG_16KBITS()
• TWAI_TIMING_CONFIG_12_5KBITS()
Acceptance Filter The TWAI controller contains a hardware acceptance filter which can be used to filter messages
of a particular ID. A node that filters out a message will not receive the message, but will still acknowledge it.
Acceptance filters can make a node more efficient by filtering out messages sent over the bus that are irrelevant to the
node. The acceptance filter is configured using two 32-bit values within twai_filter_config_t known as the
acceptance code and the acceptance mask.
The acceptance code specifies the bit sequence which a message’s ID, RTR, and data bytes must match in order
for the message to be received by the TWAI controller. The acceptance mask is a bit sequence specifying which
bits of the acceptance code can be ignored. This allows for a messages of different IDs to be accepted by a single
acceptance code.
The acceptance filter can be used under Single or Dual Filter Mode. Single Filter Mode will use the acceptance
code and mask to define a single filter. This allows for the first two data bytes of a standard frame to be filtered, or
the entirety of an extended frame’s 29-bit ID. The following diagram illustrates how the 32-bit acceptance code and
mask will be interpreted under Single Filter Mode (Note: The yellow and blue fields represent standard and extended
frame formats respectively).
Dual Filter Mode will use the acceptance code and mask to define two separate filters allowing for increased flexi-
bility of ID’s to accept, but does not allow for all 29-bits of an extended ID to be filtered. The following diagram
illustrates how the 32-bit acceptance code and mask will be interpreted under Dual Filter Mode (Note: The yellow
and blue fields represent standard and extended frame formats respectively).
Fig. 26: Bit layout of single filter mode (Right side MSBit)
Fig. 27: Bit layout of dual filter mode (Right side MSBit)
Disabling TX Queue The TX queue can be disabled during configuration by setting the tx_queue_len member
of twai_general_config_t to 0. This will allow applications that do not require message transmission to save
a small amount of memory when using the TWAI driver.
Placing ISR into IRAM The TWAI driver’s ISR (Interrupt Service Routine) can be placed into IRAM so that
the ISR can still run whilst the cache is disabled. Placing the ISR into IRAM may be necessary to maintain the TWAI
driver’s functionality during lengthy cache disabling operations (such as SPI Flash writes, OTA updates etc). Whilst
the cache is disabled, the ISR will continue to:
• Read received messages from the RX buffer and place them into the driver’s RX queue.
• Load messages pending transmission from the driver’s TX queue and write them into the TX buffer.
To place the TWAI driver’s ISR, users must do the following:
• Enable the CONFIG_TWAI_ISR_IN_IRAM option using idf.py menuconfig.
• When calling twai_driver_install(), the intr_flags member of twai_general_config_t
should set the ESP_INTR_FLAG_IRAM set.
Note: When the CONFIG_TWAI_ISR_IN_IRAM option is enabled, the TWAI driver will no longer log any alerts
(i.e., the TWAI_ALERT_AND_LOG flag will not have any effect).
ESP32 Errata Workarounds The ESP32’s TWAI controller contains multiple hardware errata (more details
about the errata can be found in the ESP32’s ECO document). Some of these errata are critical, and under specific
circumstances, can place the TWAI controller into an unrecoverable state (i.e., the controller gets stuck until it is
reset by the CPU).
The TWAI driver contains software workarounds for these critical errata. With these workarounds, the ESP32 TWAI
driver can operate normally, albeit with degraded performance. The degraded performance will affect users in the
following ways depending on what particular errata conditions are encountered:
• The TWAI driver can occasionally drop some received messages.
• The TWAI driver can be unresponsive for a short period of time (i.e., will not transmit or ACK for 11 bit times
or longer).
• If CONFIG_TWAI_ISR_IN_IRAM is enabled, the workarounds will increase IRAM usage by approximately
1KB.
The software workarounds are enabled by default and it is recommended that users keep this workarounds enabled.
Driver Operation
The TWAI driver is designed with distinct states and strict rules regarding the functions or conditions that trigger a
state transition. The following diagram illustrates the various states and their transitions.
Fig. 28: State transition diagram of the TWAI driver (see table below)
Driver States Uninstalled: In the uninstalled state, no memory is allocated for the driver and the TWAI controller
is powered OFF.
Stopped: In this state, the TWAI controller is powered ON and the TWAI driver has been installed. However the
TWAI controller will be unable to take part in any bus activities such as transmitting, receiving, or acknowledging
messages.
Running: In the running state, the TWAI controller is able to take part in bus activities. Therefore messages can
be transmitted/received/acknowledged. Furthermore the TWAI controller will be able to transmit error frames upon
detection of errors on the bus.
Bus-Off: The bus-off state is automatically entered when the TWAI controller’s Transmit Error Counter becomes
greater than or equal to 256. The bus-off state indicates the occurrence of severe errors on the bus or in the TWAI
controller. Whilst in the bus-off state, the TWAI controller will be unable to take part in any bus activities. To exit
the bus-off state, the TWAI controller must undergo the bus recovery process.
Recovering: The recovering state is entered when the TWAI controller undergoes bus recovery. The TWAI con-
troller/TWAI driver will remain in the recovering state until the 128 occurrences of 11 consecutive recessive bits is
observed on the bus.
Message Fields and Flags The TWAI driver distinguishes different types of messages by using the various bit field
members of the twai_message_t structure. These bit field members determine whether a message is in standard
or extended format, a remote frame, and the type of transmission to use when transmitting such a message.
These bit field members can also be toggled using the the flags member of twai_message_t and the following
message flags:
Examples
Configuration & Installation The following code snippet demonstrates how to configure, install,
and start the TWAI driver via the use of the various configuration structures, macro initializers, the
twai_driver_install() function, and the twai_start() function.
#include "driver/gpio.h"
#include "driver/twai.h"
void app_main()
{
//Initialize configuration structures using macro initializers
twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(GPIO_NUM_21, GPIO_
,→NUM_22, TWAI_MODE_NORMAL);
...
The usage of macro initializers is not mandatory and each of the configuration structures can be manually.
Message Transmission The following code snippet demonstrates how to transmit a message via the usage of the
twai_message_t type and twai_transmit() function.
#include "driver/twai.h"
...
Message Reception The following code snippet demonstrates how to receive a message via the usage of the
twai_message_t type and twai_receive() function.
#include "driver/twai.h"
...
Reconfiguring and Reading Alerts The following code snippet demonstrates how to reconfigure and read TWAI
driver alerts via the use of the twai_reconfigure_alerts() and twai_read_alerts() functions.
#include "driver/twai.h"
...
Stop and Uninstall The following code demonstrates how to stop and uninstall the TWAI driver via the use of the
twai_stop() and twai_driver_uninstall() functions.
#include "driver/twai.h"
...
Multiple ID Filter Configuration The acceptance mask in twai_filter_config_t can be configured such
that two or more IDs will be accepted for a single filter. For a particular filter to accept multiple IDs, the conflicting
bit positions amongst the IDs must be set in the acceptance mask. The acceptance code can be set to any one of the
IDs.
The following example shows how the calculate the acceptance mask given multiple IDs:
Application Examples Network Example: The TWAI Network example demonstrates communication between
two ESP32s using the TWAI driver API. One TWAI node acts as a network master that initiates and ceases the transfer
of a data from another node acting as a network slave. The example can be found via peripherals/twai/twai_network.
Alert and Recovery Example: This example demonstrates how to use the TWAI driver’s alert and bus-off re-
covery API. The example purposely introduces errors on the bus to put the TWAI controller into the Bus-Off state.
An alert is used to detect the Bus-Off state and trigger the bus recovery process. The example can be found via
peripherals/twai/twai_alert_and_recovery.
Self Test Example: This example uses the No Acknowledge Mode and Self Reception Request to cause the TWAI
controller to send and simultaneously receive a series of messages. This example can be used to verify if the connec-
tions between the TWAI controller and the external transceiver are working correctly. The example can be found via
peripherals/twai/twai_self_test.
API Reference
Header File
• components/hal/include/hal/twai_types.h
Structures
struct twai_message_t
Structure to store a TWAI message.
Public Members
uint32_t extd
Extended Frame Format (29bit ID)
uint32_t rtr
Message is a Remote Frame
uint32_t ss
Transmit as a Single Shot Transmission. Unused for received.
uint32_t self
Transmit as a Self Reception Request. Unused for received.
uint32_t dlc_non_comp
Message’s Data length code is larger than 8. This will break compliance with ISO 11898-1
uint32_t reserved
Reserved bits
uint32_t flags
Deprecated: Alternate way to set bits using message flags
uint32_t identifier
11 or 29 bit identifier
uint8_t data_length_code
Data length code
uint8_t data[TWAI_FRAME_MAX_DLC]
Data bytes (not relevant in RTR frame)
struct twai_timing_config_t
Structure for bit timing configuration of the TWAI driver.
Public Members
uint32_t brp
Baudrate prescaler (i.e., APB clock divider). Any even number from 2 to 128 for ESP32, 2 to 32768 for
ESP32S2. For ESP32 Rev 2 or later, multiples of 4 from 132 to 256 are also supported
uint8_t tseg_1
Timing segment 1 (Number of time quanta, between 1 to 16)
uint8_t tseg_2
Timing segment 2 (Number of time quanta, 1 to 8)
uint8_t sjw
Synchronization Jump Width (Max time quanta jump for synchronize from 1 to 4)
bool triple_sampling
Enables triple sampling when the TWAI controller samples a bit
struct twai_filter_config_t
Structure for acceptance filter configuration of the TWAI driver (see documentation)
Public Members
uint32_t acceptance_code
32-bit acceptance code
uint32_t acceptance_mask
32-bit acceptance mask
bool single_filter
Use Single Filter Mode (see documentation)
Macros
TWAI_EXTD_ID_MASK
TWAI Constants.
Bit mask for 29 bit Extended Frame Format ID
TWAI_STD_ID_MASK
Bit mask for 11 bit Standard Frame Format ID
TWAI_FRAME_MAX_DLC
Max data bytes allowed in TWAI
TWAI_FRAME_EXTD_ID_LEN_BYTES
EFF ID requires 4 bytes (29bit)
TWAI_FRAME_STD_ID_LEN_BYTES
SFF ID requires 2 bytes (11bit)
TWAI_ERR_PASS_THRESH
Error counter threshold for error passive
Enumerations
enum twai_mode_t
TWAI Controller operating modes.
Values:
enumerator TWAI_MODE_NORMAL
Normal operating mode where TWAI controller can send/receive/acknowledge messages
enumerator TWAI_MODE_NO_ACK
Transmission does not require acknowledgment. Use this mode for self testing
enumerator TWAI_MODE_LISTEN_ONLY
The TWAI controller will not influence the bus (No transmissions or acknowledgments) but can receive
messages
Header File
• components/driver/include/driver/twai.h
Functions
esp_err_t twai_driver_install(const twai_general_config_t *g_config, const twai_timing_config_t
*t_config, const twai_filter_config_t *f_config)
Install TWAI driver.
This function installs the TWAI driver using three configuration structures. The required memory is allocated
and the TWAI driver is placed in the stopped state after running this function.
Note: Macro initializers are available for the configuration structures (see documentation)
Parameters
• g_config –[in] General configuration structure
• t_config –[in] Timing configuration structure
• f_config –[in] Filter configuration structure
Returns
• ESP_OK: Successfully installed TWAI driver
• ESP_ERR_INVALID_ARG: Arguments are invalid
• ESP_ERR_NO_MEM: Insufficient memory
• ESP_ERR_INVALID_STATE: Driver is already installed
esp_err_t twai_driver_uninstall(void)
Uninstall the TWAI driver.
This function uninstalls the TWAI driver, freeing the memory utilized by the driver. This function can only be
called when the driver is in the stopped state or the bus-off state.
Warning: The application must ensure that no tasks are blocked on TX/RX queues or alerts when this
function is called.
Returns
• ESP_OK: Successfully uninstalled TWAI driver
• ESP_ERR_INVALID_STATE: Driver is not in stopped/bus-off state, or is not installed
esp_err_t twai_start(void)
Start the TWAI driver.
This function starts the TWAI driver, putting the TWAI driver into the running state. This allows the TWAI
driver to participate in TWAI bus activities such as transmitting/receiving messages. The TX and RX queue
are reset in this function, clearing any messages that are unread or pending transmission. This function can
only be called when the TWAI driver is in the stopped state.
Returns
• ESP_OK: TWAI driver is now running
• ESP_ERR_INVALID_STATE: Driver is not in stopped state, or is not installed
esp_err_t twai_stop(void)
Stop the TWAI driver.
This function stops the TWAI driver, preventing any further message from being transmitted or received until
twai_start() is called. Any messages in the TX queue are cleared. Any messages in the RX queue should be
read by the application after this function is called. This function can only be called when the TWAI driver is
in the running state.
Warning: A message currently being transmitted/received on the TWAI bus will be ceased immediately.
This may lead to other TWAI nodes interpreting the unfinished message as an error.
Returns
• ESP_OK: TWAI driver is now Stopped
• ESP_ERR_INVALID_STATE: Driver is not in running state, or is not installed
Note: This function does not guarantee that the transmission is successful. The TX_SUCCESS/TX_FAILED
alert can be enabled to alert the application upon the success/failure of a transmission.
Note: The TX_IDLE alert can be used to alert the application when no other messages are awaiting trans-
mission.
Parameters
• message –[in] Message to transmit
• ticks_to_wait –[in] Number of FreeRTOS ticks to block on the TX queue
Returns
• ESP_OK: Transmission successfully queued/initiated
• ESP_ERR_INVALID_ARG: Arguments are invalid
• ESP_ERR_TIMEOUT: Timed out waiting for space on TX queue
• ESP_FAIL: TX queue is disabled and another message is currently transmitting
• ESP_ERR_INVALID_STATE: TWAI driver is not in running state, or is not installed
• ESP_ERR_NOT_SUPPORTED: Listen Only Mode does not support transmissions
Warning: The flags field of the received message should be checked to determine if the received message
contains any data bytes.
Parameters
• message –[out] Received message
• ticks_to_wait –[in] Number of FreeRTOS ticks to block on RX queue
Returns
• ESP_OK: Message successfully received from RX queue
• ESP_ERR_TIMEOUT: Timed out waiting for message
• ESP_ERR_INVALID_ARG: Arguments are invalid
• ESP_ERR_INVALID_STATE: TWAI driver is not installed
Note: Multiple alerts can be raised simultaneously. The application should check for all alerts that have been
enabled.
Parameters
• alerts –[out] Bit field of raised alerts (see documentation for alert flags)
• ticks_to_wait –[in] Number of FreeRTOS ticks to block for alert
Returns
• ESP_OK: Alerts read
• ESP_ERR_TIMEOUT: Timed out waiting for alerts
• ESP_ERR_INVALID_ARG: Arguments are invalid
• ESP_ERR_INVALID_STATE: TWAI driver is not installed
Returns
• ESP_OK: Alerts reconfigured
• ESP_ERR_INVALID_STATE: TWAI driver is not installed
esp_err_t twai_initiate_recovery(void)
Start the bus recovery process.
This function initiates the bus recovery process when the TWAI driver is in the bus-off state. Once initiated,
the TWAI driver will enter the recovering state and wait for 128 occurrences of the bus-free signal on the
TWAI bus before returning to the stopped state. This function will reset the TX queue, clearing any messages
pending transmission.
Note: The BUS_RECOVERED alert can be enabled to alert the application when the bus recovery process
completes.
Returns
• ESP_OK: Bus recovery started
• ESP_ERR_INVALID_STATE: TWAI driver is not in the bus-off state, or is not installed
Note: The transmit queue is automatically cleared when twai_stop() or twai_initiate_recovery() is called.
Returns
• ESP_OK: Transmit queue cleared
• ESP_ERR_INVALID_STATE: TWAI driver is not installed or TX queue is disabled
esp_err_t twai_clear_receive_queue(void)
Clear the receive queue.
This function will clear the receive queue of all messages.
Returns
• ESP_OK: Transmit queue cleared
• ESP_ERR_INVALID_STATE: TWAI driver is not installed
Structures
struct twai_general_config_t
Structure for general configuration of the TWAI driver.
Public Members
twai_mode_t mode
Mode of TWAI controller
gpio_num_t tx_io
Transmit GPIO number
gpio_num_t rx_io
Receive GPIO number
gpio_num_t clkout_io
CLKOUT GPIO number (optional, set to -1 if unused)
gpio_num_t bus_off_io
Bus off indicator GPIO number (optional, set to -1 if unused)
uint32_t tx_queue_len
Number of messages TX queue can hold (set to 0 to disable TX Queue)
uint32_t rx_queue_len
Number of messages RX queue can hold
uint32_t alerts_enabled
Bit field of alerts to enable (see documentation)
uint32_t clkout_divider
CLKOUT divider. Can be 1 or any even number from 2 to 14 (optional, set to 0 if unused)
int intr_flags
Interrupt flags to set the priority of the driver’s ISR. Note that to use the ESP_INTR_FLAG_IRAM,
the CONFIG_TWAI_ISR_IN_IRAM option should be enabled first.
struct twai_status_info_t
Structure to store status information of TWAI driver.
Public Members
twai_state_t state
Current state of TWAI controller (Stopped/Running/Bus-Off/Recovery)
uint32_t msgs_to_tx
Number of messages queued for transmission or awaiting transmission completion
uint32_t msgs_to_rx
Number of messages in RX queue waiting to be read
uint32_t tx_error_counter
Current value of Transmit Error Counter
uint32_t rx_error_counter
Current value of Receive Error Counter
uint32_t tx_failed_count
Number of messages that failed transmissions
uint32_t rx_missed_count
Number of messages that were lost due to a full RX queue (or errata workaround if enabled)
uint32_t rx_overrun_count
Number of messages that were lost due to a RX FIFO overrun
uint32_t arb_lost_count
Number of instances arbitration was lost
uint32_t bus_error_count
Number of instances a bus error has occurred
Macros
TWAI_IO_UNUSED
Marks GPIO as unused in TWAI configuration
Enumerations
enum twai_state_t
TWAI driver states.
Values:
enumerator TWAI_STATE_STOPPED
Stopped state. The TWAI controller will not participate in any TWAI bus activities
enumerator TWAI_STATE_RUNNING
Running state. The TWAI controller can transmit and receive messages
enumerator TWAI_STATE_BUS_OFF
Bus-off state. The TWAI controller cannot participate in bus activities until it has recovered
enumerator TWAI_STATE_RECOVERING
Recovering state. The TWAI controller is undergoing bus recovery
Overview
A Universal Asynchronous Receiver/Transmitter (UART) is a hardware feature that handles communication (i.e.,
timing requirements and data framing) using widely-adopted asynchronous serial communication interfaces, such as
RS232, RS422, RS485. A UART provides a widely adopted and cheap method to realize full-duplex or half-duplex
data exchange among different devices.
The ESP32 chip has three UART controllers (also referred to as port), each featuring an identical set of registers to
simplify programming and for more flexibility.
Each UART controller is independently configurable with parameters such as baud rate, data bit length, bit ordering,
number of stop bits, parity bit etc. All the controllers are compatible with UART-enabled devices from various
manufacturers and can also support Infrared Data Association protocols (IrDA).
Functional Overview
The following overview describes how to establish communication between an ESP32 and other UART devices using
the functions and data types of the UART driver. The overview reflects a typical programming workflow and is broken
down into the sections provided below:
1. Setting Communication Parameters - Setting baud rate, data bits, stop bits, etc.
2. Setting Communication Pins - Assigning pins for connection to a device.
3. Driver Installation - Allocating ESP32’s resources for the UART driver.
4. Running UART Communication - Sending / receiving data
5. Using Interrupts - Triggering interrupts on specific communication events
6. Deleting a Driver - Freeing allocated resources if a UART communication is no longer required
Steps 1 to 3 comprise the configuration stage. Step 4 is where the UART starts operating. Steps 5 and 6 are optional.
The UART driver’s functions identify each of the UART controllers using uart_port_t. This identification is
needed for all the following function calls.
Setting Communication Parameters UART communication parameters can be configured all in a single step or
individually in multiple steps.
Single Step Call the function uart_param_config() and pass to it a uart_config_t structure. The
uart_config_t structure should contain all the required parameters. See the example below.
For more information on how to configure the hardware flow control options, please refer to peripher-
als/uart/uart_echo.
Multiple Steps Configure specific parameters individually by calling a dedicated function from the table given
below. These functions are also useful if re-configuring a single parameter.
Each of the above functions has a _get_ counterpart to check the currently set value. For example, to check the
current baud rate value, call uart_get_baudrate().
Setting Communication Pins After setting communication parameters, configure the physical GPIO pins to which
the other UART device will be connected. For this, call the function uart_set_pin() and specify the GPIO pin
numbers to which the driver should route the Tx, Rx, RTS, and CTS signals. If you want to keep a currently allocated
pin number for a specific signal, pass the macro UART_PIN_NO_CHANGE.
The same macro should be specified for pins that will not be used.
// Set UART pins(TX: IO4, RX: IO5, RTS: IO18, CTS: IO19)
ESP_ERROR_CHECK(uart_set_pin(UART_NUM_2, 4, 5, 18, 19));
Driver Installation Once the communication pins are set, install the driver by calling
uart_driver_install() and specify the following parameters:
• Size of Tx ring buffer
• Size of Rx ring buffer
• Event queue handle and size
• Flags to allocate an interrupt
The function will allocate the required internal resources for the UART driver.
Once this step is complete, you can connect the external UART device and check the communication.
Running UART Communication Serial communication is controlled by each UART controller’s finite state
machine (FSM).
The process of sending data involves the following steps:
1. Write data into Tx FIFO buffer
2. FSM serializes the data
3. FSM sends the data out
The process of receiving data is similar, but the steps are reversed:
1. FSM processes an incoming serial stream and parallelizes it
2. FSM writes the data into Rx FIFO buffer
3. Read the data from Rx FIFO buffer
Therefore, an application will be limited to writing and reading data from a respective buffer using
uart_write_bytes() and uart_read_bytes() respectively, and the FSM will do the rest.
Transmitting After preparing the data for transmission, call the function uart_write_bytes() and pass the
data buffer’s address and data length to it. The function will copy the data to the Tx ring buffer (either immediately
or after enough space is available), and then exit. When there is free space in the Tx FIFO buffer, an interrupt service
routine (ISR) moves the data from the Tx ring buffer to the Tx FIFO buffer in the background. The code below
demonstrates the use of this function.
Another function for writing data to the Tx FIFO buffer is uart_tx_chars(). Unlike
uart_write_bytes(), this function will not block until space is available. Instead, it will write all data
which can immediately fit into the hardware Tx FIFO, and then return the number of bytes that were written.
There is a ‘companion’function uart_wait_tx_done() that monitors the status of the Tx FIFO buffer and
returns once it is empty.
Receiving Once the data is received by the UART and saved in the Rx FIFO buffer, it needs to be retrieved using
the function uart_read_bytes(). Before reading data, you can check the number of bytes available in the
Rx FIFO buffer by calling uart_get_buffered_data_len(). An example of using these functions is given
below.
If the data in the Rx FIFO buffer is no longer needed, you can clear the buffer by calling uart_flush().
Software Flow Control If the hardware flow control is disabled, you can manually set the RTS and DTR signal
levels by using the functions uart_set_rts() and uart_set_dtr() respectively.
Communication Mode Selection The UART controller supports a number of communication modes. A mode
can be selected using the function uart_set_mode(). Once a specific mode is selected, the UART driver will
handle the behavior of a connected UART device accordingly. As an example, it can control the RS485 driver chip
using the RTS line to allow half-duplex RS485 communication.
Using Interrupts There are many interrupts that can be generated following specific UART states or detected
errors. The full list of available interrupts is provided in ESP32 Technical Reference Manual > UART Controller
(UART) > UART Interrupts and UHCI Interrupts [PDF]. You can enable or disable specific interrupts by calling
uart_enable_intr_mask() or uart_disable_intr_mask() respectively.
The uart_driver_install() function installs the driver’s internal interrupt handler to manage the Tx and
Rx ring buffers and provides high-level API functions like events (see below).
The API provides a convenient way to handle specific interrupts discussed in this document by wrapping them into
dedicated functions:
• Event detection: There are several events defined in uart_event_type_t that may be reported to a
user application using the FreeRTOS queue functionality. You can enable this functionality when calling
uart_driver_install() described in Driver Installation. An example of using Event detection can be
found in peripherals/uart/uart_events.
• FIFO space threshold or transmission timeout reached: The Tx and Rx FIFO buffers can trigger an inter-
rupt when they are filled with a specific number of characters, or on a timeout of sending or receiving data. To
use these interrupts, do the following:
– Configure respective threshold values of the buffer length and timeout by entering them in the structure
uart_intr_config_t and calling uart_intr_config()
– Enable the interrupts using the functions uart_enable_tx_intr() and
uart_enable_rx_intr()
– Disable these interrupts using the corresponding functions uart_disable_tx_intr() or
uart_disable_rx_intr()
• Pattern detection: An interrupt triggered on detecting a ‘pattern’of the same character being re-
ceived/sent repeatedly for a number of times. This functionality is demonstrated in the example peripher-
als/uart/uart_events. It can be used, e.g., to detect a command string followed by a specific number of identical
characters (the ‘pattern’) added at the end of the command string. The following functions are available:
– Configure and enable this interrupt using uart_enable_pattern_det_intr()
– Disable the interrupt using uart_disable_pattern_det_intr()
Macros The API also defines several macros. For example, UART_FIFO_LEN defines the length of hardware
FIFO buffers; UART_BITRATE_MAX gives the maximum baud rate supported by the UART controllers, etc.
supported in the UART driver and can be used by selecting the UART_MODE_RS485_APP_CTRL mode (see the
function uart_set_mode()).
The collision detection feature can work with circuit A and circuit C (see Section Interface Connection Options). In
the case of using circuit A or B, the RTS pin connected to the DE pin of the bus driver should be controlled by the
user application. Use the function uart_get_collision_flag() to check if the collision detection flag has
been raised.
The ESP32 UART controllers themselves do not support half-duplex communication as they cannot provide automatic
control of the RTS pin connected to the ~RE/DE input of RS485 bus driver. However, half-duplex communication
can be achieved via software control of the RTS pin by the UART driver. This can be enabled by selecting the
UART_MODE_RS485_HALF_DUPLEX mode when calling uart_set_mode().
Once the host starts writing data to the Tx FIFO buffer, the UART driver automatically asserts the RTS pin (logic 1);
once the last bit of the data has been transmitted, the driver de-asserts the RTS pin (logic 0). To use this mode, the
software would have to disable the hardware flow control function. This mode works with all the used circuits shown
below.
Interface Connection Options This section provides example schematics to demonstrate the basic aspects of
ESP32’s RS485 interface connection.
Note:
• The schematics below do not necessarily contain all required elements.
• The analog devices ADM483 & ADM2483 are examples of common RS485 transceivers and can be replaced
with other similar transceivers.
This circuit is preferable because it allows for collision detection and is quite simple at the same time. The receiver
in the line driver is constantly enabled, which allows the UART to monitor the RS485 bus. Echo suppression is per-
formed by the UART peripheral when the bit UART_RS485_CONF_REG.UART_RS485TX_RX_EN is enabled.
This circuit does not allow for collision detection. It suppresses the null bytes that the hardware receives when
the bit UART_RS485_CONF_REG.UART_RS485TX_RX_EN is set. The bit UART_RS485_CONF_REG.
UART_RS485RXBY_TX_EN is not applicable in this case.
VCC1 <--+--|____|--+------->| DE | |
10K | | B|---+------------+--<> B (-)
---+ +-->| /RE | | ____
10K | | | | +---|____|---+
____ | /-C +---| TXD | 10K |
TX >---|____|--+_B_|/ NPN | | | |
|\ | +---x-----------x---+ |
| \-E | | | |
| | | | |
GND1 GND1 GND1 GND2 GND2
This galvanically isolated circuit does not require RTS pin control by a software application or driver because
it controls the transceiver direction automatically. However, it requires suppressing null bytes during transmis-
sion by setting UART_RS485_CONF_REG.UART_RS485RXBY_TX_EN to 1 and UART_RS485_CONF_REG.
UART_RS485TX_RX_EN to 0. This setup can work in any RS485 UART mode or even in UART_MODE_UART.
Application Examples
The table below describes the code examples available in the directory peripherals/uart/.
API Reference
Header File
• components/driver/include/driver/uart.h
Functions
esp_err_t uart_driver_install(uart_port_t uart_num, int rx_buffer_size, int tx_buffer_size, int
queue_size, QueueHandle_t *uart_queue, int intr_alloc_flags)
Install UART driver and set the UART to the default configuration.
UART ISR handler will be attached to the same CPU core that this function is running on.
Note: Rx_buffer_size should be greater than UART_FIFO_LEN. Tx_buffer_size should be either zero or
greater than UART_FIFO_LEN.
Parameters
• uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
• rx_buffer_size –UART RX ring buffer size.
• tx_buffer_size –UART TX ring buffer size. If set to zero, driver will not use TX
buffer, TX function will block task until all data have been sent out.
• queue_size –UART event queue size/depth.
• uart_queue –UART event queue handle (out param). On success, a new queue handle
is written here to provide access to UART events. If set to NULL, driver will not use an
event queue.
• intr_alloc_flags –Flags used to allocate the interrupt. One or multiple (ORred)
ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. Do not set
ESP_INTR_FLAG_IRAM here (the driver’s ISR handler is not located in IRAM)
Returns
• ESP_OK Success
• ESP_FAIL Parameter error
esp_err_t uart_driver_delete(uart_port_t uart_num)
Uninstall UART driver.
Parameters uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
Returns
• ESP_OK Success
• ESP_FAIL Parameter error
bool uart_is_driver_installed(uart_port_t uart_num)
Checks whether the driver is installed or not.
Parameters uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
Returns
• true driver is installed
• false driver is not installed
esp_err_t uart_set_word_length(uart_port_t uart_num, uart_word_length_t data_bit)
Set UART data bits.
Parameters
• uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
• data_bit –UART data bits
Returns
• ESP_OK Success
• ESP_FAIL Parameter error
esp_err_t uart_get_word_length(uart_port_t uart_num, uart_word_length_t *data_bit)
Get the UART data bit configuration.
Parameters
• uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
• uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
• enable_mask –Bit mask of the enable bits.
Returns
• ESP_OK Success
• ESP_FAIL Parameter error
esp_err_t uart_disable_intr_mask(uart_port_t uart_num, uint32_t disable_mask)
Clear UART interrupt enable bits.
Parameters
• uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
• disable_mask –Bit mask of the disable bits.
Returns
• ESP_OK Success
• ESP_FAIL Parameter error
esp_err_t uart_enable_rx_intr(uart_port_t uart_num)
Enable UART RX interrupt (RX_FULL & RX_TIMEOUT INTERRUPT)
Parameters uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
Returns
• ESP_OK Success
• ESP_FAIL Parameter error
esp_err_t uart_disable_rx_intr(uart_port_t uart_num)
Disable UART RX interrupt (RX_FULL & RX_TIMEOUT INTERRUPT)
Parameters uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
Returns
• ESP_OK Success
• ESP_FAIL Parameter error
esp_err_t uart_disable_tx_intr(uart_port_t uart_num)
Disable UART TX interrupt (TX_FULL & TX_TIMEOUT INTERRUPT)
Parameters uart_num –UART port number
Returns
• ESP_OK Success
• ESP_FAIL Parameter error
esp_err_t uart_enable_tx_intr(uart_port_t uart_num, int enable, int thresh)
Enable UART TX interrupt (TX_FULL & TX_TIMEOUT INTERRUPT)
Parameters
• uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
• enable –1: enable; 0: disable
• thresh –Threshold of TX interrupt, 0 ~ UART_FIFO_LEN
Returns
• ESP_OK Success
• ESP_FAIL Parameter error
esp_err_t uart_set_pin(uart_port_t uart_num, int tx_io_num, int rx_io_num, int rts_io_num, int
cts_io_num)
Assign signals of a UART peripheral to GPIO pins.
Note: If the GPIO number configured for a UART signal matches one of the IOMUX signals for that GPIO,
the signal will be connected directly via the IOMUX. Otherwise the GPIO and signal will be connected via the
GPIO Matrix. For example, if on an ESP32 the call uart_set_pin(0, 1, 3, -1, -1) is performed,
as GPIO1 is UART0’s default TX pin and GPIO3 is UART0’s default RX pin, both will be connected
to respectively U0TXD and U0RXD through the IOMUX, totally bypassing the GPIO matrix. The check is
performed on a per-pin basis. Thus, it is possible to have RX pin binded to a GPIO through the GPIO matrix,
whereas TX is binded to its GPIO through the IOMUX.
Note: Internal signal can be output to multiple GPIO pads. Only one GPIO pad can connect with input signal.
Parameters
• uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
• tx_io_num –UART TX pin GPIO number.
• rx_io_num –UART RX pin GPIO number.
• rts_io_num –UART RTS pin GPIO number.
• cts_io_num –UART CTS pin GPIO number.
Returns
• ESP_OK Success
• ESP_FAIL Parameter error
Parameters
• uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
• level –1: RTS output low (active); 0: RTS output high (block)
Returns
• ESP_OK Success
• ESP_FAIL Parameter error
Note: This function should only be used when UART TX buffer is not enabled.
Parameters
• uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
• buffer –data buffer address
• len –data length to send
Returns
• (-1) Parameter error
• OTHERS (>=0) The number of bytes pushed to the TX FIFO
Otherwise, if the ‘tx_buffer_size’> 0, this function will return after copying all the data to tx ring buffer,
UART ISR will then move data from the ring buffer to TX FIFO gradually. After all data sent out, send a
break signal.
Parameters
• uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
• src –data buffer address
• size –data length to send
• brk_len –break signal duration(unit: the time it takes to send one bit at current baudrate)
Returns
• (-1) Parameter error
• OTHERS (>=0) The number of bytes pushed to the TX FIFO
int uart_read_bytes(uart_port_t uart_num, void *buf, uint32_t length, TickType_t ticks_to_wait)
UART read bytes from UART buffer.
Parameters
• uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
• buf –pointer to the buffer.
• length –data length
• ticks_to_wait –sTimeout, count in RTOS ticks
Returns
• (-1) Error
• OTHERS (>=0) The number of bytes read from UART FIFO
esp_err_t uart_flush(uart_port_t uart_num)
Alias of uart_flush_input. UART ring buffer flush. This will discard all data in the UART RX buffer.
Note: Instead of waiting the data sent out, this function will clear UART rx buffer. In order to send all the
data in tx FIFO, we can use uart_wait_tx_done function.
Parameters uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
Returns
• ESP_OK Success
• ESP_FAIL Parameter error
Note: In order to send all the data in tx FIFO, we can use uart_wait_tx_done function.
Parameters uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
Returns
• ESP_OK Success
• ESP_FAIL Parameter error
The following APIs will modify the pattern position info: uart_flush_input, uart_read_bytes,
uart_driver_delete, uart_pop_pattern_pos It is the application’s responsibility to ensure atomic access
to the pattern queue and the rx data buffer when using pattern detect feature.
Note: If the RX buffer is full and flow control is not enabled, the detected pattern may not be found in the rx
buffer due to overflow.
Parameters uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
Returns
• (-1) No pattern found for current index or parameter error
• others the pattern position in rx buffer.
The following APIs will modify the pattern position info: uart_flush_input, uart_read_bytes,
uart_driver_delete, uart_pop_pattern_pos It is the application’s responsibility to ensure atomic access
to the pattern queue and the rx data buffer when using pattern detect feature.
Note: If the RX buffer is full and flow control is not enabled, the detected pattern may not be found in the rx
buffer due to overflow.
Parameters uart_num –UART port number, the max port number is (UART_NUM_MAX -1).
Returns
• (-1) No pattern found for current index or parameter error
• others the pattern position in rx buffer.
Note: This function must be executed after uart_driver_install(), when the driver object is initialized.
Parameters
• uart_num –Uart number to configure, the max port number is (UART_NUM_MAX
-1).
• mode –UART UART mode to set
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
Note: If application is using higher baudrate and it is observed that bytes in hardware RX fifo are overwritten
then this threshold can be reduced
Parameters
• uart_num –UART_NUM_0, UART_NUM_1 or UART_NUM_2
• threshold –Threshold value above which RX fifo full interrupt is generated
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG Parameter error
• ESP_ERR_INVALID_STATE Driver is not installed
Note: in ESP32, the wakeup signal can only be input via IO_MUX (i.e. GPIO3 should be configured as
function_1 to wake up UART0, GPIO9 should be configured as function_5 to wake up UART1), UART2 does
not support light sleep wakeup feature.
Parameters
• uart_num –UART number, the max port number is (UART_NUM_MAX -1).
• wakeup_threshold –number of RX edges for light sleep wakeup, value is 3 .. 0x3ff.
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if uart_num is incorrect or wakeup_threshold is outside of
[3, 0x3ff] range.
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG Parameter error
• ESP_FAIL Driver not installed
Parameters uart_num –UART number
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG Parameter error
• ESP_FAIL Driver not installed
Parameters
• uart_num –UART number
• loop_back_en –Set ture to enable the loop back function, else set it false.
Parameters
• uart_num –UART number
• always_rx_timeout_en –Set to false enable the default behavior of timeout inter-
rupt, set it to true to always trigger timeout interrupt.
Structures
struct uart_intr_config_t
UART interrupt configuration parameters for uart_intr_config function.
Public Members
uint32_t intr_enable_mask
UART interrupt enable mask, choose from UART_XXXX_INT_ENA_M under
UART_INT_ENA_REG(i), connect with bit-or operator
uint8_t rx_timeout_thresh
UART timeout interrupt threshold (unit: time of sending one byte)
uint8_t txfifo_empty_intr_thresh
UART TX empty interrupt threshold.
uint8_t rxfifo_full_thresh
UART RX full interrupt threshold.
struct uart_event_t
Event structure used in UART event queue.
Public Members
uart_event_type_t type
UART event type
size_t size
UART data size for UART_DATA event
bool timeout_flag
UART data read timeout flag for UART_DATA event (no new data received during configured RX
TOUT) If the event is caused by FIFO-full interrupt, then there will be no event with the timeout flag
before the next byte coming.
Macros
UART_NUM_0
UART port 0
UART_NUM_1
UART port 1
UART_NUM_2
UART port 2
UART_NUM_MAX
UART port max
UART_PIN_NO_CHANGE
UART_FIFO_LEN
Length of the UART HW FIFO.
UART_BITRATE_MAX
Maximum configurable bitrate.
Type Definitions
Enumerations
enum uart_event_type_t
UART event types used in the ring buffer.
Values:
enumerator UART_DATA
UART data event
enumerator UART_BREAK
UART break event
enumerator UART_BUFFER_FULL
UART RX buffer full event
enumerator UART_FIFO_OVF
UART FIFO overflow event
enumerator UART_FRAME_ERR
UART RX frame error event
enumerator UART_PARITY_ERR
UART RX parity event
enumerator UART_DATA_BREAK
UART TX data and break event
enumerator UART_PATTERN_DET
UART pattern detected
enumerator UART_EVENT_MAX
UART event max index
Header File
• components/hal/include/hal/uart_types.h
Structures
struct uart_at_cmd_t
UART AT cmd char configuration parameters Note that this function may different on different chip. Please
refer to the TRM at confirguration.
Public Members
uint8_t cmd_char
UART AT cmd char
uint8_t char_num
AT cmd char repeat number
uint32_t gap_tout
gap time(in baud-rate) between AT cmd char
uint32_t pre_idle
the idle time(in baud-rate) between the non AT char and first AT char
uint32_t post_idle
the idle time(in baud-rate) between the last AT char and the none AT char
struct uart_sw_flowctrl_t
UART software flow control configuration parameters.
Public Members
uint8_t xon_char
Xon flow control char
uint8_t xoff_char
Xoff flow control char
uint8_t xon_thrd
If the software flow control is enabled and the data amount in rxfifo is less than xon_thrd, an xon_char
will be sent
uint8_t xoff_thrd
If the software flow control is enabled and the data amount in rxfifo is more than xoff_thrd, an xoff_char
will be sent
struct uart_config_t
UART configuration parameters for uart_param_config function.
Public Members
int baud_rate
UART baud rate
uart_word_length_t data_bits
UART byte size
uart_parity_t parity
UART parity mode
uart_stop_bits_t stop_bits
UART stop bits
uart_hw_flowcontrol_t flow_ctrl
UART HW flow control mode (cts/rts)
uint8_t rx_flow_ctrl_thresh
UART HW RTS threshold
uart_sclk_t source_clk
UART source clock selection
Type Definitions
Enumerations
enum uart_mode_t
UART mode selection.
Values:
enumerator UART_MODE_UART
mode: regular UART mode
enumerator UART_MODE_RS485_HALF_DUPLEX
mode: half duplex RS485 UART mode control by RTS pin
enumerator UART_MODE_IRDA
mode: IRDA UART mode
enumerator UART_MODE_RS485_COLLISION_DETECT
mode: RS485 collision detection UART mode (used for test purposes)
enumerator UART_MODE_RS485_APP_CTRL
mode: application control RS485 UART mode (used for test purposes)
enum uart_word_length_t
UART word length constants.
Values:
enumerator UART_DATA_5_BITS
word length: 5bits
enumerator UART_DATA_6_BITS
word length: 6bits
enumerator UART_DATA_7_BITS
word length: 7bits
enumerator UART_DATA_8_BITS
word length: 8bits
enumerator UART_DATA_BITS_MAX
enum uart_stop_bits_t
UART stop bits number.
Values:
enumerator UART_STOP_BITS_1
stop bit: 1bit
enumerator UART_STOP_BITS_1_5
stop bit: 1.5bits
enumerator UART_STOP_BITS_2
stop bit: 2bits
enumerator UART_STOP_BITS_MAX
enum uart_parity_t
UART parity constants.
Values:
enumerator UART_PARITY_DISABLE
Disable UART parity
enumerator UART_PARITY_EVEN
Enable UART even parity
enumerator UART_PARITY_ODD
Enable UART odd parity
enum uart_hw_flowcontrol_t
UART hardware flow control modes.
Values:
enumerator UART_HW_FLOWCTRL_DISABLE
disable hardware flow control
enumerator UART_HW_FLOWCTRL_RTS
enable RX hardware flow control (rts)
enumerator UART_HW_FLOWCTRL_CTS
enable TX hardware flow control (cts)
enumerator UART_HW_FLOWCTRL_CTS_RTS
enable hardware flow control
enumerator UART_HW_FLOWCTRL_MAX
enum uart_signal_inv_t
UART signal bit map.
Values:
enumerator UART_SIGNAL_INV_DISABLE
Disable UART signal inverse
enumerator UART_SIGNAL_IRDA_TX_INV
inverse the UART irda_tx signal
enumerator UART_SIGNAL_IRDA_RX_INV
inverse the UART irda_rx signal
enumerator UART_SIGNAL_RXD_INV
inverse the UART rxd signal
enumerator UART_SIGNAL_CTS_INV
inverse the UART cts signal
enumerator UART_SIGNAL_DSR_INV
inverse the UART dsr signal
enumerator UART_SIGNAL_TXD_INV
inverse the UART txd signal
enumerator UART_SIGNAL_RTS_INV
inverse the UART rts signal
enumerator UART_SIGNAL_DTR_INV
inverse the UART dtr signal
GPIO Lookup Macros The UART peripherals have dedicated IO_MUX pins to which they are connected directly.
However, signals can also be routed to other pins using the less direct GPIO matrix. To use direct routes, you need
to know which pin is a dedicated IO_MUX pin for a UART channel. GPIO Lookup Macros simplify the process of
finding and assigning IO_MUX pins. You choose a macro based on either the IO_MUX pin number, or a required
UART channel name, and the macro will return the matching counterpart for you. See some examples below.
Note: These macros are useful if you need very high UART baud rates (over 40 MHz), which means you will have
to use IO_MUX pins only. In other cases, these macros can be ignored, and you can use the GPIO Matrix as it allows
you to configure any GPIO pin for any UART function.
1. UART_NUM_2_TXD_DIRECT_GPIO_NUM returns the IO_MUX pin number of UART channel 2 TXD pin
(pin 17)
2. UART_GPIO19_DIRECT_CHANNEL returns the UART number of GPIO 19 when connected to the UART
peripheral via IO_MUX (this is UART_NUM_0)
3. UART_CTS_GPIO19_DIRECT_CHANNEL returns the UART number of GPIO 19 when used as the UART
CTS pin via IO_MUX (this is UART_NUM_0). Similar to the above macro but specifies the pin function which
is also part of the IO_MUX assignment.
Header File
• components/soc/esp32/include/soc/uart_channel.h
Macros
UART_GPIO1_DIRECT_CHANNEL
UART_NUM_0_TXD_DIRECT_GPIO_NUM
UART_GPIO3_DIRECT_CHANNEL
UART_NUM_0_RXD_DIRECT_GPIO_NUM
UART_GPIO19_DIRECT_CHANNEL
UART_NUM_0_CTS_DIRECT_GPIO_NUM
UART_GPIO22_DIRECT_CHANNEL
UART_NUM_0_RTS_DIRECT_GPIO_NUM
UART_TXD_GPIO1_DIRECT_CHANNEL
UART_RXD_GPIO3_DIRECT_CHANNEL
UART_CTS_GPIO19_DIRECT_CHANNEL
UART_RTS_GPIO22_DIRECT_CHANNEL
UART_GPIO10_DIRECT_CHANNEL
UART_NUM_1_TXD_DIRECT_GPIO_NUM
UART_GPIO9_DIRECT_CHANNEL
UART_NUM_1_RXD_DIRECT_GPIO_NUM
UART_GPIO6_DIRECT_CHANNEL
UART_NUM_1_CTS_DIRECT_GPIO_NUM
UART_GPIO11_DIRECT_CHANNEL
UART_NUM_1_RTS_DIRECT_GPIO_NUM
UART_TXD_GPIO10_DIRECT_CHANNEL
UART_RXD_GPIO9_DIRECT_CHANNEL
UART_CTS_GPIO6_DIRECT_CHANNEL
UART_RTS_GPIO11_DIRECT_CHANNEL
UART_GPIO17_DIRECT_CHANNEL
UART_NUM_2_TXD_DIRECT_GPIO_NUM
UART_GPIO16_DIRECT_CHANNEL
UART_NUM_2_RXD_DIRECT_GPIO_NUM
UART_GPIO8_DIRECT_CHANNEL
UART_NUM_2_CTS_DIRECT_GPIO_NUM
UART_GPIO7_DIRECT_CHANNEL
UART_NUM_2_RTS_DIRECT_GPIO_NUM
UART_TXD_GPIO17_DIRECT_CHANNEL
UART_RXD_GPIO16_DIRECT_CHANNEL
UART_CTS_GPIO8_DIRECT_CHANNEL
UART_RTS_GPIO7_DIRECT_CHANNEL
Code examples for this API section are provided in the peripherals directory of ESP-IDF examples.
2.7.1 Introduction
ESP-IDF uses kconfiglib which is a Python-based extension to the Kconfig system which provides a compile-time
project configuration mechanism. Kconfig is based around options of several types: integer, string, boolean. Kconfig
files specify dependencies between options, default values of the options, the way the options are grouped together,
etc.
For the complete list of available features please see Kconfig and kconfiglib extentions.
Application developers can open a terminal-based project configuration menu with the idf.py menuconfig
build target.
After being updated, this configuration is saved inside sdkconfig file in the project root directory. Based on sd-
kconfig, application build targets will generate sdkconfig.h file in the build directory, and will make sdkconfig
options available to the project build system and source files.
In some cases, such as when sdkconfig file is under revision control, the fact that sdkconfig file gets changed
by the build system may be inconvenient. The build system offers a way to avoid this, in the form of sdkconfig.
defaults file. This file is never touched by the build system, and can be created manually or automatically.
It can contain all the options which matter for the given application and are different from the default ones. The
format is the same as that of the sdkconfig file. sdkconfig.defaults can be created manually when one
remembers all the changed configurations. Otherwise, the file can be generated automatically by running the idf.py
save-defconfig command.
Once sdkconfig.defaults is created, sdkconfig can be deleted and added to the ignore list of the revision
control system (e.g. .gitignore file for git). Project build targets will automatically create sdkconfig file,
populated with the settings from sdkconfig.defaults file, and the rest of the settings will be set to their
default values. Note that the build process will not override settings that are already in sdkconfig by ones from
sdkconfig.defaults. For more information, see Custom sdkconfig defaults.
Format checker
tools/check_kconfigs.py is provided for checking the Kconfig formatting rules. The checker checks all
Kconfig and Kconfig.projbuild files in the ESP-IDF directory and generates a new file with suffix .new
with some recommendations how to fix issues (if there are any). Please note that the checker cannot correct all
rules and the responsibility of the developer is to check and make final corrections in order to pass the tests. For
example, indentations will be corrected if there isn’t some misleading previous formatting but it cannot come up
with a common prefix for options inside a menu.
The standard Kconfig tools ignore unknown options in sdkconfig. So if a developer has custom settings for
options which are renamed in newer ESP-IDF releases then the given setting for the option would be silently ignored.
Therefore, several features have been adopted to avoid this:
1. confgen.py is used by the tool chain to pre-process sdkconfig files before anything else, for example
menuconfig, would read them. As the consequence, the settings for old options will be kept and not ignored.
2. confgen.py recursively finds all sdkconfig.rename files in ESP-IDF directory which contain old and
new Kconfig option names. Old options are replaced by new ones in the sdkconfig file. Renames that
should only appear for a single target can be placed in a target specific rename file: sdkconfig.rename.TARGET,
where TARGET is the target name, e.g. sdkconfig.rename.esp32s2.
3. confgen.py post-processes sdkconfig files and generates all build outputs (sdkconfig.h, sdkcon-
fig.cmake, auto.conf) by adding a list of compatibility statements, i.e. value of the old option is set
the value of the new option (after modification). This is done in order to not break customer codes where old
option might still be used.
4. Deprecated options and their replacements are automatically generated by confgen.py.
Subsequent sections contain the list of available ESP-IDF options, automatically generated from Kconfig files. Note
that depending on the options selected, some options listed here may not be visible by default in the interface of
menuconfig.
By convention, all option names are upper case with underscores. When Kconfig generates sdkconfig and sdkconfig.h
files, option names are prefixed with CONFIG_. So if an option ENABLE_FOO is defined in a Kconfig file and
selected in menuconfig, then sdkconfig and sdkconfig.h files will have CONFIG_ENABLE_FOO defined. In this
reference, option names are also prefixed with CONFIG_, same as in the source code.
Build type
Contains:
• CONFIG_APP_COMPATIBLE_PRE_V3_1_BOOTLOADERS
• CONFIG_APP_COMPATIBLE_PRE_V2_1_BOOTLOADERS
• CONFIG_APP_BUILD_TYPE
• CONFIG_APP_REPRODUCIBLE_BUILD
• CONFIG_APP_NO_BLOBS
CONFIG_APP_BUILD_TYPE
Application build type
Found in: Build type
Select the way the application is built.
By default, the application is built as a binary file in a format compatible with the ESP-IDF bootloader.
In addition to this application, 2nd stage bootloader is also built. Application and bootloader binaries
can be written into flash and loaded/executed from there.
Another option, useful for only very small and limited applications, is to only link the .elf file of the
application, such that it can be loaded directly into RAM over JTAG. Note that since IRAM and DRAM
sizes are very limited, it is not possible to build any complex application this way. However for kinds of
testing and debugging, this option may provide faster iterations, since the application does not need to
be written into flash. Note that at the moment, ESP-IDF does not contain all the startup code required
to initialize the CPUs and ROM memory (data/bss). Therefore it is necessary to execute a bit of ROM
code prior to executing the application. A gdbinit file may look as follows (for ESP32):
# Connect to a running instance of OpenOCD target remote :3333 # Reset and halt the target
mon reset halt # Run to a specific point in ROM code, # where most of initialization is
complete. thb *0x40007d54 c # Load the application into RAM load # Run till app_main tb
app_main c
Execute this gdbinit file as follows:
xtensa-esp32-elf-gdb build/app-name.elf -x gdbinit
Example gdbinit files for other targets can be found in tools/test_apps/system/gdb_loadable_elf/
Recommended sdkconfig.defaults for building loadable ELF files is as follows. CON-
FIG_APP_BUILD_TYPE_ELF_RAM is required, other options help reduce application memory
footprint.
CONFIG_APP_BUILD_TYPE_ELF_RAM=y CONFIG_VFS_SUPPORT_TERMIOS=
CONFIG_NEWLIB_NANO_FORMAT=y CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT=y
CONFIG_ESP_DEBUG_STUBS_ENABLE= CONFIG_ESP_ERR_TO_NAME_LOOKUP=
Available options:
• Default (binary application + 2nd stage bootloader)
(APP_BUILD_TYPE_APP_2NDBOOT)
• ELF file, loadable into RAM (EXPERIMENTAL)) (APP_BUILD_TYPE_ELF_RAM)
CONFIG_APP_REPRODUCIBLE_BUILD
Enable reproducible build
Found in: Build type
If enabled, all date, time, and path information would be eliminated. A .gdbinit file would be create
automatically. (or will be append if you have one already)
Default value:
• No (disabled)
CONFIG_APP_NO_BLOBS
No Binary Blobs
Found in: Build type
If enabled, this disables the linking of binary libraries in the application build. Note that after enabling
this Wi-Fi/Bluetooth will not work.
Default value:
• No (disabled)
CONFIG_APP_COMPATIBLE_PRE_V2_1_BOOTLOADERS
App compatible with bootloaders before ESP-IDF v2.1
Found in: Build type
Bootloaders before ESP-IDF v2.1 did less initialisation of the system clock. This setting needs to be
enabled to build an app which can be booted by these older bootloaders.
If this setting is enabled, the app can be booted by any bootloader from IDF v1.0 up to the current
version.
If this setting is disabled, the app can only be booted by bootloaders from IDF v2.1 or newer.
Enabling this setting adds approximately 1KB to the app’s IRAM usage.
Default value:
• No (disabled)
CONFIG_APP_COMPATIBLE_PRE_V3_1_BOOTLOADERS
App compatible with bootloader and partition table before ESP-IDF v3.1
Found in: Build type
Partition tables before ESP-IDF V3.1 do not contain an MD5 checksum field, and the bootloader before
ESP-IDF v3.1 cannot read a partition table that contains an MD5 checksum field.
Enable this option only if your app needs to boot on a bootloader and/or partition table that was generated
from a version *before* ESP-IDF v3.1.
If this option and Flash Encryption are enabled at the same time, and any data partitions in the partition
table are marked Encrypted, then the partition encrypted flag should be manually verified in the app
before accessing the partition (see CVE-2021-27926).
Default value:
• No (disabled)
Application manager
Contains:
• CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR
• CONFIG_APP_EXCLUDE_PROJECT_VER_VAR
• CONFIG_APP_PROJECT_VER_FROM_CONFIG
• CONFIG_APP_RETRIEVE_LEN_ELF_SHA
• CONFIG_APP_COMPILE_TIME_DATE
CONFIG_APP_COMPILE_TIME_DATE
Use time/date stamp for app
Found in: Application manager
If set, then the app will be built with the current time/date stamp. It is stored in the app description
structure. If not set, time/date stamp will be excluded from app image. This can be useful for getting
the same binary image files made from the same source, but at different times.
Default value:
• Yes (enabled)
CONFIG_APP_EXCLUDE_PROJECT_VER_VAR
Exclude PROJECT_VER from firmware image
Found in: Application manager
The PROJECT_VER variable from the build system will not affect the firmware image. This value will
not be contained in the esp_app_desc structure.
Default value:
• No (disabled)
CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR
Exclude PROJECT_NAME from firmware image
Found in: Application manager
The PROJECT_NAME variable from the build system will not affect the firmware image. This value
will not be contained in the esp_app_desc structure.
Default value:
• No (disabled)
CONFIG_APP_PROJECT_VER_FROM_CONFIG
Get the project version from Kconfig
Found in: Application manager
If this is enabled, then config item APP_PROJECT_VER will be used for the variable PROJECT_VER.
Other ways to set PROJECT_VER will be ignored.
Default value:
• No (disabled)
CONFIG_APP_PROJECT_VER
Project version
Found in: Application manager > CONFIG_APP_PROJECT_VER_FROM_CONFIG
Project version
Default value:
• 1 if CONFIG_APP_PROJECT_VER_FROM_CONFIG
CONFIG_APP_RETRIEVE_LEN_ELF_SHA
The length of APP ELF SHA is stored in RAM(chars)
Found in: Application manager
At startup, the app will read this many hex characters from the embedded APP ELF SHA-256 hash
value and store it in static RAM. This ensures the app ELF SHA-256 value is always available if it needs
to be printed by the panic handler code. Changing this value will change the size of a static buffer, in
bytes.
Range:
• from 8 to 64
Default value:
• 16
Bootloader config
Contains:
• CONFIG_BOOTLOADER_LOG_LEVEL
• CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION
• CONFIG_BOOTLOADER_SPI_WP_PIN
• CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE
• CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE
• CONFIG_BOOTLOADER_FLASH_XMC_SUPPORT
• CONFIG_BOOTLOADER_APP_TEST
• CONFIG_BOOTLOADER_FACTORY_RESET
• CONFIG_BOOTLOADER_HOLD_TIME_GPIO
• CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC
• CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS
• CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON
• CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP
• CONFIG_BOOTLOADER_SPI_CUSTOM_WP_PIN
• CONFIG_BOOTLOADER_WDT_ENABLE
• CONFIG_BOOTLOADER_VDDSDIO_BOOST
CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION
Bootloader optimization Level
Found in: Bootloader config
This option sets compiler optimization level (gcc -O argument) for the bootloader.
• The default “Size”setting will add the -0s flag to CFLAGS.
• The “Debug”setting will add the -Og flag to CFLAGS.
• The “Performance”setting will add the -O2 flag to CFLAGS.
• The “None”setting will add the -O0 flag to CFLAGS.
Note that custom optimization levels may be unsupported.
Available options:
• Size (-Os) (BOOTLOADER_COMPILER_OPTIMIZATION_SIZE)
• Debug (-Og) (BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG)
• Optimize for performance (-O2) (BOOTLOADER_COMPILER_OPTIMIZATION_PERF)
• Debug without optimization (-O0) (BOOTLOADER_COMPILER_OPTIMIZATION_NONE)
CONFIG_BOOTLOADER_LOG_LEVEL
Bootloader log verbosity
Found in: Bootloader config
Specify how much output to see in bootloader logs.
Available options:
• No output (BOOTLOADER_LOG_LEVEL_NONE)
• Error (BOOTLOADER_LOG_LEVEL_ERROR)
• Warning (BOOTLOADER_LOG_LEVEL_WARN)
• Info (BOOTLOADER_LOG_LEVEL_INFO)
• Debug (BOOTLOADER_LOG_LEVEL_DEBUG)
• Verbose (BOOTLOADER_LOG_LEVEL_VERBOSE)
CONFIG_BOOTLOADER_SPI_CUSTOM_WP_PIN
Use custom SPI Flash WP Pin when flash pins set in eFuse (read help)
Found in: Bootloader config
This setting is only used if the SPI flash pins have been overridden by setting the eFuses
SPI_PAD_CONFIG_xxx, and the SPI flash mode is QIO or QOUT.
When this is the case, the eFuse config only defines 3 of the 4 Quad I/O data pins. The WP pin (aka
ESP32 pin “SD_DATA_3”or SPI flash pin “IO2”) is not specified in eFuse. The same pin is also
used for external SPIRAM if it is enabled.
If this config item is set to N (default), the correct WP pin will be automatically used for any Espressif
chip or module with integrated flash. If a custom setting is needed, set this config item to Y and specify
the GPIO number connected to the WP.
Default value:
CONFIG_BOOTLOADER_SPI_WP_PIN
Custom SPI Flash WP Pin
Found in: Bootloader config
The option “Use custom SPI Flash WP Pin”must be set or this value is ignored
If burning a customized set of SPI flash pins in eFuse and using QIO or QOUT mode for flash, set this
value to the GPIO number of the SPI flash WP pin.
Range:
• from 0 to 33 if ESPTOOLPY_FLASHMODE_QIO || ESP-
TOOLPY_FLASHMODE_QOUT
Default value:
• 7 if ESPTOOLPY_FLASHMODE_QIO || ESPTOOLPY_FLASHMODE_QOUT
CONFIG_BOOTLOADER_VDDSDIO_BOOST
VDDSDIO LDO voltage
Found in: Bootloader config
If this option is enabled, and VDDSDIO LDO is set to 1.8V (using eFuse or MTDI bootstrapping pin),
bootloader will change LDO settings to output 1.9V instead. This helps prevent flash chip from browning
out during flash programming operations.
This option has no effect if VDDSDIO is set to 3.3V, or if the internal VDDSDIO regulator is disabled
via eFuse.
Available options:
• 1.8V (BOOTLOADER_VDDSDIO_BOOST_1_8V)
• 1.9V (BOOTLOADER_VDDSDIO_BOOST_1_9V)
CONFIG_BOOTLOADER_FACTORY_RESET
GPIO triggers factory reset
Found in: Bootloader config
Allows to reset the device to factory settings: - clear one or more data partitions; - boot from “factory”
partition. The factory reset will occur if there is a GPIO input held at the configured level while device
starts up. See settings below.
Default value:
• No (disabled)
CONFIG_BOOTLOADER_NUM_PIN_FACTORY_RESET
Number of the GPIO input for factory reset
Found in: Bootloader config > CONFIG_BOOTLOADER_FACTORY_RESET
The selected GPIO will be configured as an input with internal pull-up enabled (note that on some SoCs.
not all pins have an internal pull-up, consult the hardware datasheet for details.) To trigger a factory
reset, this GPIO must be held high or low (as configured) on startup.
Range:
• from 0 to 39 if CONFIG_BOOTLOADER_FACTORY_RESET
Default value:
• 4 if CONFIG_BOOTLOADER_FACTORY_RESET
CONFIG_BOOTLOADER_FACTORY_RESET_PIN_LEVEL
Factory reset GPIO level
Found in: Bootloader config > CONFIG_BOOTLOADER_FACTORY_RESET
Pin level for factory reset, can be triggered on low or high.
Available options:
• Reset on GPIO low (BOOTLOADER_FACTORY_RESET_PIN_LOW)
• Reset on GPIO high (BOOTLOADER_FACTORY_RESET_PIN_HIGH)
CONFIG_BOOTLOADER_OTA_DATA_ERASE
Clear OTA data on factory reset (select factory partition)
Found in: Bootloader config > CONFIG_BOOTLOADER_FACTORY_RESET
The device will boot from “factory”partition (or OTA slot 0 if no factory partition is present) after a
factory reset.
CONFIG_BOOTLOADER_DATA_FACTORY_RESET
Comma-separated names of partitions to clear on factory reset
Found in: Bootloader config > CONFIG_BOOTLOADER_FACTORY_RESET
Allows customers to select which data partitions will be erased while factory reset.
Specify the names of partitions as a comma-delimited with optional spaces for readability. (Like this:
“nvs, phy_init, …”) Make sure that the name specified in the partition table and here are the same.
Partitions of type “app”cannot be specified here.
Default value:
• “nvs”if CONFIG_BOOTLOADER_FACTORY_RESET
CONFIG_BOOTLOADER_APP_TEST
GPIO triggers boot from test app partition
Found in: Bootloader config
Allows to run the test app from “TEST”partition. A boot from “test”partition will occur if there is
a GPIO input pulled low while device starts up. See settings below.
Default value:
• No (disabled) if CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
CONFIG_BOOTLOADER_NUM_PIN_APP_TEST
Number of the GPIO input to boot TEST partition
Found in: Bootloader config > CONFIG_BOOTLOADER_APP_TEST
The selected GPIO will be configured as an input with internal pull-up enabled. To trigger a test app,
this GPIO must be pulled low on reset. After the GPIO input is deactivated and the device reboots, the
old application will boot. (factory or OTA[x]). Note that GPIO34-39 do not have an internal pullup and
an external one must be provided.
Range:
• from 0 to 39 if CONFIG_BOOTLOADER_APP_TEST
Default value:
• 18 if CONFIG_BOOTLOADER_APP_TEST
CONFIG_BOOTLOADER_APP_TEST_PIN_LEVEL
App test GPIO level
Found in: Bootloader config > CONFIG_BOOTLOADER_APP_TEST
Pin level for app test, can be triggered on low or high.
Available options:
• Enter test app on GPIO low (BOOTLOADER_APP_TEST_PIN_LOW)
• Enter test app on GPIO high (BOOTLOADER_APP_TEST_PIN_HIGH)
CONFIG_BOOTLOADER_HOLD_TIME_GPIO
Hold time of GPIO for reset/test mode (seconds)
Found in: Bootloader config
The GPIO must be held low continuously for this period of time after reset before a factory reset or test
partition boot (as applicable) is performed.
Default value:
• 5 if CONFIG_BOOTLOADER_FACTORY_RESET || CONFIG_BOOTLOADER_APP_TEST
CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE
Enable protection for unmapped memory regions
Found in: Bootloader config
Protects the unmapped memory regions of the entire address space from unintended accesses. This will
ensure that an exception will be triggered whenever the CPU performs a memory operation on unmapped
regions of the address space.
Default value:
• Yes (enabled)
CONFIG_BOOTLOADER_WDT_ENABLE
Use RTC watchdog in start code
Found in: Bootloader config
Tracks the execution time of startup code. If the execution time is exceeded, the RTC_WDT will restart
system. It is also useful to prevent a lock up in start code caused by an unstable power source. NOTE:
Tracks the execution time starts from the bootloader code - re-set timeout, while selecting the source
for slow_clk - and ends calling app_main. Re-set timeout is needed due to WDT uses a SLOW_CLK
clock source. After changing a frequency slow_clk a time of WDT needs to re-set for new frequency.
slow_clk depends on RTC_CLK_SRC (INTERNAL_RC or EXTERNAL_CRYSTAL).
Default value:
• Yes (enabled)
CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE
Allows RTC watchdog disable in user code
Found in: Bootloader config > CONFIG_BOOTLOADER_WDT_ENABLE
If this option is set, the ESP-IDF app must explicitly reset, feed, or disable the rtc_wdt in the app’s
own code. If this option is not set (default), then rtc_wdt will be disabled by ESP-IDF before calling the
app_main() function.
Use function rtc_wdt_feed() for resetting counter of rtc_wdt. Use function rtc_wdt_disable() for dis-
abling rtc_wdt.
Default value:
• No (disabled)
CONFIG_BOOTLOADER_WDT_TIME_MS
Timeout for RTC watchdog (ms)
Found in: Bootloader config > CONFIG_BOOTLOADER_WDT_ENABLE
Verify that this parameter is correct and more then the execution time. Pay attention to options such as
reset to factory, trigger test partition and encryption on boot - these options can increase the execution
time. Note: RTC_WDT will reset while encryption operations will be performed.
Range:
• from 0 to 120000
Default value:
• 9000
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE
Enable app rollback support
Found in: Bootloader config
After updating the app, the bootloader runs a new app with the
“ESP_OTA_IMG_PENDING_VERIFY”state set. This state prevents the re-run of this app.
After the first boot of the new app in the user code, the function should be called to confirm the
operability of the app or vice versa about its non-operability. If the app is working, then it is marked
as valid. Otherwise, it is marked as not valid and rolls back to the previous working app. A reboot is
performed, and the app is booted before the software update. Note: If during the first boot a new app
the power goes out or the WDT works, then roll back will happen. Rollback is possible only between
the apps with the same security versions.
Default value:
• No (disabled)
CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
Enable app anti-rollback support
Found in: Bootloader config > CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE
This option prevents rollback to previous firmware/application image with lower security version.
Default value:
• No (disabled) if CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE
CONFIG_BOOTLOADER_APP_SECURE_VERSION
eFuse secure version of app
Found in: Bootloader config > CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE > CON-
FIG_BOOTLOADER_APP_ANTI_ROLLBACK
The secure version is the sequence number stored in the header of each firmware. The security ver-
sion is set in the bootloader, version is recorded in the eFuse field as the number of set ones. The
allocated number of bits in the efuse field for storing the security version is limited (see BOOT-
LOADER_APP_SEC_VER_SIZE_EFUSE_FIELD option).
Bootloader: When bootloader selects an app to boot, an app is selected that has a security version greater
or equal that recorded in eFuse field. The app is booted with a higher (or equal) secure version.
The security version is worth increasing if in previous versions there is a significant vulnerability and
their use is not acceptable.
Your partition table should has a scheme with ota_0 + ota_1 (without factory).
Default value:
• 0 if CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
CONFIG_BOOTLOADER_APP_SEC_VER_SIZE_EFUSE_FIELD
Size of the efuse secure version field
Found in: Bootloader config > CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE > CON-
FIG_BOOTLOADER_APP_ANTI_ROLLBACK
The size of the efuse secure version field. Its length is limited to 32 bits for ESP32 and 16 bits for
ESP32-S2. This determines how many times the security version can be increased.
Range:
• from 1 to 32 if CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
• from 1 to 16 if CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
Default value:
• 32 if CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
• 16 if CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
CONFIG_BOOTLOADER_EFUSE_SECURE_VERSION_EMULATE
Emulate operations with efuse secure version(only test)
Found in: Bootloader config > CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE > CON-
FIG_BOOTLOADER_APP_ANTI_ROLLBACK
This option allows to emulate read/write operations with all eFuses and efuse secure version. It allows
to test anti-rollback implemention without permanent write eFuse bits. There should be an entry in
partition table with following details: emul_efuse, data, efuse, , 0x2000.
This option enables: EFUSE_VIRTUAL and EFUSE_VIRTUAL_KEEP_IN_FLASH.
Default value:
• No (disabled) if CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP
Skip image validation when exiting deep sleep
Found in: Bootloader config
This option disables the normal validation of an image coming out of deep sleep (checksums, SHA256,
and signature). This is a trade-off between wakeup performance from deep sleep, and image integrity
checks.
Only enable this if you know what you are doing. It should not be used in conjunction with using
deep_sleep() entry and changing the active OTA partition as this would skip the validation upon first
load of the new OTA partition.
It is possible to enable this option with Secure Boot if “allow insecure options”is enabled, however it’
s strongly recommended to NOT enable it as it may allow a Secure Boot bypass.
Default value:
• No (disabled) if (CONFIG_SECURE_BOOT && CONFIG_SECURE_BOOT_INSECURE) ||
CONFIG_SECURE_BOOT
CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON
CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS
Skip image validation always (READ HELP FIRST)
Found in: Bootloader config
Selecting this option prevents the bootloader from ever validating the app image before booting it. Any
flash corruption of the selected app partition will make the entire SoC unbootable.
Although flash corruption is a very rare case, it is not recommended to select this option. Consider
selecting “Skip image validation from power on reset”instead. However, if boot time is the only
important factor then it can be enabled.
Default value:
• No (disabled)
CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC
Reserve RTC FAST memory for custom purposes
Found in: Bootloader config
This option allows the customer to place data in the RTC FAST memory, this area remains valid when
rebooted, except for power loss. This memory is located at a fixed address and is available for both
the bootloader and the application. (The application and bootoloader must be compiled with the same
option). The RTC FAST memory has access only through PRO_CPU.
Default value:
• No (disabled)
CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC_SIZE
Size in bytes for custom purposes
Found in: Bootloader config > CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC
This option reserves in RTC FAST memory the area for custom purposes. If you want to create your
own bootloader and save more information in this area of memory, you can increase it. It must be a
multiple of 4 bytes. This area (rtc_retain_mem_t) is reserved and has access from the bootloader and
an application.
Range:
• from 0 to 0x10 if CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC
Default value:
• 0 if CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC
CONFIG_BOOTLOADER_FLASH_XMC_SUPPORT
Enable the support for flash chips of XMC (READ HELP FIRST)
Found in: Bootloader config
Perform the startup flow recommended by XMC. Please consult XMC for the details of this flow. XMC
chips will be forbidden to be used, when this option is disabled.
DON’T DISABLE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.
Default value:
• Yes (enabled)
Security features
Contains:
• CONFIG_SECURE_BOOT_INSECURE
• CONFIG_SECURE_SIGNED_APPS_SCHEME
• CONFIG_SECURE_SIGNED_ON_BOOT_NO_SECURE_BOOT
• CONFIG_SECURE_FLASH_CHECK_ENC_EN_IN_APP
• CONFIG_SECURE_BOOT_ECDSA_KEY_LEN_SIZE
• CONFIG_SECURE_BOOT_ENABLE_AGGRESSIVE_KEY_REVOKE
• CONFIG_SECURE_FLASH_ENC_ENABLED
• CONFIG_SECURE_BOOT
• CONFIG_SECURE_BOOTLOADER_KEY_ENCODING
• Potentially insecure options
• CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT
• CONFIG_SECURE_BOOT_VERIFICATION_KEY
• CONFIG_SECURE_BOOTLOADER_MODE
• CONFIG_SECURE_BOOT_BUILD_SIGNED_BINARIES
• CONFIG_SECURE_UART_ROM_DL_MODE
• CONFIG_SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT
CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT
Require signed app images
Found in: Security features
Require apps to be signed to verify their integrity.
This option uses the same app signature scheme as hardware secure boot, but unlike hardware secure
boot it does not prevent the bootloader from being physically updated. This means that the device can
be secured against remote network access, but not physical access. Compared to using hardware Secure
Boot this option is much simpler to implement.
CONFIG_SECURE_SIGNED_APPS_SCHEME
App Signing Scheme
Found in: Security features
Select the Secure App signing scheme. Depends on the Chip Revision. There are two secure boot
versions:
1. Secure boot V1
• Legacy custom secure boot scheme. Supported in ESP32 SoC.
2. Secure boot V2
• RSA based secure boot scheme. Supported in ESP32-ECO3 (ESP32 Chip Revision 3
onwards), ESP32-S2, ESP32-C3, ESP32-S3 SoCs.
• ECDSA based secure boot scheme. Supported in ESP32-C2 SoC.
Available options:
• ECDSA (SECURE_SIGNED_APPS_ECDSA_SCHEME)
Embeds the ECDSA public key in the bootloader and signs the application with an ECDSA
key. Refer to the documentation before enabling.
• RSA (SECURE_SIGNED_APPS_RSA_SCHEME)
Appends the RSA-3072 based Signature block to the application. Refer to <Secure Boot
Version 2 documentation link> before enabling.
• ECDSA (V2) (SECURE_SIGNED_APPS_ECDSA_V2_SCHEME)
For Secure boot V2 (e.g., ESP32-C2 SoC), appends ECDSA based signature block to the
application. Refer to documentation before enabling.
CONFIG_SECURE_BOOT_ECDSA_KEY_LEN_SIZE
ECDSA key size
Found in: Security features
Select the ECDSA key size. Two key sizes are supported
• 192 bit key using NISTP192 curve
• 256 bit key using NISTP256 curve (Recommended)
The advantage of using 256 bit key is the extra randomness which makes it difficult to be bruteforced
compared to 192 bit key. At present, both key sizes are practically implausible to bruteforce.
Available options:
• Using ECC curve NISTP192 (SECURE_BOOT_ECDSA_KEY_LEN_192_BITS)
• Using ECC curve NISTP256 (Recommended) (SECURE_BOOT_ECDSA_KEY_LEN_256_BITS)
CONFIG_SECURE_SIGNED_ON_BOOT_NO_SECURE_BOOT
Bootloader verifies app signatures
Found in: Security features
If this option is set, the bootloader will be compiled with code to verify that an app is signed before
booting it.
If hardware secure boot is enabled, this option is always enabled and cannot be disabled. If hardware
secure boot is not enabled, this option doesn’t add significant security by itself so most users will want
to leave it disabled.
Default value:
• No (disabled) if CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT && SE-
CURE_SIGNED_APPS_ECDSA_SCHEME
CONFIG_SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT
Verify app signature on update
Found in: Security features
If this option is set, any OTA updated apps will have the signature verified before being considered valid.
When enabled, the signature is automatically checked whenever the esp_ota_ops.h APIs are used for
OTA updates, or esp_image_format.h APIs are used to verify apps.
If hardware secure boot is enabled, this option is always enabled and cannot be disabled. If hardware
secure boot is not enabled, this option still adds significant security against network-based attackers by
preventing spoofing of OTA updates.
Default value:
• Yes (enabled) if CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT
CONFIG_SECURE_BOOT
Enable hardware Secure Boot in bootloader (READ DOCS FIRST)
Found in: Security features
Build a bootloader which enables Secure Boot on first boot.
Once enabled, Secure Boot will not boot a modified bootloader. The bootloader will only load a partition
table or boot an app if the data has a verified digital signature. There are implications for reflashing
updated apps once secure boot is enabled.
When enabling secure boot, JTAG and ROM BASIC Interpreter are permanently disabled by default.
Default value:
• No (disabled)
CONFIG_SECURE_BOOT_VERSION
Select secure boot version
Found in: Security features > CONFIG_SECURE_BOOT
Select the Secure Boot Version. Depends on the Chip Revision. Secure Boot V2 is the new RSA /
ECDSA based secure boot scheme.
• RSA based scheme is supported in ESP32 (Revision 3 onwards), ESP32-S2, ESP32-C3 (ECO3),
ESP32-S3.
• ECDSA based scheme is supported in ESP32-C2 SoC.
Please note that, RSA or ECDSA secure boot is property of specific SoC based on its HW design,
supported crypto accelerators, die-size, cost and similar parameters. Please note that RSA scheme has
requirement for bigger key sizes but at the same time it is comparatively faster than ECDSA verification.
Secure Boot V1 is the AES based (custom) secure boot scheme supported in ESP32 SoC.
Available options:
• Enable Secure Boot version 1 (SECURE_BOOT_V1_ENABLED)
Build a bootloader which enables secure boot version 1 on first boot. Refer to the Secure Boot
section of the ESP-IDF Programmer’s Guide for this version before enabling.
• Enable Secure Boot version 2 (SECURE_BOOT_V2_ENABLED)
Build a bootloader which enables Secure Boot version 2 on first boot. Refer to Secure Boot
V2 section of the ESP-IDF Programmer’s Guide for this version before enabling.
CONFIG_SECURE_BOOTLOADER_MODE
Secure bootloader mode
Found in: Security features
Available options:
• One-time flash (SECURE_BOOTLOADER_ONE_TIME_FLASH)
On first boot, the bootloader will generate a key which is not readable externally or by software.
A digest is generated from the bootloader image itself. This digest will be verified on each
subsequent boot.
Enabling this option means that the bootloader cannot be changed after the first time it is
booted.
• Reflashable (SECURE_BOOTLOADER_REFLASHABLE)
Generate a reusable secure bootloader key, derived (via SHA-256) from the secure boot sign-
ing key.
This allows the secure bootloader to be re-flashed by anyone with access to the secure boot
signing key.
This option is less secure than one-time flash, because a leak of the digest key from one device
allows reflashing of any device that uses it.
CONFIG_SECURE_BOOT_BUILD_SIGNED_BINARIES
Sign binaries during build
Found in: Security features
Once secure boot or signed app requirement is enabled, app images are required to be signed.
If enabled (default), these binary files are signed as part of the build process. The file named in“Secure
boot private signing key”will be used to sign the image.
If disabled, unsigned app/partition data will be built. They must be signed manually using espsecure.py.
Version 1 to enable ECDSA Based Secure Boot and Version 2 to enable RSA based Secure Boot. (for
example, on a remote signing server.)
CONFIG_SECURE_BOOT_SIGNING_KEY
Secure boot private signing key
Found in: Security features > CONFIG_SECURE_BOOT_BUILD_SIGNED_BINARIES
Path to the key file used to sign app images.
Key file is an ECDSA private key (NIST256p curve) in PEM format for Secure Boot V1. Key file is an
RSA private key in PEM format for Secure Boot V2.
Path is evaluated relative to the project directory.
You can generate a new signing key by running the following command: espsecure.py gener-
ate_signing_key secure_boot_signing_key.pem
See the Secure Boot section of the ESP-IDF Programmer’s Guide for this version for details.
Default value:
• “secure_boot_signing_key.pem”if CONFIG_SECURE_BOOT_BUILD_SIGNED_BINARIES
CONFIG_SECURE_BOOT_VERIFICATION_KEY
Secure boot public signature verification key
Found in: Security features
Path to a public key file used to verify signed images. Secure Boot V1: This ECDSA public key is
compiled into the bootloader and/or app, to verify app images. Secure Boot V2: This RSA public key
is compiled into the signature block at the end of the bootloader/app.
Key file is in raw binary format, and can be extracted from a PEM formatted private key using the
espsecure.py extract_public_key command.
Refer to the Secure Boot section of the ESP-IDF Programmer’s Guide for this version before enabling.
CONFIG_SECURE_BOOT_ENABLE_AGGRESSIVE_KEY_REVOKE
Enable Aggressive key revoke strategy
Found in: Security features
If this option is set, ROM bootloader will revoke the public key digest burned in efuse block if it fails to
verify the signature of software bootloader with it. Revocation of keys does not happen when enabling
secure boot. Once secure boot is enabled, key revocation checks will be done on subsequent boot-up,
while verifying the software bootloader
This feature provides a strong resistance against physical attacks on the device.
NOTE: Once a digest slot is revoked, it can never be used again to verify an image This can lead to
permanent bricking of the device, in case all keys are revoked because of signature verification failure.
Default value:
• No (disabled) if CONFIG_SECURE_BOOT && SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY
CONFIG_SECURE_BOOTLOADER_KEY_ENCODING
Hardware Key Encoding
Found in: Security features
In reflashable secure bootloader mode, a hardware key is derived from the signing key (with SHA-256)
and can be written to eFuse with espefuse.py.
Normally this is a 256-bit key, but if 3/4 Coding Scheme is used on the device then the eFuse key is
truncated to 192 bits.
This configuration item doesn’t change any firmware code, it only changes the size of key binary which
is generated at build time.
Available options:
• No encoding (256 bit key) (SECURE_BOOTLOADER_KEY_ENCODING_256BIT)
• 3/4 encoding (192 bit key) (SECURE_BOOTLOADER_KEY_ENCODING_192BIT)
CONFIG_SECURE_BOOT_INSECURE
Allow potentially insecure options
Found in: Security features
You can disable some of the default protections offered by secure boot, in order to enable testing or a
custom combination of security features.
Only enable these options if you are very sure.
Refer to the Secure Boot section of the ESP-IDF Programmer’s Guide for this version before enabling.
Default value:
• No (disabled) if CONFIG_SECURE_BOOT
CONFIG_SECURE_FLASH_ENC_ENABLED
Enable flash encryption on boot (READ DOCS FIRST)
Found in: Security features
If this option is set, flash contents will be encrypted by the bootloader on first boot.
Note: After first boot, the system will be permanently encrypted. Re-flashing an encrypted system is
complicated and not always possible.
Read Flash Encryption before enabling.
Default value:
• No (disabled)
CONFIG_SECURE_FLASH_ENCRYPTION_KEYSIZE
Size of generated AES-XTS key
Found in: Security features > CONFIG_SECURE_FLASH_ENC_ENABLED
Size of generated AES-XTS key.
• AES-128 uses a 256-bit key (32 bytes) derived from 128 bits (16 bytes) burned in half Efuse key
block. Internally, it calculates SHA256(128 bits)
• AES-128 uses a 256-bit key (32 bytes) which occupies one Efuse key block.
• AES-256 uses a 512-bit key (64 bytes) which occupies two Efuse key blocks.
This setting is ignored if either type of key is already burned to Efuse before the first boot. In this case,
the pre-burned key is used and no new key is generated.
Available options:
• AES-128 key derived from 128 bits (SHA256(128 bits)) (SE-
CURE_FLASH_ENCRYPTION_AES128_DERIVED)
• AES-128 (256-bit key) (SECURE_FLASH_ENCRYPTION_AES128)
• AES-256 (512-bit key) (SECURE_FLASH_ENCRYPTION_AES256)
CONFIG_SECURE_FLASH_ENCRYPTION_MODE
Enable usage mode
Found in: Security features > CONFIG_SECURE_FLASH_ENC_ENABLED
By default Development mode is enabled which allows ROM download mode to perform flash encryption
operations (plaintext is sent to the device, and it encrypts it internally and writes ciphertext to flash.) This
mode is not secure, it’s possible for an attacker to write their own chosen plaintext to flash.
Release mode should always be selected for production or manufacturing. Once enabled it’s no longer
possible for the device in ROM Download Mode to use the flash encryption hardware.
Refer to the Flash Encryption section of the ESP-IDF Programmer’s Guide for details.
Available options:
• Development (NOT SECURE) (SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT)
• Release (SECURE_FLASH_ENCRYPTION_MODE_RELEASE)
CONFIG_SECURE_BOOT_ALLOW_ROM_BASIC
Leave ROM BASIC Interpreter available on reset
Found in: Security features > Potentially insecure options
By default, the BASIC ROM Console starts on reset if no valid bootloader is read from the flash.
When either flash encryption or secure boot are enabled, the default is to disable this BASIC fallback
mode permanently via eFuse.
If this option is set, this eFuse is not burned and the BASIC ROM Console may remain accessible. Only
set this option in testing environments.
Default value:
• No (disabled) if CONFIG_SECURE_BOOT_INSECURE || SE-
CURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT
CONFIG_SECURE_BOOT_ALLOW_JTAG
Allow JTAG Debugging
Found in: Security features > Potentially insecure options
If not set (default), the bootloader will permanently disable JTAG (across entire chip) on first boot when
either secure boot or flash encryption is enabled.
Setting this option leaves JTAG on for debugging, which negates all protections of flash encryption and
some of the protections of secure boot.
Only set this option in testing environments.
Default value:
• No (disabled) if CONFIG_SECURE_BOOT_INSECURE || SE-
CURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT
CONFIG_SECURE_BOOT_ALLOW_SHORT_APP_PARTITION
Allow app partition length not 64KB aligned
Found in: Security features > Potentially insecure options
If not set (default), app partition size must be a multiple of 64KB. App images are padded to 64KB
length, and the bootloader checks any trailing bytes after the signature (before the next 64KB boundary)
have not been written. This is because flash cache maps entire 64KB pages into the address space. This
prevents an attacker from appending unverified data after the app image in the flash, causing it to be
mapped into the address space.
Setting this option allows the app partition length to be unaligned, and disables padding of the app image
to this length. It is generally not recommended to set this option, unless you have a legacy partitioning
scheme which doesn’t support 64KB aligned partition lengths.
CONFIG_SECURE_BOOT_V2_ALLOW_EFUSE_RD_DIS
Allow additional read protecting of efuses
Found in: Security features > Potentially insecure options
If not set (default, recommended), on first boot the bootloader will burn the WR_DIS_RD_DIS efuse
when Secure Boot is enabled. This prevents any more efuses from being read protected.
If this option is set, it will remain possible to write the EFUSE_RD_DIS efuse field after Secure Boot
is enabled. This may allow an attacker to read-protect the BLK2 efuse (for ESP32) and BLOCK4-
BLOCK10 (i.e. BLOCK_KEY0-BLOCK_KEY5)(for other chips) holding the public key digest, caus-
ing an immediate denial of service and possibly allowing an additional fault injection attack to bypass
the signature protection.
NOTE: Once a BLOCK is read-protected, the application will read all zeros from that block
NOTE: If “UART ROM download mode (Permanently disabled (recommended))”or “UART ROM
download mode (Permanently switch to Secure mode (recommended))”is set, then it is __NOT__
possible to read/write efuses using espefuse.py utility. However, efuse can be read/written from the
application
CONFIG_SECURE_BOOT_ALLOW_UNUSED_DIGEST_SLOTS
Leave unused digest slots available (not revoke)
Found in: Security features > Potentially insecure options
If not set (default), during startup in the app all unused digest slots will be revoked. To revoke unused
slot will be called esp_efuse_set_digest_revoke(num_digest) for each digest. Revoking unused digest
slots makes ensures that no trusted keys can be added later by an attacker. If set, it means that you have
a plan to use unused digests slots later.
Default value:
• No (disabled) if CONFIG_SECURE_BOOT_INSECURE &&
SOC_EFUSE_REVOKE_BOOT_KEY_DIGESTS
CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_ENC
Leave UART bootloader encryption enabled
Found in: Security features > Potentially insecure options
If not set (default), the bootloader will permanently disable UART bootloader encryption access on first
boot. If set, the UART bootloader will still be able to access hardware encryption.
It is recommended to only set this option in testing environments.
Default value:
• No (disabled) if SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT
CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_DEC
Leave UART bootloader decryption enabled
Found in: Security features > Potentially insecure options
If not set (default), the bootloader will permanently disable UART bootloader decryption access on first
boot. If set, the UART bootloader will still be able to access hardware decryption.
Only set this option in testing environments. Setting this option allows complete bypass of flash encryp-
tion.
Default value:
• No (disabled) if SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT
CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_CACHE
Leave UART bootloader flash cache enabled
Found in: Security features > Potentially insecure options
If not set (default), the bootloader will permanently disable UART bootloader flash cache access on first
boot. If set, the UART bootloader will still be able to access the flash cache.
Only set this option in testing environments.
Default value:
• No (disabled) if SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT
CONFIG_SECURE_FLASH_REQUIRE_ALREADY_ENABLED
Require flash encryption to be already enabled
Found in: Security features > Potentially insecure options
If not set (default), and flash encryption is not yet enabled in eFuses, the 2nd stage bootloader will enable
flash encryption: generate the flash encryption key and program eFuses. If this option is set, and flash
encryption is not yet enabled, the bootloader will error out and reboot. If flash encryption is enabled in
eFuses, this option does not change the bootloader behavior.
Only use this option in testing environments, to avoid accidentally enabling flash encryption on the wrong
device. The device needs to have flash encryption already enabled using espefuse.py.
Default value:
• No (disabled) if SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT
CONFIG_SECURE_FLASH_CHECK_ENC_EN_IN_APP
Check Flash Encryption enabled on app startup
Found in: Security features
If set (default), in an app during startup code, there is a check of the flash encryption eFuse bit is on (as
the bootloader should already have set it). The app requires this bit is on to continue work otherwise
abort.
If not set, the app does not care if the flash encryption eFuse bit is set or not.
Default value:
• Yes (enabled) if CONFIG_SECURE_FLASH_ENC_ENABLED
CONFIG_SECURE_UART_ROM_DL_MODE
UART ROM download mode
Found in: Security features
Available options:
• UART ROM download mode (Permanently disabled (recommended)) (SE-
CURE_DISABLE_ROM_DL_MODE)
If set, during startup the app will burn an eFuse bit to permanently disable the UART ROM
Download Mode. This prevents any future use of esptool.py, espefuse.py and similar tools.
Once disabled, if the SoC is booted with strapping pins set for ROM Download Mode then
an error is printed instead.
It is recommended to enable this option in any production application where Flash Encryption
and/or Secure Boot is enabled and access to Download Mode is not required.
It is also possible to permanently disable Download Mode by calling
esp_efuse_disable_rom_download_mode() at runtime.
• UART ROM download mode (Permanently switch to Secure mode (recommended)) (SE-
CURE_ENABLE_SECURE_ROM_DL_MODE)
If set, during startup the app will burn an eFuse bit to permanently switch the UART ROM
Download Mode into a separate Secure Download mode. This option can only work if Down-
load Mode is not already disabled by eFuse.
Secure Download mode limits the use of Download Mode functions to simple flash read,
write and erase operations, plus a command to return a summary of currently enabled security
features.
Secure Download mode is not compatible with the esptool.py flasher stub feature, espefuse.py,
read/writing memory or registers, encrypted download, or any other features that interact with
unsupported Download Mode commands.
Secure Download mode should be enabled in any application where Flash Encryption and/or
Secure Boot is enabled. Disabling this option does not immediately cancel the benefits of the
security features, but it increases the potential “attack surface”for an attacker to try and
bypass them with a successful physical attack.
It is also possible to enable secure download mode at runtime by calling
esp_efuse_enable_rom_secure_download_mode()
Note: Secure Download mode is not available for ESP32 (includes revisions till ECO3).
• UART ROM download mode (Enabled (not recommended)) (SE-
CURE_INSECURE_ALLOW_DL_MODE)
This is a potentially insecure option. Enabling this option will allow the full UART download
mode to stay enabled. This option SHOULD NOT BE ENABLED for production use cases.
Contains:
• CONFIG_ESPTOOLPY_AFTER
• CONFIG_ESPTOOLPY_BEFORE
• CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE
• CONFIG_ESPTOOLPY_NO_STUB
• CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE
• CONFIG_ESPTOOLPY_FLASHSIZE
• CONFIG_ESPTOOLPY_FLASHMODE
• CONFIG_ESPTOOLPY_FLASHFREQ
CONFIG_ESPTOOLPY_NO_STUB
Disable download stub
Found in: Serial flasher config
The flasher tool sends a precompiled download stub first by default. That stub allows things like com-
pressed downloads and more. Usually you should not need to disable that feature
Default value:
• No (disabled)
CONFIG_ESPTOOLPY_FLASHMODE
Flash SPI mode
Found in: Serial flasher config
Mode the flash chip is flashed in, as well as the default mode for the binary to run in.
Available options:
• QIO (ESPTOOLPY_FLASHMODE_QIO)
• QOUT (ESPTOOLPY_FLASHMODE_QOUT)
• DIO (ESPTOOLPY_FLASHMODE_DIO)
• DOUT (ESPTOOLPY_FLASHMODE_DOUT)
• OPI (ESPTOOLPY_FLASHMODE_OPI)
CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE
Flash Sampling Mode
Found in: Serial flasher config
Available options:
• STR Mode (ESPTOOLPY_FLASH_SAMPLE_MODE_STR)
• DTR Mode (ESPTOOLPY_FLASH_SAMPLE_MODE_DTR)
CONFIG_ESPTOOLPY_FLASHFREQ
Flash SPI speed
Found in: Serial flasher config
Available options:
• 120 MHz (ESPTOOLPY_FLASHFREQ_120M)
• 80 MHz (ESPTOOLPY_FLASHFREQ_80M)
• 60 MHz (ESPTOOLPY_FLASHFREQ_60M)
• 48 MHz (ESPTOOLPY_FLASHFREQ_48M)
• 40 MHz (ESPTOOLPY_FLASHFREQ_40M)
• 30 MHz (ESPTOOLPY_FLASHFREQ_30M)
• 26 MHz (ESPTOOLPY_FLASHFREQ_26M)
• 24 MHz (ESPTOOLPY_FLASHFREQ_24M)
• 20 MHz (ESPTOOLPY_FLASHFREQ_20M)
• 15 MHz (ESPTOOLPY_FLASHFREQ_15M)
CONFIG_ESPTOOLPY_FLASHSIZE
Flash size
Found in: Serial flasher config
SPI flash size, in megabytes
Available options:
• 1 MB (ESPTOOLPY_FLASHSIZE_1MB)
• 2 MB (ESPTOOLPY_FLASHSIZE_2MB)
• 4 MB (ESPTOOLPY_FLASHSIZE_4MB)
• 8 MB (ESPTOOLPY_FLASHSIZE_8MB)
• 16 MB (ESPTOOLPY_FLASHSIZE_16MB)
• 32 MB (ESPTOOLPY_FLASHSIZE_32MB)
• 64 MB (ESPTOOLPY_FLASHSIZE_64MB)
• 128 MB (ESPTOOLPY_FLASHSIZE_128MB)
CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE
Detect flash size when flashing bootloader
Found in: Serial flasher config
If this option is set, flashing the project will automatically detect the flash size of the target chip and
update the bootloader image before it is flashed.
Enabling this option turns off the image protection against corruption by a SHA256 digest. Updating
the bootloader image before flashing would invalidate the digest.
Default value:
• No (disabled)
CONFIG_ESPTOOLPY_BEFORE
Before flashing
Found in: Serial flasher config
Configure whether esptool.py should reset the ESP32 before flashing.
Automatic resetting depends on the RTS & DTR signals being wired from the serial port to the ESP32.
Most USB development boards do this internally.
Available options:
• Reset to bootloader (ESPTOOLPY_BEFORE_RESET)
• No reset (ESPTOOLPY_BEFORE_NORESET)
CONFIG_ESPTOOLPY_AFTER
After flashing
Found in: Serial flasher config
Configure whether esptool.py should reset the ESP32 after flashing.
Automatic resetting depends on the RTS & DTR signals being wired from the serial port to the ESP32.
Most USB development boards do this internally.
Available options:
• Reset after flashing (ESPTOOLPY_AFTER_RESET)
• Stay in bootloader (ESPTOOLPY_AFTER_NORESET)
Partition Table
Contains:
• CONFIG_PARTITION_TABLE_CUSTOM_FILENAME
• CONFIG_PARTITION_TABLE_MD5
• CONFIG_PARTITION_TABLE_OFFSET
• CONFIG_PARTITION_TABLE_TYPE
CONFIG_PARTITION_TABLE_TYPE
Partition Table
Found in: Partition Table
The partition table to flash to the ESP32. The partition table determines where apps, data and other
resources are expected to be found.
The predefined partition table CSV descriptions can be found in the components/partition_table direc-
tory. These are mostly intended for example and development use, it’s expect that for production use
you will copy one of these CSV files and create a custom partition CSV for your application.
Available options:
• Single factory app, no OTA (PARTITION_TABLE_SINGLE_APP)
This is the default partition table, designed to fit into a 2MB or larger flash with a single 1MB
app partition.
The corresponding CSV file in the IDF directory is compo-
nents/partition_table/partitions_singleapp.csv
This partition table is not suitable for an app that needs OTA (over the air update) capability.
• Single factory app (large), no OTA (PARTITION_TABLE_SINGLE_APP_LARGE)
This is a variation of the default partition table, that expands the 1MB app partition size to
1.5MB to fit more code.
The corresponding CSV file in the IDF directory is compo-
nents/partition_table/partitions_singleapp_large.csv
This partition table is not suitable for an app that needs OTA (over the air update) capability.
• Factory app, two OTA definitions (PARTITION_TABLE_TWO_OTA)
This is a basic OTA-enabled partition table with a factory app partition plus two OTA app
partitions. All are 1MB, so this partition table requires 4MB or larger flash size.
The corresponding CSV file in the IDF directory is compo-
nents/partition_table/partitions_two_ota.csv
• Custom partition table CSV (PARTITION_TABLE_CUSTOM)
Specify the path to the partition table CSV to use for your project.
Consult the Partition Table section in the ESP-IDF Programmers Guide for more information.
• Single factory app, no OTA, encrypted NVS (PARTI-
TION_TABLE_SINGLE_APP_ENCRYPTED_NVS)
This is a variation of the default “Single factory app, no OTA”partition table that supports
encrypted NVS when using flash encryption. See the Flash Encryption section in the ESP-IDF
Programmers Guide for more information.
The corresponding CSV file in the IDF directory is compo-
nents/partition_table/partitions_singleapp_encr_nvs.csv
• Single factory app (large), no OTA, encrypted NVS (PARTI-
TION_TABLE_SINGLE_APP_LARGE_ENC_NVS)
This is a variation of the “Single factory app (large), no OTA”partition table that supports
encrypted NVS when using flash encryption. See the Flash Encryption section in the ESP-IDF
Programmers Guide for more information.
The corresponding CSV file in the IDF directory is compo-
nents/partition_table/partitions_singleapp_large_encr_nvs.csv
• Factory app, two OTA definitions, encrypted NVS (PARTI-
TION_TABLE_TWO_OTA_ENCRYPTED_NVS)
This is a variation of the “Factory app, two OTA definitions”partition table that supports
encrypted NVS when using flash encryption. See the Flash Encryption section in the ESP-IDF
Programmers Guide for more information.
The corresponding CSV file in the IDF directory is compo-
nents/partition_table/partitions_two_ota_encr_nvs.csv
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME
Custom partition CSV file
Found in: Partition Table
Name of the custom partition CSV filename. This path is evaluated relative to the project root directory.
Default value:
• “partitions.csv”
CONFIG_PARTITION_TABLE_OFFSET
Offset of partition table
Found in: Partition Table
The address of partition table (by default 0x8000). Allows you to move the partition table, it gives more
space for the bootloader. Note that the bootloader and app will both need to be compiled with the same
PARTITION_TABLE_OFFSET value.
This number should be a multiple of 0x1000.
Note that partition offsets in the partition table CSV file may need to be changed if this value is set to a
higher value. To have each partition offset adapt to the configured partition table offset, leave all partition
offsets blank in the CSV file.
Default value:
• “0x8000”
CONFIG_PARTITION_TABLE_MD5
Generate an MD5 checksum for the partition table
Found in: Partition Table
Generate an MD5 checksum for the partition table for protecting the integrity of the table. The gen-
eration should be turned off for legacy bootloaders which cannot recognize the MD5 checksum in the
partition table.
Default value:
• Yes (enabled) if CONFIG_APP_COMPATIBLE_PRE_V3_1_BOOTLOADERS
Compiler options
Contains:
• CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL
• CONFIG_COMPILER_FLOAT_LIB_FROM
• CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT
• CONFIG_COMPILER_DUMP_RTL_FILES
• CONFIG_COMPILER_WARN_WRITE_STRINGS
• CONFIG_COMPILER_CXX_EXCEPTIONS
• CONFIG_COMPILER_CXX_RTTI
• CONFIG_COMPILER_OPTIMIZATION
• CONFIG_COMPILER_HIDE_PATHS_MACROS
• CONFIG_COMPILER_STACK_CHECK_MODE
CONFIG_COMPILER_OPTIMIZATION
Optimization Level
Found in: Compiler options
This option sets compiler optimization level (gcc -O argument) for the app.
• The “Default”setting will add the -0g flag to CFLAGS.
• The “Size”setting will add the -0s flag to CFLAGS.
• The “Performance”setting will add the -O2 flag to CFLAGS.
• The “None”setting will add the -O0 flag to CFLAGS.
The “Size”setting cause the compiled code to be smaller and faster, but may lead to difficulties of
correlating code addresses to source file lines when debugging.
The “Performance”setting causes the compiled code to be larger and faster, but will be easier to
correlated code addresses to source file lines.
“None”with -O0 produces compiled code without optimization.
Note that custom optimization levels may be unsupported.
Compiler optimization for the IDF bootloader is set separately, see the BOOT-
LOADER_COMPILER_OPTIMIZATION setting.
Available options:
• Debug (-Og) (COMPILER_OPTIMIZATION_DEFAULT)
• Optimize for size (-Os) (COMPILER_OPTIMIZATION_SIZE)
• Optimize for performance (-O2) (COMPILER_OPTIMIZATION_PERF)
• Debug without optimization (-O0) (COMPILER_OPTIMIZATION_NONE)
CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL
Assertion level
Found in: Compiler options
Assertions can be:
• Enabled. Failure will print verbose assertion details. This is the default.
• Set to “silent”to save code size (failed assertions will abort() but user needs to use the aborting
address to find the line number with the failed assertion.)
• Disabled entirely (not recommended for most configurations.) -DNDEBUG is added to
CPPFLAGS in this case.
Available options:
• Enabled (COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE)
Enable assertions. Assertion content and line number will be printed on failure.
• Silent (saves code size) (COMPILER_OPTIMIZATION_ASSERTIONS_SILENT)
Enable silent assertions. Failed assertions will abort(), user needs to use the aborting address
to find the line number with the failed assertion.
• Disabled (sets -DNDEBUG) (COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE)
If assertions are disabled, -DNDEBUG is added to CPPFLAGS.
CONFIG_COMPILER_FLOAT_LIB_FROM
Compiler float lib source
Found in: Compiler options
In the soft-fp part of libgcc, riscv version is written in C, and handles all edge cases in IEEE754, which
makes it larger and performance is slow.
RVfplib is an optimized RISC-V library for FP arithmetic on 32-bit integer processors, for single and
double-precision FP. RVfplib is “fast”, but it has a few exceptions from IEEE 754 compliance.
Available options:
• libgcc (COMPILER_FLOAT_LIB_FROM_GCCLIB)
• librvfp (COMPILER_FLOAT_LIB_FROM_RVFPLIB)
CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT
Disable messages in ESP_RETURN_ON_* and ESP_EXIT_ON_* macros
Found in: Compiler options
If enabled, the error messages will be discarded in following check macros: -
ESP_RETURN_ON_ERROR - ESP_EXIT_ON_ERROR - ESP_RETURN_ON_FALSE -
ESP_EXIT_ON_FALSE
Default value:
• No (disabled)
CONFIG_COMPILER_HIDE_PATHS_MACROS
Replace ESP-IDF and project paths in binaries
Found in: Compiler options
When expanding the __FILE__ and __BASE_FILE__ macros, replace paths inside ESP-IDF with paths
relative to the placeholder string“IDF”, and convert paths inside the project directory to relative paths.
This allows building the project with assertions or other code that embeds file paths, without the binary
containing the exact path to the IDF or project directories.
This option passes -fmacro-prefix-map options to the GCC command line. To replace additional paths in
your binaries, modify the project CMakeLists.txt file to pass custom -fmacro-prefix-map or -ffile-prefix-
map arguments.
Default value:
• Yes (enabled)
CONFIG_COMPILER_CXX_EXCEPTIONS
Enable C++ exceptions
Found in: Compiler options
Enabling this option compiles all IDF C++ files with exception support enabled.
Disabling this option disables C++ exception support in all compiled files, and any libstdc++ code which
throws an exception will abort instead.
Enabling this option currently adds an additional ~500 bytes of heap overhead when an exception is
thrown in user code for the first time.
Default value:
• No (disabled)
Contains:
• CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE
CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE
Emergency Pool Size
Found in: Compiler options > CONFIG_COMPILER_CXX_EXCEPTIONS
Size (in bytes) of the emergency memory pool for C++ exceptions. This pool will be used to allocate
memory for thrown exceptions when there is not enough memory on the heap.
Default value:
• 0 if CONFIG_COMPILER_CXX_EXCEPTIONS
CONFIG_COMPILER_CXX_RTTI
Enable C++ run-time type info (RTTI)
Found in: Compiler options
Enabling this option compiles all C++ files with RTTI support enabled. This increases binary size (typ-
ically by tens of kB) but allows using dynamic_cast conversion and typeid operator.
Default value:
• No (disabled)
CONFIG_COMPILER_STACK_CHECK_MODE
Stack smashing protection mode
Found in: Compiler options
Stack smashing protection mode. Emit extra code to check for buffer overflows, such as stack smashing
attacks. This is done by adding a guard variable to functions with vulnerable objects. The guards are
initialized when a function is entered and then checked when the function exits. If a guard check fails,
program is halted. Protection has the following modes:
• In NORMAL mode (GCC flag: -fstack-protector) only functions that call alloca, and functions
with buffers larger than 8 bytes are protected.
• STRONG mode (GCC flag: -fstack-protector-strong) is like NORMAL, but includes additional
functions to be protected –those that have local array definitions, or have references to local frame
addresses.
• In OVERALL mode (GCC flag: -fstack-protector-all) all functions are protected.
Modes have the following impact on code performance and coverage:
• performance: NORMAL > STRONG > OVERALL
• coverage: NORMAL < STRONG < OVERALL
The performance impact includes increasing the amount of stack memory required for each task.
Available options:
• None (COMPILER_STACK_CHECK_MODE_NONE)
• Normal (COMPILER_STACK_CHECK_MODE_NORM)
• Strong (COMPILER_STACK_CHECK_MODE_STRONG)
• Overall (COMPILER_STACK_CHECK_MODE_ALL)
CONFIG_COMPILER_WARN_WRITE_STRINGS
Enable -Wwrite-strings warning flag
Found in: Compiler options
Adds -Wwrite-strings flag for the C/C++ compilers.
For C, this gives string constants the type const char[] so that copying the address of one into a
non-const char \* pointer produces a warning. This warning helps to find at compile time code that
tries to write into a string constant.
For C++, this warns about the deprecated conversion from string literals to char \*.
Default value:
• No (disabled)
CONFIG_COMPILER_DUMP_RTL_FILES
Dump RTL files during compilation
Found in: Compiler options
If enabled, RTL files will be produced during compilation. These files can be used by other tools, for
example to calculate call graphs.
Component config
Contains:
• ADC-Calibration
• Application Level Tracing
• Bluetooth
• Common ESP-related
• Core dump
• Driver Configurations
• eFuse Bit Manager
• CONFIG_BLE_MESH
• ESP HTTP client
• ESP HTTPS OTA
• ESP HTTPS server
• ESP NETIF Adapter
• ESP PSRAM
• ESP System Settings
• ESP-MQTT Configurations
• ESP-TLS
• Ethernet
• Event Loop Library
• FAT Filesystem support
• FreeRTOS
• GDB Stub
• Hardware Abstraction Layer (HAL) and Low Level (LL)
• Hardware Settings
• Heap memory debugging
• High resolution timer (esp_timer)
• HTTP Server
• IPC (Inter-Processor Call)
• LCD and Touch Panel
• Log output
• LWIP
• mbedTLS
• Newlib
• NVS
• OpenThread
• PHY
• Power Management
• Protocomm
• PThreads
• SPI Flash driver
• SPIFFS Configuration
• Supplicant
• TCP Transport
• Ultra Low Power (ULP) Co-processor
• Unity unit testing library
• Virtual file system
• Wear Levelling
• Wi-Fi
• Wi-Fi Provisioning Manager
CONFIG_APPTRACE_DESTINATION1
Data Destination 1
Found in: Component config > Application Level Tracing
Select destination for application trace: JTAG or none (to disable).
Available options:
• JTAG (APPTRACE_DEST_JTAG)
• None (APPTRACE_DEST_NONE)
CONFIG_APPTRACE_DESTINATION2
Data Destination 2
Found in: Component config > Application Level Tracing
Select destination for application trace: UART(XX) or none (to disable).
Available options:
• UART0 (APPTRACE_DEST_UART0)
• UART1 (APPTRACE_DEST_UART1)
• UART2 (APPTRACE_DEST_UART2)
• USB_CDC (APPTRACE_DEST_USB_CDC)
• None (APPTRACE_DEST_UART_NONE)
CONFIG_APPTRACE_UART_TX_GPIO
UART TX on GPIO#
Found in: Component config > Application Level Tracing
This GPIO is used for UART TX pin.
CONFIG_APPTRACE_UART_RX_GPIO
UART RX on GPIO#
Found in: Component config > Application Level Tracing
CONFIG_APPTRACE_UART_BAUDRATE
UART baud rate
Found in: Component config > Application Level Tracing
This baud rate is used for UART.
The app’s maximum baud rate depends on the UART clock source. If Power Management is disabled,
the UART clock source is the APB clock and all baud rates in the available range will be sufficiently
accurate. If Power Management is enabled, REF_TICK clock source is used so the baud rate is divided
from 1MHz. Baud rates above 1Mbps are not possible and values between 500Kbps and 1Mbps may
not be accurate.
CONFIG_APPTRACE_UART_RX_BUFF_SIZE
UART RX ring buffer size
Found in: Component config > Application Level Tracing
Size of the UART input ring buffer. This size related to the baudrate, system tick frequency and amount
of data to transfer. The data placed to this buffer before sent out to the interface.
CONFIG_APPTRACE_UART_TX_BUFF_SIZE
UART TX ring buffer size
Found in: Component config > Application Level Tracing
Size of the UART output ring buffer. This size related to the baudrate, system tick frequency and amount
of data to transfer.
CONFIG_APPTRACE_UART_TX_MSG_SIZE
UART TX message size
Found in: Component config > Application Level Tracing
Maximum size of the single message to transfer.
CONFIG_APPTRACE_UART_TASK_PRIO
UART Task Priority
Found in: Component config > Application Level Tracing
UART task priority. In case of high events rate, this parameter could be changed up to (config-
MAX_PRIORITIES-1).
Range:
• from 1 to 32
Default value:
• 1
CONFIG_APPTRACE_ONPANIC_HOST_FLUSH_TMO
Timeout for flushing last trace data to host on panic
Found in: Component config > Application Level Tracing
Timeout for flushing last trace data to host in case of panic. In ms. Use -1 to disable timeout and wait
forever.
CONFIG_APPTRACE_POSTMORTEM_FLUSH_THRESH
Threshold for flushing last trace data to host on panic
Found in: Component config > Application Level Tracing
Threshold for flushing last trace data to host on panic in post-mortem mode. This is minimal amount of
data needed to perform flush. In bytes.
CONFIG_APPTRACE_BUF_SIZE
Size of the apptrace buffer
Found in: Component config > Application Level Tracing
Size of the memory buffer for trace data in bytes.
CONFIG_APPTRACE_PENDING_DATA_SIZE_MAX
Size of the pending data buffer
Found in: Component config > Application Level Tracing
Size of the buffer for events in bytes. It is useful for buffering events from the time critical code (sched-
uler, ISRs etc). If this parameter is 0 then events will be discarded when main HW buffer is full.
CONFIG_APPTRACE_SV_ENABLE
SystemView Tracing Enable
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Enables supporrt for SEGGER SystemView tracing functionality.
CONFIG_APPTRACE_SV_DEST
SystemView destination
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing > CON-
FIG_APPTRACE_SV_ENABLE
SystemView witt transfer data trough defined interface.
Available options:
• Data destination JTAG (APPTRACE_SV_DEST_JTAG)
Send SEGGER SystemView events through JTAG interface.
• Data destination UART (APPTRACE_SV_DEST_UART)
Send SEGGER SystemView events through UART interface.
CONFIG_APPTRACE_SV_CPU
CPU to trace
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Define the CPU to trace by SystemView.
Available options:
• CPU0 (APPTRACE_SV_DEST_CPU_0)
Send SEGGER SystemView events for Pro CPU.
• CPU1 (APPTRACE_SV_DEST_CPU_1)
Send SEGGER SystemView events for App CPU.
CONFIG_APPTRACE_SV_TS_SOURCE
Timer to use as timestamp source
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
SystemView needs to use a hardware timer as the source of timestamps when tracing. This option selects
the timer for it.
Available options:
• CPU cycle counter (CCOUNT) (APPTRACE_SV_TS_SOURCE_CCOUNT)
• General Purpose Timer (Timer Group) (APPTRACE_SV_TS_SOURCE_GPTIMER)
• esp_timer high resolution timer (APPTRACE_SV_TS_SOURCE_ESP_TIMER)
CONFIG_APPTRACE_SV_MAX_TASKS
Maximum supported tasks
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Configures maximum supported tasks in sysview debug
CONFIG_APPTRACE_SV_BUF_WAIT_TMO
Trace buffer wait timeout
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Configures timeout (in us) to wait for free space in trace buffer. Set to -1 to wait forever and avoid lost
events.
CONFIG_APPTRACE_SV_EVT_OVERFLOW_ENABLE
Trace Buffer Overflow Event
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Enables “Trace Buffer Overflow”event.
CONFIG_APPTRACE_SV_EVT_ISR_ENTER_ENABLE
ISR Enter Event
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Enables “ISR Enter”event.
CONFIG_APPTRACE_SV_EVT_ISR_EXIT_ENABLE
ISR Exit Event
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Enables “ISR Exit”event.
CONFIG_APPTRACE_SV_EVT_ISR_TO_SCHED_ENABLE
ISR Exit to Scheduler Event
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Enables “ISR to Scheduler”event.
CONFIG_APPTRACE_SV_EVT_TASK_START_EXEC_ENABLE
Task Start Execution Event
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Enables “Task Start Execution”event.
CONFIG_APPTRACE_SV_EVT_TASK_STOP_EXEC_ENABLE
Task Stop Execution Event
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Enables “Task Stop Execution”event.
CONFIG_APPTRACE_SV_EVT_TASK_START_READY_ENABLE
Task Start Ready State Event
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Enables “Task Start Ready State”event.
CONFIG_APPTRACE_SV_EVT_TASK_STOP_READY_ENABLE
Task Stop Ready State Event
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Enables “Task Stop Ready State”event.
CONFIG_APPTRACE_SV_EVT_TASK_CREATE_ENABLE
Task Create Event
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Enables “Task Create”event.
CONFIG_APPTRACE_SV_EVT_TASK_TERMINATE_ENABLE
Task Terminate Event
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Enables “Task Terminate”event.
CONFIG_APPTRACE_SV_EVT_IDLE_ENABLE
System Idle Event
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Enables “System Idle”event.
CONFIG_APPTRACE_SV_EVT_TIMER_ENTER_ENABLE
Timer Enter Event
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Enables “Timer Enter”event.
CONFIG_APPTRACE_SV_EVT_TIMER_EXIT_ENABLE
Timer Exit Event
Found in: Component config > Application Level Tracing > FreeRTOS SystemView Tracing
Enables “Timer Exit”event.
CONFIG_APPTRACE_GCOV_ENABLE
GCOV to Host Enable
Found in: Component config > Application Level Tracing
Enables support for GCOV data transfer to host.
Bluetooth Contains:
• Bluedroid Options
• CONFIG_BT_ENABLED
• Controller Options
• NimBLE Options
CONFIG_BT_ENABLED
Bluetooth
Found in: Component config > Bluetooth
Select this option to enable Bluetooth and show the submenu with Bluetooth configuration choices.
CONFIG_BT_HOST
Host
Found in: Component config > Bluetooth > CONFIG_BT_ENABLED
This helps to choose Bluetooth host stack
Available options:
CONFIG_BT_CONTROLLER
Controller
Found in: Component config > Bluetooth > CONFIG_BT_ENABLED
This helps to choose Bluetooth controller stack
Available options:
• Enabled (BT_CONTROLLER_ENABLED)
This option is recommended for Bluetooth controller usecases
• Disabled (BT_CONTROLLER_DISABLED)
This option is recommended for Bluetooth Host only usecases
CONFIG_BT_BTC_TASK_STACK_SIZE
Bluetooth event (callback to application) task stack size
Found in: Component config > Bluetooth > Bluedroid Options
This select btc task stack size
Default value:
• 3072 if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_BLUEDROID_PINNED_TO_CORE_CHOICE
The cpu core which Bluedroid run
Found in: Component config > Bluetooth > Bluedroid Options
Which the cpu core to run Bluedroid. Can choose core0 and core1. Can not specify no-affinity.
Available options:
• Core 0 (PRO CPU) (BT_BLUEDROID_PINNED_TO_CORE_0)
• Core 1 (APP CPU) (BT_BLUEDROID_PINNED_TO_CORE_1)
CONFIG_BT_BTU_TASK_STACK_SIZE
Bluetooth Bluedroid Host Stack task stack size
Found in: Component config > Bluetooth > Bluedroid Options
This select btu task stack size
Default value:
• 4096 if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_BLUEDROID_MEM_DEBUG
Bluedroid memory debug
Found in: Component config > Bluetooth > Bluedroid Options
Bluedroid memory debug
Default value:
• No (disabled) if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_CLASSIC_ENABLED
Classic Bluetooth
Found in: Component config > Bluetooth > Bluedroid Options
For now this option needs “SMP_ENABLE”to be set to yes
Default value:
• No (disabled) if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_A2DP_ENABLE
A2DP
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED
Advanced Audio Distrubution Profile
Default value:
• No (disabled) if CONFIG_BT_CLASSIC_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_SPP_ENABLED
SPP
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED
This enables the Serial Port Profile
Default value:
• No (disabled) if CONFIG_BT_CLASSIC_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_L2CAP_ENABLED
BT L2CAP
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED
This enables the Logical Link Control and Adaptation Layer Protocol. Only supported classic bluetooth.
Default value:
• No (disabled) if CONFIG_BT_CLASSIC_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_HFP_ENABLE
Hands Free/Handset Profile
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED
Default value:
• No (disabled) if CONFIG_BT_CLASSIC_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_HFP_ROLE
Hands-free Profile Role configuration
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED >
CONFIG_BT_HFP_ENABLE
Available options:
• Hands Free Unit (BT_HFP_CLIENT_ENABLE)
• Audio Gateway (BT_HFP_AG_ENABLE)
CONFIG_BT_HFP_AUDIO_DATA_PATH
audio(SCO) data path
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_CLASSIC_ENABLED >
CONFIG_BT_HFP_ENABLE
SCO data path, i.e. HCI or PCM. This option is set using API “esp_bredr_sco_datapath_set”in
Bluetooth host. Default SCO data path can also be set in Bluetooth Controller.
Available options:
• PCM (BT_HFP_AUDIO_DATA_PATH_PCM)
• HCI (BT_HFP_AUDIO_DATA_PATH_HCI)
CONFIG_BT_HFP_WBS_ENABLE
Wide Band Speech
Found in: Component config > Bluetooth > Bluedroid Options
This enables Wide Band Speech. Should disable it when SCO data path is PCM. Otherwise there will
be no data transmited via GPIOs.
Default value:
• Yes (enabled) if BT_HFP_AUDIO_DATA_PATH_HCI &&
BT_BLUEDROID_ENABLED
CONFIG_BT_HID_ENABLED
Classic BT HID
Found in: Component config > Bluetooth > Bluedroid Options
This enables the BT HID Host
Default value:
• No (disabled) if CONFIG_BT_CLASSIC_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_HID_ROLE
Profile Role configuration
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_HID_ENABLED
Available options:
• Classic BT HID Host (BT_HID_HOST_ENABLED)
This enables the BT HID Host
• Classic BT HID Device (BT_HID_DEVICE_ENABLED)
This enables the BT HID Device
CONFIG_BT_SSP_ENABLED
Secure Simple Pairing
Found in: Component config > Bluetooth > Bluedroid Options
This enables the Secure Simple Pairing. If disable this option, Bluedroid will only support Legacy Pairing
Default value:
• Yes (enabled) if CONFIG_BT_CLASSIC_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_BLE_ENABLED
Bluetooth Low Energy
Found in: Component config > Bluetooth > Bluedroid Options
This enables Bluetooth Low Energy
Default value:
• Yes (enabled) if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_GATTS_ENABLE
Include GATT server module(GATTS)
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED
This option can be disabled when the app work only on gatt client mode
Default value:
• Yes (enabled) if CONFIG_BT_BLE_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_GATTS_PPCP_CHAR_GAP
Enable Peripheral Preferred Connection Parameters characteristic in GAP service
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CON-
FIG_BT_GATTS_ENABLE
This enables “Peripheral Preferred Connection Parameters”characteristic (UUID: 0x2A04) in GAP
service that has connection parameters like min/max connection interval, slave latency and supervision
timeout multiplier
Default value:
• No (disabled) if CONFIG_BT_GATTS_ENABLE && BT_BLUEDROID_ENABLED
CONFIG_BT_BLE_BLUFI_ENABLE
Include blufi function
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CON-
FIG_BT_GATTS_ENABLE
This option can be close when the app does not require blufi function.
Default value:
• No (disabled) if CONFIG_BT_GATTS_ENABLE && BT_BLUEDROID_ENABLED
CONFIG_BT_GATT_MAX_SR_PROFILES
Max GATT Server Profiles
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CON-
FIG_BT_GATTS_ENABLE
Maximum GATT Server Profiles Count
Range:
• from 1 to 32 if CONFIG_BT_GATTS_ENABLE && BT_BLUEDROID_ENABLED &&
BT_BLUEDROID_ENABLED
Default value:
• 8 if CONFIG_BT_GATTS_ENABLE && BT_BLUEDROID_ENABLED &&
BT_BLUEDROID_ENABLED
CONFIG_BT_GATTS_SEND_SERVICE_CHANGE_MODE
GATTS Service Change Mode
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CON-
FIG_BT_GATTS_ENABLE
Service change indication mode for GATT Server.
Available options:
• GATTS manually send service change indication (BT_GATTS_SEND_SERVICE_CHANGE_MANUAL)
Manually send service change indication through API
esp_ble_gatts_send_service_change_indication()
• GATTS automatically send service change indication
(BT_GATTS_SEND_SERVICE_CHANGE_AUTO)
Let Bluedroid handle the service change indication internally
CONFIG_BT_GATTC_ENABLE
Include GATT client module(GATTC)
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED
This option can be close when the app work only on gatt server mode
Default value:
• Yes (enabled) if CONFIG_BT_BLE_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_GATTC_CACHE_NVS_FLASH
Save gattc cache data to nvs flash
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CON-
FIG_BT_GATTC_ENABLE
This select can save gattc cache data to nvs flash
Default value:
• No (disabled) if CONFIG_BT_GATTC_ENABLE && BT_BLUEDROID_ENABLED
CONFIG_BT_GATTC_CONNECT_RETRY_COUNT
The number of attempts to reconnect if the connection establishment failed
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CON-
FIG_BT_GATTC_ENABLE
The number of attempts to reconnect if the connection establishment failed
Range:
• from 0 to 7 if CONFIG_BT_GATTC_ENABLE && BT_BLUEDROID_ENABLED
Default value:
• 3 if CONFIG_BT_GATTC_ENABLE && BT_BLUEDROID_ENABLED
CONFIG_BT_BLE_SMP_ENABLE
Include BLE security module(SMP)
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED
This option can be close when the app not used the ble security connect.
Default value:
• Yes (enabled) if CONFIG_BT_BLE_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_SMP_SLAVE_CON_PARAMS_UPD_ENABLE
Slave enable connection parameters update during pairing
Found in: Component config > Bluetooth > Bluedroid Options > CONFIG_BT_BLE_ENABLED > CON-
FIG_BT_BLE_SMP_ENABLE
In order to reduce the pairing time, slave actively initiates connection parameters update during pairing.
Default value:
• No (disabled) if CONFIG_BT_BLE_SMP_ENABLE && BT_BLUEDROID_ENABLED
CONFIG_BT_STACK_NO_LOG
Disable BT debug logs (minimize bin size)
Found in: Component config > Bluetooth > Bluedroid Options
This select can save the rodata code size
Default value:
• No (disabled) if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
• CONFIG_BT_LOG_GAP_TRACE_LEVEL
• CONFIG_BT_LOG_GATT_TRACE_LEVEL
• CONFIG_BT_LOG_HCI_TRACE_LEVEL
• CONFIG_BT_LOG_HID_TRACE_LEVEL
• CONFIG_BT_LOG_L2CAP_TRACE_LEVEL
• CONFIG_BT_LOG_MCA_TRACE_LEVEL
• CONFIG_BT_LOG_OSI_TRACE_LEVEL
• CONFIG_BT_LOG_PAN_TRACE_LEVEL
• CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL
• CONFIG_BT_LOG_SDP_TRACE_LEVEL
• CONFIG_BT_LOG_SMP_TRACE_LEVEL
CONFIG_BT_LOG_HCI_TRACE_LEVEL
HCI layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for HCI layer
Available options:
• NONE (BT_LOG_HCI_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_HCI_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_HCI_TRACE_LEVEL_WARNING)
• API (BT_LOG_HCI_TRACE_LEVEL_API)
• EVENT (BT_LOG_HCI_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_HCI_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_HCI_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_BTM_TRACE_LEVEL
BTM layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for BTM layer
Available options:
• NONE (BT_LOG_BTM_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_BTM_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_BTM_TRACE_LEVEL_WARNING)
• API (BT_LOG_BTM_TRACE_LEVEL_API)
• EVENT (BT_LOG_BTM_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_BTM_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_BTM_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_L2CAP_TRACE_LEVEL
L2CAP layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for L2CAP layer
Available options:
• NONE (BT_LOG_L2CAP_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_L2CAP_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_L2CAP_TRACE_LEVEL_WARNING)
• API (BT_LOG_L2CAP_TRACE_LEVEL_API)
• EVENT (BT_LOG_L2CAP_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_L2CAP_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_L2CAP_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL
RFCOMM layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for RFCOMM layer
Available options:
• NONE (BT_LOG_RFCOMM_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_RFCOMM_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_RFCOMM_TRACE_LEVEL_WARNING)
• API (BT_LOG_RFCOMM_TRACE_LEVEL_API)
• EVENT (BT_LOG_RFCOMM_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_RFCOMM_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_RFCOMM_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_SDP_TRACE_LEVEL
SDP layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for SDP layer
Available options:
• NONE (BT_LOG_SDP_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_SDP_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_SDP_TRACE_LEVEL_WARNING)
• API (BT_LOG_SDP_TRACE_LEVEL_API)
• EVENT (BT_LOG_SDP_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_SDP_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_SDP_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_GAP_TRACE_LEVEL
GAP layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for GAP layer
Available options:
• NONE (BT_LOG_GAP_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_GAP_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_GAP_TRACE_LEVEL_WARNING)
• API (BT_LOG_GAP_TRACE_LEVEL_API)
• EVENT (BT_LOG_GAP_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_GAP_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_GAP_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_BNEP_TRACE_LEVEL
BNEP layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for BNEP layer
Available options:
• NONE (BT_LOG_BNEP_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_BNEP_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_BNEP_TRACE_LEVEL_WARNING)
• API (BT_LOG_BNEP_TRACE_LEVEL_API)
• EVENT (BT_LOG_BNEP_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_BNEP_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_BNEP_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_PAN_TRACE_LEVEL
PAN layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for PAN layer
Available options:
• NONE (BT_LOG_PAN_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_PAN_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_PAN_TRACE_LEVEL_WARNING)
• API (BT_LOG_PAN_TRACE_LEVEL_API)
• EVENT (BT_LOG_PAN_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_PAN_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_PAN_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_A2D_TRACE_LEVEL
A2D layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for A2D layer
Available options:
• NONE (BT_LOG_A2D_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_A2D_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_A2D_TRACE_LEVEL_WARNING)
• API (BT_LOG_A2D_TRACE_LEVEL_API)
• EVENT (BT_LOG_A2D_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_A2D_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_A2D_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_AVDT_TRACE_LEVEL
AVDT layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for AVDT layer
Available options:
• NONE (BT_LOG_AVDT_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_AVDT_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_AVDT_TRACE_LEVEL_WARNING)
• API (BT_LOG_AVDT_TRACE_LEVEL_API)
• EVENT (BT_LOG_AVDT_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_AVDT_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_AVDT_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_AVCT_TRACE_LEVEL
AVCT layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for AVCT layer
Available options:
• NONE (BT_LOG_AVCT_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_AVCT_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_AVCT_TRACE_LEVEL_WARNING)
• API (BT_LOG_AVCT_TRACE_LEVEL_API)
• EVENT (BT_LOG_AVCT_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_AVCT_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_AVCT_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_AVRC_TRACE_LEVEL
AVRC layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for AVRC layer
Available options:
• NONE (BT_LOG_AVRC_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_AVRC_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_AVRC_TRACE_LEVEL_WARNING)
• API (BT_LOG_AVRC_TRACE_LEVEL_API)
• EVENT (BT_LOG_AVRC_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_AVRC_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_AVRC_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_MCA_TRACE_LEVEL
MCA layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for MCA layer
Available options:
• NONE (BT_LOG_MCA_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_MCA_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_MCA_TRACE_LEVEL_WARNING)
• API (BT_LOG_MCA_TRACE_LEVEL_API)
• EVENT (BT_LOG_MCA_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_MCA_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_MCA_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_HID_TRACE_LEVEL
HID layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for HID layer
Available options:
• NONE (BT_LOG_HID_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_HID_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_HID_TRACE_LEVEL_WARNING)
• API (BT_LOG_HID_TRACE_LEVEL_API)
• EVENT (BT_LOG_HID_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_HID_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_HID_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_APPL_TRACE_LEVEL
APPL layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for APPL layer
Available options:
• NONE (BT_LOG_APPL_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_APPL_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_APPL_TRACE_LEVEL_WARNING)
• API (BT_LOG_APPL_TRACE_LEVEL_API)
• EVENT (BT_LOG_APPL_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_APPL_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_APPL_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_GATT_TRACE_LEVEL
GATT layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for GATT layer
Available options:
• NONE (BT_LOG_GATT_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_GATT_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_GATT_TRACE_LEVEL_WARNING)
• API (BT_LOG_GATT_TRACE_LEVEL_API)
• EVENT (BT_LOG_GATT_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_GATT_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_GATT_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_SMP_TRACE_LEVEL
SMP layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for SMP layer
Available options:
• NONE (BT_LOG_SMP_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_SMP_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_SMP_TRACE_LEVEL_WARNING)
• API (BT_LOG_SMP_TRACE_LEVEL_API)
• EVENT (BT_LOG_SMP_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_SMP_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_SMP_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_BTIF_TRACE_LEVEL
BTIF layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for BTIF layer
Available options:
• NONE (BT_LOG_BTIF_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_BTIF_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_BTIF_TRACE_LEVEL_WARNING)
• API (BT_LOG_BTIF_TRACE_LEVEL_API)
• EVENT (BT_LOG_BTIF_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_BTIF_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_BTIF_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_BTC_TRACE_LEVEL
BTC layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for BTC layer
Available options:
• NONE (BT_LOG_BTC_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_BTC_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_BTC_TRACE_LEVEL_WARNING)
• API (BT_LOG_BTC_TRACE_LEVEL_API)
• EVENT (BT_LOG_BTC_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_BTC_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_BTC_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_OSI_TRACE_LEVEL
OSI layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for OSI layer
Available options:
• NONE (BT_LOG_OSI_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_OSI_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_OSI_TRACE_LEVEL_WARNING)
• API (BT_LOG_OSI_TRACE_LEVEL_API)
• EVENT (BT_LOG_OSI_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_OSI_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_OSI_TRACE_LEVEL_VERBOSE)
CONFIG_BT_LOG_BLUFI_TRACE_LEVEL
BLUFI layer
Found in: Component config > Bluetooth > Bluedroid Options > BT DEBUG LOG LEVEL
Define BT trace level for BLUFI layer
Available options:
• NONE (BT_LOG_BLUFI_TRACE_LEVEL_NONE)
• ERROR (BT_LOG_BLUFI_TRACE_LEVEL_ERROR)
• WARNING (BT_LOG_BLUFI_TRACE_LEVEL_WARNING)
• API (BT_LOG_BLUFI_TRACE_LEVEL_API)
• EVENT (BT_LOG_BLUFI_TRACE_LEVEL_EVENT)
• DEBUG (BT_LOG_BLUFI_TRACE_LEVEL_DEBUG)
• VERBOSE (BT_LOG_BLUFI_TRACE_LEVEL_VERBOSE)
CONFIG_BT_ACL_CONNECTIONS
BT/BLE MAX ACL CONNECTIONS(1~7)
Found in: Component config > Bluetooth > Bluedroid Options
Maximum BT/BLE connection count
Range:
• from 1 to 7 if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
Default value:
• 4 if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_MULTI_CONNECTION_ENBALE
Enable BLE multi-conections
Found in: Component config > Bluetooth > Bluedroid Options
Enable this option if there are multiple connections
Default value:
• Yes (enabled) if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_ALLOCATION_FROM_SPIRAM_FIRST
BT/BLE will first malloc the memory from the PSRAM
Found in: Component config > Bluetooth > Bluedroid Options
This select can save the internal RAM if there have the PSRAM
Default value:
• No (disabled) if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_BLE_DYNAMIC_ENV_MEMORY
Use dynamic memory allocation in BT/BLE stack
Found in: Component config > Bluetooth > Bluedroid Options
This select can make the allocation of memory will become more flexible
Default value:
• No (disabled) if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_BLE_HOST_QUEUE_CONG_CHECK
BLE queue congestion check
Found in: Component config > Bluetooth > Bluedroid Options
When scanning and scan duplicate is not enabled, if there are a lot of adv packets around or application
layer handling adv packets is slow, it will cause the controller memory to run out. if enabled, adv packets
will be lost when host queue is congested.
Default value:
• No (disabled) if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_BLE_ACT_SCAN_REP_ADV_SCAN
Report adv data and scan response individually when BLE active scan
Found in: Component config > Bluetooth > Bluedroid Options
Originally, when doing BLE active scan, Bluedroid will not report adv to application layer until receive
scan response. This option is used to disable the behavior. When enable this option, Bluedroid will
report adv data or scan response to application layer immediately.
# Memory reserved at start of DRAM for Bluetooth stack
Default value:
CONFIG_BT_BLE_ESTAB_LINK_CONN_TOUT
Timeout of BLE connection establishment
Found in: Component config > Bluetooth > Bluedroid Options
Bluetooth Connection establishment maximum time, if connection time exceeds this value, the connec-
tion establishment fails, ESP_GATTC_OPEN_EVT or ESP_GATTS_OPEN_EVT is triggered.
Range:
• from 1 to 60 if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
Default value:
• 30 if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_MAX_DEVICE_NAME_LEN
length of bluetooth device name
Found in: Component config > Bluetooth > Bluedroid Options
Bluetooth Device name length shall be no larger than 248 octets, If the broadcast data cannot contain
the complete device name, then only the shortname will be displayed, the rest parts that can’t fit in will
be truncated.
Range:
• from 32 to 248 if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
Default value:
• 32 if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_BLE_RPA_SUPPORTED
Update RPA to Controller
Found in: Component config > Bluetooth > Bluedroid Options
This enables controller RPA list function. For ESP32, ESP32 only support network privacy mode. If
this option is enabled, ESP32 will only accept advertising packets from peer devices that contain private
address, HW will not receive the advertising packets contain identity address after IRK changed. If this
option is disabled, address resolution will be performed in the host, so the functions that require controller
to resolve address in the white list cannot be used. This option is disabled by default on ESP32, please
enable or disable this option according to your own needs.
For ESP32C3, ESP32S3, ESP32H2 and ESP32C2, devices support network privacy mode and device
privacy mode, users can switch the two modes according to their own needs. So this option is enabled
by default.
Default value:
• No (disabled) if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
• Yes (enabled) if BT_BLUEDROID_ENABLED && BT_BLUEDROID_ENABLED
CONFIG_BT_BLE_50_FEATURES_SUPPORTED
Enable BLE 5.0 features
Found in: Component config > Bluetooth > Bluedroid Options
This enables BLE 5.0 features, this option only support esp32c3/esp32s3 chip
Default value:
• Yes (enabled) if BT_BLUEDROID_ENABLED && SOC_ESP_NIMBLE_CONTROLLER
&& BT_BLUEDROID_ENABLED
CONFIG_BT_BLE_42_FEATURES_SUPPORTED
Enable BLE 4.2 features
Found in: Component config > Bluetooth > Bluedroid Options
This enables BLE 4.2 features.
Default value:
• No (disabled) if BT_BLUEDROID_ENABLED && SOC_ESP_NIMBLE_CONTROLLER
&& BT_BLUEDROID_ENABLED
CONFIG_BT_NIMBLE_MEM_ALLOC_MODE
Memory allocation strategy
Found in: Component config > Bluetooth > NimBLE Options
Allocation strategy for NimBLE host stack, essentially provides ability to allocate all required dynamic
allocations from,
• Internal DRAM memory only
• External SPIRAM memory only
• Either internal or external memory based on default malloc() behavior in ESP-IDF
• Internal IRAM memory wherever applicable else internal DRAM
Available options:
CONFIG_BT_NIMBLE_LOG_LEVEL
NimBLE Host log verbosity
Found in: Component config > Bluetooth > NimBLE Options
Select NimBLE log level. Please make a note that the selected NimBLE log verbosity can not exceed
the level set in “Component config –> Log output –> Default log verbosity”.
Available options:
• No logs (BT_NIMBLE_LOG_LEVEL_NONE)
• Error logs (BT_NIMBLE_LOG_LEVEL_ERROR)
• Warning logs (BT_NIMBLE_LOG_LEVEL_WARNING)
• Info logs (BT_NIMBLE_LOG_LEVEL_INFO)
• Debug logs (BT_NIMBLE_LOG_LEVEL_DEBUG)
CONFIG_BT_NIMBLE_MAX_CONNECTIONS
Maximum number of concurrent connections
Found in: Component config > Bluetooth > NimBLE Options
Defines maximum number of concurrent BLE connections. For ESP32, user is expected to configure
BTDM_CTRL_BLE_MAX_CONN from controller menu along with this option. Similarly for ESP32-
C3 or ESP32-S3, user is expected to configure BT_CTRL_BLE_MAX_ACT from controller menu.
Range:
• from 1 to 9 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MAX_BONDS
Maximum number of bonds to save across reboots
Found in: Component config > Bluetooth > NimBLE Options
Defines maximum number of bonds to save for peer security and our security
Default value:
• 3 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MAX_CCCDS
Maximum number of CCC descriptors to save across reboots
Found in: Component config > Bluetooth > NimBLE Options
Defines maximum number of CCC descriptors to save
Default value:
• 8 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_L2CAP_COC_MAX_NUM
Maximum number of connection oriented channels
Found in: Component config > Bluetooth > NimBLE Options
Defines maximum number of BLE Connection Oriented Channels. When set to (0), BLE COC is not
compiled in
Range:
• from 0 to 9 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
Default value:
• 0 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_PINNED_TO_CORE_CHOICE
The CPU core on which NimBLE host will run
Found in: Component config > Bluetooth > NimBLE Options
The CPU core on which NimBLE host will run. You can choose Core 0 or Core 1. Cannot specify
no-affinity
Available options:
• Core 0 (PRO CPU) (BT_NIMBLE_PINNED_TO_CORE_0)
• Core 1 (APP CPU) (BT_NIMBLE_PINNED_TO_CORE_1)
CONFIG_BT_NIMBLE_HOST_TASK_STACK_SIZE
NimBLE Host task stack size
Found in: Component config > Bluetooth > NimBLE Options
This configures stack size of NimBLE host task
Default value:
• 5120 if CONFIG_BLE_MESH && BT_NIMBLE_ENABLED &&
BT_NIMBLE_ENABLED
• 4096 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_ROLE_CENTRAL
Enable BLE Central role
Found in: Component config > Bluetooth > NimBLE Options
Enables central role
Default value:
• Yes (enabled) if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_ROLE_PERIPHERAL
Enable BLE Peripheral role
Found in: Component config > Bluetooth > NimBLE Options
Enable peripheral role
Default value:
• Yes (enabled) if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_ROLE_BROADCASTER
Enable BLE Broadcaster role
Found in: Component config > Bluetooth > NimBLE Options
Enables broadcaster role
Default value:
• Yes (enabled) if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_ROLE_OBSERVER
Enable BLE Observer role
Found in: Component config > Bluetooth > NimBLE Options
Enables observer role
Default value:
• Yes (enabled) if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_NVS_PERSIST
Persist the BLE Bonding keys in NVS
Found in: Component config > Bluetooth > NimBLE Options
Enable this flag to make bonding persistent across device reboots
Default value:
• No (disabled) if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_SECURITY_ENABLE
Enable BLE SM feature
Found in: Component config > Bluetooth > NimBLE Options
Enable BLE sm feature
Default value:
• Yes (enabled) if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
Contains:
• CONFIG_BT_NIMBLE_LL_CFG_FEAT_LE_ENCRYPTION
• CONFIG_BT_NIMBLE_SM_LEGACY
• CONFIG_BT_NIMBLE_SM_SC
CONFIG_BT_NIMBLE_SM_LEGACY
Security manager legacy pairing
Found in: Component config > Bluetooth > NimBLE Options > CON-
FIG_BT_NIMBLE_SECURITY_ENABLE
Enable security manager legacy pairing
Default value:
• Yes (enabled) if CONFIG_BT_NIMBLE_SECURITY_ENABLE &&
BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_SM_SC
Security manager secure connections (4.2)
Found in: Component config > Bluetooth > NimBLE Options > CON-
FIG_BT_NIMBLE_SECURITY_ENABLE
Enable security manager secure connections
Default value:
• Yes (enabled) if CONFIG_BT_NIMBLE_SECURITY_ENABLE &&
BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_SM_SC_DEBUG_KEYS
Use predefined public-private key pair
Found in: Component config > Bluetooth > NimBLE Options > CON-
FIG_BT_NIMBLE_SECURITY_ENABLE > CONFIG_BT_NIMBLE_SM_SC
If this option is enabled, SM uses predefined DH key pair as described in Core Specification, Vol. 3,
Part H, 2.3.5.6.1. This allows to decrypt air traffic easily and thus should only be used for debugging.
Default value:
• No (disabled) if CONFIG_BT_NIMBLE_SECURITY_ENABLE && CON-
FIG_BT_NIMBLE_SM_SC && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_LL_CFG_FEAT_LE_ENCRYPTION
Enable LE encryption
Found in: Component config > Bluetooth > NimBLE Options > CON-
FIG_BT_NIMBLE_SECURITY_ENABLE
Enable encryption connection
Default value:
• Yes (enabled) if CONFIG_BT_NIMBLE_SECURITY_ENABLE &&
BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_DEBUG
Enable extra runtime asserts and host debugging
Found in: Component config > Bluetooth > NimBLE Options
This enables extra runtime asserts and host debugging
Default value:
• No (disabled) if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_SVC_GAP_DEVICE_NAME
BLE GAP default device name
Found in: Component config > Bluetooth > NimBLE Options
The Device Name characteristic shall contain the name of the device as an UTF-8 string. This name
can be changed by using API ble_svc_gap_device_name_set()
Default value:
• “nimble”if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_GAP_DEVICE_NAME_MAX_LEN
Maximum length of BLE device name in octets
Found in: Component config > Bluetooth > NimBLE Options
Device Name characteristic value shall be 0 to 248 octets in length
Default value:
• 31 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_ATT_PREFERRED_MTU
Preferred MTU size in octets
Found in: Component config > Bluetooth > NimBLE Options
This is the default value of ATT MTU indicated by the device during an ATT MTU exchange. This
value can be changed using API ble_att_set_preferred_mtu()
Default value:
• 256 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_SVC_GAP_APPEARANCE
External appearance of the device
Found in: Component config > Bluetooth > NimBLE Options
Standard BLE GAP Appearance value in HEX format e.g. 0x02C0
Default value:
• 0 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MSYS_1_BLOCK_COUNT
MSYS_1 Block Count
Found in: Component config > Bluetooth > NimBLE Options > Memory Settings
MSYS is a system level mbuf registry. For prepare write & prepare responses MBUFs are allocated
out of msys_1 pool. For NIMBLE_MESH enabled cases, this block count is increased by 8 than user
defined count.
Default value:
• 12 if BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MSYS_1_BLOCK_SIZE
MSYS_1 Block Size
Found in: Component config > Bluetooth > NimBLE Options > Memory Settings
Dynamic memory size of block 1
Default value:
• 256 if BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MSYS_2_BLOCK_COUNT
MSYS_2 Block Count
Found in: Component config > Bluetooth > NimBLE Options > Memory Settings
Dynamic memory count
Default value:
• 24 if BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MSYS_2_BLOCK_SIZE
MSYS_2 Block Size
Found in: Component config > Bluetooth > NimBLE Options > Memory Settings
Dynamic memory size of block 2
Default value:
• 320 if BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_ACL_BUF_COUNT
ACL Buffer count
Found in: Component config > Bluetooth > NimBLE Options > Memory Settings
The number of ACL data buffers.
Default value:
• 24 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_ACL_BUF_SIZE
ACL Buffer size
Found in: Component config > Bluetooth > NimBLE Options > Memory Settings
This is the maximum size of the data portion of HCI ACL data packets. It does not include the HCI
data header (of 4 bytes)
Default value:
• 255 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_HCI_EVT_BUF_SIZE
HCI Event Buffer size
Found in: Component config > Bluetooth > NimBLE Options > Memory Settings
This is the size of each HCI event buffer in bytes. In case of extended advertising, packets can be
fragmented. 257 bytes is the maximum size of a packet.
Default value:
CONFIG_BT_NIMBLE_HCI_EVT_HI_BUF_COUNT
High Priority HCI Event Buffer count
Found in: Component config > Bluetooth > NimBLE Options > Memory Settings
This is the high priority HCI events’buffer size. High-priority event buffers are for everything except
advertising reports. If there are no free high-priority event buffers then host will try to allocate a low-
priority buffer instead
Default value:
• 30 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_HCI_EVT_LO_BUF_COUNT
Low Priority HCI Event Buffer count
Found in: Component config > Bluetooth > NimBLE Options > Memory Settings
This is the low priority HCI events’buffer size. Low-priority event buffers are only used for advertising
reports. If there are no free low-priority event buffers, then an incoming advertising report will get
dropped
Default value:
• 8 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_HS_FLOW_CTRL
Enable Host Flow control
Found in: Component config > Bluetooth > NimBLE Options
Enable Host Flow control
Default value:
• Yes (enabled) if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
• No (disabled) if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_HS_FLOW_CTRL_ITVL
Host Flow control interval
Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_HS_FLOW_CTRL
Host flow control interval in msecs
Default value:
• 1000 if CONFIG_BT_NIMBLE_HS_FLOW_CTRL && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_HS_FLOW_CTRL_THRESH
Host Flow control threshold
Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_HS_FLOW_CTRL
Host flow control threshold, if the number of free buffers are at or below this threshold, send an imme-
diate number-of-completed-packets event
Default value:
• 2 if CONFIG_BT_NIMBLE_HS_FLOW_CTRL && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_HS_FLOW_CTRL_TX_ON_DISCONNECT
Host Flow control on disconnect
Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_HS_FLOW_CTRL
Enable this option to send number-of-completed-packets event to controller after disconnection
Default value:
• Yes (enabled) if CONFIG_BT_NIMBLE_HS_FLOW_CTRL && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_RPA_TIMEOUT
RPA timeout in seconds
Found in: Component config > Bluetooth > NimBLE Options
Time interval between RPA address change. This is applicable in case of Host based RPA
Range:
• from 1 to 41400 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
Default value:
• 900 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MESH
Enable BLE mesh functionality
Found in: Component config > Bluetooth > NimBLE Options
Enable BLE Mesh functionality
Default value:
• No (disabled) if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
Contains:
• CONFIG_BT_NIMBLE_MESH_PROVISIONER
• CONFIG_BT_NIMBLE_MESH_PROV
• CONFIG_BT_NIMBLE_MESH_GATT_PROXY
• CONFIG_BT_NIMBLE_MESH_FRIEND
• CONFIG_BT_NIMBLE_MESH_LOW_POWER
• CONFIG_BT_NIMBLE_MESH_PROXY
• CONFIG_BT_NIMBLE_MESH_RELAY
• CONFIG_BT_NIMBLE_MESH_DEVICE_NAME
• CONFIG_BT_NIMBLE_MESH_NODE_COUNT
CONFIG_BT_NIMBLE_MESH_PROXY
Enable mesh proxy functionality
Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH
Enable proxy. This is automatically set whenever NIMBLE_MESH_PB_GATT or NIM-
BLE_MESH_GATT_PROXY is set
Default value:
• No (disabled) if CONFIG_BT_NIMBLE_MESH && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MESH_PROV
Enable BLE mesh provisioning
Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH
Enable mesh provisioning
Default value:
• Yes (enabled) if CONFIG_BT_NIMBLE_MESH && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MESH_PB_ADV
Enable mesh provisioning over advertising bearer
Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH > CON-
FIG_BT_NIMBLE_MESH_PROV
Enable this option to allow the device to be provisioned over the advertising bearer
Default value:
• Yes (enabled) if CONFIG_BT_NIMBLE_MESH_PROV && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MESH_PB_GATT
Enable mesh provisioning over GATT bearer
Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH > CON-
FIG_BT_NIMBLE_MESH_PROV
Enable this option to allow the device to be provisioned over the GATT bearer
Default value:
• Yes (enabled) if CONFIG_BT_NIMBLE_MESH_PROV && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MESH_GATT_PROXY
Enable GATT Proxy functionality
Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH
This option enables support for the Mesh GATT Proxy Service, i.e. the ability to act as a proxy between
a Mesh GATT Client and a Mesh network
Default value:
• Yes (enabled) if CONFIG_BT_NIMBLE_MESH && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MESH_RELAY
Enable mesh relay functionality
Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH
Support for acting as a Mesh Relay Node
Default value:
• No (disabled) if CONFIG_BT_NIMBLE_MESH && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MESH_LOW_POWER
Enable mesh low power mode
Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH
Enable this option to be able to act as a Low Power Node
Default value:
• No (disabled) if CONFIG_BT_NIMBLE_MESH && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MESH_FRIEND
Enable mesh friend functionality
Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH
Enable this option to be able to act as a Friend Node
Default value:
• No (disabled) if CONFIG_BT_NIMBLE_MESH && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MESH_DEVICE_NAME
Set mesh device name
Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH
This value defines Bluetooth Mesh device/node name
Default value:
• “nimble-mesh-node”if CONFIG_BT_NIMBLE_MESH && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MESH_NODE_COUNT
Set mesh node count
Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH
Defines mesh node count.
Default value:
• 1 if CONFIG_BT_NIMBLE_MESH && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MESH_PROVISIONER
Enable BLE mesh provisioner
Found in: Component config > Bluetooth > NimBLE Options > CONFIG_BT_NIMBLE_MESH
Enable mesh provisioner.
Default value:
• 0 if CONFIG_BT_NIMBLE_MESH && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_CRYPTO_STACK_MBEDTLS
Override TinyCrypt with mbedTLS for crypto computations
Found in: Component config > Bluetooth > NimBLE Options
Enable this option to choose mbedTLS instead of TinyCrypt for crypto computations.
Default value:
• Yes (enabled) if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_HS_STOP_TIMEOUT_MS
BLE host stop timeout in msec
Found in: Component config > Bluetooth > NimBLE Options
BLE Host stop procedure timeout in milliseconds.
Default value:
• 2000 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_ENABLE_CONN_REATTEMPT
Enable connection reattempts on connection establishment error
Found in: Component config > Bluetooth > NimBLE Options
Enable to make the NimBLE host to reattempt GAP connection on connection establishment failure.
Default value:
• No (disabled) if BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MAX_CONN_REATTEMPT
Maximum number connection reattempts
Found in: Component config > Bluetooth > NimBLE Options > CON-
FIG_BT_NIMBLE_ENABLE_CONN_REATTEMPT
Defines maximum number of connection reattempts.
Range:
• from 1 to 7 if BT_NIMBLE_ENABLED && CON-
FIG_BT_NIMBLE_ENABLE_CONN_REATTEMPT && BT_NIMBLE_ENABLED
Default value:
• 3 if BT_NIMBLE_ENABLED && CONFIG_BT_NIMBLE_ENABLE_CONN_REATTEMPT
&& BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT
Enable BLE 5 feature
Found in: Component config > Bluetooth > NimBLE Options
Enable BLE 5 feature
Default value:
• Yes (enabled) if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
Contains:
• CONFIG_BT_NIMBLE_LL_CFG_FEAT_LE_2M_PHY
• CONFIG_BT_NIMBLE_LL_CFG_FEAT_LE_CODED_PHY
• CONFIG_BT_NIMBLE_EXT_ADV
• CONFIG_BT_NIMBLE_MAX_PERIODIC_SYNCS
CONFIG_BT_NIMBLE_LL_CFG_FEAT_LE_2M_PHY
Enable 2M Phy
Found in: Component config > Bluetooth > NimBLE Options > CON-
FIG_BT_NIMBLE_50_FEATURE_SUPPORT
Enable 2M-PHY
Default value:
• Yes (enabled) if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT &&
BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_LL_CFG_FEAT_LE_CODED_PHY
Enable coded Phy
Found in: Component config > Bluetooth > NimBLE Options > CON-
FIG_BT_NIMBLE_50_FEATURE_SUPPORT
Enable coded-PHY
Default value:
• Yes (enabled) if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT &&
BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_EXT_ADV
Enable extended advertising
Found in: Component config > Bluetooth > NimBLE Options > CON-
FIG_BT_NIMBLE_50_FEATURE_SUPPORT
Enable this option to do extended advertising. Extended advertising will be supported from BLE 5.0
onwards.
Default value:
• No (disabled) if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT &&
BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MAX_EXT_ADV_INSTANCES
Maximum number of extended advertising instances.
Found in: Component config > Bluetooth > NimBLE Options > CON-
FIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_EXT_ADV
Change this option to set maximum number of extended advertising instances. Minimum there is always
one instance of advertising. Enter how many more advertising instances you want.
Range:
• from 0 to 4 if CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_EXT_ADV &&
BT_NIMBLE_ENABLED
Default value:
• 1 if CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_EXT_ADV && CON-
FIG_BT_NIMBLE_EXT_ADV && BT_NIMBLE_ENABLED
• 0 if CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_EXT_ADV &&
BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_EXT_ADV_MAX_SIZE
Maximum length of the advertising data.
Found in: Component config > Bluetooth > NimBLE Options > CON-
FIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_EXT_ADV
Defines the length of the extended adv data. The value should not exceed 1650.
Range:
• from 0 to 1650 if CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_EXT_ADV
&& BT_NIMBLE_ENABLED
Default value:
• 1650 if CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_EXT_ADV &&
CONFIG_BT_NIMBLE_EXT_ADV && BT_NIMBLE_ENABLED
• 0 if CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_EXT_ADV &&
BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_ENABLE_PERIODIC_ADV
Enable periodic advertisement.
Found in: Component config > Bluetooth > NimBLE Options > CON-
FIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_EXT_ADV
Enable this option to start periodic advertisement.
Default value:
• Yes (enabled) if CONFIG_BT_NIMBLE_EXT_ADV && CONFIG_BT_NIMBLE_EXT_ADV
&& BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_PERIODIC_ADV_SYNC_TRANSFER
Enable Transer Sync Events
Found in: Component config > Bluetooth > NimBLE Options > CON-
FIG_BT_NIMBLE_50_FEATURE_SUPPORT > CONFIG_BT_NIMBLE_EXT_ADV > CON-
FIG_BT_NIMBLE_ENABLE_PERIODIC_ADV
This enables controller transfer periodic sync events to host
Default value:
• Yes (enabled) if CONFIG_BT_NIMBLE_ENABLE_PERIODIC_ADV && CON-
FIG_BT_NIMBLE_EXT_ADV && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_MAX_PERIODIC_SYNCS
Maximum number of periodic advertising syncs
Found in: Component config > Bluetooth > NimBLE Options > CON-
FIG_BT_NIMBLE_50_FEATURE_SUPPORT
Set this option to set the upper limit for number of periodic sync connections. This should be less than
maximum connections allowed by controller.
Range:
• from 0 to 8 if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT &&
BT_NIMBLE_ENABLED
Default value:
• 1 if CONFIG_BT_NIMBLE_ENABLE_PERIODIC_ADV && CON-
FIG_BT_NIMBLE_50_FEATURE_SUPPORT && BT_NIMBLE_ENABLED
• 0 if CONFIG_BT_NIMBLE_50_FEATURE_SUPPORT && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_COEX_PHY_CODED_TX_RX_TLIM
Coexistence: limit on MAX Tx/Rx time for coded-PHY connection
Found in: Component config > Bluetooth > NimBLE Options
When using PHY-Coded in BLE connection, limitation on max tx/rx time can be applied to better avoid
dramatic performance deterioration of Wi-Fi.
Available options:
• Force Enable (BT_NIMBLE_COEX_PHY_CODED_TX_RX_TLIM_EN)
Always enable the limitation on max tx/rx time for Coded-PHY connection
• Force Disable (BT_NIMBLE_COEX_PHY_CODED_TX_RX_TLIM_DIS)
Disable the limitation on max tx/rx time for Coded-PHY connection
CONFIG_BT_NIMBLE_WHITELIST_SIZE
BLE white list size
Found in: Component config > Bluetooth > NimBLE Options
BLE list size
Range:
• from 1 to 15 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
Default value:
• 12 if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_TEST_THROUGHPUT_TEST
Throughput Test Mode enable
Found in: Component config > Bluetooth > NimBLE Options
Enable the throughput test mode
Default value:
• No (disabled) if BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_BLUFI_ENABLE
Enable blufi functionality
Found in: Component config > Bluetooth > NimBLE Options
Set this option to enable blufi functionality.
Default value:
• No (disabled) if BT_NIMBLE_ENABLED && BT_NIMBLE_ENABLED
CONFIG_BT_NIMBLE_USE_ESP_TIMER
Enable Esp Timer for Nimble
Found in: Component config > Bluetooth > NimBLE Options
Set this option to use Esp Timer which has higher priority timer instead of FreeRTOS timer
Default value:
• Yes (enabled) if BT_NIMBLE_ENABLED
CONFIG_BTDM_CTRL_MODE
Bluetooth controller mode (BR/EDR/BLE/DUALMODE)
Found in: Component config > Bluetooth > Controller Options
Specify the bluetooth controller mode (BR/EDR, BLE or dual mode).
Available options:
• BLE Only (BTDM_CTRL_MODE_BLE_ONLY)
• BR/EDR Only (BTDM_CTRL_MODE_BR_EDR_ONLY)
CONFIG_BTDM_CTRL_BLE_MAX_CONN
BLE Max Connections
Found in: Component config > Bluetooth > Controller Options
BLE maximum connections of bluetooth controller. Each connection uses 1KB static DRAM whenever
the BT controller is enabled.
Range:
• from 1 to 9 if (BTDM_CTRL_MODE_BLE_ONLY || BTDM_CTRL_MODE_BTDM) &&
BT_CONTROLLER_ENABLED
Default value:
• 3 if (BTDM_CTRL_MODE_BLE_ONLY || BTDM_CTRL_MODE_BTDM) &&
BT_CONTROLLER_ENABLED
CONFIG_BTDM_CTRL_BR_EDR_MAX_ACL_CONN
BR/EDR ACL Max Connections
Found in: Component config > Bluetooth > Controller Options
BR/EDR ACL maximum connections of bluetooth controller. Each connection uses 1.2 KB DRAM
whenever the BT controller is enabled.
Range:
• from 1 to 7 if (BTDM_CTRL_MODE_BR_EDR_ONLY || BTDM_CTRL_MODE_BTDM)
&& BT_CONTROLLER_ENABLED
Default value:
• 2 if (BTDM_CTRL_MODE_BR_EDR_ONLY || BTDM_CTRL_MODE_BTDM) &&
BT_CONTROLLER_ENABLED
CONFIG_BTDM_CTRL_BR_EDR_MAX_SYNC_CONN
BR/EDR Sync(SCO/eSCO) Max Connections
Found in: Component config > Bluetooth > Controller Options
BR/EDR Synchronize maximum connections of bluetooth controller. Each connection uses 2 KB
DRAM whenever the BT controller is enabled.
Range:
• from 0 to 3 if (BTDM_CTRL_MODE_BR_EDR_ONLY || BTDM_CTRL_MODE_BTDM)
&& BT_CONTROLLER_ENABLED
Default value:
• 0 if (BTDM_CTRL_MODE_BR_EDR_ONLY || BTDM_CTRL_MODE_BTDM) &&
BT_CONTROLLER_ENABLED
CONFIG_BTDM_CTRL_BR_EDR_SCO_DATA_PATH
BR/EDR Sync(SCO/eSCO) default data path
Found in: Component config > Bluetooth > Controller Options
SCO data path, i.e. HCI or PCM. SCO data can be sent/received through HCI synchronous packets, or
the data can be routed to on-chip PCM module on ESP32. PCM input/output signals can be“matrixed”
to GPIOs. The default data path can also be set using API “esp_bredr_sco_datapath_set”
Available options:
• HCI (BTDM_CTRL_BR_EDR_SCO_DATA_PATH_HCI)
• PCM (BTDM_CTRL_BR_EDR_SCO_DATA_PATH_PCM)
CONFIG_BTDM_CTRL_PCM_ROLE_EDGE_CONFIG
PCM Signal Config (Role and Polar)
Found in: Component config > Bluetooth > Controller Options
Default value:
• Yes (enabled) if BTDM_CTRL_BR_EDR_SCO_DATA_PATH_PCM &&
BT_CONTROLLER_ENABLED
Contains:
• CONFIG_BTDM_CTRL_PCM_POLAR
• CONFIG_BTDM_CTRL_PCM_ROLE
CONFIG_BTDM_CTRL_PCM_ROLE
PCM Role
Found in: Component config > Bluetooth > Controller Options > CON-
FIG_BTDM_CTRL_PCM_ROLE_EDGE_CONFIG
PCM role can be configured as PCM master or PCM slave
Available options:
• PCM Master (BTDM_CTRL_PCM_ROLE_MASTER)
• PCM Slave (BTDM_CTRL_PCM_ROLE_SLAVE)
CONFIG_BTDM_CTRL_PCM_POLAR
PCM Polar
Found in: Component config > Bluetooth > Controller Options > CON-
FIG_BTDM_CTRL_PCM_ROLE_EDGE_CONFIG
PCM polarity can be configured as Falling Edge or Rising Edge
Available options:
• Falling Edge (BTDM_CTRL_PCM_POLAR_FALLING_EDGE)
• Rising Edge (BTDM_CTRL_PCM_POLAR_RISING_EDGE)
CONFIG_BTDM_CTRL_AUTO_LATENCY
Auto latency
Found in: Component config > Bluetooth > Controller Options
BLE auto latency, used to enhance classic BT performance while classic BT and BLE are enabled at the
same time.
Default value:
• No (disabled) if BTDM_CTRL_MODE_BTDM && BT_CONTROLLER_ENABLED
CONFIG_BTDM_CTRL_LEGACY_AUTH_VENDOR_EVT
Legacy Authentication Vendor Specific Event Enable
Found in: Component config > Bluetooth > Controller Options
To protect from BIAS attack during Legacy authentication, Legacy authentication Vendor specific event
should be enabled
Default value:
• Yes (enabled) if (BTDM_CTRL_MODE_BR_EDR_ONLY ||
BTDM_CTRL_MODE_BTDM) && BT_CONTROLLER_ENABLED
CONFIG_BTDM_CTRL_PINNED_TO_CORE_CHOICE
The cpu core which bluetooth controller run
Found in: Component config > Bluetooth > Controller Options
Specify the cpu core to run bluetooth controller. Can not specify no-affinity.
Available options:
• Core 0 (PRO CPU) (BTDM_CTRL_PINNED_TO_CORE_0)
• Core 1 (APP CPU) (BTDM_CTRL_PINNED_TO_CORE_1)
CONFIG_BTDM_CTRL_HCI_MODE_CHOICE
HCI mode
Found in: Component config > Bluetooth > Controller Options
Speicify HCI mode as VHCI or UART(H4)
Available options:
• VHCI (BTDM_CTRL_HCI_MODE_VHCI)
Normal option. Mostly, choose this VHCI when bluetooth host run on ESP32, too.
• UART(H4) (BTDM_CTRL_HCI_MODE_UART_H4)
If use external bluetooth host which run on other hardware and use UART as the HCI interface,
choose this option.
CONFIG_BTDM_CTRL_HCI_UART_NO
UART Number for HCI
Found in: Component config > Bluetooth > Controller Options > HCI UART(H4) Options
Uart number for HCI. The available uart is UART1 and UART2.
Range:
• from 1 to 2 if BTDM_CTRL_HCI_MODE_UART_H4 &&
BT_CONTROLLER_ENABLED
Default value:
• 1 if BTDM_CTRL_HCI_MODE_UART_H4 && BT_CONTROLLER_ENABLED
CONFIG_BTDM_CTRL_HCI_UART_BAUDRATE
UART Baudrate for HCI
Found in: Component config > Bluetooth > Controller Options > HCI UART(H4) Options
UART Baudrate for HCI. Please use standard baudrate.
Range:
• from 115200 to 921600 if BTDM_CTRL_HCI_MODE_UART_H4 &&
BT_CONTROLLER_ENABLED
Default value:
• 921600 if BTDM_CTRL_HCI_MODE_UART_H4 && BT_CONTROLLER_ENABLED
CONFIG_BTDM_CTRL_MODEM_SLEEP
Bluetooth modem sleep
Found in: Component config > Bluetooth > Controller Options > MODEM SLEEP Options
Enable/disable bluetooth controller low power mode.
Default value:
• Yes (enabled) if BT_CONTROLLER_ENABLED
CONFIG_BTDM_CTRL_MODEM_SLEEP_MODE
Bluetooth Modem sleep mode
Found in: Component config > Bluetooth > Controller Options > MODEM SLEEP Options > CON-
FIG_BTDM_CTRL_MODEM_SLEEP
To select which strategy to use for modem sleep
Available options:
• ORIG Mode(sleep with low power clock) (BTDM_CTRL_MODEM_SLEEP_MODE_ORIG)
ORIG mode is a bluetooth sleep mode that can be used for dual mode controller. In this mode,
bluetooth controller sleeps between BR/EDR frames and BLE events. A low power clock is
used to maintain bluetooth reference clock.
• EVED Mode(For internal test only) (BTDM_CTRL_MODEM_SLEEP_MODE_EVED)
EVED mode is for BLE only and is only for internal test. Do not use it for production. this
mode is not compatible with DFS nor light sleep
CONFIG_BTDM_CTRL_LOW_POWER_CLOCK
Bluetooth low power clock
Found in: Component config > Bluetooth > Controller Options > MODEM SLEEP Options
Select the low power clock source for bluetooth controller. Bluetooth low power clock is the clock source
to maintain time in sleep mode.
• “Main crystal”option provides good accuracy and can support Dynamic Frequency Scaling to be
used with Bluetooth modem sleep. Light sleep is not supported.
• “External 32kHz crystal”option allows user to use a 32.768kHz crystal as Bluetooth low power
clock. This option is allowed as long as External 32kHz crystal is configured as the system RTC
clock source. This option provides good accuracy and supports Bluetooth modem sleep to be used
alongside Dynamic Frequency Scaling or light sleep.
Available options:
• Main crystal (BTDM_CTRL_LPCLK_SEL_MAIN_XTAL)
Main crystal can be used as low power clock for bluetooth modem sleep. If this option is
selected, bluetooth modem sleep can work under Dynamic Frequency Scaling(DFS) enabled,
but cannot work when light sleep is enabled. Main crystal has a good performance in accuracy
as the bluetooth low power clock source.
• External 32kHz crystal (BTDM_CTRL_LPCLK_SEL_EXT_32K_XTAL)
External 32kHz crystal has a nominal frequency of 32.768kHz and provides good frequency
stability. If used as Bluetooth low power clock, External 32kHz can support Bluetooth modem
sleep to be used with both DFS and light sleep.
CONFIG_BTDM_BLE_SLEEP_CLOCK_ACCURACY
BLE Sleep Clock Accuracy
Found in: Component config > Bluetooth > Controller Options
BLE Sleep Clock Accuracy(SCA) for the local device is used to estimate window widening in BLE con-
nection events. With a lower level of clock accuracy(e.g. 500ppm over 250ppm), the slave needs a larger
RX window to synchronize with master in each anchor point, thus resulting in an increase of power con-
sumption but a higher level of robustness in keeping connected. According to the requirements of Blue-
tooth Core specification 4.2, the worst-case accuracy of Classic Bluetooth low power oscialltor(LPO)
is +/-250ppm in STANDBY and in low power modes such as sniff. For BLE the worst-case SCA is
+/-500ppm.
• “151ppm to 250ppm”option is the default value for Bluetooth Dual mode
• “251ppm to 500ppm”option can be used in BLE only mode when using external 32kHz crystal as
low power clock. This option is provided in case that BLE sleep clock has a lower level of
accuracy, or other error sources contribute to the inaccurate timing during sleep.
Available options:
• 251ppm to 500ppm (BTDM_BLE_DEFAULT_SCA_500PPM)
• 151ppm to 250ppm (BTDM_BLE_DEFAULT_SCA_250PPM)
CONFIG_BTDM_BLE_SCAN_DUPL
BLE Scan Duplicate Options
Found in: Component config > Bluetooth > Controller Options
This select enables parameters setting of BLE scan duplicate.
Default value:
• Yes (enabled) if (BTDM_CTRL_MODE_BTDM || BTDM_CTRL_MODE_BLE_ONLY)
&& BT_CONTROLLER_ENABLED
CONFIG_BTDM_SCAN_DUPL_TYPE
Scan Duplicate Type
Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_SCAN_DUPL
Scan duplicate have three ways. one is“Scan Duplicate By Device Address”, This way is to use advertiser
address filtering. The adv packet of the same address is only allowed to be reported once. Another way
is“Scan Duplicate By Device Address And Advertising Data”. This way is to use advertising data and
device address filtering. All different adv packets with the same address are allowed to be reported. The
last way is “Scan Duplicate By Advertising Data”. This way is to use advertising data filtering. All
same advertising data only allow to be reported once even though they are from different devices.
Available options:
• Scan Duplicate By Device Address (BTDM_SCAN_DUPL_TYPE_DEVICE)
This way is to use advertiser address filtering. The adv packet of the same address is only
allowed to be reported once
• Scan Duplicate By Advertising Data (BTDM_SCAN_DUPL_TYPE_DATA)
This way is to use advertising data filtering. All same advertising data only allow to be reported
once even though they are from different devices.
• Scan Duplicate By Device Address And Advertising Data
(BTDM_SCAN_DUPL_TYPE_DATA_DEVICE)
This way is to use advertising data and device address filtering. All different adv packets with
the same address are allowed to be reported.
CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE
Maximum number of devices in scan duplicate filter
Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_SCAN_DUPL
Maximum number of devices which can be recorded in scan duplicate filter. When the maximum amount
of device in the filter is reached, the cache will be refreshed.
Range:
CONFIG_BTDM_BLE_MESH_SCAN_DUPL_EN
Special duplicate scan mechanism for BLE Mesh scan
Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_SCAN_DUPL
This enables the BLE scan duplicate for special BLE Mesh scan.
Default value:
• No (disabled) if CONFIG_BTDM_BLE_SCAN_DUPL && BT_CONTROLLER_ENABLED
CONFIG_BTDM_MESH_DUPL_SCAN_CACHE_SIZE
Maximum number of Mesh adv packets in scan duplicate filter
Found in: Component config > Bluetooth > Controller Options > CONFIG_BTDM_BLE_SCAN_DUPL >
CONFIG_BTDM_BLE_MESH_SCAN_DUPL_EN
Maximum number of adv packets which can be recorded in duplicate scan cache for BLE Mesh. When
the maximum amount of device in the filter is reached, the cache will be refreshed.
Range:
• from 10 to 1000 if CONFIG_BTDM_BLE_MESH_SCAN_DUPL_EN &&
BT_CONTROLLER_ENABLED
Default value:
• 200 if CONFIG_BTDM_BLE_MESH_SCAN_DUPL_EN &&
BT_CONTROLLER_ENABLED
CONFIG_BTDM_CTRL_FULL_SCAN_SUPPORTED
BLE full scan feature supported
Found in: Component config > Bluetooth > Controller Options
The full scan function is mainly used to provide BLE scan performance. This is required for scenes with
high scan performance requirements, such as BLE Mesh scenes.
Default value:
• Yes (enabled) if (BTDM_CTRL_MODE_BLE_ONLY || BTDM_CTRL_MODE_BTDM)
&& BT_CONTROLLER_ENABLED
CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP
BLE adv report flow control supported
Found in: Component config > Bluetooth > Controller Options
The function is mainly used to enable flow control for advertising reports. When it is enabled, advertising
reports will be discarded by the controller if the number of unprocessed advertising reports exceeds the
size of BLE adv report flow control.
Default value:
• Yes (enabled) if (BTDM_CTRL_MODE_BTDM || BTDM_CTRL_MODE_BLE_ONLY)
&& BT_CONTROLLER_ENABLED
CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM
BLE adv report flow control number
Found in: Component config > Bluetooth > Controller Options > CON-
FIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP
The number of unprocessed advertising report that Bluedroid can save.If you set
BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM to a small value, this may cause adv packets
lost. If you set BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM to a large value, Bluedroid
may cache a lot of adv packets and this may cause system memory run out. For example,
if you set it to 50, the maximum memory consumed by host is 35 * 50 bytes. Please set
BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM according to your system free memory and
handle adv packets as fast as possible, otherwise it will cause adv packets lost.
Range:
• from 50 to 1000 if CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP &&
BT_CONTROLLER_ENABLED
Default value:
• 100 if CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP &&
BT_CONTROLLER_ENABLED
CONFIG_BTDM_BLE_ADV_REPORT_DISCARD_THRSHOLD
BLE adv lost event threshold value
Found in: Component config > Bluetooth > Controller Options > CON-
FIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP
When adv report flow control is enabled, The ADV lost event will be generated when the number of
ADV packets lost in the controller reaches this threshold. It is better to set a larger value. If you set
BTDM_BLE_ADV_REPORT_DISCARD_THRSHOLD to a small value or printf every adv lost event, it
may cause adv packets lost more.
Range:
• from 1 to 1000 if CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP &&
BT_CONTROLLER_ENABLED
Default value:
• 20 if CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP &&
BT_CONTROLLER_ENABLED
CONFIG_BTDM_CTRL_HLI
High level interrupt
Found in: Component config > Bluetooth > Controller Options
Using Level 4 interrupt for Bluetooth.
Default value:
• Yes (enabled) if CONFIG_BT_ENABLED && BT_CONTROLLER_ENABLED
CONFIG_BLE_MESH
ESP BLE Mesh Support
Found in: Component config
This option enables ESP BLE Mesh support. The specific features that are available may depend on other
features that have been enabled in the stack, such as Bluetooth Support, Bluedroid Support & GATT
support.
Contains:
CONFIG_BLE_MESH_HCI_5_0
Support sending 20ms non-connectable adv packets
Found in: Component config > CONFIG_BLE_MESH
It is a temporary solution and needs further modifications.
Default value:
• Yes (enabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_USE_DUPLICATE_SCAN
Support Duplicate Scan in BLE Mesh
Found in: Component config > CONFIG_BLE_MESH
Enable this option to allow using specific duplicate scan filter in BLE Mesh, and Scan Duplicate Type
must be set by choosing the option in the Bluetooth Controller section in menuconfig, which is “Scan
CONFIG_BLE_MESH_MEM_ALLOC_MODE
Memory allocation strategy
Found in: Component config > CONFIG_BLE_MESH
Allocation strategy for BLE Mesh stack, essentially provides ability to allocate all required dynamic
allocations from,
• Internal DRAM memory only
• External SPIRAM memory only
• Either internal or external memory based on default malloc() behavior in ESP-IDF
• Internal IRAM memory wherever applicable else internal DRAM
Recommended mode here is always internal (*), since that is most preferred from security perspective.
But if application requirement does not allow sufficient free internal memory then alternate mode can
be selected.
(*) In case of ESP32-S2/ESP32-S3, hardware allows encryption of external SPIRAM contents provided
hardware flash encryption feature is enabled. In that case, using external SPIRAM allocation strategy is
also safe choice from security perspective.
Available options:
• Internal DRAM (BLE_MESH_MEM_ALLOC_MODE_INTERNAL)
• External SPIRAM (BLE_MESH_MEM_ALLOC_MODE_EXTERNAL)
• Default alloc mode (BLE_MESH_MEM_ALLOC_MODE_DEFAULT)
Enable this option to use the default memory allocation strategy when external SPIRAM is
enabled. See the SPIRAM options for more details.
• Internal IRAM (BLE_MESH_MEM_ALLOC_MODE_IRAM_8BIT)
Allows to use IRAM memory region as 8bit accessible region. Every unaligned (8bit or
16bit) access will result in an exception and incur penalty of certain clock cycles per unaligned
read/write.
CONFIG_BLE_MESH_FREERTOS_STATIC_ALLOC
Enable FreeRTOS static allocation
Found in: Component config > CONFIG_BLE_MESH
Enable this option to use FreeRTOS static allocation APIs for BLE Mesh, which provides the ability
to use different dynamic memory (i.e. SPIRAM or IRAM) for FreeRTOS objects. If this option is
disabled, the FreeRTOS static allocation APIs will not be used, and internal DRAM will be allocated
for FreeRTOS objects.
Default value:
• No (disabled) if (CONFIG_SPIRAM || CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY)
&& CONFIG_BLE_MESH
CONFIG_BLE_MESH_FREERTOS_STATIC_ALLOC_MODE
Memory allocation for FreeRTOS objects
Found in: Component config > CONFIG_BLE_MESH > CON-
FIG_BLE_MESH_FREERTOS_STATIC_ALLOC
Choose the memory to be used for FreeRTOS objects.
Available options:
CONFIG_BLE_MESH_DEINIT
Support de-initialize BLE Mesh stack
Found in: Component config > CONFIG_BLE_MESH
If enabled, users can use the function esp_ble_mesh_deinit() to de-initialize the whole BLE Mesh stack.
Default value:
• Yes (enabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_SUPPORT_BLE_ADV
Support sending normal BLE advertising packets
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh and BLE coexistence support
When selected, users can send normal BLE advertising packets with specific API.
Default value:
• No (disabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_BLE_ADV_BUF_COUNT
Number of advertising buffers for BLE advertising packets
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh and BLE coexistence support > CON-
FIG_BLE_MESH_SUPPORT_BLE_ADV
Number of advertising buffers for BLE packets available.
Range:
• from 1 to 255 if CONFIG_BLE_MESH_SUPPORT_BLE_ADV && CONFIG_BLE_MESH
Default value:
• 3 if CONFIG_BLE_MESH_SUPPORT_BLE_ADV && CONFIG_BLE_MESH
CONFIG_BLE_MESH_SUPPORT_BLE_SCAN
Support scanning normal BLE advertising packets
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh and BLE coexistence support
When selected, users can register a callback and receive normal BLE advertising packets in the appli-
cation layer.
Default value:
• No (disabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_FAST_PROV
Enable BLE Mesh Fast Provisioning
Found in: Component config > CONFIG_BLE_MESH
Enable this option to allow BLE Mesh fast provisioning solution to be used. When there are multiple
unprovisioned devices around, fast provisioning can greatly reduce the time consumption of the whole
provisioning process. When this option is enabled, and after an unprovisioned device is provisioned into
a node successfully, it can be changed to a temporary Provisioner.
Default value:
• No (disabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_NODE
Support for BLE Mesh Node
Found in: Component config > CONFIG_BLE_MESH
Enable the device to be provisioned into a node. This option should be enabled when an unprovisioned
device is going to be provisioned into a node and communicate with other nodes in the BLE Mesh
network.
CONFIG_BLE_MESH_PROVISIONER
Support for BLE Mesh Provisioner
Found in: Component config > CONFIG_BLE_MESH
Enable the device to be a Provisioner. The option should be enabled when a device is going to act as a
Provisioner and provision unprovisioned devices into the BLE Mesh network.
CONFIG_BLE_MESH_WAIT_FOR_PROV_MAX_DEV_NUM
Maximum number of unprovisioned devices that can be added to device queue
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER
This option specifies how many unprovisioned devices can be added to device queue for provisioning.
Users can use this option to define the size of the queue in the bottom layer which is used to store
unprovisioned device information (e.g. Device UUID, address).
Range:
• from 1 to 100 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH
Default value:
• 10 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_MAX_PROV_NODES
Maximum number of devices that can be provisioned by Provisioner
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER
This option specifies how many devices can be provisioned by a Provisioner. This value indicates the
maximum number of unprovisioned devices which can be provisioned by a Provisioner. For instance,
if the value is 6, it means the Provisioner can provision up to 6 unprovisioned devices. Theoretically a
Provisioner without the limitation of its memory can provision up to 32766 unprovisioned devices, here
we limit the maximum number to 100 just to limit the memory used by a Provisioner. The bigger the
value is, the more memory it will cost by a Provisioner to store the information of nodes.
Range:
• from 1 to 1000 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH
Default value:
CONFIG_BLE_MESH_PBA_SAME_TIME
Maximum number of PB-ADV running at the same time by Provisioner
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER
This option specifies how many devices can be provisioned at the same time using PB-ADV. For exam-
ples, if the value is 2, it means a Provisioner can provision two unprovisioned devices with PB-ADV at
the same time.
Range:
• from 1 to 10 if CONFIG_BLE_MESH_PB_ADV && CONFIG_BLE_MESH_PROVISIONER
&& CONFIG_BLE_MESH
Default value:
• 2 if CONFIG_BLE_MESH_PB_ADV && CONFIG_BLE_MESH_PROVISIONER && CON-
FIG_BLE_MESH
CONFIG_BLE_MESH_PBG_SAME_TIME
Maximum number of PB-GATT running at the same time by Provisioner
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER
This option specifies how many devices can be provisioned at the same time using PB-GATT. For ex-
ample, if the value is 2, it means a Provisioner can provision two unprovisioned devices with PB-GATT
at the same time.
Range:
• from 1 to 5 if CONFIG_BLE_MESH_PB_GATT && CONFIG_BLE_MESH_PROVISIONER
&& CONFIG_BLE_MESH
Default value:
• 1 if CONFIG_BLE_MESH_PB_GATT && CONFIG_BLE_MESH_PROVISIONER && CON-
FIG_BLE_MESH
CONFIG_BLE_MESH_PROVISIONER_SUBNET_COUNT
Maximum number of mesh subnets that can be created by Provisioner
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER
This option specifies how many subnets per network a Provisioner can create. Indeed, this value decides
the number of network keys which can be added by a Provisioner.
Range:
• from 1 to 4096 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH
Default value:
• 3 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_PROVISIONER_APP_KEY_COUNT
Maximum number of application keys that can be owned by Provisioner
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER
This option specifies how many application keys the Provisioner can have. Indeed, this value decides the
number of the application keys which can be added by a Provisioner.
Range:
• from 1 to 4096 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH
Default value:
• 3 if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_PROVISIONER_RECV_HB
Support receiving Heartbeat messages
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER
When this option is enabled, Provisioner can call specific functions to enable or disable receiving Heart-
beat messages and notify them to the application layer.
Default value:
• No (disabled) if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_PROVISIONER_RECV_HB_FILTER_SIZE
Maximum number of filter entries for receiving Heartbeat messages
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PROVISIONER > CON-
FIG_BLE_MESH_PROVISIONER_RECV_HB
This option specifies how many heartbeat filter entries Provisioner supports. The heartbeat filter (ac-
ceptlist or rejectlist) entries are used to store a list of SRC and DST which can be used to decide if a
heartbeat message will be processed and notified to the application layer by Provisioner. Note: The filter
is an empty rejectlist by default.
Range:
• from 1 to 1000 if CONFIG_BLE_MESH_PROVISIONER_RECV_HB && CON-
FIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH
Default value:
• 3 if CONFIG_BLE_MESH_PROVISIONER_RECV_HB && CON-
FIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_PROV
BLE Mesh Provisioning support
Found in: Component config > CONFIG_BLE_MESH
Enable this option to support BLE Mesh Provisioning functionality. For BLE Mesh, this option should
be always enabled.
Default value:
• Yes (enabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_PB_ADV
Provisioning support using the advertising bearer (PB-ADV)
Found in: Component config > CONFIG_BLE_MESH
Enable this option to allow the device to be provisioned over the advertising bearer. This option should
be enabled if PB-ADV is going to be used during provisioning procedure.
Default value:
• Yes (enabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_UNPROVISIONED_BEACON_INTERVAL
Interval between two consecutive Unprovisioned Device Beacon
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_PB_ADV
This option specifies the interval of sending two consecutive unprovisioned device beacon, users can
use this option to change the frequency of sending unprovisioned device beacon. For example, if the
value is 5, it means the unprovisioned device beacon will send every 5 seconds. When the option of
BLE_MESH_FAST_PROV is selected, the value is better to be 3 seconds, or less.
Range:
• from 1 to 100 if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PB_ADV &&
CONFIG_BLE_MESH
Default value:
• 5 if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PB_ADV && CON-
FIG_BLE_MESH
• 3 if CONFIG_BLE_MESH_FAST_PROV && CONFIG_BLE_MESH_NODE && CON-
FIG_BLE_MESH_PB_ADV && CONFIG_BLE_MESH
CONFIG_BLE_MESH_PB_GATT
Provisioning support using GATT (PB-GATT)
Found in: Component config > CONFIG_BLE_MESH
Enable this option to allow the device to be provisioned over GATT. This option should be enabled if
PB-GATT is going to be used during provisioning procedure.
# Virtual option enabled whenever any Proxy protocol is needed
CONFIG_BLE_MESH_PROXY
BLE Mesh Proxy protocol support
Found in: Component config > CONFIG_BLE_MESH
Enable this option to support BLE Mesh Proxy protocol used by PB-GATT and other proxy pdu trans-
mission.
Default value:
• Yes (enabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_GATT_PROXY_SERVER
BLE Mesh GATT Proxy Server
Found in: Component config > CONFIG_BLE_MESH
This option enables support for Mesh GATT Proxy Service, i.e. the ability to act as a proxy between a
Mesh GATT Client and a Mesh network. This option should be enabled if a node is going to be a Proxy
Server.
Default value:
• Yes (enabled) if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH
CONFIG_BLE_MESH_NODE_ID_TIMEOUT
Node Identity advertising timeout
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_SERVER
This option determines for how long the local node advertises using Node Identity. The given value is
in seconds. The specification limits this to 60 seconds and lists it as the recommended value as well. So
leaving the default value is the safest option. When an unprovisioned device is provisioned successfully
and becomes a node, it will start to advertise using Node Identity during the time set by this option. And
after that, Network ID will be advertised.
Range:
• from 1 to 60 if CONFIG_BLE_MESH_GATT_PROXY_SERVER && CONFIG_BLE_MESH
Default value:
• 60 if CONFIG_BLE_MESH_GATT_PROXY_SERVER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_PROXY_FILTER_SIZE
Maximum number of filter entries per Proxy Client
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_GATT_PROXY_SERVER
This option specifies how many Proxy Filter entries the local node supports. The entries of Proxy filter
(whitelist or blacklist) are used to store a list of addresses which can be used to decide which messages
will be forwarded to the Proxy Client by the Proxy Server.
Range:
• from 1 to 32767 if CONFIG_BLE_MESH_GATT_PROXY_SERVER && CON-
FIG_BLE_MESH
Default value:
• 4 if CONFIG_BLE_MESH_GATT_PROXY_SERVER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_GATT_PROXY_CLIENT
BLE Mesh GATT Proxy Client
Found in: Component config > CONFIG_BLE_MESH
This option enables support for Mesh GATT Proxy Client. The Proxy Client can use the GATT bearer
to send mesh messages to a node that supports the advertising bearer.
Default value:
• No (disabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_SETTINGS
Store BLE Mesh configuration persistently
Found in: Component config > CONFIG_BLE_MESH
When selected, the BLE Mesh stack will take care of storing/restoring the BLE Mesh configuration
persistently in flash. If the device is a BLE Mesh node, when this option is enabled, the configuration
of the device will be stored persistently, including unicast address, NetKey, AppKey, etc. And if the
device is a BLE Mesh Provisioner, the information of the device will be stored persistently, including
the information of provisioned nodes, NetKey, AppKey, etc.
Default value:
• No (disabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_STORE_TIMEOUT
Delay (in seconds) before storing anything persistently
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS
This value defines in seconds how soon any pending changes are actually written into persistent storage
(flash) after a change occurs. The option allows nodes to delay a certain period of time to save proper
information to flash. The default value is 0, which means information will be stored immediately once
there are updates.
Range:
• from 0 to 1000000 if CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH
Default value:
• 0 if CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH
CONFIG_BLE_MESH_SEQ_STORE_RATE
CONFIG_BLE_MESH_RPL_STORE_TIMEOUT
Minimum frequency that the RPL gets updated in storage
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS
This value defines in seconds how soon the RPL (Replay Protection List) gets written to persistent storage
after a change occurs. If the node receives messages frequently, then a large value is recommended. If
the node receives messages rarely, then the value can be as low as 0 (which means the RPL is written
into the storage immediately). Note that if the node operates in a security-sensitive case, and there is a
risk of sudden power-off, then a value of 0 is strongly recommended. Otherwise, a power loss before
RPL being written into the storage may introduce message replay attacks and system security will be in
a vulnerable state.
Range:
• from 0 to 1000000 if CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH
Default value:
• 0 if CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH
CONFIG_BLE_MESH_SETTINGS_BACKWARD_COMPATIBILITY
A specific option for settings backward compatibility
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS
This option is created to solve the issue of failure in recovering node information after mesh stack up-
dates. In the old version mesh stack, there is no key of “mesh/role”in nvs. In the new version mesh
stack, key of “mesh/role”is added in nvs, recovering node information needs to check “mesh/role”
key in nvs and implements selective recovery of mesh node information. Therefore, there may be failure
in recovering node information during node restarting after OTA.
The new version mesh stack adds the option of “mesh/role”because we have added the support of
storing Provisioner information, while the old version only supports storing node information.
If users are updating their nodes from old version to new version, we recommend enabling this option,
so that system could set the flag in advance before recovering node information and make sure the node
information recovering could work as expected.
Default value:
• No (disabled) if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_SETTINGS &&
CONFIG_BLE_MESH
CONFIG_BLE_MESH_SPECIFIC_PARTITION
Use a specific NVS partition for BLE Mesh
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS
When selected, the mesh stack will use a specified NVS partition instead of default NVS partition. Note
that the specified partition must be registered with NVS using nvs_flash_init_partition() API, and the
partition must exists in the csv file. When Provisioner needs to store a large amount of nodes’information
in the flash (e.g. more than 20), this option is recommended to be enabled.
Default value:
• No (disabled) if CONFIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH
CONFIG_BLE_MESH_PARTITION_NAME
Name of the NVS partition for BLE Mesh
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS > CON-
FIG_BLE_MESH_SPECIFIC_PARTITION
This value defines the name of the specified NVS partition used by the mesh stack.
Default value:
• “ble_mesh”if CONFIG_BLE_MESH_SPECIFIC_PARTITION && CON-
FIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH
CONFIG_BLE_MESH_USE_MULTIPLE_NAMESPACE
Support using multiple NVS namespaces by Provisioner
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS
When selected, Provisioner can use different NVS namespaces to store different instances of mesh in-
formation. For example, if in the first room, Provisioner uses NetKey A, AppKey A and provisions
three devices, these information will be treated as mesh information instance A. When the Provisioner
moves to the second room, it uses NetKey B, AppKey B and provisions two devices, then the informa-
tion will be treated as mesh information instance B. Here instance A and instance B will be stored in
different namespaces. With this option enabled, Provisioner needs to use specific functions to open the
corresponding NVS namespace, restore the mesh information, release the mesh information or erase the
mesh information.
Default value:
• No (disabled) if CONFIG_BLE_MESH_PROVISIONER && CON-
FIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH
CONFIG_BLE_MESH_MAX_NVS_NAMESPACE
Maximum number of NVS namespaces
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_SETTINGS > CON-
FIG_BLE_MESH_USE_MULTIPLE_NAMESPACE
This option specifies the maximum NVS namespaces supported by Provisioner.
Range:
• from 1 to 255 if CONFIG_BLE_MESH_USE_MULTIPLE_NAMESPACE && CON-
FIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH
Default value:
• 2 if CONFIG_BLE_MESH_USE_MULTIPLE_NAMESPACE && CON-
FIG_BLE_MESH_SETTINGS && CONFIG_BLE_MESH
CONFIG_BLE_MESH_SUBNET_COUNT
Maximum number of mesh subnets per network
Found in: Component config > CONFIG_BLE_MESH
This option specifies how many subnets a Mesh network can have at the same time. Indeed, this value
decides the number of the network keys which can be owned by a node.
Range:
• from 1 to 4096 if CONFIG_BLE_MESH
Default value:
• 3 if CONFIG_BLE_MESH
CONFIG_BLE_MESH_APP_KEY_COUNT
Maximum number of application keys per network
Found in: Component config > CONFIG_BLE_MESH
This option specifies how many application keys the device can store per network. Indeed, this value
decides the number of the application keys which can be owned by a node.
Range:
• from 1 to 4096 if CONFIG_BLE_MESH
Default value:
• 3 if CONFIG_BLE_MESH
CONFIG_BLE_MESH_MODEL_KEY_COUNT
Maximum number of application keys per model
Found in: Component config > CONFIG_BLE_MESH
This option specifies the maximum number of application keys to which each model can be bound.
Range:
• from 1 to 4096 if CONFIG_BLE_MESH
Default value:
• 3 if CONFIG_BLE_MESH
CONFIG_BLE_MESH_MODEL_GROUP_COUNT
Maximum number of group address subscriptions per model
Found in: Component config > CONFIG_BLE_MESH
This option specifies the maximum number of addresses to which each model can be subscribed.
Range:
• from 1 to 4096 if CONFIG_BLE_MESH
Default value:
• 3 if CONFIG_BLE_MESH
CONFIG_BLE_MESH_LABEL_COUNT
Maximum number of Label UUIDs used for Virtual Addresses
Found in: Component config > CONFIG_BLE_MESH
This option specifies how many Label UUIDs can be stored. Indeed, this value decides the number of
the Virtual Addresses can be supported by a node.
Range:
• from 0 to 4096 if CONFIG_BLE_MESH
Default value:
• 3 if CONFIG_BLE_MESH
CONFIG_BLE_MESH_CRPL
Maximum capacity of the replay protection list
Found in: Component config > CONFIG_BLE_MESH
This option specifies the maximum capacity of the replay protection list. It is similar to Network message
cache size, but has a different purpose. The replay protection list is used to prevent a node from replay
attack, which will store the source address and sequence number of the received mesh messages. For
Provisioner, the replay protection list size should not be smaller than the maximum number of nodes
whose information can be stored. And the element number of each node should also be taken into
consideration. For example, if Provisioner can provision up to 20 nodes and each node contains two
elements, then the replay protection list size of Provisioner should be at least 40.
Range:
• from 2 to 65535 if CONFIG_BLE_MESH
Default value:
• 10 if CONFIG_BLE_MESH
CONFIG_BLE_MESH_MSG_CACHE_SIZE
Network message cache size
Found in: Component config > CONFIG_BLE_MESH
Number of messages that are cached for the network. This helps prevent unnecessary decryption opera-
tions and unnecessary relays. This option is similar to Replay protection list, but has a different purpose.
A node is not required to cache the entire Network PDU and may cache only part of it for tracking, such
as values for SRC/SEQ or others.
Range:
• from 2 to 65535 if CONFIG_BLE_MESH
Default value:
• 10 if CONFIG_BLE_MESH
CONFIG_BLE_MESH_ADV_BUF_COUNT
Number of advertising buffers
Found in: Component config > CONFIG_BLE_MESH
Number of advertising buffers available. The transport layer reserves ADV_BUF_COUNT - 3 buffers
for outgoing segments. The maximum outgoing SDU size is 12 times this value (out of which 4 or 8
bytes are used for the Transport Layer MIC). For example, 5 segments means the maximum SDU size
is 60 bytes, which leaves 56 bytes for application layer data using a 4-byte MIC, or 52 bytes using an
8-byte MIC.
Range:
• from 6 to 256 if CONFIG_BLE_MESH
Default value:
• 60 if CONFIG_BLE_MESH
CONFIG_BLE_MESH_IVU_DIVIDER
Divider for IV Update state refresh timer
Found in: Component config > CONFIG_BLE_MESH
When the IV Update state enters Normal operation or IV Update in Progress, we need to keep track of
how many hours has passed in the state, since the specification requires us to remain in the state at least
for 96 hours (Update in Progress has an additional upper limit of 144 hours).
In order to fulfill the above requirement, even if the node might be powered off once in a while, we need
to store persistently how many hours the node has been in the state. This doesn’t necessarily need to
happen every hour (thanks to the flexible duration range). The exact cadence will depend a lot on the
ways that the node will be used and what kind of power source it has.
Since there is no single optimal answer, this configuration option allows specifying a divider, i.e. how
many intervals the 96 hour minimum gets split into. After each interval the duration that the node has
been in the current state gets stored to flash. E.g. the default value of 4 means that the state is saved
every 24 hours (96 / 4).
Range:
• from 2 to 96 if CONFIG_BLE_MESH
Default value:
• 4 if CONFIG_BLE_MESH
CONFIG_BLE_MESH_TX_SEG_MSG_COUNT
Maximum number of simultaneous outgoing segmented messages
Found in: Component config > CONFIG_BLE_MESH
Maximum number of simultaneous outgoing multi-segment and/or reliable messages. The default value
is 1, which means the device can only send one segmented message at a time. And if another segmented
message is going to be sent, it should wait for the completion of the previous one. If users are going to
send multiple segmented messages at the same time, this value should be configured properly.
Range:
• from 1 to if CONFIG_BLE_MESH
Default value:
• 1 if CONFIG_BLE_MESH
CONFIG_BLE_MESH_RX_SEG_MSG_COUNT
Maximum number of simultaneous incoming segmented messages
Found in: Component config > CONFIG_BLE_MESH
Maximum number of simultaneous incoming multi-segment and/or reliable messages. The default value
is 1, which means the device can only receive one segmented message at a time. And if another seg-
mented message is going to be received, it should wait for the completion of the previous one. If users
are going to receive multiple segmented messages at the same time, this value should be configured
properly.
Range:
• from 1 to 255 if CONFIG_BLE_MESH
Default value:
• 1 if CONFIG_BLE_MESH
CONFIG_BLE_MESH_RX_SDU_MAX
Maximum incoming Upper Transport Access PDU length
Found in: Component config > CONFIG_BLE_MESH
Maximum incoming Upper Transport Access PDU length. Leave this to the default value, unless you
really need to optimize memory usage.
Range:
• from 36 to 384 if CONFIG_BLE_MESH
Default value:
• 384 if CONFIG_BLE_MESH
CONFIG_BLE_MESH_TX_SEG_MAX
Maximum number of segments in outgoing messages
Found in: Component config > CONFIG_BLE_MESH
Maximum number of segments supported for outgoing messages. This value should typically be fine-
tuned based on what models the local node supports, i.e. what’s the largest message payload that the
node needs to be able to send. This value affects memory and call stack consumption, which is why the
default is lower than the maximum that the specification would allow (32 segments).
The maximum outgoing SDU size is 12 times this number (out of which 4 or 8 bytes is used for the
Transport Layer MIC). For example, 5 segments means the maximum SDU size is 60 bytes, which
leaves 56 bytes for application layer data using a 4-byte MIC and 52 bytes using an 8-byte MIC.
Be sure to specify a sufficient number of advertising buffers when setting this option to a higher value.
There must be at least three more advertising buffers (BLE_MESH_ADV_BUF_COUNT) as there are
outgoing segments.
Range:
• from 2 to 32 if CONFIG_BLE_MESH
Default value:
• 32 if CONFIG_BLE_MESH
CONFIG_BLE_MESH_RELAY
Relay support
Found in: Component config > CONFIG_BLE_MESH
Support for acting as a Mesh Relay Node. Enabling this option will allow a node to support the Relay fea-
ture, and the Relay feature can still be enabled or disabled by proper configuration messages. Disabling
this option will let a node not support the Relay feature.
Default value:
• Yes (enabled) if CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH
CONFIG_BLE_MESH_RELAY_ADV_BUF
Use separate advertising buffers for relay packets
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_RELAY
When selected, self-send packets will be put in a high-priority queue and relay packets will be put in a
low-priority queue.
Default value:
• No (disabled) if CONFIG_BLE_MESH_RELAY && CONFIG_BLE_MESH
CONFIG_BLE_MESH_RELAY_ADV_BUF_COUNT
Number of advertising buffers for relay packets
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_RELAY > CON-
FIG_BLE_MESH_RELAY_ADV_BUF
Number of advertising buffers for relay packets available.
Range:
• from 6 to 256 if CONFIG_BLE_MESH_RELAY_ADV_BUF && CON-
FIG_BLE_MESH_RELAY && CONFIG_BLE_MESH
Default value:
• 60 if CONFIG_BLE_MESH_RELAY_ADV_BUF && CONFIG_BLE_MESH_RELAY &&
CONFIG_BLE_MESH
CONFIG_BLE_MESH_LOW_POWER
Support for Low Power features
Found in: Component config > CONFIG_BLE_MESH
Enable this option to operate as a Low Power Node. If low power consumption is required by a node,
this option should be enabled. And once the node enters the mesh network, it will try to find a Friend
node and establish a friendship.
CONFIG_BLE_MESH_LPN_ESTABLISHMENT
Perform Friendship establishment using low power
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER
Perform the Friendship establishment using low power with the help of a reduced scan duty cycle. The
downside of this is that the node may miss out on messages intended for it until it has successfully set up
Friendship with a Friend node. When this option is enabled, the node will stop scanning for a period of
time after a Friend Request or Friend Poll is sent, so as to reduce more power consumption.
Default value:
• No (disabled) if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_LPN_AUTO
Automatically start looking for Friend nodes once provisioned
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER
Once provisioned, automatically enable LPN functionality and start looking for Friend nodes. If this
option is disabled LPN mode needs to be manually enabled by calling bt_mesh_lpn_set(true). When an
unprovisioned device is provisioned successfully and becomes a node, enabling this option will trigger
the node starts to send Friend Request at a certain period until it finds a proper Friend node.
Default value:
• No (disabled) if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_LPN_AUTO_TIMEOUT
Time from last received message before going to LPN mode
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER > CON-
FIG_BLE_MESH_LPN_AUTO
Time in seconds from the last received message, that the node waits out before starting to look for Friend
nodes.
Range:
• from 0 to 3600 if CONFIG_BLE_MESH_LPN_AUTO && CON-
FIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
Default value:
• 15 if CONFIG_BLE_MESH_LPN_AUTO && CONFIG_BLE_MESH_LOW_POWER &&
CONFIG_BLE_MESH
CONFIG_BLE_MESH_LPN_RETRY_TIMEOUT
Retry timeout for Friend requests
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER
Time in seconds between Friend Requests, if a previous Friend Request did not yield any acceptable
Friend Offers.
Range:
CONFIG_BLE_MESH_LPN_RSSI_FACTOR
RSSIFactor, used in Friend Offer Delay calculation
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER
The contribution of the RSSI, measured by the Friend node, used in Friend Offer Delay calculations. 0
= 1, 1 = 1.5, 2 = 2, 3 = 2.5. RSSIFactor, one of the parameters carried by Friend Request sent by Low
Power node, which is used to calculate the Friend Offer Delay.
Range:
• from 0 to 3 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
Default value:
• 0 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_LPN_RECV_WIN_FACTOR
ReceiveWindowFactor, used in Friend Offer Delay calculation
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER
The contribution of the supported Receive Window used in Friend Offer Delay calculations. 0 = 1, 1
= 1.5, 2 = 2, 3 = 2.5. ReceiveWindowFactor, one of the parameters carried by Friend Request sent by
Low Power node, which is used to calculate the Friend Offer Delay.
Range:
• from 0 to 3 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
Default value:
• 0 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_LPN_MIN_QUEUE_SIZE
Minimum size of the acceptable friend queue (MinQueueSizeLog)
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER
The MinQueueSizeLog field is defined as log_2(N), where N is the minimum number of maximum size
Lower Transport PDUs that the Friend node can store in its Friend Queue. As an example, MinQueue-
SizeLog value 1 gives N = 2, and value 7 gives N = 128.
Range:
• from 1 to 7 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
Default value:
• 1 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_LPN_RECV_DELAY
Receive delay requested by the local node
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER
The ReceiveDelay is the time between the Low Power node sending a request and listening for a response.
This delay allows the Friend node time to prepare the response. The value is in units of milliseconds.
Range:
• from 10 to 255 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
Default value:
• 100 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_LPN_POLL_TIMEOUT
The value of the PollTimeout timer
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER
PollTimeout timer is used to measure time between two consecutive requests sent by a Low Power node.
If no requests are received the Friend node before the PollTimeout timer expires, then the friendship
is considered terminated. The value is in units of 100 milliseconds, so e.g. a value of 300 means 30
seconds. The smaller the value, the faster the Low Power node tries to get messages from corresponding
Friend node and vice versa.
Range:
• from 10 to 244735 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
Default value:
• 300 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_LPN_INIT_POLL_TIMEOUT
The starting value of the PollTimeout timer
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER
The initial value of the PollTimeout timer when Friendship is to be established for the first time. After
this, the timeout gradually grows toward the actual PollTimeout, doubling in value for each iteration.
The value is in units of 100 milliseconds, so e.g. a value of 300 means 30 seconds.
Range:
• from 10 to if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
Default value:
• if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_LPN_SCAN_LATENCY
Latency for enabling scanning
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER
Latency (in milliseconds) is the time it takes to enable scanning. In practice, it means how much time in
advance of the Receive Window, the request to enable scanning is made.
Range:
• from 0 to 50 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
Default value:
• 10 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_LPN_GROUPS
Number of groups the LPN can subscribe to
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_LOW_POWER
Maximum number of groups to which the LPN can subscribe.
Range:
• from 0 to 16384 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
Default value:
• 8 if CONFIG_BLE_MESH_LOW_POWER && CONFIG_BLE_MESH
CONFIG_BLE_MESH_FRIEND
CONFIG_BLE_MESH_FRIEND_RECV_WIN
Friend Receive Window
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND
Receive Window in milliseconds supported by the Friend node.
Range:
• from 1 to 255 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH
Default value:
• 255 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH
CONFIG_BLE_MESH_FRIEND_QUEUE_SIZE
Minimum number of buffers supported per Friend Queue
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND
Minimum number of buffers available to be stored for each local Friend Queue. This option decides the
size of each buffer which can be used by a Friend node to store messages for each Low Power node.
Range:
• from 2 to 65536 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH
Default value:
• 16 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH
CONFIG_BLE_MESH_FRIEND_SUB_LIST_SIZE
Friend Subscription List Size
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND
Size of the Subscription List that can be supported by a Friend node for a Low Power node. And Low
Power node can send Friend Subscription List Add or Friend Subscription List Remove messages to the
Friend node to add or remove subscription addresses.
Range:
• from 0 to 1023 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH
Default value:
• 3 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH
CONFIG_BLE_MESH_FRIEND_LPN_COUNT
Number of supported LPN nodes
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND
Number of Low Power Nodes with which a Friend can have Friendship simultaneously. A Friend node
can have friendship with multiple Low Power nodes at the same time, while a Low Power node can only
establish friendship with only one Friend node at the same time.
Range:
• from 1 to 1000 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH
Default value:
• 2 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH
CONFIG_BLE_MESH_FRIEND_SEG_RX
Number of incomplete segment lists per LPN
Found in: Component config > CONFIG_BLE_MESH > CONFIG_BLE_MESH_FRIEND
Number of incomplete segment lists tracked for each Friends’LPN. In other words, this determines from
how many elements can segmented messages destined for the Friend queue be received simultaneously.
Range:
• from 1 to 1000 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH
Default value:
• 1 if CONFIG_BLE_MESH_FRIEND && CONFIG_BLE_MESH
CONFIG_BLE_MESH_NO_LOG
Disable BLE Mesh debug logs (minimize bin size)
Found in: Component config > CONFIG_BLE_MESH
Select this to save the BLE Mesh related rodata code size. Enabling this option will disable the output
of BLE Mesh debug log.
Default value:
• No (disabled) if CONFIG_BLE_MESH && CONFIG_BLE_MESH
CONFIG_BLE_MESH_STACK_TRACE_LEVEL
BLE_MESH_STACK
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh STACK DEBUG LOG LEVEL
Define BLE Mesh trace level for BLE Mesh stack.
Available options:
• NONE (BLE_MESH_TRACE_LEVEL_NONE)
• ERROR (BLE_MESH_TRACE_LEVEL_ERROR)
• WARNING (BLE_MESH_TRACE_LEVEL_WARNING)
• INFO (BLE_MESH_TRACE_LEVEL_INFO)
• DEBUG (BLE_MESH_TRACE_LEVEL_DEBUG)
• VERBOSE (BLE_MESH_TRACE_LEVEL_VERBOSE)
CONFIG_BLE_MESH_NET_BUF_TRACE_LEVEL
BLE_MESH_NET_BUF
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh NET BUF DEBUG LOG LEVEL
Define BLE Mesh trace level for BLE Mesh net buffer.
Available options:
• NONE (BLE_MESH_NET_BUF_TRACE_LEVEL_NONE)
• ERROR (BLE_MESH_NET_BUF_TRACE_LEVEL_ERROR)
• WARNING (BLE_MESH_NET_BUF_TRACE_LEVEL_WARNING)
• INFO (BLE_MESH_NET_BUF_TRACE_LEVEL_INFO)
• DEBUG (BLE_MESH_NET_BUF_TRACE_LEVEL_DEBUG)
• VERBOSE (BLE_MESH_NET_BUF_TRACE_LEVEL_VERBOSE)
CONFIG_BLE_MESH_CLIENT_MSG_TIMEOUT
Timeout(ms) for client message response
Found in: Component config > CONFIG_BLE_MESH
Timeout value used by the node to get response of the acknowledged message which is sent by the client
model. This value indicates the maximum time that a client model waits for the response of the sent
acknowledged messages. If a client model uses 0 as the timeout value when sending acknowledged
messages, then the default value will be used which is four seconds.
Range:
• from 100 to 1200000 if CONFIG_BLE_MESH
Default value:
• 4000 if CONFIG_BLE_MESH
CONFIG_BLE_MESH_CFG_CLI
Configuration Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models
Enable support for Configuration Client model.
CONFIG_BLE_MESH_HEALTH_CLI
Health Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models
Enable support for Health Client model.
CONFIG_BLE_MESH_HEALTH_SRV
Health Server model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Foundation models
Enable support for Health Server model.
Default value:
• Yes (enabled) if CONFIG_BLE_MESH
• CONFIG_BLE_MESH_LIGHT_CTL_CLI
• CONFIG_BLE_MESH_LIGHT_HSL_CLI
• CONFIG_BLE_MESH_LIGHT_LC_CLI
• CONFIG_BLE_MESH_LIGHT_LIGHTNESS_CLI
• CONFIG_BLE_MESH_LIGHT_XYL_CLI
• CONFIG_BLE_MESH_LIGHTING_SERVER
• CONFIG_BLE_MESH_SCENE_CLI
• CONFIG_BLE_MESH_SCHEDULER_CLI
• CONFIG_BLE_MESH_SENSOR_CLI
• CONFIG_BLE_MESH_SENSOR_SERVER
• CONFIG_BLE_MESH_TIME_SCENE_SERVER
• CONFIG_BLE_MESH_TIME_CLI
CONFIG_BLE_MESH_GENERIC_ONOFF_CLI
Generic OnOff Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Generic OnOff Client model.
CONFIG_BLE_MESH_GENERIC_LEVEL_CLI
Generic Level Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Generic Level Client model.
CONFIG_BLE_MESH_GENERIC_DEF_TRANS_TIME_CLI
Generic Default Transition Time Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Generic Default Transition Time Client model.
CONFIG_BLE_MESH_GENERIC_POWER_ONOFF_CLI
Generic Power OnOff Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Generic Power OnOff Client model.
CONFIG_BLE_MESH_GENERIC_POWER_LEVEL_CLI
Generic Power Level Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Generic Power Level Client model.
CONFIG_BLE_MESH_GENERIC_BATTERY_CLI
Generic Battery Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Generic Battery Client model.
CONFIG_BLE_MESH_GENERIC_LOCATION_CLI
Generic Location Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Generic Location Client model.
CONFIG_BLE_MESH_GENERIC_PROPERTY_CLI
Generic Property Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Generic Property Client model.
CONFIG_BLE_MESH_SENSOR_CLI
Sensor Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Sensor Client model.
CONFIG_BLE_MESH_TIME_CLI
Time Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Time Client model.
CONFIG_BLE_MESH_SCENE_CLI
Scene Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Scene Client model.
CONFIG_BLE_MESH_SCHEDULER_CLI
Scheduler Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Scheduler Client model.
CONFIG_BLE_MESH_LIGHT_LIGHTNESS_CLI
Light Lightness Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Light Lightness Client model.
CONFIG_BLE_MESH_LIGHT_CTL_CLI
Light CTL Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Light CTL Client model.
CONFIG_BLE_MESH_LIGHT_HSL_CLI
Light HSL Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Light HSL Client model.
CONFIG_BLE_MESH_LIGHT_XYL_CLI
Light XYL Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Light XYL Client model.
CONFIG_BLE_MESH_LIGHT_LC_CLI
Light LC Client model
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Light LC Client model.
CONFIG_BLE_MESH_GENERIC_SERVER
Generic server models
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Generic server models.
Default value:
• Yes (enabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_SENSOR_SERVER
Sensor server models
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Sensor server models.
Default value:
• Yes (enabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_TIME_SCENE_SERVER
Time and Scenes server models
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Time and Scenes server models.
Default value:
• Yes (enabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_LIGHTING_SERVER
Lighting server models
Found in: Component config > CONFIG_BLE_MESH > Support for BLE Mesh Client/Server models
Enable support for Lighting server models.
Default value:
• Yes (enabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_IV_UPDATE_TEST
Test the IV Update Procedure
Found in: Component config > CONFIG_BLE_MESH
This option removes the 96 hour limit of the IV Update Procedure and lets the state to be changed at
any time. If IV Update test mode is going to be used, this option should be enabled.
Default value:
• No (disabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_SELF_TEST
Perform BLE Mesh self-tests
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option
This option adds extra self-tests which are run every time BLE Mesh networking is initialized.
Default value:
• No (disabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_TEST_AUTO_ENTER_NETWORK
Unprovisioned device enters mesh network automatically
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CON-
FIG_BLE_MESH_SELF_TEST
With this option enabled, an unprovisioned device can automatically enters mesh network using a specific
test function without the pro- visioning procedure. And on the Provisioner side, a test function needs to
be invoked to add the node information into the mesh stack.
Default value:
• Yes (enabled) if CONFIG_BLE_MESH_SELF_TEST && CONFIG_BLE_MESH
CONFIG_BLE_MESH_TEST_USE_WHITE_LIST
Use white list to filter mesh advertising packets
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CON-
FIG_BLE_MESH_SELF_TEST
With this option enabled, users can use white list to filter mesh advertising packets while scanning.
Default value:
• No (disabled) if CONFIG_BLE_MESH_SELF_TEST && CONFIG_BLE_MESH
CONFIG_BLE_MESH_SHELL
Enable BLE Mesh shell
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option
Activate shell module that provides BLE Mesh commands to the console.
Default value:
• No (disabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_DEBUG
Enable BLE Mesh debug logs
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option
Enable debug logs for the BLE Mesh functionality.
Default value:
• No (disabled) if CONFIG_BLE_MESH
CONFIG_BLE_MESH_DEBUG_NET
Network layer debug
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CON-
FIG_BLE_MESH_DEBUG
Enable Network layer debug logs for the BLE Mesh functionality.
CONFIG_BLE_MESH_DEBUG_TRANS
Transport layer debug
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CON-
FIG_BLE_MESH_DEBUG
Enable Transport layer debug logs for the BLE Mesh functionality.
CONFIG_BLE_MESH_DEBUG_BEACON
Beacon debug
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CON-
FIG_BLE_MESH_DEBUG
Enable Beacon-related debug logs for the BLE Mesh functionality.
CONFIG_BLE_MESH_DEBUG_CRYPTO
Crypto debug
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CON-
FIG_BLE_MESH_DEBUG
Enable cryptographic debug logs for the BLE Mesh functionality.
CONFIG_BLE_MESH_DEBUG_PROV
Provisioning debug
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CON-
FIG_BLE_MESH_DEBUG
Enable Provisioning debug logs for the BLE Mesh functionality.
CONFIG_BLE_MESH_DEBUG_ACCESS
Access layer debug
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CON-
FIG_BLE_MESH_DEBUG
Enable Access layer debug logs for the BLE Mesh functionality.
CONFIG_BLE_MESH_DEBUG_MODEL
Foundation model debug
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CON-
FIG_BLE_MESH_DEBUG
Enable Foundation Models debug logs for the BLE Mesh functionality.
CONFIG_BLE_MESH_DEBUG_ADV
Advertising debug
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CON-
FIG_BLE_MESH_DEBUG
Enable advertising debug logs for the BLE Mesh functionality.
CONFIG_BLE_MESH_DEBUG_LOW_POWER
Low Power debug
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CON-
FIG_BLE_MESH_DEBUG
Enable Low Power debug logs for the BLE Mesh functionality.
CONFIG_BLE_MESH_DEBUG_FRIEND
Friend debug
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CON-
FIG_BLE_MESH_DEBUG
Enable Friend debug logs for the BLE Mesh functionality.
CONFIG_BLE_MESH_DEBUG_PROXY
Proxy debug
Found in: Component config > CONFIG_BLE_MESH > BLE Mesh specific test option > CON-
FIG_BLE_MESH_DEBUG
Enable Proxy protocol debug logs for the BLE Mesh functionality.
CONFIG_ADC_FORCE_XPD_FSM
Use the FSM to control ADC power
Found in: Component config > Driver Configurations > ADC Configuration
ADC power can be controlled by the FSM instead of software. This allows the ADC to be shut off when
it is not working leading to lower power consumption. However using the FSM control ADC power will
increase the noise of ADC.
Default value:
• No (disabled)
CONFIG_ADC_DISABLE_DAC
Disable DAC when ADC2 is used on GPIO 25 and 26
Found in: Component config > Driver Configurations > ADC Configuration
If this is set, the ADC2 driver will disable the output of the DAC corresponding to the specified channel.
This is the default value.
For testing, disable this option so that we can measure the output of DAC by internal ADC.
Default value:
• Yes (enabled)
CONFIG_SPI_MASTER_IN_IRAM
Place transmitting functions of SPI master into IRAM
Found in: Component config > Driver Configurations > SPI Configuration
Normally only the ISR of SPI master is placed in the IRAM, so that it can work without the flash when
interrupt is triggered. For other functions, there’s some possibility that the flash cache miss when
running inside and out of SPI functions, which may increase the interval of SPI transactions. Enable
this to put queue\_trans, get\_trans\_result and transmit functions into the IRAM to
avoid possible cache miss.
During unit test, this is enabled to measure the ideal case of api.
Default value:
• No (disabled)
CONFIG_SPI_MASTER_ISR_IN_IRAM
Place SPI master ISR function into IRAM
Found in: Component config > Driver Configurations > SPI Configuration
Place the SPI master ISR in to IRAM to avoid possible cache miss.
Also you can forbid the ISR being disabled during flash writing access, by add
ESP_INTR_FLAG_IRAM when initializing the driver.
Default value:
• Yes (enabled)
CONFIG_SPI_SLAVE_IN_IRAM
Place transmitting functions of SPI slave into IRAM
Found in: Component config > Driver Configurations > SPI Configuration
Normally only the ISR of SPI slave is placed in the IRAM, so that it can work without the flash when
interrupt is triggered. For other functions, there’s some possibility that the flash cache miss when
running inside and out of SPI functions, which may increase the interval of SPI transactions. Enable
this to put queue\_trans, get\_trans\_result and transmit functions into the IRAM to
avoid possible cache miss.
Default value:
• No (disabled)
CONFIG_SPI_SLAVE_ISR_IN_IRAM
Place SPI slave ISR function into IRAM
Found in: Component config > Driver Configurations > SPI Configuration
Place the SPI slave ISR in to IRAM to avoid possible cache miss.
Also you can forbid the ISR being disabled during flash writing access, by add
ESP_INTR_FLAG_IRAM when initializing the driver.
Default value:
• Yes (enabled)
CONFIG_TWAI_ISR_IN_IRAM
Place TWAI ISR function into IRAM
Found in: Component config > Driver Configurations > TWAI Configuration
Place the TWAI ISR in to IRAM. This will allow the ISR to avoid cache misses, and also be able to run
whilst the cache is disabled (such as when writing to SPI Flash). Note that if this option is enabled: -
Users should also set the ESP_INTR_FLAG_IRAM in the driver configuration structure when installing
the driver (see docs for specifics). - Alert logging (i.e., setting of the TWAI_ALERT_AND_LOG flag)
will have no effect.
Default value:
• No (disabled)
CONFIG_TWAI_ERRATA_FIX_BUS_OFF_REC
Add SW workaround for REC change during bus-off
Found in: Component config > Driver Configurations > TWAI Configuration
When the bus-off condition is reached, the REC should be reset to 0 and frozen (via LOM) by the driver’
s ISR. However on the ESP32, there is an edge case where the REC will increase before the driver’s
ISR can respond in time (e.g., due to the rapid occurrence of bus errors), thus causing the REC to be
non-zero after bus-off. A non-zero REC can prevent bus-off recovery as the bus-off recovery condition
is that both TEC and REC become 0. Enabling this option will add a workaround in the driver to forcibly
reset REC to zero on reaching bus-off.
Default value:
• Yes (enabled)
CONFIG_TWAI_ERRATA_FIX_TX_INTR_LOST
Add SW workaround for TX interrupt lost errata
Found in: Component config > Driver Configurations > TWAI Configuration
On the ESP32, when a transmit interrupt occurs, and interrupt register is read on the same APB clock
cycle, the transmit interrupt could be lost. Enabling this option will add a workaround that checks the
transmit buffer status bit to recover any lost transmit interrupt.
Default value:
• Yes (enabled)
CONFIG_TWAI_ERRATA_FIX_RX_FRAME_INVALID
Add SW workaround for invalid RX frame errata
Found in: Component config > Driver Configurations > TWAI Configuration
On the ESP32, when receiving a data or remote frame, if a bus error occurs in the data or CRC field,
the data of the next received frame could be invalid. Enabling this option will add a workaround that
will reset the peripheral on detection of this errata condition. Note that if a frame is transmitted on the
bus whilst the reset is ongoing, the message will not be receive by the peripheral sent on the bus during
the reset, the message will be lost.
Default value:
• Yes (enabled)
CONFIG_TWAI_ERRATA_FIX_RX_FIFO_CORRUPT
Add SW workaround for RX FIFO corruption errata
Found in: Component config > Driver Configurations > TWAI Configuration
On the ESP32, when the RX FIFO overruns and the RX message counter maxes out at 64 messages,
the entire RX FIFO is no longer recoverable. Enabling this option will add a workaround that resets the
peripheral on detection of this errata condition. Note that if a frame is being sent on the bus during the
reset bus during the reset, the message will be lost.
Default value:
• Yes (enabled)
CONFIG_TEMP_SENSOR_SUPPRESS_DEPRECATE_WARN
Suppress legacy driver deprecated warning
Found in: Component config > Driver Configurations > Temperature sensor Configuration
Wether to suppress the deprecation warnings when using legacy temperature sensor driver
(driver/temp_sensor.h). If you want to continue using the legacy driver, and don’t want to see related
deprecation warnings, you can enable this option.
Default value:
• No (disabled) if SOC_TEMP_SENSOR_SUPPORTED
CONFIG_TEMP_SENSOR_ENABLE_DEBUG_LOG
Enable debug log
Found in: Component config > Driver Configurations > Temperature sensor Configuration
Wether to enable the debug log message for temperature sensor driver. Note that, this option only
controls the temperature sensor driver log, won’t affect other drivers.
Default value:
• No (disabled) if SOC_TEMP_SENSOR_SUPPORTED
CONFIG_UART_ISR_IN_IRAM
Place UART ISR function into IRAM
Found in: Component config > Driver Configurations > UART Configuration
If this option is not selected, UART interrupt will be disabled for a long time and may cause data lost
when doing spi flash operation.
Default value:
• No (disabled)
CONFIG_GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL
Support light sleep GPIO pullup/pulldown configuration for ESP32
Found in: Component config > Driver Configurations > GPIO Configuration
This option is intended to fix the bug that ESP32 is not able to switch to configured pullup/pulldown
mode in sleep. If this option is selected, chip will automatically emulate the behaviour of switching, and
about 450B of source codes would be placed into IRAM.
CONFIG_GPIO_CTRL_FUNC_IN_IRAM
Place GPIO control functions into IRAM
Found in: Component config > Driver Configurations > GPIO Configuration
Place GPIO control functions (like intr_disable/set_level) into IRAM, so that these functions can be
IRAM-safe and able to be called in the other IRAM interrupt context.
Default value:
• No (disabled)
CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
Place GPTimer control functions into IRAM
Found in: Component config > Driver Configurations > GPTimer Configuration
Place GPTimer control functions (like start/stop) into IRAM, so that these functions can be IRAM-safe
and able to be called in the other IRAM interrupt context. Enabling this option can improve driver
performance as well.
Default value:
• No (disabled)
CONFIG_GPTIMER_ISR_IRAM_SAFE
GPTimer ISR IRAM-Safe
Found in: Component config > Driver Configurations > GPTimer Configuration
Ensure the GPTimer interrupt is IRAM-Safe by allowing the interrupt handler to be executable when
the cache is disabled (e.g. SPI Flash write).
Default value:
• No (disabled)
CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN
Suppress legacy driver deprecated warning
Found in: Component config > Driver Configurations > GPTimer Configuration
Wether to suppress the deprecation warnings when using legacy timer group driver (driver/timer.h). If
you want to continue using the legacy driver, and don’t want to see related deprecation warnings, you
can enable this option.
Default value:
• No (disabled)
CONFIG_GPTIMER_ENABLE_DEBUG_LOG
Enable debug log
Found in: Component config > Driver Configurations > GPTimer Configuration
Wether to enable the debug log message for GPTimer driver. Note that, this option only controls the
GPTimer driver log, won’t affect other drivers.
Default value:
• No (disabled)
CONFIG_PCNT_CTRL_FUNC_IN_IRAM
Place PCNT control functions into IRAM
Found in: Component config > Driver Configurations > PCNT Configuration
Place PCNT control functions (like start/stop) into IRAM, so that these functions can be IRAM-safe
and able to be called in the other IRAM interrupt context. Enabling this option can improve driver
performance as well.
Default value:
• No (disabled)
CONFIG_PCNT_ISR_IRAM_SAFE
PCNT ISR IRAM-Safe
Found in: Component config > Driver Configurations > PCNT Configuration
Ensure the PCNT interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the
cache is disabled (e.g. SPI Flash write).
Default value:
• No (disabled)
CONFIG_PCNT_SUPPRESS_DEPRECATE_WARN
Suppress legacy driver deprecated warning
Found in: Component config > Driver Configurations > PCNT Configuration
Wether to suppress the deprecation warnings when using legacy PCNT driver (driver/pcnt.h). If you
want to continue using the legacy driver, and don’t want to see related deprecation warnings, you can
enable this option.
Default value:
• No (disabled)
CONFIG_PCNT_ENABLE_DEBUG_LOG
Enable debug log
Found in: Component config > Driver Configurations > PCNT Configuration
Wether to enable the debug log message for PCNT driver. Note that, this option only controls the PCNT
driver log, won’t affect other drivers.
Default value:
• No (disabled)
CONFIG_RMT_ISR_IRAM_SAFE
RMT ISR IRAM-Safe
Found in: Component config > Driver Configurations > RMT Configuration
Ensure the RMT interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the
cache is disabled (e.g. SPI Flash write).
Default value:
• No (disabled)
CONFIG_RMT_SUPPRESS_DEPRECATE_WARN
Suppress legacy driver deprecated warning
Found in: Component config > Driver Configurations > RMT Configuration
Wether to suppress the deprecation warnings when using legacy rmt driver (driver/rmt.h). If you want
to continue using the legacy driver, and don’t want to see related deprecation warnings, you can enable
this option.
Default value:
• No (disabled)
CONFIG_RMT_ENABLE_DEBUG_LOG
Enable debug log
Found in: Component config > Driver Configurations > RMT Configuration
Wether to enable the debug log message for RMT driver. Note that, this option only controls the RMT
driver log, won’t affect other drivers.
Default value:
• No (disabled)
CONFIG_MCPWM_ISR_IRAM_SAFE
Place MCPWM ISR function into IRAM
Found in: Component config > Driver Configurations > MCPWM Configuration
This will ensure the MCPWM interrupt handle is IRAM-Safe, allow to avoid flash cache misses, and
also be able to run whilst the cache is disabled. (e.g. SPI Flash write)
Default value:
• No (disabled)
CONFIG_I2S_ISR_IRAM_SAFE
I2S ISR IRAM-Safe
Found in: Component config > Driver Configurations > I2S Configuration
Ensure the I2S interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the cache
is disabled (e.g. SPI Flash write).
Default value:
• No (disabled)
CONFIG_I2S_SUPPRESS_DEPRECATE_WARN
Suppress leagcy driver deprecated warning
Found in: Component config > Driver Configurations > I2S Configuration
Enable this option will suppress the deprecation warnings of using APIs in legacy I2S driver.
Default value:
• No (disabled)
CONFIG_I2S_ENABLE_DEBUG_LOG
Enable I2S debug log
Found in: Component config > Driver Configurations > I2S Configuration
Wether to enable the debug log message for I2S driver. Note that, this option only controls the I2S driver
log, will not affect other drivers.
Default value:
• No (disabled)
CONFIG_EFUSE_CUSTOM_TABLE
Use custom eFuse table
Found in: Component config > eFuse Bit Manager
Allows to generate a structure for eFuse from the CSV file.
Default value:
• No (disabled)
CONFIG_EFUSE_CUSTOM_TABLE_FILENAME
Custom eFuse CSV file
Found in: Component config > eFuse Bit Manager > CONFIG_EFUSE_CUSTOM_TABLE
Name of the custom eFuse CSV filename. This path is evaluated relative to the project root directory.
Default value:
• “main/esp_efuse_custom_table.csv”if CONFIG_EFUSE_CUSTOM_TABLE
CONFIG_EFUSE_VIRTUAL
Simulate eFuse operations in RAM
Found in: Component config > eFuse Bit Manager
If“n”- No virtual mode. All eFuse operations are real and use eFuse registers. If“y”- The virtual mode
is enabled and all eFuse operations (read and write) are redirected to RAM instead of eFuse registers,
all permanent changes (via eFuse) are disabled. Log output will state changes that would be applied, but
they will not be.
During startup, the eFuses are copied into RAM. This mode is useful for fast tests.
Default value:
• No (disabled)
CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH
Keep eFuses in flash
Found in: Component config > eFuse Bit Manager > CONFIG_EFUSE_VIRTUAL
In addition to the “Simulate eFuse operations in RAM”option, this option just adds a feature to keep
eFuses after reboots in flash memory. To use this mode the partition_table should have the efuse partition.
partition.csv: “efuse_em, data, efuse, , 0x2000,”
During startup, the eFuses are copied from flash or, in case if flash is empty, from real eFuse to RAM
and then update flash. This mode is useful when need to keep changes after reboot (testing secure_boot
and flash_encryption).
CONFIG_EFUSE_CODE_SCHEME_SELECTOR
Coding Scheme Compatibility
Found in: Component config > eFuse Bit Manager
Selector eFuse code scheme.
Available options:
• None Only (EFUSE_CODE_SCHEME_COMPAT_NONE)
• 3/4 and None (EFUSE_CODE_SCHEME_COMPAT_3_4)
• Repeat, 3/4 and None (common table does not support it)
(EFUSE_CODE_SCHEME_COMPAT_REPEAT)
ESP-TLS Contains:
• CONFIG_ESP_TLS_INSECURE
• CONFIG_ESP_TLS_LIBRARY_CHOOSE
• CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS
• CONFIG_ESP_DEBUG_WOLFSSL
• CONFIG_ESP_TLS_SERVER
• CONFIG_ESP_TLS_PSK_VERIFICATION
• CONFIG_ESP_WOLFSSL_SMALL_CERT_VERIFY
• CONFIG_ESP_TLS_USE_DS_PERIPHERAL
• CONFIG_ESP_TLS_USE_SECURE_ELEMENT
CONFIG_ESP_TLS_LIBRARY_CHOOSE
Choose SSL/TLS library for ESP-TLS (See help for more Info)
Found in: Component config > ESP-TLS
The ESP-TLS APIs support multiple backend TLS libraries. Currently mbedTLS and WolfSSL are
supported. Different TLS libraries may support different features and have different resource usage.
Consult the ESP-TLS documentation in ESP-IDF Programming guide for more details.
Available options:
• mbedTLS (ESP_TLS_USING_MBEDTLS)
• wolfSSL (License info in wolfSSL directory README) (ESP_TLS_USING_WOLFSSL)
CONFIG_ESP_TLS_USE_SECURE_ELEMENT
Use Secure Element (ATECC608A) with ESP-TLS
Found in: Component config > ESP-TLS
Enable use of Secure Element for ESP-TLS, this enables internal support for ATECC608A peripheral
on ESPWROOM32SE, which can be used for TLS connection.
CONFIG_ESP_TLS_USE_DS_PERIPHERAL
Use Digital Signature (DS) Peripheral with ESP-TLS
Found in: Component config > ESP-TLS
Enable use of the Digital Signature Peripheral for ESP-TLS.The DS peripheral can only be used when
it is appropriately configured for TLS. Consult the ESP-TLS documentation in ESP-IDF Programming
Guide for more details.
Default value:
• Yes (enabled) if ESP_TLS_USING_MBEDTLS && SOC_DIG_SIGN_SUPPORTED
CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS
Enable client session tickets
Found in: Component config > ESP-TLS
Enable session ticket support as specified in RFC5077.
CONFIG_ESP_TLS_SERVER
Enable ESP-TLS Server
Found in: Component config > ESP-TLS
Enable support for creating server side SSL/TLS session, available for mbedTLS as well as wolfSSL
TLS library.
CONFIG_ESP_TLS_SERVER_SESSION_TICKETS
Enable server session tickets
Found in: Component config > ESP-TLS > CONFIG_ESP_TLS_SERVER
Enable session ticket support as specified in RFC5077
CONFIG_ESP_TLS_SERVER_SESSION_TICKET_TIMEOUT
Server session ticket timeout in seconds
Found in: Component config > ESP-TLS > CONFIG_ESP_TLS_SERVER > CON-
FIG_ESP_TLS_SERVER_SESSION_TICKETS
Sets the session ticket timeout used in the tls server.
Default value:
• 86400 if CONFIG_ESP_TLS_SERVER_SESSION_TICKETS
CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL
ESP-TLS Server: Set minimum Certificate Verification mode to Optional
Found in: Component config > ESP-TLS > CONFIG_ESP_TLS_SERVER
When this option is enabled, the peer (here, the client) certificate is checked by the server, however the
handshake continues even if verification failed. By default, the peer certificate is not checked and ignored
by the server.
mbedtls_ssl_get_verify_result() can be called after the handshake is complete to retrieve status of veri-
fication.
CONFIG_ESP_TLS_PSK_VERIFICATION
Enable PSK verification
Found in: Component config > ESP-TLS
Enable support for pre shared key ciphers, supported for both mbedTLS as well as wolfSSL TLS library.
CONFIG_ESP_TLS_INSECURE
Allow potentially insecure options
Found in: Component config > ESP-TLS
You can enable some potentially insecure options. These options should only be used for testing pusposes.
Only enable these options if you are very sure.
CONFIG_ESP_TLS_SKIP_SERVER_CERT_VERIFY
Skip server certificate verification by default (WARNING: ONLY FOR TESTING PURPOSE, READ
HELP)
Found in: Component config > ESP-TLS > CONFIG_ESP_TLS_INSECURE
After enabling this option the esp-tls client will skip the server certificate verification by default. Note that
this option will only modify the default behaviour of esp-tls client regarding server cert verification. The
default behaviour should only be applicable when no other option regarding the server cert verification
is opted in the esp-tls config (e.g. crt_bundle_attach, use_global_ca_store etc.). WARNING : Enabling
this option comes with a potential risk of establishing a TLS connection with a server which has a fake
identity, provided that the server certificate is not provided either through API or other mechanism like
ca_store etc.
CONFIG_ESP_WOLFSSL_SMALL_CERT_VERIFY
Enable SMALL_CERT_VERIFY
Found in: Component config > ESP-TLS
Enables server verification with Intermediate CA cert, does not authenticate full chain of trust upto the
root CA cert (After Enabling this option client only needs to have Intermediate CA certificate of the
server to authenticate server, root CA cert is not necessary).
Default value:
• Yes (enabled) if ESP_TLS_USING_WOLFSSL
CONFIG_ESP_DEBUG_WOLFSSL
Enable debug logs for wolfSSL
Found in: Component config > ESP-TLS
Enable detailed debug prints for wolfSSL SSL library.
ADC-Calibration Contains:
• CONFIG_ADC_CAL_EFUSE_VREF_ENABLE
• CONFIG_ADC_CAL_LUT_ENABLE
• CONFIG_ADC_CAL_EFUSE_TP_ENABLE
CONFIG_ADC_CAL_EFUSE_TP_ENABLE
Use Two Point Values
Found in: Component config > ADC-Calibration
Some ESP32s have Two Point calibration values burned into eFuse BLOCK3. This option will allow
the ADC calibration component to characterize the ADC-Voltage curve using Two Point values if they
are available.
Default value:
• Yes (enabled)
CONFIG_ADC_CAL_EFUSE_VREF_ENABLE
Use eFuse Vref
Found in: Component config > ADC-Calibration
Some ESP32s have Vref burned into eFuse BLOCK0. This option will allow the ADC calibration
component to characterize the ADC-Voltage curve using eFuse Vref if it is available.
Default value:
• Yes (enabled)
CONFIG_ADC_CAL_LUT_ENABLE
Use Lookup Tables
Found in: Component config > ADC-Calibration
This option will allow the ADC calibration component to use Lookup Tables to correct for non-linear
behavior in 11db attenuation. Other attenuations do not exhibit non-linear behavior hence will not be
affected by this option.
Default value:
• Yes (enabled)
CONFIG_ESP_ERR_TO_NAME_LOOKUP
Enable lookup of error code strings
Found in: Component config > Common ESP-related
Functions esp_err_to_name() and esp_err_to_name_r() return string representations of error codes from
a pre-generated lookup table. This option can be used to turn off the use of the look-up table in order
to save memory but this comes at the price of sacrificing distinguishable (meaningful) output string
representations.
Default value:
• Yes (enabled)
Ethernet Contains:
• CONFIG_ETH_TRANSMIT_MUTEX
• CONFIG_ETH_USE_ESP32_EMAC
• CONFIG_ETH_USE_OPENETH
• CONFIG_ETH_USE_SPI_ETHERNET
CONFIG_ETH_USE_ESP32_EMAC
Support ESP32 internal EMAC controller
Found in: Component config > Ethernet
ESP32 integrates a 10/100M Ethernet MAC controller.
Default value:
• Yes (enabled)
Contains:
• CONFIG_ETH_DMA_RX_BUFFER_NUM
• CONFIG_ETH_DMA_TX_BUFFER_NUM
• CONFIG_ETH_SOFT_FLOW_CONTROL
• CONFIG_ETH_DMA_BUFFER_SIZE
• CONFIG_ETH_RMII_CLK_OUTPUT_GPIO0
• CONFIG_ETH_PHY_INTERFACE
• CONFIG_ETH_RMII_CLK_OUT_GPIO
• CONFIG_ETH_RMII_CLK_MODE
CONFIG_ETH_PHY_INTERFACE
PHY interface
Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC
Select the communication interface between MAC and PHY chip.
Available options:
• Reduced Media Independent Interface (RMII) (ETH_PHY_INTERFACE_RMII)
CONFIG_ETH_RMII_CLK_MODE
RMII clock mode
Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC
Select external or internal RMII clock.
Available options:
• Input RMII clock from external (ETH_RMII_CLK_INPUT)
MAC will get RMII clock from outside. Note that ESP32 only supports GPIO0 to input the
RMII clock.
• Output RMII clock from internal (ETH_RMII_CLK_OUTPUT)
ESP32 can generate RMII clock by internal APLL. This clock can be routed to the external
PHY device. ESP32 supports to route the RMII clock to GPIO0/16/17.
CONFIG_ETH_RMII_CLK_OUTPUT_GPIO0
Output RMII clock from GPIO0 (Experimental!)
Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC
GPIO0 can be set to output a pre-divided PLL clock (test only!). Enabling this option will configure
GPIO0 to output a 50MHz clock. In fact this clock doesn’t have directly relationship with EMAC
peripheral. Sometimes this clock won’t work well with your PHY chip. You might need to add some
extra devices after GPIO0 (e.g. inverter). Note that outputting RMII clock on GPIO0 is an experimental
practice. If you want the Ethernet to work with WiFi, don’t select GPIO0 output mode for stability.
Default value:
• No (disabled) if ETH_RMII_CLK_OUTPUT && CONFIG_ETH_USE_ESP32_EMAC
CONFIG_ETH_RMII_CLK_OUT_GPIO
RMII clock GPIO number
Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC
Set the GPIO number to output RMII Clock.
Range:
• from 16 to 17 if CONFIG_ETH_RMII_CLK_OUTPUT_GPIO0 &&
ETH_RMII_CLK_OUTPUT && CONFIG_ETH_USE_ESP32_EMAC
Default value:
• 17 if CONFIG_ETH_RMII_CLK_OUTPUT_GPIO0 && ETH_RMII_CLK_OUTPUT &&
CONFIG_ETH_USE_ESP32_EMAC
CONFIG_ETH_DMA_BUFFER_SIZE
Ethernet DMA buffer size (Byte)
Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC
Set the size of each buffer used by Ethernet MAC DMA.
Range:
• from 256 to 1600
Default value:
• 512
CONFIG_ETH_DMA_RX_BUFFER_NUM
Amount of Ethernet DMA Rx buffers
Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC
Number of DMA receive buffers. Each buffer’s size is ETH_DMA_BUFFER_SIZE. Larger number
of buffers could increase throughput somehow.
Range:
• from 3 to 30
Default value:
• 10
CONFIG_ETH_DMA_TX_BUFFER_NUM
Amount of Ethernet DMA Tx buffers
Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC
Number of DMA transmit buffers. Each buffer’s size is ETH_DMA_BUFFER_SIZE. Larger number
of buffers could increase throughput somehow.
Range:
• from 3 to 30
Default value:
• 10
CONFIG_ETH_SOFT_FLOW_CONTROL
Enable software flow control
Found in: Component config > Ethernet > CONFIG_ETH_USE_ESP32_EMAC
Ethernet MAC engine on ESP32 doesn’t feature a flow control logic. The MAC driver can perform
a software flow control if you enable this option. Note that, if the RX buffer number is small, enabling
software flow control will cause obvious performance loss.
Default value:
• No (disabled) if CONFIG_ETH_DMA_RX_BUFFER_NUM > 15 && CON-
FIG_ETH_USE_ESP32_EMAC
CONFIG_ETH_USE_SPI_ETHERNET
Support SPI to Ethernet Module
Found in: Component config > Ethernet
ESP-IDF can also support some SPI-Ethernet modules.
Default value:
• Yes (enabled)
Contains:
• CONFIG_ETH_SPI_ETHERNET_DM9051
• CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL
• CONFIG_ETH_SPI_ETHERNET_W5500
CONFIG_ETH_SPI_ETHERNET_DM9051
Use DM9051
Found in: Component config > Ethernet > CONFIG_ETH_USE_SPI_ETHERNET
DM9051 is a fast Ethernet controller with an SPI interface. It’s also integrated with a 10/100M PHY
and MAC. Select this to enable DM9051 driver.
CONFIG_ETH_SPI_ETHERNET_W5500
Use W5500 (MAC RAW)
Found in: Component config > Ethernet > CONFIG_ETH_USE_SPI_ETHERNET
W5500 is a HW TCP/IP embedded Ethernet controller. TCP/IP stack, 10/100 Ethernet MAC and
PHY are embedded in a single chip. However the driver in ESP-IDF only enables the RAW MAC
mode, making it compatible with the software TCP/IP stack. Say yes to enable W5500 driver.
CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL
Use KSZ8851SNL
Found in: Component config > Ethernet > CONFIG_ETH_USE_SPI_ETHERNET
The KSZ8851SNL is a single-chip Fast Ethernet controller consisting of a 10/100 physical layer
transceiver (PHY), a MAC, and a Serial Peripheral Interface (SPI). Select this to enable KSZ8851SNL
driver.
CONFIG_ETH_USE_OPENETH
Support OpenCores Ethernet MAC (for use with QEMU)
Found in: Component config > Ethernet
OpenCores Ethernet MAC driver can be used when an ESP-IDF application is executed in QEMU. This
driver is not supported when running on a real chip.
Default value:
• No (disabled)
Contains:
• CONFIG_ETH_OPENETH_DMA_RX_BUFFER_NUM
• CONFIG_ETH_OPENETH_DMA_TX_BUFFER_NUM
CONFIG_ETH_OPENETH_DMA_RX_BUFFER_NUM
Number of Ethernet DMA Rx buffers
Found in: Component config > Ethernet > CONFIG_ETH_USE_OPENETH
Number of DMA receive buffers, each buffer is 1600 bytes.
Range:
• from 1 to 64 if CONFIG_ETH_USE_OPENETH
Default value:
• 4 if CONFIG_ETH_USE_OPENETH
CONFIG_ETH_OPENETH_DMA_TX_BUFFER_NUM
Number of Ethernet DMA Tx buffers
Found in: Component config > Ethernet > CONFIG_ETH_USE_OPENETH
Number of DMA transmit buffers, each buffer is 1600 bytes.
Range:
• from 1 to 64 if CONFIG_ETH_USE_OPENETH
Default value:
• 1 if CONFIG_ETH_USE_OPENETH
CONFIG_ETH_TRANSMIT_MUTEX
Enable Transmit Mutex
Found in: Component config > Ethernet
Prevents multiple accesses when Ethernet interface is used as shared resource and multiple functionalities
might try to access it at a time.
Default value:
• No (disabled)
CONFIG_ESP_EVENT_LOOP_PROFILING
Enable event loop profiling
Found in: Component config > Event Loop Library
Enables collections of statistics in the event loop library such as the number of events posted to/recieved
by an event loop, number of callbacks involved, number of events dropped to to a full event loop queue,
run time of event handlers, and number of times/run time of each event handler.
Default value:
• No (disabled)
CONFIG_ESP_EVENT_POST_FROM_ISR
Support posting events from ISRs
Found in: Component config > Event Loop Library
Enable posting events from interrupt handlers.
Default value:
• Yes (enabled)
CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR
Support posting events from ISRs placed in IRAM
Found in: Component config > Event Loop Library > CONFIG_ESP_EVENT_POST_FROM_ISR
Enable posting events from interrupt handlers placed in IRAM. Enabling this option places API functions
esp_event_post and esp_event_post_to in IRAM.
Default value:
• Yes (enabled)
CONFIG_ESP_GDBSTUB_SUPPORT_TASKS
Enable listing FreeRTOS tasks through GDB Stub
Found in: Component config > GDB Stub
If enabled, GDBStub can supply the list of FreeRTOS tasks to GDB. Thread list can be queried from
GDB using ‘info threads’command. Note that if GDB task lists were corrupted, this feature may not
work. If GDBStub fails, try disabling this feature.
CONFIG_ESP_GDBSTUB_MAX_TASKS
Maximum number of tasks supported by GDB Stub
Found in: Component config > GDB Stub > CONFIG_ESP_GDBSTUB_SUPPORT_TASKS
Set the number of tasks which GDB Stub will support.
Default value:
• 32 if CONFIG_ESP_GDBSTUB_SUPPORT_TASKS
CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS
Enable https
Found in: Component config > ESP HTTP client
This option will enable https protocol by linking esp-tls library and initializing SSL transport
Default value:
• Yes (enabled)
CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH
Enable HTTP Basic Authentication
Found in: Component config > ESP HTTP client
This option will enable HTTP Basic Authentication. It is disabled by default as Basic auth uses unen-
crypted encoding, so it introduces a vulnerability when not using TLS
Default value:
• No (disabled)
CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH
Enable HTTP Digest Authentication
Found in: Component config > ESP HTTP client
This option will enable HTTP Digest Authentication. It is enabled by default, but use of this configuration
is not recommended as the password can be derived from the exchange, so it introduces a vulnerability
when not using TLS
Default value:
• No (disabled)
CONFIG_HTTPD_MAX_REQ_HDR_LEN
Max HTTP Request Header Length
Found in: Component config > HTTP Server
This sets the maximum supported size of headers section in HTTP request packet to be processed by
the server
Default value:
• 512
CONFIG_HTTPD_MAX_URI_LEN
Max HTTP URI Length
Found in: Component config > HTTP Server
This sets the maximum supported size of HTTP request URI to be processed by the server
Default value:
• 512
CONFIG_HTTPD_ERR_RESP_NO_DELAY
Use TCP_NODELAY socket option when sending HTTP error responses
Found in: Component config > HTTP Server
Using TCP_NODEALY socket option ensures that HTTP error response reaches the client before the
underlying socket is closed. Please note that turning this off may cause multiple test failures
Default value:
• Yes (enabled)
CONFIG_HTTPD_PURGE_BUF_LEN
Length of temporary buffer for purging data
Found in: Component config > HTTP Server
This sets the size of the temporary buffer used to receive and discard any remaining data that is received
from the HTTP client in the request, but not processed as part of the server HTTP request handler.
If the remaining data is larger than the available buffer size, the buffer will be filled in multiple iterations.
The buffer should be small enough to fit on the stack, but large enough to avoid excessive iterations.
Default value:
• 32
CONFIG_HTTPD_LOG_PURGE_DATA
Log purged content data at Debug level
Found in: Component config > HTTP Server
Enabling this will log discarded binary HTTP request data at Debug level. For large content data this
may not be desirable as it will clutter the log.
Default value:
• No (disabled)
CONFIG_HTTPD_WS_SUPPORT
WebSocket server support
Found in: Component config > HTTP Server
This sets the WebSocket server support.
Default value:
• No (disabled)
CONFIG_HTTPD_QUEUE_WORK_BLOCKING
httpd_queue_work as blocking API
Found in: Component config > HTTP Server
This makes httpd_queue_work() API to wait until a message space is available on UDP control socket.
It internally uses a counting semaphore with count set to LWIP_UDP_RECVMBOX_SIZE to achieve this.
This config will slightly change API behavior to block until message gets delivered on control socket.
CONFIG_ESP_HTTPS_OTA_DECRYPT_CB
Provide decryption callback
Found in: Component config > ESP HTTPS OTA
Exposes an additional callback whereby firmware data could be decrypted before being processed by
OTA update component. This can help to integrate external encryption related format and removal of
such encapsulation layer from firmware image.
Default value:
• No (disabled)
CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP
Allow HTTP for OTA (WARNING: ONLY FOR TESTING PURPOSE, READ HELP)
Found in: Component config > ESP HTTPS OTA
It is highly recommended to keep HTTPS (along with server certificate validation) enabled. Enabling this
option comes with potential risk of: - Non-encrypted communication channel with server - Accepting
firmware upgrade image from server with fake identity
Default value:
• No (disabled)
CONFIG_ESP_HTTPS_SERVER_ENABLE
Enable ESP_HTTPS_SERVER component
Found in: Component config > ESP HTTPS server
Enable ESP HTTPS server component
CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES
Number of universally administered (by IEEE) MAC address
Found in: Component config > Hardware Settings > MAC Config
Configure the number of universally administered (by IEEE) MAC addresses. During initialization,
MAC addresses for each network interface are generated or derived from a single base MAC address.
If the number of universal MAC addresses is four, all four interfaces (WiFi station, WiFi softap, Blue-
tooth and Ethernet) receive a universally administered MAC address. These are generated sequentially
by adding 0, 1, 2 and 3 (respectively) to the final octet of the base MAC address. If the number of
universal MAC addresses is two, only two interfaces (WiFi station and Bluetooth) receive a universally
administered MAC address. These are generated sequentially by adding 0 and 1 (respectively) to the
base MAC address. The remaining two interfaces (WiFi softap and Ethernet) receive local MAC ad-
dresses. These are derived from the universal WiFi station and Bluetooth MAC addresses, respectively.
When using the default (Espressif-assigned) base MAC address, either setting can be used. When us-
ing a custom universal MAC address range, the correct setting will depend on the allocation of MAC
addresses in this range (either 2 or 4 per device.)
Available options:
• Two (ESP32_UNIVERSAL_MAC_ADDRESSES_TWO)
• Four (ESP32_UNIVERSAL_MAC_ADDRESSES_FOUR)
CONFIG_ESP_SLEEP_POWER_DOWN_FLASH
Power down flash in light sleep when there is no SPIRAM
Found in: Component config > Hardware Settings > Sleep Config
If enabled, chip will try to power down flash as part of esp_light_sleep_start(), which costs more time
when chip wakes up. Can only be enabled if there is no SPIRAM configured. This option will in fact
consider VDD_SDIO auto power value (ESP_PD_OPTION_AUTO) as OFF. Also, it is possible to
force a power domain to stay ON during light sleep by using esp_sleep_pd_config() function.
Default value:
• Yes (enabled) if CONFIG_SPIRAM
CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND
light sleep GPIO reset workaround
Found in: Component config > Hardware Settings > Sleep Config
esp32c2, esp32c3 and esp32s3 will reset at wake-up if GPIO is received a small electrostatic pulse during
light sleep, with specific condition
• GPIO needs to be configured as input-mode only
• The pin receives a small electrostatic pulse, and reset occurs when the pulse voltage is higher than
6V
For GPIO set to input mode only, it is not a good practice to leave it open/floating, The hardware design
needs to controlled it with determined supply or ground voltage is necessary.
This option provides a software workaround for this issue. Configure to isolate all GPIO pins in sleep
state.
CONFIG_ESP_SLEEP_PSRAM_LEAKAGE_WORKAROUND
PSRAM leakage current workaround in light sleep
Found in: Component config > Hardware Settings > Sleep Config
When the CS pin of SPIRAM is not pulled up, the sleep current will increase during light sleep. If the
CS pin of SPIRAM has an external pull-up, you do not need to select this option, otherwise, you should
enable this option.
CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND
Flash leakage current workaround in light sleep
Found in: Component config > Hardware Settings > Sleep Config
When the CS pin of Flash is not pulled up, the sleep current will increase during light sleep. If the CS
pin of Flash has an external pull-up, you do not need to select this option, otherwise, you should enable
this option.
CONFIG_ESP_SLEEP_DEEP_SLEEP_WAKEUP_DELAY
Extra delay in deep sleep wake stub (in us)
Found in: Component config > Hardware Settings > Sleep Config
When the chip exits deep sleep, the CPU and the flash chip are powered on at the same time. CPU
will run deep sleep stub first, and then proceed to load code from flash. Some flash chips need sufficient
time to pass between power on and first read operation. By default, without any extra delay, this time is
approximately 900us, although some flash chip types need more than that.
By default extra delay is set to 2000us. When optimizing startup time for applications which require it,
this value may be reduced.
If you are seeing “flash read err, 1000”message printed to the console after deep sleep reset, try
increasing this value.
Range:
• from 0 to 5000
Default value:
• 2000
CONFIG_RTC_CLK_SRC
RTC clock source
Found in: Component config > Hardware Settings > RTC Clock Config
Choose which clock is used as RTC clock source.
• “Internal 150kHz oscillator”option provides lowest deep sleep current consumption, and
does not require extra external components. However frequency stability with respect to tem-
perature is poor, so time may drift in deep/light sleep modes.
• “External 32kHz crystal”provides better frequency stability, at the expense of slightly
higher (1uA) deep sleep current consumption.
• “External 32kHz oscillator”allows using 32kHz clock generated by an external circuit. In
this case, external clock signal must be connected to 32K_XN pin. Amplitude should be
<1.2V in case of sine wave signal, and <1V in case of square wave signal. Common mode
voltage should be 0.1 < Vcm < 0.5Vamp, where Vamp is the signal amplitude. Additionally,
1nF capacitor must be connected between 32K_XP pin and ground. 32K_XP pin can not be
used as a GPIO in this case.
• “Internal 8.5MHz oscillator divided by 256”option results in higher deep sleep current
(by 5uA) but has better frequency stability than the internal 150kHz oscillator. It does not
require external components.
Available options:
• Internal 150kHz RC oscillator (RTC_CLK_SRC_INT_RC)
• External 32kHz crystal (RTC_CLK_SRC_EXT_CRYS)
• External 32kHz oscillator at 32K_XN pin (RTC_CLK_SRC_EXT_OSC)
• Internal 8.5MHz oscillator, divided by 256 (~33kHz) (RTC_CLK_SRC_INT_8MD256)
CONFIG_RTC_EXT_CRYST_ADDIT_CURRENT_METHOD
Additional current for external 32kHz crystal
Found in: Component config > Hardware Settings > RTC Clock Config
With some 32kHz crystal configurations, the X32N and X32P pins may not have enough drive strength
to keep the crystal oscillating. Choose the method to provide additional current from touchpad 9 to the
external 32kHz crystal. Note that the deep sleep current is slightly high (4-5uA) and the touchpad and
the wakeup sources of both touchpad and ULP are not available in method 1 and method 2.
This problem is fixed in ESP32 ECO 3, so this workaround is not needed. Setting the project configura-
tion to minimum revision ECO3 will disable this option, , allow all wakeup sources, and save some code
size.
• “None”option will not provide additional current to external crystal
• “Method 1”option can’t ensure 100% to solve the external 32k crystal start failed
issue, but the touchpad can work in this method.
• “Method 2”option can solve the external 32k issue, but the touchpad can’t work in
this method.
Available options:
• None (RTC_EXT_CRYST_ADDIT_CURRENT_NONE)
• Method 1 (RTC_EXT_CRYST_ADDIT_CURRENT)
• Method 2 (RTC_EXT_CRYST_ADDIT_CURRENT_V2)
CONFIG_RTC_CLK_CAL_CYCLES
Number of cycles for RTC_SLOW_CLK calibration
Found in: Component config > Hardware Settings > RTC Clock Config
When the startup code initializes RTC_SLOW_CLK, it can perform calibration by comparing
the RTC_SLOW_CLK frequency with main XTAL frequency. This option sets the number of
RTC_SLOW_CLK cycles measured by the calibration routine. Higher numbers increase calibration
precision, which may be important for applications which spend a lot of time in deep sleep. Lower
numbers reduce startup time.
When this option is set to 0, clock calibration will not be performed at startup, and approximate clock
frequencies will be assumed:
• 150000 Hz if internal RC oscillator is used as clock source. For this use value 1024.
• 32768 Hz if the 32k crystal oscillator is used. For this use value 3000 or more. In case
more value will help improve the definition of the launch of the crystal. If the crystal could
not start, it will be switched to internal RC.
Range:
• from 0 to 27000 if RTC_CLK_SRC_EXT_CRYS || RTC_CLK_SRC_EXT_OSC ||
RTC_CLK_SRC_INT_8MD256
• from 0 to 32766
Default value:
• 3000 if RTC_CLK_SRC_EXT_CRYS || RTC_CLK_SRC_EXT_OSC ||
RTC_CLK_SRC_INT_8MD256
• 1024
CONFIG_RTC_XTAL_CAL_RETRY
Number of attempts to repeat 32k XTAL calibration
Found in: Component config > Hardware Settings > RTC Clock Config
Number of attempts to repeat 32k XTAL calibration before giving up and switching to the internal RC.
Increase this option if the 32k crystal oscillator does not start and switches to internal RC.
Default value:
• 1 if RTC_CLK_SRC_EXT_CRYS
CONFIG_PERIPH_CTRL_FUNC_IN_IRAM
Place peripheral control functions into IRAM
Found in: Component config > Hardware Settings > Peripheral Control
Place peripheral control functions (e.g. periph_module_reset) into IRAM, so that these functions can
be IRAM-safe and able to be called in the other IRAM interrupt context.
Default value:
• No (disabled)
MMU Config
CONFIG_ESP32_REV_MIN
Minimum Supported ESP32 Revision
Found in: Component config > Hardware Settings
Minimum revision that ESP-IDF would support. ESP-IDF performs different strategy on different esp32
revision.
Available options:
• Rev 0 (ESP32_REV_MIN_0)
• Rev 1 (ESP32_REV_MIN_1)
• Rev 2 (ESP32_REV_MIN_2)
• Rev 3 (ESP32_REV_MIN_3)
CONFIG_ESP32_XTAL_FREQ_SEL
Main XTAL frequency
Found in: Component config > Hardware Settings
ESP32 currently supports the following XTAL frequencies:
• 26 MHz
• 40 MHz
Startup code can automatically estimate XTAL frequency. This feature uses the internal 8MHz os-
cillator as a reference. Because the internal oscillator frequency is temperature dependent, it is not
recommended to use automatic XTAL frequency detection in applications which need to work at high
ambient temperatures and use high-temperature qualified chips and modules.
Available options:
• 40 MHz (ESP32_XTAL_FREQ_40)
• 26 MHz (ESP32_XTAL_FREQ_26)
• Autodetect (ESP32_XTAL_FREQ_AUTO)
CONFIG_GDMA_CTRL_FUNC_IN_IRAM
Place GDMA control functions into IRAM
Found in: Component config > Hardware Settings > GDMA Configuration
Place GDMA control functions (like start/stop/append/reset) into IRAM, so that these functions can be
IRAM-safe and able to be called in the other IRAM interrupt context. Enabling this option can improve
driver performance as well.
Default value:
• No (disabled) if SOC_GDMA_SUPPORTED
CONFIG_GDMA_ISR_IRAM_SAFE
GDMA ISR IRAM-Safe
Found in: Component config > Hardware Settings > GDMA Configuration
This will ensure the GDMA interrupt handler is IRAM-Safe, allow to avoid flash cache misses, and also
be able to run whilst the cache is disabled. (e.g. SPI Flash write).
Default value:
• No (disabled) if SOC_GDMA_SUPPORTED
CONFIG_LCD_PANEL_IO_FORMAT_BUF_SIZE
LCD panel io format buffer size
Found in: Component config > LCD and Touch Panel > LCD Peripheral Configuration
LCD driver allocates an internal buffer to transform the data into a proper format, because of the endian
order mismatch. This option is to set the size of the buffer, in bytes.
Default value:
• 32
CONFIG_LCD_ENABLE_DEBUG_LOG
Enable debug log
Found in: Component config > LCD and Touch Panel > LCD Peripheral Configuration
Wether to enable the debug log message for LCD driver. Note that, this option only controls the LCD
driver log, won’t affect other drivers.
Default value:
• No (disabled)
CONFIG_LCD_RGB_ISR_IRAM_SAFE
RGB LCD ISR IRAM-Safe
Found in: Component config > LCD and Touch Panel > LCD Peripheral Configuration
Ensure the LCD interrupt is IRAM-Safe by allowing the interrupt handler to be executable when the
cache is disabled (e.g. SPI Flash write). If you want the LCD driver to keep flushing the screen even
when cache ops disabled, you can enable this option. Note, this will also increase the IRAM usage.
Default value:
• No (disabled) if SOC_LCD_RGB_SUPPORTED
CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL
IP Address lost timer interval (seconds)
Found in: Component config > ESP NETIF Adapter
The value of 0 indicates the IP lost timer is disabled, otherwise the timer is enabled.
The IP address may be lost because of some reasons, e.g. when the station disconnects from soft-AP,
or when DHCP IP renew fails etc. If the IP lost timer is enabled, it will be started everytime the IP is
lost. Event SYSTEM_EVENT_STA_LOST_IP will be raised if the timer expires. The IP lost timer is
stopped if the station get the IP again before the timer expires.
Range:
• from 0 to 65535
Default value:
• 120
CONFIG_ESP_NETIF_USE_TCPIP_STACK_LIB
TCP/IP Stack Library
Found in: Component config > ESP NETIF Adapter
Choose the TCP/IP Stack to work, for example, LwIP, uIP, etc.
Available options:
• LwIP (ESP_NETIF_TCPIP_LWIP)
lwIP is a small independent implementation of the TCP/IP protocol suite.
• Loopback (ESP_NETIF_LOOPBACK)
Dummy implementation of esp-netif functionality which connects driver transmit to receive
function. This option is for testing purpose only
CONFIG_ESP_NETIF_L2_TAP
Enable netif L2 TAP support
Found in: Component config > ESP NETIF Adapter
A user program can read/write link layer (L2) frames from/to ESP TAP device. The ESP TAP device
can be currently associated only with Ethernet physical interfaces.
CONFIG_ESP_NETIF_L2_TAP_MAX_FDS
Maximum number of opened L2 TAP File descriptors
Found in: Component config > ESP NETIF Adapter > CONFIG_ESP_NETIF_L2_TAP
Maximum number of opened File descriptors (FD’s) associated with ESP TAP device. ESP TAP FD’
s take up a certain amount of memory, and allowing fewer FD’s to be opened at the same time conserves
memory.
Range:
• from 1 to 10 if CONFIG_ESP_NETIF_L2_TAP
Default value:
• 5 if CONFIG_ESP_NETIF_L2_TAP
CONFIG_ESP_NETIF_L2_TAP_RX_QUEUE_SIZE
Size of L2 TAP Rx queue
Found in: Component config > ESP NETIF Adapter > CONFIG_ESP_NETIF_L2_TAP
Maximum number of frames queued in opened File descriptor. Once the queue is full, the newly arriv-
ing frames are dropped until the queue has enough room to accept incoming traffic (Tail Drop queue
management).
Range:
• from 1 to 100 if CONFIG_ESP_NETIF_L2_TAP
Default value:
• 20 if CONFIG_ESP_NETIF_L2_TAP
CONFIG_ESP_NETIF_BRIDGE_EN
Enable LwIP IEEE 802.1D bridge
Found in: Component config > ESP NETIF Adapter
Enable LwIP IEEE 802.1D bridge support in ESP-NETIF. Note that “Number of clients store data
in netif”(LWIP_NUM_NETIF_CLIENT_DATA) option needs to be properly configured to be LwIP
bridge avaiable!
Default value:
• No (disabled)
PHY Contains:
• CONFIG_ESP_PHY_MAX_WIFI_TX_POWER
• CONFIG_ESP_PHY_REDUCE_TX_POWER
• CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE
• CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION
CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE
Store phy calibration data in NVS
Found in: Component config > PHY
If this option is enabled, NVS will be initialized and calibration data will be loaded from there. PHY
calibration will be skipped on deep sleep wakeup. If calibration data is not found, full calibration will
be performed and stored in NVS. Normally, only partial calibration will be performed. If this option is
disabled, full calibration will be performed.
If it’s easy that your board calibrate bad data, choose‘n’. Two cases for example, you should choose
‘n’: 1.If your board is easy to be booted up with antenna disconnected. 2.Because of your board design,
each time when you do calibration, the result are too unstable. If unsure, choose ‘y’.
Default value:
• Yes (enabled)
CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION
Use a partition to store PHY init data
Found in: Component config > PHY
If enabled, PHY init data will be loaded from a partition. When using a custom partition table, make
sure that PHY data partition is included (type:‘data’, subtype:‘phy’). With default partition tables,
this is done automatically. If PHY init data is stored in a partition, it has to be flashed there, otherwise
runtime error will occur.
If this option is not enabled, PHY init data will be embedded into the application binary.
If unsure, choose ‘n’.
Default value:
• No (disabled)
Contains:
• CONFIG_ESP_PHY_DEFAULT_INIT_IF_INVALID
• CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN
CONFIG_ESP_PHY_DEFAULT_INIT_IF_INVALID
Reset default PHY init data if invalid
Found in: Component config > PHY > CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION
If enabled, PHY init data will be restored to default if it cannot be verified successfully to avoid endless
bootloops.
If unsure, choose ‘n’.
Default value:
• No (disabled) if CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION
CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN
Support multiple PHY init data bin
Found in: Component config > PHY > CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION
If enabled, the corresponding PHY init data type can be automatically switched according to the country
code. China’s PHY init data bin is used by default. Can be modified by country information in API
esp_wifi_set_country(). The priority of switching the PHY init data type is: 1. Country configured by
API esp_wifi_set_country() and the parameter policy is WIFI_COUNTRY_POLICY_MANUAL. 2.
Country notified by the connected AP. 3. Country configured by API esp_wifi_set_country() and the
parameter policy is WIFI_COUNTRY_POLICY_AUTO.
Default value:
• No (disabled) if CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION && CON-
FIG_ESP_PHY_INIT_DATA_IN_PARTITION
CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN_EMBED
Support embedded multiple phy init data bin to app bin
Found in: Component config > PHY > CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION > CON-
FIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN
If enabled, multiple phy init data bin will embedded into app bin If not enabled, multiple phy init data
bin will still leave alone, and need to be flashed by users.
Default value:
• No (disabled) if CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN && CON-
FIG_ESP_PHY_INIT_DATA_IN_PARTITION
CONFIG_ESP_PHY_INIT_DATA_ERROR
Terminate operation when PHY init data error
Found in: Component config > PHY > CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION > CON-
FIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN
If enabled, when an error occurs while the PHY init data is updated, the program will terminate and
restart. If not enabled, the PHY init data will not be updated when an error occurs.
Default value:
• No (disabled) if CONFIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN && CON-
FIG_ESP_PHY_INIT_DATA_IN_PARTITION
CONFIG_ESP_PHY_MAX_WIFI_TX_POWER
Max WiFi TX power (dBm)
Found in: Component config > PHY
Set maximum transmit power for WiFi radio. Actual transmit power for high data rates may be lower
than this setting.
Range:
• from 10 to 20
Default value:
• 20
CONFIG_ESP_PHY_REDUCE_TX_POWER
Reduce PHY TX power when brownout reset
Found in: Component config > PHY
When brownout reset occurs, reduce PHY TX power to keep the code running.
Default value:
• Yes (enabled)
CONFIG_PM_ENABLE
Support for power management
Found in: Component config > Power Management
If enabled, application is compiled with support for power management. This option has run-time over-
head (increased interrupt latency, longer time to enter idle state), and it also reduces accuracy of RTOS
ticks and timers used for timekeeping. Enable this option if application uses power management APIs.
Default value:
• No (disabled) if CONFIG_FREERTOS_SMP
CONFIG_PM_DFS_INIT_AUTO
Enable dynamic frequency scaling (DFS) at startup
Found in: Component config > Power Management > CONFIG_PM_ENABLE
If enabled, startup code configures dynamic frequency scaling. Max CPU frequency is set to DE-
FAULT_CPU_FREQ_MHZ setting, min frequency is set to XTAL frequency. If disabled, DFS will
not be active until the application configures it using esp_pm_configure function.
Default value:
• No (disabled) if CONFIG_PM_ENABLE
CONFIG_PM_PROFILING
Enable profiling counters for PM locks
Found in: Component config > Power Management > CONFIG_PM_ENABLE
If enabled, esp_pm_* functions will keep track of the amount of time each of the power management
locks has been held, and esp_pm_dump_locks function will print this information. This feature can be
used to analyze which locks are preventing the chip from going into a lower power state, and see what
time the chip spends in each power saving mode. This feature does incur some run-time overhead, so
should typically be disabled in production builds.
Default value:
• No (disabled) if CONFIG_PM_ENABLE
CONFIG_PM_TRACE
Enable debug tracing of PM using GPIOs
Found in: Component config > Power Management > CONFIG_PM_ENABLE
If enabled, some GPIOs will be used to signal events such as RTOS ticks, frequency switching, entry/exit
from idle state. Refer to pm_trace.c file for the list of GPIOs. This feature is intended to be used when
analyzing/debugging behavior of power management implementation, and should be kept disabled in
applications.
Default value:
• No (disabled) if CONFIG_PM_ENABLE
CONFIG_PM_SLP_IRAM_OPT
Put lightsleep related codes in internal RAM
Found in: Component config > Power Management
If enabled, about 1.8KB of lightsleep related source code would be in IRAM and chip would sleep
longer for 760us at most each time. This feature is intended to be used when lower power consumption
is needed while there is enough place in IRAM to place source code.
CONFIG_PM_RTOS_IDLE_OPT
Put RTOS IDLE related codes in internal RAM
Found in: Component config > Power Management
If enabled, about 260B of RTOS_IDLE related source code would be in IRAM and chip would sleep
longer for 40us at most each time. This feature is intended to be used when lower power consumption
is needed while there is enough place in IRAM to place source code.
CONFIG_PM_SLP_DISABLE_GPIO
Disable all GPIO when chip at sleep
Found in: Component config > Power Management
This feature is intended to disable all GPIO pins at automantic sleep to get a lower power mode.
If enabled, chips will disable all GPIO pins at automantic sleep to reduce about 200~300 uA cur-
rent. If you want to specifically use some pins normally as chip wakes when chip sleeps, you
can call ‘gpio_sleep_sel_dis’to disable this feature on those pins. You can also keep this fea-
ture on and call ‘gpio_sleep_set_direction’and ‘gpio_sleep_set_pull_mode’to have a different
GPIO configuration at sleep. Waring: If you want to enable this option on ESP32, you should en-
able GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL at first, otherwise you will not be able to switch
pullup/pulldown mode.
CONFIG_SPIRAM
Support for external, SPI-connected RAM
Found in: Component config > ESP PSRAM
This enables support for an external SPI RAM chip, connected in parallel with the main SPI flash chip.
Default value:
• No (disabled)
• CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP
• CONFIG_SPIRAM_TYPE
• CONFIG_SPIRAM_CUSTOM_SPIWP_SD3_PIN
CONFIG_SPIRAM_TYPE
Type of SPI RAM chip in use
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
Available options:
• Auto-detect (SPIRAM_TYPE_AUTO)
• ESP-PSRAM16 or APS1604 (SPIRAM_TYPE_ESPPSRAM16)
• ESP-PSRAM32 (SPIRAM_TYPE_ESPPSRAM32)
• ESP-PSRAM64 or LY68L6400 (SPIRAM_TYPE_ESPPSRAM64)
CONFIG_SPIRAM_SPEED
Set RAM clock speed
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
Select the speed for the SPI RAM chip. If SPI RAM is enabled, we only support three combinations of
SPI speed mode we supported now:
1. Flash SPI running at 40Mhz and RAM SPI running at 40Mhz
2. Flash SPI running at 80Mhz and RAM SPI running at 40Mhz
3. Flash SPI running at 80Mhz and RAM SPI running at 80Mhz
Note: If the third mode(80Mhz+80Mhz) is enabled for SPI RAM of type 32MBit, one of the HSPI/VSPI
host will be occupied by the system. Which SPI host to use can be selected by the config item
SPIRAM_OCCUPY_SPI_HOST. Application code should never touch HSPI/VSPI hardware in this
case. The option to select 80MHz will only be visible if the flash SPI speed is also 80MHz. (ESP-
TOOLPY_FLASHFREQ_80M is true)
Available options:
• 40MHz clock speed (SPIRAM_SPEED_40M)
• 80MHz clock speed (SPIRAM_SPEED_80M)
CONFIG_SPIRAM_BOOT_INIT
Initialize SPI RAM during startup
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
If this is enabled, the SPI RAM will be enabled during initial boot. Unless you have specific requirements,
you’ll want to leave this enabled so memory allocated during boot-up can also be placed in SPI RAM.
Default value:
• Yes (enabled) if CONFIG_SPIRAM
CONFIG_SPIRAM_IGNORE_NOTFOUND
Ignore PSRAM when not found
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > CON-
FIG_SPIRAM_BOOT_INIT
Normally, if psram initialization is enabled during compile time but not found at runtime, it is seen as an
error making the CPU panic. If this is enabled, booting will complete but no PSRAM will be available.
Default value:
• No (disabled) if CONFIG_SPIRAM_BOOT_INIT && CON-
FIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY && CONFIG_SPIRAM
CONFIG_SPIRAM_USE
SPI RAM access method
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
The SPI RAM can be accessed in multiple methods: by just having it available as an unmanaged mem-
ory region in the CPU’s memory map, by integrating it in the heap as ‘special’memory needing
heap_caps_malloc to allocate, or by fully integrating it making malloc() also able to return SPI RAM
pointers.
Available options:
• Integrate RAM into memory map (SPIRAM_USE_MEMMAP)
• Make RAM allocatable using heap_caps_malloc(…, MALLOC_CAP_SPIRAM) (SPI-
RAM_USE_CAPS_ALLOC)
• Make RAM allocatable using malloc() as well (SPIRAM_USE_MALLOC)
CONFIG_SPIRAM_MEMTEST
Run memory test on SPI RAM initialization
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
Runs a rudimentary memory test on initialization. Aborts when memory test fails. Disable this for
slightly faster startup.
Default value:
• Yes (enabled) if CONFIG_SPIRAM_BOOT_INIT && CONFIG_SPIRAM
CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL
Maximum malloc() size, in bytes, to always put in internal memory
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
If malloc() is capable of also allocating SPI-connected ram, its allocation strategy will prefer to allocate
chunks less than this size in internal memory, while allocations larger than this will be done from external
RAM. If allocation from the preferred region fails, an attempt is made to allocate from the non-preferred
region instead, so malloc() will not suddenly fail when either internal or external memory is full.
Range:
• from 0 to 131072 if SPIRAM_USE_MALLOC && CONFIG_SPIRAM
Default value:
• 16384 if SPIRAM_USE_MALLOC && CONFIG_SPIRAM
CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP
Try to allocate memories of WiFi and LWIP in SPIRAM firstly. If failed, allocate internal memory
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
Try to allocate memories of WiFi and LWIP in SPIRAM firstly. If failed, try to allocate internal memory
then.
Default value:
• No (disabled) if (SPIRAM_USE_CAPS_ALLOC || SPIRAM_USE_MALLOC) && CON-
FIG_SPIRAM
CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL
Reserve this amount of bytes for data that specifically needs to be in DMA or internal memory
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
Because the external/internal RAM allocation strategy is not always perfect, it sometimes may happen
that the internal memory is entirely filled up. This causes allocations that are specifically done in internal
memory, for example the stack for new tasks or memory to service DMA or have memory that’s also
available when SPI cache is down, to fail. This option reserves a pool specifically for requests like that;
the memory in this pool is not given out when a normal malloc() is called.
Set this to 0 to disable this feature.
Note that because FreeRTOS stacks are forced to internal memory, they will also use this memory pool;
be sure to keep this in mind when adjusting this value.
Note also that the DMA reserved pool may not be one single contiguous memory region, depending on
the configured size and the static memory usage of the app.
Range:
• from 0 to 262144 if SPIRAM_USE_MALLOC && CONFIG_SPIRAM
Default value:
• 32768 if SPIRAM_USE_MALLOC && CONFIG_SPIRAM
CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY
Allow .bss segment placed in external memory
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
If enabled, variables with EXT_RAM_BSS_ATTR attribute will be placed in SPIRAM instead of in-
ternal DRAM. BSS section of lwip, net80211, pp, bt libraries will be automatically placed in SPIRAM.
BSS sections from other object files and libraries can also be placed in SPIRAM through linker fragment
scheme extram_bss.
Note that the variables placed in SPIRAM using EXT_RAM_BSS_ATTR will be zero initialized.
Default value:
• No (disabled) if CONFIG_SPIRAM && CONFIG_SPIRAM
CONFIG_SPIRAM_ALLOW_NOINIT_SEG_EXTERNAL_MEMORY
Allow .noinit segment placed in external memory
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
If enabled, noinit variables can be placed in PSRAM using EXT_RAM_NOINIT_ATTR.
Note the values placed into this section will not be initialized at startup and should keep its value after
software restart.
Default value:
• No (disabled) if CONFIG_SPIRAM && CONFIG_SPIRAM
CONFIG_SPIRAM_CACHE_WORKAROUND
Enable workaround for bug in SPI RAM cache for Rev1 ESP32s
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
Revision 1 of the ESP32 has a bug that can cause a write to PSRAM not to take place in some situations
when the cache line needs to be fetched from external RAM and an interrupt occurs. This enables a fix
in the compiler (-mfix-esp32-psram-cache-issue) that makes sure the specific code that is vulnerable to
this will not be emitted.
This will also not use any bits of newlib that are located in ROM, opting for a version that is compiled
with the workaround and located in flash instead.
The workaround is not required for ESP32 revision 3 and above.
Default value:
CONFIG_SPIRAM_CACHE_WORKAROUND_STRATEGY
Workaround strategy
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM cache
workaround debugging
Select the workaround strategy. Note that the strategy for precompiled libraries (libgcc, newlib, bt, wifi)
is not affected by this selection.
Unless you know you need a different strategy, it’s suggested you stay with the default MEMW strategy.
Note that DUPLDST can interfere with hardware encryption and this will be automatically disabled if
this workaround is selected. ‘Insert nops’is the workaround that was used in older esp-idf versions.
This workaround still can cause faulty data transfers from/to SPI RAM in some situation.
Available options:
• Insert memw after vulnerable instructions (default) (SPI-
RAM_CACHE_WORKAROUND_STRATEGY_MEMW)
• Duplicate LD/ST for 32-bit, memw for 8/16 bit (SPI-
RAM_CACHE_WORKAROUND_STRATEGY_DUPLDST)
• Insert nops between vulnerable loads/stores (old strategy, obsolete) (SPI-
RAM_CACHE_WORKAROUND_STRATEGY_NOPS)
CONFIG_SPIRAM_CACHE_LIBJMP_IN_IRAM
Put libc’s jump related functions in IRAM
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM
workaround libraries placement
The functions affected by this option are: longjmp and setjmp. Putting these function in IRAM will
allow them to be called when flash cache is disabled but it will also reduce the available size of free
IRAM for the user application.
Default value:
• Yes (enabled) if CONFIG_SPIRAM_CACHE_WORKAROUND && CONFIG_SPIRAM
CONFIG_SPIRAM_CACHE_LIBMATH_IN_IRAM
Put libc’s math related functions in IRAM
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM
workaround libraries placement
The functions affected by this option are: abs, div, labs, ldiv, quorem, fpclassify, and nan. Putting these
function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the
available size of free IRAM for the user application.
Default value:
• Yes (enabled) if CONFIG_SPIRAM_CACHE_WORKAROUND && CONFIG_SPIRAM
CONFIG_SPIRAM_CACHE_LIBNUMPARSER_IN_IRAM
Put libc’s number parsing related functions in IRAM
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM
workaround libraries placement
The functions affected by this option are: utoa, itoa, atoi, atol, strtol, and strtoul. Putting these function
in IRAM will allow them to be called when flash cache is disabled but it will also reduce the available
size of free IRAM for the user application.
Default value:
• Yes (enabled) if CONFIG_SPIRAM_CACHE_WORKAROUND && CONFIG_SPIRAM
CONFIG_SPIRAM_CACHE_LIBIO_IN_IRAM
Put libc’s I/O related functions in IRAM
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM
workaround libraries placement
The functions affected by this option are: wcrtomb, fvwrite, wbuf, wsetup, fputwc, wctomb_r, ungetc,
makebuf, fflush, refill, and sccl. Putting these function in IRAM will allow them to be called when flash
cache is disabled but it will also reduce the available size of free IRAM for the user application.
Default value:
• Yes (enabled) if CONFIG_SPIRAM_CACHE_WORKAROUND && CONFIG_SPIRAM
CONFIG_SPIRAM_CACHE_LIBTIME_IN_IRAM
Put libc’s time related functions in IRAM
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM
workaround libraries placement
The functions affected by this option are: 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. Putting these function in IRAM will allow them to be called when
flash cache is disabled but it will also reduce the available size of free IRAM for the user application.
Default value:
• Yes (enabled) if CONFIG_SPIRAM_CACHE_WORKAROUND && CONFIG_SPIRAM
CONFIG_SPIRAM_CACHE_LIBCHAR_IN_IRAM
Put libc’s characters related functions in IRAM
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM
workaround libraries placement
The functions affected by this option are: ctype_, toupper, tolower, toascii, strupr, bzero, isalnum, isal-
pha, isascii, isblank, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, and isupper. Putting these
function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the
available size of free IRAM for the user application.
Default value:
• Yes (enabled) if CONFIG_SPIRAM_CACHE_WORKAROUND && CONFIG_SPIRAM
CONFIG_SPIRAM_CACHE_LIBMEM_IN_IRAM
Put libc’s memory related functions in IRAM
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM
workaround libraries placement
The functions affected by this option are: memccpy, memchr memmove, and memrchr. Putting these
function in IRAM will allow them to be called when flash cache is disabled but it will also reduce the
available size of free IRAM for the user application.
Default value:
• Yes (enabled) if CONFIG_SPIRAM_CACHE_WORKAROUND && CONFIG_SPIRAM
CONFIG_SPIRAM_CACHE_LIBSTR_IN_IRAM
Put libc’s string related functions in IRAM
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM
workaround libraries placement
The functions affected by this option are: strcasecmp, strcasestr, strchr, strcoll, strcpy, strcspn, strdup,
strdup_r, strlcat, strlcpy, strlen, strlwr, strncasecmp, strncat, strncmp, strncpy, strndup, strndup_r, str-
rchr, strsep, strspn, strstr, strtok_r, and strupr. Putting these function in IRAM will allow them to be
called when flash cache is disabled but it will also reduce the available size of free IRAM for the user
application.
Default value:
• Yes (enabled) if CONFIG_SPIRAM_CACHE_WORKAROUND && CONFIG_SPIRAM
CONFIG_SPIRAM_CACHE_LIBRAND_IN_IRAM
Put libc’s random related functions in IRAM
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM
workaround libraries placement
The functions affected by this option are: srand, rand, and rand_r. Putting these function in IRAM will
allow them to be called when flash cache is disabled but it will also reduce the available size of free
IRAM for the user application.
Default value:
• Yes (enabled) if CONFIG_SPIRAM_CACHE_WORKAROUND && CONFIG_SPIRAM
CONFIG_SPIRAM_CACHE_LIBENV_IN_IRAM
Put libc’s environment related functions in IRAM
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM
workaround libraries placement
The functions affected by this option are: environ, envlock, and getenv_r. Putting these function in
IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size
of free IRAM for the user application.
Default value:
CONFIG_SPIRAM_CACHE_LIBFILE_IN_IRAM
Put libc’s file related functions in IRAM
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM
workaround libraries placement
The functions affected by this option are: lock, isatty, fclose, open, close, creat, read, rshift, sbrk, stdio,
syssbrk, sysclose, sysopen, creat, sysread, syswrite, impure, fwalk, and findfp. Putting these function in
IRAM will allow them to be called when flash cache is disabled but it will also reduce the available size
of free IRAM for the user application.
Default value:
• Yes (enabled) if CONFIG_SPIRAM_CACHE_WORKAROUND && CONFIG_SPIRAM
CONFIG_SPIRAM_CACHE_LIBMISC_IN_IRAM
Put libc’s miscellaneous functions in IRAM, see help
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > SPIRAM
workaround libraries placement
The functions affected by this option are: raise and system Putting these function in IRAM will allow
them to be called when flash cache is disabled but it will also reduce the available size of free IRAM for
the user application.
Default value:
• Yes (enabled) if CONFIG_SPIRAM_CACHE_WORKAROUND && CONFIG_SPIRAM
CONFIG_SPIRAM_BANKSWITCH_ENABLE
Enable bank switching for >4MiB external RAM
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
The ESP32 only supports 4MiB of external RAM in its address space. The hardware does support larger
memories, but these have to be bank-switched in and out of this address space. Enabling this allows you
to reserve some MMU pages for this, which allows the use of the esp_himem api to manage these banks.
#Note that this is limited to 62 banks, as esp_psram_extram_writeback_cache needs some kind of map-
ping of #some banks below that mark to work. We cannot at this moment guarantee this to exist when
himem is #enabled.
If spiram 2T mode is enabled, the size of 64Mbit psram will be changed as 32Mbit, so himem will be
unusable.
Default value:
• Yes (enabled) if (SPIRAM_USE_MEMMAP || SPIRAM_USE_CAPS_ALLOC || SPI-
RAM_USE_MALLOC) && CONFIG_SPIRAM
CONFIG_SPIRAM_BANKSWITCH_RESERVE
Amount of 32K pages to reserve for bank switching
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > CON-
FIG_SPIRAM_BANKSWITCH_ENABLE
Select the amount of banks reserved for bank switching. Note that the amount of RAM allocatable with
malloc/esp_heap_alloc_caps will decrease by 32K for each page reserved here.
Note that this reservation is only actually done if your program actually uses the himem API. Without
any himem calls, the reservation is not done and the original amount of memory will be available to
malloc/esp_heap_alloc_caps.
Range:
• from 1 to 62 if CONFIG_SPIRAM_BANKSWITCH_ENABLE && CONFIG_SPIRAM
Default value:
• 8 if CONFIG_SPIRAM_BANKSWITCH_ENABLE && CONFIG_SPIRAM
CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY
Allow external memory as an argument to xTaskCreateStatic
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
Because some bits of the ESP32 code environment cannot be recompiled with the cache workaround,
normally tasks cannot be safely run with their stack residing in external memory; for this reason
xTaskCreate (and related task creaton functions) always allocate stack in internal memory and xTaskCre-
ateStatic will check if the memory passed to it is in internal memory. If you have a task that needs a large
amount of stack and does not call on ROM code in any way (no direct calls, but also no Bluetooth/WiFi),
you can try enable this to cause xTaskCreateStatic to allow tasks stack in external memory.
Default value:
• No (disabled) if SPIRAM_USE_MALLOC && CONFIG_SPIRAM
CONFIG_SPIRAM_OCCUPY_SPI_HOST
SPI host to use for 32MBit PSRAM
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
When both flash and PSRAM is working under 80MHz, and the PSRAM is of type 32MBit, one of the
HSPI/VSPI host will be used to output the clock. Select which one to use here.
Available options:
• HSPI host (SPI2) (SPIRAM_OCCUPY_HSPI_HOST)
• VSPI host (SPI3) (SPIRAM_OCCUPY_VSPI_HOST)
• Will not try to use any host, will abort if not able to use the PSRAM (SPI-
RAM_OCCUPY_NO_HOST)
CONFIG_D0WD_PSRAM_CLK_IO
PSRAM CLK IO number
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and
cs IO for ESP32-DOWD
The PSRAM CLOCK IO can be any unused GPIO, user can config it based on hardware design. If user
use 1.8V flash and 1.8V psram, this value can only be one of 6, 7, 8, 9, 10, 11, 16, 17.
Range:
• from 0 to 33 if CONFIG_SPIRAM && CONFIG_SPIRAM
Default value:
• 17 if CONFIG_SPIRAM && CONFIG_SPIRAM
CONFIG_D0WD_PSRAM_CS_IO
PSRAM CS IO number
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and
cs IO for ESP32-DOWD
The PSRAM CS IO can be any unused GPIO, user can config it based on hardware design. If user use
1.8V flash and 1.8V psram, this value can only be one of 6, 7, 8, 9, 10, 11, 16, 17.
Range:
• from 0 to 33 if CONFIG_SPIRAM && CONFIG_SPIRAM
Default value:
• 16 if CONFIG_SPIRAM && CONFIG_SPIRAM
CONFIG_D2WD_PSRAM_CLK_IO
PSRAM CLK IO number
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and
cs IO for ESP32-D2WD
User can config it based on hardware design. For ESP32-D2WD chip, the psram can only be 1.8V
psram, so this value can only be one of 6, 7, 8, 9, 10, 11, 16, 17.
Range:
• from 0 to 33 if CONFIG_SPIRAM && CONFIG_SPIRAM
Default value:
• 9 if CONFIG_SPIRAM && CONFIG_SPIRAM
CONFIG_D2WD_PSRAM_CS_IO
PSRAM CS IO number
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and
cs IO for ESP32-D2WD
User can config it based on hardware design. For ESP32-D2WD chip, the psram can only be 1.8V
psram, so this value can only be one of 6, 7, 8, 9, 10, 11, 16, 17.
Range:
• from 0 to 33 if CONFIG_SPIRAM && CONFIG_SPIRAM
Default value:
• 10 if CONFIG_SPIRAM && CONFIG_SPIRAM
CONFIG_PICO_PSRAM_CS_IO
PSRAM CS IO number
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config > PSRAM clock and
cs IO for ESP32-PICO
The PSRAM CS IO can be any unused GPIO, user can config it based on hardware design.
For ESP32-PICO chip, the psram share clock with flash, so user do not need
to configure the clock IO. For the reference hardware design, please refer to
https://www.espressif.com/sites/default/files/documentation/esp32-pico-d4_datasheet_en.pdf
Range:
• from 0 to 33 if CONFIG_SPIRAM && CONFIG_SPIRAM
Default value:
• 10 if CONFIG_SPIRAM && CONFIG_SPIRAM
CONFIG_SPIRAM_CUSTOM_SPIWP_SD3_PIN
Use custom SPI PSRAM WP(SD3) Pin when flash pins set in eFuse (read help)
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
This setting is only used if the SPI flash pins have been overridden by setting the eFuses
SPI_PAD_CONFIG_xxx, and the SPI flash mode is DIO or DOUT.
When this is the case, the eFuse config only defines 3 of the 4 Quad I/O data pins. The WP pin (aka
ESP32 pin “SD_DATA_3”or SPI flash pin “IO2”) is not specified in eFuse. The psram only has
QPI mode, so a WP pin setting is necessary.
If this config item is set to N (default), the correct WP pin will be automatically used for any Espressif
chip or module with integrated flash. If a custom setting is needed, set this config item to Y and specify
the GPIO number connected to the WP pin.
When flash mode is set to QIO or QOUT, the PSRAM WP pin will be set the same as the SPI Flash
WP pin configured in the bootloader.
Default value:
• No (disabled) if (ESPTOOLPY_FLASHMODE_DIO || ESP-
TOOLPY_FLASHMODE_DOUT) && CONFIG_SPIRAM
CONFIG_SPIRAM_SPIWP_SD3_PIN
Custom SPI PSRAM WP(SD3) Pin
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
The option “Use custom SPI PSRAM WP(SD3) pin”must be set or this value is ignored
If burning a customized set of SPI flash pins in eFuse and using DIO or DOUT mode for flash, set this
value to the GPIO number of the SPIRAM WP pin.
Range:
• from 0 to 33 if (ESPTOOLPY_FLASHMODE_DIO || ESP-
TOOLPY_FLASHMODE_DOUT) && CONFIG_SPIRAM
Default value:
• 7 if (ESPTOOLPY_FLASHMODE_DIO || ESPTOOLPY_FLASHMODE_DOUT) &&
CONFIG_SPIRAM
CONFIG_SPIRAM_2T_MODE
Enable SPI PSRAM 2T mode
Found in: Component config > ESP PSRAM > CONFIG_SPIRAM > SPI RAM config
Enable this option to fix single bit errors inside 64Mbit PSRAM.
Some 64Mbit PSRAM chips have a hardware issue in the RAM which causes bit errors at multiple fixed
bit positions.
Note: If this option is enabled, the 64Mbit PSRAM chip will appear to be 32Mbit in size. Applications
will not be affected unless the use the esp_himem APIs, which are not supported in 2T mode.
Default value:
• No (disabled) if CONFIG_SPIRAM && CONFIG_SPIRAM
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ
CPU frequency
Found in: Component config > ESP System Settings
CPU frequency to be set on application startup.
Available options:
• 40 MHz (ESP_DEFAULT_CPU_FREQ_MHZ_40)
• 80 MHz (ESP_DEFAULT_CPU_FREQ_MHZ_80)
• 160 MHz (ESP_DEFAULT_CPU_FREQ_MHZ_160)
• 240 MHz (ESP_DEFAULT_CPU_FREQ_MHZ_240)
Memory Contains:
• CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY
• CONFIG_ESP32_RTCDATA_IN_FAST_MEM
• CONFIG_ESP32_USE_FIXED_STATIC_RAM_SIZE
CONFIG_ESP32_RTCDATA_IN_FAST_MEM
Place RTC_DATA_ATTR and RTC_RODATA_ATTR variables into RTC fast memory segment
Found in: Component config > ESP System Settings > Memory
This option allows to place .rtc_data and .rtc_rodata sections into RTC fast memory segment to free the
slow memory region for ULP programs. This option depends on the CONFIG_FREERTOS_UNICORE
option because RTC fast memory can be accessed only by PRO_CPU core.
Default value:
• No (disabled) if CONFIG_FREERTOS_UNICORE
CONFIG_ESP32_USE_FIXED_STATIC_RAM_SIZE
Use fixed static RAM size
Found in: Component config > ESP System Settings > Memory
If this option is disabled, the DRAM part of the heap starts right after the .bss section, within the
dram0_0 region. As a result, adding or removing some static variables will change the available heap
size.
If this option is enabled, the DRAM part of the heap starts right after the dram0_0 region, where its
length is set with ESP32_FIXED_STATIC_RAM_SIZE
Default value:
• No (disabled)
CONFIG_ESP32_FIXED_STATIC_RAM_SIZE
Fixed Static RAM size
Found in: Component config > ESP System Settings > Memory > CON-
FIG_ESP32_USE_FIXED_STATIC_RAM_SIZE
RAM size dedicated for static variables (.data & .bss sections). Please note that the actual length will be
reduced by BTDM_RESERVE_DRAM if Bluetooth controller is enabled.
Range:
• from 0 to 0x2c200 if CONFIG_ESP32_USE_FIXED_STATIC_RAM_SIZE
Default value:
• “0x1E000”if CONFIG_ESP32_USE_FIXED_STATIC_RAM_SIZE
CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY
Enable IRAM as 8 bit accessible memory
Found in: Component config > ESP System Settings > Memory
If enabled, application can use IRAM as byte accessible region for storing data (Note: IRAM region
cannot be used as task stack)
This is possible due to handling of exceptions LoadStoreError (3) and LoadStoreAlignmentError (9) Each
unaligned read/write access will incur a penalty of maximum of 167 CPU cycles.
CONFIG_ESP32_TRAX
Use TRAX tracing feature
Found in: Component config > ESP System Settings > Trace memory
The ESP32 contains a feature which allows you to trace the execution path the processor has taken
through the program. This is stored in a chunk of 32K (16K for single-processor) of memory that can’
t be used for general purposes anymore. Disable this if you do not know what this is.
Default value:
• No (disabled)
CONFIG_ESP32_TRAX_TWOBANKS
Reserve memory for tracing both pro as well as app cpu execution
Found in: Component config > ESP System Settings > Trace memory > CONFIG_ESP32_TRAX
The ESP32 contains a feature which allows you to trace the execution path the processor has taken
through the program. This is stored in a chunk of 32K (16K for single-processor) of memory that can’
t be used for general purposes anymore. Disable this if you do not know what this is.
# Memory to reverse for trace, used in linker script
Default value:
• No (disabled) if CONFIG_ESP32_TRAX && CONFIG_FREERTOS_UNICORE
CONFIG_ESP_SYSTEM_PANIC
Panic handler behaviour
Found in: Component config > ESP System Settings
If FreeRTOS detects unexpected behaviour or an unhandled exception, the panic handler is invoked.
Configure the panic handler’s action here.
Available options:
• Print registers and halt (ESP_SYSTEM_PANIC_PRINT_HALT)
Outputs the relevant registers over the serial port and halt the processor. Needs a manual reset
to restart.
• Print registers and reboot (ESP_SYSTEM_PANIC_PRINT_REBOOT)
Outputs the relevant registers over the serial port and immediately reset the processor.
• Silent reboot (ESP_SYSTEM_PANIC_SILENT_REBOOT)
Just resets the processor without outputting anything
• GDBStub on panic (ESP_SYSTEM_PANIC_GDBSTUB)
Invoke gdbstub on the serial port, allowing for gdb to attach to it to do a postmortem of the
crash.
• GDBStub at runtime (ESP_SYSTEM_GDBSTUB_RUNTIME)
Invoke gdbstub on the serial port, allowing for gdb to attach to it and to do a debug on runtime.
CONFIG_ESP_SYSTEM_RTC_EXT_XTAL_BOOTSTRAP_CYCLES
Bootstrap cycles for external 32kHz crystal
Found in: Component config > ESP System Settings
To reduce the startup time of an external RTC crystal, we bootstrap it with a 32kHz square wave for a
fixed number of cycles. Setting 0 will disable bootstrapping (if disabled, the crystal may take longer to
start up or fail to oscillate under some conditions).
If this value is too high, a faulty crystal may initially start and then fail. If this value is too low, an
otherwise good crystal may not start.
To accurately determine if the crystal has started, set a larger“Number of cycles for RTC_SLOW_CLK
calibration”(about 3000).
CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP
Enable RTC fast memory for dynamic allocations
Found in: Component config > ESP System Settings
This config option allows to add RTC fast memory region to system heap with capability similar to that
of DRAM region but without DMA. This memory will be consumed first per heap initialization order
by early startup services and scheduler related code. Speed wise RTC fast memory operates on APB
clock and hence does not have much performance impact.
CONFIG_ESP_SYSTEM_PMP_IDRAM_SPLIT
Enable IRAM/DRAM split protection
Found in: Component config > ESP System Settings > Memory protection
If enabled, the CPU watches all the memory access and raises an exception in case of any memory
violation. This feature automatically splits the SRAM memory, using PMP, into data and instruction
segments and sets Read/Execute permissions for the instruction part (below given splitting address) and
Read/Write permissions for the data part (above the splitting address). The memory protection is effec-
tive on all access through the IRAM0 and DRAM0 buses.
Default value:
• Yes (enabled) if SOC_CPU_IDRAM_SPLIT_USING_PMP
CONFIG_ESP_SYSTEM_MEMPROT_FEATURE
Enable memory protection
Found in: Component config > ESP System Settings > Memory protection
If enabled, the permission control module watches all the memory access and fires the panic handler
if a permission violation is detected. This feature automatically splits the SRAM memory into data
and instruction segments and sets Read/Execute permissions for the instruction part (below given split-
ting address) and Read/Write permissions for the data part (above the splitting address). The memory
protection is effective on all access through the IRAM0 and DRAM0 buses.
Default value:
• Yes (enabled) if SOC_MEMPROT_SUPPORTED
CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK
Lock memory protection settings
Found in: Component config > ESP System Settings > Memory protection > CON-
FIG_ESP_SYSTEM_MEMPROT_FEATURE
Once locked, memory protection settings cannot be changed anymore. The lock is reset only on the chip
startup.
Default value:
• Yes (enabled) if CONFIG_ESP_SYSTEM_MEMPROT_FEATURE
CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE
System event queue size
Found in: Component config > ESP System Settings
Config system event queue size in different application.
Default value:
• 32
CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE
Event loop task stack size
Found in: Component config > ESP System Settings
Config system event task stack size in different application.
Default value:
• 2304
CONFIG_ESP_MAIN_TASK_STACK_SIZE
Main task stack size
Found in: Component config > ESP System Settings
Configure the“main task”stack size. This is the stack of the task which calls app_main(). If app_main()
returns then this task is deleted and its stack memory is freed.
Default value:
• 3584
CONFIG_ESP_MAIN_TASK_AFFINITY
Main task core affinity
Found in: Component config > ESP System Settings
Configure the “main task”core affinity. This is the used core of the task which calls app_main(). If
app_main() returns then this task is deleted.
Available options:
• CPU0 (ESP_MAIN_TASK_AFFINITY_CPU0)
• CPU1 (ESP_MAIN_TASK_AFFINITY_CPU1)
• No affinity (ESP_MAIN_TASK_AFFINITY_NO_AFFINITY)
CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE
Minimal allowed size for shared stack
Found in: Component config > ESP System Settings
Minimal value of size, in bytes, accepted to execute a expression with shared stack.
Default value:
• 2048
CONFIG_ESP_CONSOLE_UART
Channel for console output
Found in: Component config > ESP System Settings
Select where to send console output (through stdout and stderr).
• Default is to use UART0 on pre-defined GPIOs.
• If “Custom”is selected, UART0 or UART1 can be chosen, and any pins can be selected.
• If “None”is selected, there will be no console output on any UART, except for initial output
from ROM bootloader. This ROM output can be suppressed by GPIO strapping or EFUSE, refer
to chip datasheet for details.
• On chips with USB OTG peripheral,“USB CDC”option redirects output to the CDC port. This
option uses the CDC driver in the chip ROM. This option is incompatible with TinyUSB stack.
• On chips with an USB serial/JTAG debug controller, selecting the option for that redirects output
to the CDC/ACM (serial port emulation) component of that device.
Available options:
• Default: UART0 (ESP_CONSOLE_UART_DEFAULT)
• USB CDC (ESP_CONSOLE_USB_CDC)
• USB Serial/JTAG Controller (ESP_CONSOLE_USB_SERIAL_JTAG)
• Custom UART (ESP_CONSOLE_UART_CUSTOM)
• None (ESP_CONSOLE_NONE)
CONFIG_ESP_CONSOLE_UART_NUM
UART peripheral to use for console output (0-1)
Found in: Component config > ESP System Settings
This UART peripheral is used for console output from the ESP-IDF Bootloader and the app.
If the configuration is different in the Bootloader binary compared to the app binary, UART is recon-
figured after the bootloader exits and the app starts.
Due to an ESP32 ROM bug, UART2 is not supported for console output via esp_rom_printf.
Available options:
• UART0 (ESP_CONSOLE_UART_CUSTOM_NUM_0)
• UART1 (ESP_CONSOLE_UART_CUSTOM_NUM_1)
CONFIG_ESP_CONSOLE_UART_TX_GPIO
UART TX on GPIO#
Found in: Component config > ESP System Settings
This GPIO is used for console UART TX output in the ESP-IDF Bootloader and the app (including boot
log output and default standard output and standard error of the app).
If the configuration is different in the Bootloader binary compared to the app binary, UART is recon-
figured after the bootloader exits and the app starts.
Range:
• from 0 to 46 if ESP_CONSOLE_UART_CUSTOM
Default value:
• 1 if ESP_CONSOLE_UART_CUSTOM
• 43 if ESP_CONSOLE_UART_CUSTOM
CONFIG_ESP_CONSOLE_UART_RX_GPIO
UART RX on GPIO#
Found in: Component config > ESP System Settings
This GPIO is used for UART RX input in the ESP-IDF Bootloader and the app (including default default
standard input of the app).
Note: The default ESP-IDF Bootloader configures this pin but doesn’t read anything from the UART.
If the configuration is different in the Bootloader binary compared to the app binary, UART is recon-
figured after the bootloader exits and the app starts.
Range:
• from 0 to 46 if ESP_CONSOLE_UART_CUSTOM
Default value:
• 3 if ESP_CONSOLE_UART_CUSTOM
• 44 if ESP_CONSOLE_UART_CUSTOM
CONFIG_ESP_CONSOLE_UART_BAUDRATE
UART console baud rate
Found in: Component config > ESP System Settings
This baud rate is used by both the ESP-IDF Bootloader and the app (including boot log output and
default standard input/output/error of the app).
The app’s maximum baud rate depends on the UART clock source. If Power Management is disabled,
the UART clock source is the APB clock and all baud rates in the available range will be sufficiently
accurate. If Power Management is enabled, REF_TICK clock source is used so the baud rate is divided
from 1MHz. Baud rates above 1Mbps are not possible and values between 500Kbps and 1Mbps may
not be accurate.
If the configuration is different in the Bootloader binary compared to the app binary, UART is recon-
figured after the bootloader exits and the app starts.
Range:
• from 1200 to 4000000 if CONFIG_PM_ENABLE
• from 1200 to 1000000 if CONFIG_PM_ENABLE
Default value:
• 115200
CONFIG_ESP_INT_WDT
Interrupt watchdog
Found in: Component config > ESP System Settings
This watchdog timer can detect if the FreeRTOS tick interrupt has not been called for a certain time,
either because a task turned off interrupts and did not turn them on for a long time, or because an
interrupt handler did not return. It will try to invoke the panic handler first and failing that reset the SoC.
Default value:
• Yes (enabled)
CONFIG_ESP_INT_WDT_TIMEOUT_MS
Interrupt watchdog timeout (ms)
Found in: Component config > ESP System Settings > CONFIG_ESP_INT_WDT
The timeout of the watchdog, in miliseconds. Make this higher than the FreeRTOS tick rate.
Range:
• from 10 to 10000
Default value:
• 300 if CONFIG_SPIRAM && CONFIG_ESP_INT_WDT
• 800 if CONFIG_SPIRAM && CONFIG_ESP_INT_WDT
CONFIG_ESP_INT_WDT_CHECK_CPU1
Also watch CPU1 tick interrupt
Found in: Component config > ESP System Settings > CONFIG_ESP_INT_WDT
Also detect if interrupts on CPU 1 are disabled for too long.
Default value:
• Yes (enabled) if CONFIG_ESP_INT_WDT && CONFIG_FREERTOS_UNICORE
CONFIG_ESP_TASK_WDT
Initialize Task Watchdog Timer on startup
Found in: Component config > ESP System Settings
The Task Watchdog Timer can be used to make sure individual tasks are still running. Enabling this
option will cause the Task Watchdog Timer to be initialized automatically at startup. The Task Watchdog
timer can be initialized after startup as well (see Task Watchdog Timer API Reference)
Default value:
• Yes (enabled)
CONFIG_ESP_TASK_WDT_PANIC
Invoke panic handler on Task Watchdog timeout
Found in: Component config > ESP System Settings > CONFIG_ESP_TASK_WDT
If this option is enabled, the Task Watchdog Timer will be configured to trigger the panic handler when
it times out. This can also be configured at run time (see Task Watchdog Timer API Reference)
Default value:
• No (disabled)
CONFIG_ESP_TASK_WDT_TIMEOUT_S
Task Watchdog timeout period (seconds)
Found in: Component config > ESP System Settings > CONFIG_ESP_TASK_WDT
Timeout period configuration for the Task Watchdog Timer in seconds. This is also configurable at run
time (see Task Watchdog Timer API Reference)
Range:
• from 1 to 60
Default value:
• 5
CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0
Watch CPU0 Idle Task
Found in: Component config > ESP System Settings > CONFIG_ESP_TASK_WDT
If this option is enabled, the Task Watchdog Timer will watch the CPU0 Idle Task. Having the Task
Watchdog watch the Idle Task allows for detection of CPU starvation as the Idle Task not being called is
usually a symptom of CPU starvation. Starvation of the Idle Task is detrimental as FreeRTOS household
tasks depend on the Idle Task getting some runtime every now and then.
Default value:
• Yes (enabled)
CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1
Watch CPU1 Idle Task
Found in: Component config > ESP System Settings > CONFIG_ESP_TASK_WDT
If this option is enabled, the Task Wtachdog Timer will wach the CPU1 Idle Task.
Default value:
• Yes (enabled) if CONFIG_ESP_TASK_WDT && CONFIG_FREERTOS_UNICORE
CONFIG_ESP_PANIC_HANDLER_IRAM
Place panic handler code in IRAM
Found in: Component config > ESP System Settings
If this option is disabled (default), the panic handler code is placed in flash not IRAM. This means that
if ESP-IDF crashes while flash cache is disabled, the panic handler will automatically re-enable flash
cache before running GDB Stub or Core Dump. This adds some minor risk, if the flash cache status is
also corrupted during the crash.
If this option is enabled, the panic handler code (including required UART functions) is placed in IRAM.
This may be necessary to debug some complex issues with crashes while flash cache is disabled (for
example, when writing to SPI flash) or when flash cache is corrupted when an exception is triggered.
Default value:
• No (disabled)
CONFIG_ESP_DEBUG_STUBS_ENABLE
OpenOCD debug stubs
Found in: Component config > ESP System Settings
Debug stubs are used by OpenOCD to execute pre-compiled onboard code which does some useful
debugging stuff, e.g. GCOV data dump.
Default value:
• “COMPILER_OPTIMIZATION_LEVEL_DEBUG”if CONFIG_ESP32_TRAX &&
ESP32S2_TRAX && ESP32S3_TRAX
CONFIG_ESP_DEBUG_OCDAWARE
Make exception and panic handlers JTAG/OCD aware
Found in: Component config > ESP System Settings
The FreeRTOS panic and unhandled exception handers can detect a JTAG OCD debugger and instead
of panicking, have the debugger stop on the offending instruction.
Default value:
• Yes (enabled)
CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL
Interrupt level to use for Interrupt Watchdog and other system checks
Found in: Component config > ESP System Settings
Interrupt level to use for Interrupt Watchdog and other system checks.
Available options:
• Level 5 interrupt (ESP_SYSTEM_CHECK_INT_LEVEL_5)
Using level 5 interrupt for Interrupt Watchdog and other system checks.
• Level 4 interrupt (ESP_SYSTEM_CHECK_INT_LEVEL_4)
Using level 4 interrupt for Interrupt Watchdog and other system checks.
CONFIG_ESP_BROWNOUT_DET
Hardware brownout detect & reset
Found in: Component config > ESP System Settings > Brownout Detector
The ESP has a built-in brownout detector which can detect if the voltage is lower than a specific value.
If this happens, it will reset the chip in order to prevent unintended behaviour.
Default value:
• Yes (enabled)
CONFIG_ESP_BROWNOUT_DET_LVL_SEL
Brownout voltage level
Found in: Component config > ESP System Settings > Brownout Detector > CON-
FIG_ESP_BROWNOUT_DET
The brownout detector will reset the chip when the supply voltage is approximately below this level.
Note that there may be some variation of brownout voltage level between each ESP chip.
#The voltage levels here are estimates, more work needs to be done to figure out the exact voltages #of
the brownout threshold levels.
Available options:
• 2.43V +/- 0.05 (ESP_BROWNOUT_DET_LVL_SEL_0)
• 2.48V +/- 0.05 (ESP_BROWNOUT_DET_LVL_SEL_1)
• 2.58V +/- 0.05 (ESP_BROWNOUT_DET_LVL_SEL_2)
• 2.62V +/- 0.05 (ESP_BROWNOUT_DET_LVL_SEL_3)
• 2.67V +/- 0.05 (ESP_BROWNOUT_DET_LVL_SEL_4)
• 2.70V +/- 0.05 (ESP_BROWNOUT_DET_LVL_SEL_5)
• 2.77V +/- 0.05 (ESP_BROWNOUT_DET_LVL_SEL_6)
• 2.80V +/- 0.05 (ESP_BROWNOUT_DET_LVL_SEL_7)
CONFIG_ESP32_DISABLE_BASIC_ROM_CONSOLE
Permanently disable BASIC ROM Console
Found in: Component config > ESP System Settings
If set, the first time the app boots it will disable the BASIC ROM Console permanently (by burning an
eFuse).
Otherwise, the BASIC ROM Console starts on reset if no valid bootloader is read from the flash.
(Enabling secure boot also disables the BASIC ROM Console by default.)
Default value:
• No (disabled)
CONFIG_ESP_IPC_TASK_STACK_SIZE
Inter-Processor Call (IPC) task stack size
Found in: Component config > IPC (Inter-Processor Call)
Configure the IPC tasks stack size. An IPC task runs on each core (in dual core mode), and allows for
cross-core function calls. See IPC documentation for more details. The default IPC stack size should be
enough for most common simple use cases. However, users can increase/decrease the stack size to their
needs.
Range:
• from 512 to 65536
Default value:
• 1024
CONFIG_ESP_IPC_USES_CALLERS_PRIORITY
IPC runs at caller’s priority
Found in: Component config > IPC (Inter-Processor Call)
If this option is not enabled then the IPC task will keep behavior same as prior to that of ESP-IDF v4.0,
hence IPC task will run at (configMAX_PRIORITIES - 1) priority.
Default value:
• Yes (enabled) if CONFIG_FREERTOS_UNICORE
CONFIG_ESP_TIMER_PROFILING
Enable esp_timer profiling features
Found in: Component config > High resolution timer (esp_timer)
If enabled, esp_timer_dump will dump information such as number of times the timer was started,
number of times the timer has triggered, and the total time it took for the callback to run. This option
has some effect on timer performance and the amount of memory used for timer storage, and should
only be used for debugging/testing purposes.
Default value:
• No (disabled)
CONFIG_ESP_TIMER_TASK_STACK_SIZE
High-resolution timer task stack size
Found in: Component config > High resolution timer (esp_timer)
Configure the stack size of “timer_task”task. This task is used to dispatch callbacks of timers created
using ets_timer and esp_timer APIs. If you are seing stack overflow errors in timer task, increase this
value.
Note that this is not the same as FreeRTOS timer task. To configure FreeRTOS timer task size, see
“FreeRTOS timer task stack size”option in “FreeRTOS”menu.
Range:
• from 2048 to 65536
Default value:
• 3584
CONFIG_ESP_TIMER_INTERRUPT_LEVEL
Interrupt level
Found in: Component config > High resolution timer (esp_timer)
It sets the interrupt level for esp_timer ISR in range 1..3. A higher level (3) helps to decrease the ISR
esp_timer latency.
Range:
• from 1 to 3
• from 1 to 1
Default value:
• 1
CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD
Support ISR dispatch method
Found in: Component config > High resolution timer (esp_timer)
Allows using ESP_TIMER_ISR dispatch method (ESP_TIMER_TASK dispatch method is also aval-
ible). - ESP_TIMER_TASK - Timer callbacks are dispatched from a high-priority esp_timer task. -
ESP_TIMER_ISR - Timer callbacks are dispatched directly from the timer interrupt handler. The ISR
dispatch can be used, in some cases, when a callback is very simple or need a lower-latency.
Default value:
• No (disabled)
Wi-Fi Contains:
• CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA
• CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE
• CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN
• CONFIG_ESP32_WIFI_CACHE_TX_BUFFER_NUM
• CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM
• CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM
• CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM
• CONFIG_ESP32_WIFI_STATIC_TX_BUFFER_NUM
• CONFIG_ESP_WIFI_STA_DISCONNECTED_PM_ENABLE
• CONFIG_ESP32_WIFI_SW_COEXIST_ENABLE
• CONFIG_ESP32_WIFI_TX_BUFFER
• CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED
• CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED
• CONFIG_ESP32_WIFI_AMSDU_TX_ENABLED
• CONFIG_ESP32_WIFI_CSI_ENABLED
• CONFIG_ESP_WIFI_FTM_ENABLE
• CONFIG_ESP_WIFI_GCMP_SUPPORT
• CONFIG_ESP_WIFI_GMAC_SUPPORT
• CONFIG_ESP32_WIFI_IRAM_OPT
• CONFIG_ESP32_WIFI_MGMT_SBUF_NUM
• CONFIG_ESP32_WIFI_NVS_ENABLED
• CONFIG_ESP32_WIFI_RX_IRAM_OPT
• CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT
• CONFIG_ESP_WIFI_SLP_IRAM_OPT
• CONFIG_ESP_WIFI_SOFTAP_SUPPORT
• CONFIG_ESP32_WIFI_TASK_CORE_ID
CONFIG_ESP32_WIFI_SW_COEXIST_ENABLE
CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM
Max number of WiFi static RX buffers
Found in: Component config > Wi-Fi
Set the number of WiFi static RX buffers. Each buffer takes approximately 1.6KB of RAM. The static
rx buffers are allocated when esp_wifi_init is called, they are not freed until esp_wifi_deinit is called.
WiFi hardware use these buffers to receive all 802.11 frames. A higher number may allow higher
throughput but increases memory use. If ESP32_WIFI_AMPDU_RX_ENABLED is enabled, this
value is recommended to set equal or bigger than ESP32_WIFI_RX_BA_WIN in order to achieve better
throughput and compatibility with both stations and APs.
Range:
• from 2 to 25
Default value:
• 10 if CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP
• 16 if CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP
CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM
Max number of WiFi dynamic RX buffers
Found in: Component config > Wi-Fi
Set the number of WiFi dynamic RX buffers, 0 means unlimited RX buffers will be allocated (provided
sufficient free RAM). The size of each dynamic RX buffer depends on the size of the received data
frame.
For each received data frame, the WiFi driver makes a copy to an RX buffer and then delivers it to the
high layer TCP/IP stack. The dynamic RX buffer is freed after the higher layer has successfully received
the data frame.
For some applications, WiFi data frames may be received faster than the application can process them.
In these cases we may run out of memory if RX buffer number is unlimited (0).
If a dynamic RX buffer limit is set, it should be at least the number of static RX buffers.
Range:
• from 0 to 128 if CONFIG_LWIP_WND_SCALE
• from 0 to 1024 if CONFIG_LWIP_WND_SCALE
Default value:
• 32
CONFIG_ESP32_WIFI_TX_BUFFER
Type of WiFi TX buffers
Found in: Component config > Wi-Fi
Select type of WiFi TX buffers:
If“Static”is selected, WiFi TX buffers are allocated when WiFi is initialized and released when WiFi
is de-initialized. The size of each static TX buffer is fixed to about 1.6KB.
If “Dynamic”is selected, each WiFi TX buffer is allocated as needed when a data frame is delivered
to the Wifi driver from the TCP/IP stack. The buffer is freed after the data frame has been sent by the
WiFi driver. The size of each dynamic TX buffer depends on the length of each data frame sent by the
TCP/IP layer.
If PSRAM is enabled, “Static”should be selected to guarantee enough WiFi TX buffers. If PSRAM
is disabled, “Dynamic”should be selected to improve the utilization of RAM.
Available options:
• Static (ESP32_WIFI_STATIC_TX_BUFFER)
• Dynamic (ESP32_WIFI_DYNAMIC_TX_BUFFER)
CONFIG_ESP32_WIFI_STATIC_TX_BUFFER_NUM
Max number of WiFi static TX buffers
Found in: Component config > Wi-Fi
Set the number of WiFi static TX buffers. Each buffer takes approximately 1.6KB of RAM. The static
RX buffers are allocated when esp_wifi_init() is called, they are not released until esp_wifi_deinit() is
called.
For each transmitted data frame from the higher layer TCP/IP stack, the WiFi driver makes a copy of
it in a TX buffer. For some applications especially UDP applications, the upper layer can deliver frames
faster than WiFi layer can transmit. In these cases, we may run out of TX buffers.
Range:
• from 1 to 64 if ESP32_WIFI_STATIC_TX_BUFFER
Default value:
• 16 if ESP32_WIFI_STATIC_TX_BUFFER
CONFIG_ESP32_WIFI_CACHE_TX_BUFFER_NUM
Max number of WiFi cache TX buffers
Found in: Component config > Wi-Fi
Set the number of WiFi cache TX buffer number.
For each TX packet from uplayer, such as LWIP etc, WiFi driver needs to allocate a static TX buffer
and makes a copy of uplayer packet. If WiFi driver fails to allocate the static TX buffer, it caches the
uplayer packets to a dedicated buffer queue, this option is used to configure the size of the cached TX
queue.
Range:
• from 16 to 128 if CONFIG_SPIRAM
Default value:
• 32 if CONFIG_SPIRAM
CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM
Max number of WiFi dynamic TX buffers
Found in: Component config > Wi-Fi
Set the number of WiFi dynamic TX buffers. The size of each dynamic TX buffer is not fixed, it depends
on the size of each transmitted data frame.
For each transmitted frame from the higher layer TCP/IP stack, the WiFi driver makes a copy of it in a
TX buffer. For some applications, especially UDP applications, the upper layer can deliver frames faster
than WiFi layer can transmit. In these cases, we may run out of TX buffers.
Range:
• from 1 to 128
Default value:
• 32
CONFIG_ESP32_WIFI_CSI_ENABLED
WiFi CSI(Channel State Information)
Found in: Component config > Wi-Fi
Select this option to enable CSI(Channel State Information) feature. CSI takes about CON-
FIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM KB of RAM. If CSI is not used, it is better to dis-
able this feature in order to save memory.
Default value:
• No (disabled)
CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED
WiFi AMPDU TX
Found in: Component config > Wi-Fi
Select this option to enable AMPDU TX feature
Default value:
• Yes (enabled)
CONFIG_ESP32_WIFI_TX_BA_WIN
WiFi AMPDU TX BA window size
Found in: Component config > Wi-Fi > CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED
Set the size of WiFi Block Ack TX window. Generally a bigger value means higher throughput but
more memory. Most of time we should NOT change the default value unless special reason, e.g. test
the maximum UDP TX throughput with iperf etc. For iperf test in shieldbox, the recommended value
is 9~12.
Range:
• from 2 to 32
Default value:
• 6
CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED
WiFi AMPDU RX
Found in: Component config > Wi-Fi
Select this option to enable AMPDU RX feature
Default value:
• Yes (enabled)
CONFIG_ESP32_WIFI_RX_BA_WIN
WiFi AMPDU RX BA window size
Found in: Component config > Wi-Fi > CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED
Set the size of WiFi Block Ack RX window. Generally a bigger value means higher throughput and
better compatibility but more memory. Most of time we should NOT change the default value unless
special reason, e.g. test the maximum UDP RX throughput with iperf etc. For iperf test in shieldbox,
the recommended value is 9~12. If PSRAM is used and WiFi memory is prefered to allocat in PSRAM
first, the default and minimum value should be 16 to achieve better throughput and compatibility with
both stations and APs.
Range:
• from 2 to 32
Default value:
• 6 if CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP && CON-
FIG_ESP32_WIFI_AMPDU_RX_ENABLED
• 16 if CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP && CON-
FIG_ESP32_WIFI_AMPDU_RX_ENABLED
CONFIG_ESP32_WIFI_AMSDU_TX_ENABLED
WiFi AMSDU TX
Found in: Component config > Wi-Fi
Select this option to enable AMSDU TX feature
Default value:
• No (disabled) if CONFIG_SPIRAM
CONFIG_ESP32_WIFI_NVS_ENABLED
WiFi NVS flash
Found in: Component config > Wi-Fi
Select this option to enable WiFi NVS flash
Default value:
• Yes (enabled)
CONFIG_ESP32_WIFI_TASK_CORE_ID
WiFi Task Core ID
Found in: Component config > Wi-Fi
Pinned WiFi task to core 0 or core 1.
Available options:
• Core 0 (ESP32_WIFI_TASK_PINNED_TO_CORE_0)
• Core 1 (ESP32_WIFI_TASK_PINNED_TO_CORE_1)
CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN
Max length of WiFi SoftAP Beacon
Found in: Component config > Wi-Fi
ESP-MESH utilizes beacon frames to detect and resolve root node conflicts (see documentation). How-
ever the default length of a beacon frame can simultaneously hold only five root node identifier structures,
meaning that a root node conflict of up to five nodes can be detected at one time. In the occurence of
more root nodes conflict involving more than five root nodes, the conflict resolution process will detect
five of the root nodes, resolve the conflict, and re-detect more root nodes. This process will repeat until
all root node conflicts are resolved. However this process can generally take a very long time.
To counter this situation, the beacon frame length can be increased such that more root nodes can be
detected simultaneously. Each additional root node will require 36 bytes and should be added ontop
of the default beacon frame length of 752 bytes. For example, if you want to detect 10 root nodes
simultaneously, you need to set the beacon frame length as 932 (752+36*5).
Setting a longer beacon length also assists with debugging as the conflicting root nodes can be identified
more quickly.
Range:
• from 752 to 1256
Default value:
• 752
CONFIG_ESP32_WIFI_MGMT_SBUF_NUM
WiFi mgmt short buffer number
Found in: Component config > Wi-Fi
Set the number of WiFi management short buffer.
Range:
• from 6 to 32
Default value:
• 32
CONFIG_ESP32_WIFI_IRAM_OPT
WiFi IRAM speed optimization
Found in: Component config > Wi-Fi
Select this option to place frequently called Wi-Fi library functions in IRAM. When this option is dis-
abled, more than 10Kbytes of IRAM memory will be saved but Wi-Fi throughput will be reduced.
Default value:
• No (disabled) if CONFIG_BT_ENABLED && CONFIG_SPIRAM
• Yes (enabled)
CONFIG_ESP32_WIFI_RX_IRAM_OPT
WiFi RX IRAM speed optimization
Found in: Component config > Wi-Fi
Select this option to place frequently called Wi-Fi library RX functions in IRAM. When this option is
disabled, more than 17Kbytes of IRAM memory will be saved but Wi-Fi performance will be reduced.
Default value:
• No (disabled) if CONFIG_BT_ENABLED && CONFIG_SPIRAM
• Yes (enabled)
CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE
Enable WPA3-Personal
Found in: Component config > Wi-Fi
Select this option to allow the device to establish a WPA3-Personal connection with eligible AP’s.
PMF (Protected Management Frames) is a prerequisite feature for a WPA3 connection, it needs to be
explicitly configured before attempting connection. Please refer to the Wi-Fi Driver API Guide for
details.
Default value:
• Yes (enabled)
CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA
Enable OWE STA
Found in: Component config > Wi-Fi
Select this option to allow the device to establish OWE connection with eligible AP’s. PMF (Protected
Management Frames) is a prerequisite feature for a WPA3 connection, it needs to be explicitly configured
before attempting connection. Please refer to the Wi-Fi Driver API Guide for details.
Default value:
• Yes (enabled)
CONFIG_ESP_WIFI_SLP_IRAM_OPT
WiFi SLP IRAM speed optimization
Found in: Component config > Wi-Fi
Select this option to place called Wi-Fi library TBTT process and receive beacon functions
in IRAM. Some functions can be put in IRAM either by ESP32_WIFI_IRAM_OPT and
ESP32_WIFI_RX_IRAM_OPT, or this one. If already enabled ESP32_WIFI_IRAM_OPT,
the other 7.3KB IRAM memory would be taken by this option. If already enabled
ESP32_WIFI_RX_IRAM_OPT, the other 1.3KB IRAM memory would be taken by this option.
If neither of them are enabled, the other 7.4KB IRAM memory would be taken by this option. Wi-Fi
power-save mode average current would be reduced if this option is enabled.
CONFIG_ESP_WIFI_SLP_DEFAULT_MIN_ACTIVE_TIME
Minimum active time
Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_IRAM_OPT
The minimum timeout for waiting to receive data, unit: milliseconds.
Range:
• from 8 to 60 if CONFIG_ESP_WIFI_SLP_IRAM_OPT
Default value:
• 50 if CONFIG_ESP_WIFI_SLP_IRAM_OPT
CONFIG_ESP_WIFI_SLP_DEFAULT_MAX_ACTIVE_TIME
Maximum keep alive time
Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_IRAM_OPT
The maximum time that wifi keep alive, unit: seconds.
Range:
• from 10 to 60 if CONFIG_ESP_WIFI_SLP_IRAM_OPT
Default value:
• 10 if CONFIG_ESP_WIFI_SLP_IRAM_OPT
CONFIG_ESP_WIFI_FTM_ENABLE
WiFi FTM
Found in: Component config > Wi-Fi
Enable feature Fine Timing Measurement for calculating WiFi Round-Trip-Time (RTT).
CONFIG_ESP_WIFI_FTM_INITIATOR_SUPPORT
FTM Initiator support
Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_FTM_ENABLE
Default value:
• Yes (enabled) if CONFIG_ESP_WIFI_FTM_ENABLE
CONFIG_ESP_WIFI_FTM_RESPONDER_SUPPORT
FTM Responder support
Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_FTM_ENABLE
Default value:
• Yes (enabled) if CONFIG_ESP_WIFI_FTM_ENABLE
CONFIG_ESP_WIFI_STA_DISCONNECTED_PM_ENABLE
Power Management for station at disconnected
Found in: Component config > Wi-Fi
Select this option to enable power_management for station when disconnected. Chip will do modem-
sleep when rf module is not in use any more.
CONFIG_ESP_WIFI_GCMP_SUPPORT
WiFi GCMP Support(GCMP128 and GCMP256)
Found in: Component config > Wi-Fi
Select this option to enable GCMP support. GCMP support is compulsory for WiFi Suite-B support.
CONFIG_ESP_WIFI_GMAC_SUPPORT
WiFi GMAC Support(GMAC128 and GMAC256)
Found in: Component config > Wi-Fi
Select this option to enable GMAC support. GMAC support is compulsory for WiFi 192 bit certification.
Default value:
• No (disabled)
CONFIG_ESP_WIFI_SOFTAP_SUPPORT
WiFi SoftAP Support
Found in: Component config > Wi-Fi
WiFi module can be compiled without SoftAP to save code size.
Default value:
• Yes (enabled)
CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT
Wifi sleep optimize when beacon lost
Found in: Component config > Wi-Fi
Enable wifi sleep optimization when beacon loss occurs and immediately enter sleep mode when the
WiFi module detects beacon loss.
CONFIG_ESP_WIFI_SLP_BEACON_LOST_TIMEOUT
Beacon loss timeout
Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT
Timeout time for close rf phy when beacon loss occurs, Unit: 1024 microsecond.
Range:
• from 5 to 100 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT
Default value:
• 10 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT
CONFIG_ESP_WIFI_SLP_BEACON_LOST_THRESHOLD
Maximum number of consecutive lost beacons allowed
Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT
Maximum number of consecutive lost beacons allowed, WiFi keeps Rx state when the number of con-
secutive beacons lost is greater than the given threshold.
Range:
• from 0 to 8 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT
Default value:
• 3 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT
CONFIG_ESP_WIFI_SLP_PHY_ON_DELTA_EARLY_TIME
Delta early time for RF PHY on
Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT
Delta early time for rf phy on, When the beacon is lost, the next rf phy on will be earlier the time specified
by the configuration item, Unit: 32 microsecond.
Range:
• from 0 to 100 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT
Default value:
• 2 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT
CONFIG_ESP_WIFI_SLP_PHY_OFF_DELTA_TIMEOUT_TIME
Delta timeout time for RF PHY off
Found in: Component config > Wi-Fi > CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT
Delta timeout time for rf phy off, When the beacon is lost, the next rf phy off will be delayed for the
time specified by the configuration item. Unit: 1024 microsecond.
Range:
• from 0 to 8 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT
Default value:
• 2 if CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT
• CONFIG_ESP_COREDUMP_STACK_SIZE
CONFIG_ESP_COREDUMP_TO_FLASH_OR_UART
Data destination
Found in: Component config > Core dump
Select place to store core dump: flash, uart or none (to disable core dumps generation).
Core dumps to Flash are not available if PSRAM is used for task stacks.
If core dump is configured to be stored in flash and custom partition table is used add corresponding
entry to your CSV. For examples, please see predefined partition table CSV descriptions in the compo-
nents/partition_table directory.
Available options:
• Flash (ESP_COREDUMP_ENABLE_TO_FLASH)
• UART (ESP_COREDUMP_ENABLE_TO_UART)
• None (ESP_COREDUMP_ENABLE_TO_NONE)
CONFIG_ESP_COREDUMP_DATA_FORMAT
Core dump data format
Found in: Component config > Core dump
Select the data format for core dump.
Available options:
• Binary format (ESP_COREDUMP_DATA_FORMAT_BIN)
• ELF format (ESP_COREDUMP_DATA_FORMAT_ELF)
CONFIG_ESP_COREDUMP_CHECKSUM
Core dump data integrity check
Found in: Component config > Core dump
Select the integrity check for the core dump.
Available options:
• Use CRC32 for integrity verification (ESP_COREDUMP_CHECKSUM_CRC32)
• Use SHA256 for integrity verification (ESP_COREDUMP_CHECKSUM_SHA256)
CONFIG_ESP_COREDUMP_CHECK_BOOT
Check core dump data integrity on boot
Found in: Component config > Core dump
When enabled, if any data are found on the flash core dump partition, they will be checked by calculating
their checksum.
Default value:
• Yes (enabled) if ESP_COREDUMP_ENABLE_TO_FLASH
CONFIG_ESP_COREDUMP_MAX_TASKS_NUM
Maximum number of tasks
Found in: Component config > Core dump
Maximum number of tasks snapshots in core dump.
CONFIG_ESP_COREDUMP_UART_DELAY
Delay before print to UART
Found in: Component config > Core dump
Config delay (in ms) before printing core dump to UART. Delay can be interrupted by pressing Enter
key.
Default value:
• 0 if ESP_COREDUMP_ENABLE_TO_UART
CONFIG_ESP_COREDUMP_STACK_SIZE
Reserved stack size
Found in: Component config > Core dump
Size of the memory to be reserved for core dump stack. If 0 core dump process will run on the stack
of crashed task/ISR, otherwise special stack will be allocated. To ensure that core dump itself will not
overflow task/ISR stack set this to the value above 800. NOTE: It eats DRAM.
CONFIG_ESP_COREDUMP_DECODE
Handling of UART core dumps in IDF Monitor
Found in: Component config > Core dump
Available options:
• Decode and show summary (info_corefile) (ESP_COREDUMP_DECODE_INFO)
• Don’t decode (ESP_COREDUMP_DECODE_DISABLE)
CONFIG_FATFS_VOLUME_COUNT
Number of volumes
Found in: Component config > FAT Filesystem support
Number of volumes (logical drives) to use.
Range:
• from 1 to 10
Default value:
• 2
CONFIG_FATFS_SECTOR_SIZE
Sector size
Found in: Component config > FAT Filesystem support
Specify the size of the sector in bytes for FATFS partition generator.
Available options:
• 512 (FATFS_SECTOR_512)
• 1024 (FATFS_SECTOR_1024)
• 2048 (FATFS_SECTOR_2048)
• 4096 (FATFS_SECTOR_4096)
CONFIG_FATFS_SECTORS_PER_CLUSTER
Sectors per cluster
Found in: Component config > FAT Filesystem support
This value specifies how many sectors there are in one cluster.
Available options:
• 1 (FATFS_SECTORS_PER_CLUSTER_1)
• 2 (FATFS_SECTORS_PER_CLUSTER_2)
• 4 (FATFS_SECTORS_PER_CLUSTER_4)
• 8 (FATFS_SECTORS_PER_CLUSTER_8)
• 16 (FATFS_SECTORS_PER_CLUSTER_16)
• 32 (FATFS_SECTORS_PER_CLUSTER_32)
• 64 (FATFS_SECTORS_PER_CLUSTER_64)
• 128 (FATFS_SECTORS_PER_CLUSTER_128)
CONFIG_FATFS_CHOOSE_CODEPAGE
OEM Code Page
Found in: Component config > FAT Filesystem support
OEM code page used for file name encodings.
If“Dynamic”is selected, code page can be chosen at runtime using f_setcp function. Note that choosing
this option will increase application size by ~480kB.
Available options:
• Dynamic (all code pages supported) (FATFS_CODEPAGE_DYNAMIC)
• US (CP437) (FATFS_CODEPAGE_437)
• Arabic (CP720) (FATFS_CODEPAGE_720)
• Greek (CP737) (FATFS_CODEPAGE_737)
• KBL (CP771) (FATFS_CODEPAGE_771)
• Baltic (CP775) (FATFS_CODEPAGE_775)
• Latin 1 (CP850) (FATFS_CODEPAGE_850)
• Latin 2 (CP852) (FATFS_CODEPAGE_852)
• Cyrillic (CP855) (FATFS_CODEPAGE_855)
• Turkish (CP857) (FATFS_CODEPAGE_857)
• Portugese (CP860) (FATFS_CODEPAGE_860)
• Icelandic (CP861) (FATFS_CODEPAGE_861)
• Hebrew (CP862) (FATFS_CODEPAGE_862)
• Canadian French (CP863) (FATFS_CODEPAGE_863)
• Arabic (CP864) (FATFS_CODEPAGE_864)
• Nordic (CP865) (FATFS_CODEPAGE_865)
• Russian (CP866) (FATFS_CODEPAGE_866)
• Greek 2 (CP869) (FATFS_CODEPAGE_869)
• Japanese (DBCS) (CP932) (FATFS_CODEPAGE_932)
CONFIG_FATFS_CHOOSE_TYPE
FAT type
Found in: Component config > FAT Filesystem support
If user specifies automatic detection of the FAT type, the FATFS generator will determine the type by
the size.
Available options:
• Select a suitable FATFS type automatically. (FATFS_AUTO_TYPE)
• FAT12 (FATFS_FAT12)
• FAT16 (FATFS_FAT16)
CONFIG_FATFS_LONG_FILENAMES
Long filename support
Found in: Component config > FAT Filesystem support
Support long filenames in FAT. Long filename data increases memory usage. FATFS can be configured
to store the buffer for long filename data in stack or heap (Currently not supported by FATFS partition
generator).
Available options:
• No long filenames (FATFS_LFN_NONE)
• Long filename buffer in heap (FATFS_LFN_HEAP)
• Long filename buffer on stack (FATFS_LFN_STACK)
CONFIG_FATFS_MAX_LFN
Max long filename length
Found in: Component config > FAT Filesystem support
Maximum long filename length. Can be reduced to save RAM.
Range:
• from 12 to 255
Default value:
• 255
CONFIG_FATFS_API_ENCODING
API character encoding
Found in: Component config > FAT Filesystem support
Choose encoding for character and string arguments/returns when using FATFS APIs. The encoding of
arguments will usually depend on text editor settings.
Available options:
• API uses ANSI/OEM encoding (FATFS_API_ENCODING_ANSI_OEM)
• API uses UTF-8 encoding (FATFS_API_ENCODING_UTF_8)
CONFIG_FATFS_FS_LOCK
Number of simultaneously open files protected by lock function
Found in: Component config > FAT Filesystem support
This option sets the FATFS configuration value _FS_LOCK. The option _FS_LOCK switches file lock
function to control duplicated file open and illegal operation to open objects.
* 0: Disable file lock function. To avoid volume corruption, application should avoid illegal open, remove
and rename to the open objects.
* >0: Enable file lock function. The value defines how many files/sub-directories can be opened simul-
taneously under file lock control.
Note that the file lock control is independent of re-entrancy.
Range:
• from 0 to 65535
Default value:
• 0
CONFIG_FATFS_TIMEOUT_MS
Timeout for acquiring a file lock, ms
Found in: Component config > FAT Filesystem support
This option sets FATFS configuration value _FS_TIMEOUT, scaled to milliseconds. Sets the number
of milliseconds FATFS will wait to acquire a mutex when operating on an open file. For example, if one
task is performing a lenghty operation, another task will wait for the first task to release the lock, and
time out after amount of time set by this option.
Default value:
• 10000
CONFIG_FATFS_PER_FILE_CACHE
Use separate cache for each file
Found in: Component config > FAT Filesystem support
This option affects FATFS configuration value _FS_TINY.
If this option is set, _FS_TINY is 0, and each open file has its own cache, size of the cache is equal to
the _MAX_SS variable (512 or 4096 bytes). This option uses more RAM if more than 1 file is open,
but needs less reads and writes to the storage for some operations.
If this option is not set, _FS_TINY is 1, and single cache is used for all open files, size is also equal to
_MAX_SS variable. This reduces the amount of heap used when multiple files are open, but increases
the number of read and write operations which FATFS needs to make.
Default value:
• Yes (enabled)
CONFIG_FATFS_ALLOC_PREFER_EXTRAM
Perfer external RAM when allocating FATFS buffers
Found in: Component config > FAT Filesystem support
When the option is enabled, internal buffers used by FATFS will be allocated from external RAM. If
the allocation from external RAM fails, the buffer will be allocated from the internal RAM. Disable this
option if optimizing for performance. Enable this option if optimizing for internal memory size.
Default value:
CONFIG_FATFS_USE_FASTSEEK
Enable fast seek algorithm when using lseek function through VFS FAT
Found in: Component config > FAT Filesystem support
The fast seek feature enables fast backward/long seek operations without FAT access by using an in-
memory CLMT (cluster link map table). Please note, fast-seek is only allowed for read-mode files, if a
file is opened in write-mode, the seek mechanism will automatically fallback to the default implemen-
tation.
Default value:
• No (disabled)
CONFIG_FATFS_FAST_SEEK_BUFFER_SIZE
Fast seek CLMT buffer size
Found in: Component config > FAT Filesystem support > CONFIG_FATFS_USE_FASTSEEK
If fast seek algorithm is enabled, this defines the size of CLMT buffer used by this algorithm in 32-bit
word units. This value should be chosen based on prior knowledge of maximum elements of each file
entry would store.
Default value:
• 64 if CONFIG_FATFS_USE_FASTSEEK
FreeRTOS Contains:
• Kernel
• Port
Kernel Contains:
• CONFIG_FREERTOS_CHECK_STACKOVERFLOW
• CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY
• CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS
• CONFIG_FREERTOS_MAX_TASK_NAME_LEN
• CONFIG_FREERTOS_IDLE_TASK_STACKSIZE
• CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS
• CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE
• CONFIG_FREERTOS_HZ
• CONFIG_FREERTOS_TIMER_QUEUE_LENGTH
• CONFIG_FREERTOS_TIMER_TASK_PRIORITY
• CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH
• CONFIG_FREERTOS_USE_IDLE_HOOK
• CONFIG_FREERTOS_OPTIMIZED_SCHEDULER
• CONFIG_FREERTOS_USE_TICK_HOOK
• CONFIG_FREERTOS_USE_TICKLESS_IDLE
• CONFIG_FREERTOS_USE_TRACE_FACILITY
• CONFIG_FREERTOS_UNICORE
• CONFIG_FREERTOS_SMP
• CONFIG_FREERTOS_USE_MINIMAL_IDLE_HOOK
CONFIG_FREERTOS_SMP
CONFIG_FREERTOS_UNICORE
Run FreeRTOS only on first core
Found in: Component config > FreeRTOS > Kernel
This version of FreeRTOS normally takes control of all cores of the CPU. Select this if you only want
to start it on the first core. This is needed when e.g. another process needs complete control over the
second core.
CONFIG_FREERTOS_HZ
configTICK_RATE_HZ
Found in: Component config > FreeRTOS > Kernel
Sets the FreeRTOS tick interrupt frequency in Hz (see configTICK_RATE_HZ documentation for more
details).
Range:
• from 1 to 1000
Default value:
• 100
CONFIG_FREERTOS_OPTIMIZED_SCHEDULER
configUSE_PORT_OPTIMISED_TASK_SELECTION
Found in: Component config > FreeRTOS > Kernel
Enables port specific task selection method. This option can will speed up the search of ready tasks
when scheduling (see configUSE_PORT_OPTIMISED_TASK_SELECTION documentation for more
details).
Default value:
• Yes (enabled) if CONFIG_FREERTOS_UNICORE
CONFIG_FREERTOS_CHECK_STACKOVERFLOW
configCHECK_FOR_STACK_OVERFLOW
Found in: Component config > FreeRTOS > Kernel
Enables FreeRTOS to check for stack overflows (see configCHECK_FOR_STACK_OVERFLOW doc-
umentation for more details).
Note: If users do not provide their own vApplicationStackOverflowHook() function, a de-
fault function will be provided by ESP-IDF.
Available options:
• No checking (FREERTOS_CHECK_STACKOVERFLOW_NONE)
Do not check for stack overflows (configCHECK_FOR_STACK_OVERFLOW = 0)
CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS
configNUM_THREAD_LOCAL_STORAGE_POINTERS
Found in: Component config > FreeRTOS > Kernel
Set the number of thread local storage pointers in each task (see con-
figNUM_THREAD_LOCAL_STORAGE_POINTERS documentation for more details).
Note: In ESP-IDF, this value must be at least 1. Index 0 is reserved for use by the pthreads API thread-
local-storage. Other indexes can be used for any desired purpose.
Range:
• from 1 to 256
Default value:
• 1
CONFIG_FREERTOS_IDLE_TASK_STACKSIZE
configMINIMAL_STACK_SIZE (Idle task stack size)
Found in: Component config > FreeRTOS > Kernel
Sets the idle task stack size in bytes (see configMINIMAL_STACK_SIZE documentation for more
details).
Note:
• ESP-IDF specifies stack sizes in bytes instead of words.
• The default size is enough for most use cases.
• The stack size may need to be increased above the default if the app installs idle or thread local
storage cleanup hooks that use a lot of stack memory.
• Conversely, the stack size can be reduced to the minimum if non of the idle features are used.
Range:
• from 768 to 32768
Default value:
• 1536
CONFIG_FREERTOS_USE_IDLE_HOOK
configUSE_IDLE_HOOK
Found in: Component config > FreeRTOS > Kernel
Enables the idle task application hook (see configUSE_IDLE_HOOK documentation for more details).
Note:
• The application must provide the hook function void vApplicationIdleHook( void
);
• vApplicationIdleHook() is called from FreeRTOS idle task(s)
• The FreeRTOS idle hook is NOT the same as the ESP-IDF Idle Hook, but both can be enabled
simultaneously.
Default value:
• No (disabled)
CONFIG_FREERTOS_USE_MINIMAL_IDLE_HOOK
Use FreeRTOS minimal idle hook
Found in: Component config > FreeRTOS > Kernel
Enables the minimal idle task application hook (see configUSE_IDLE_HOOK documentation for more
details).
Note:
• The application must provide the hook function void vApplicationMinimalIdleHook(
void );
• vApplicationMinimalIdleHook() is called from FreeRTOS minimal idle task(s)
Default value:
• No (disabled) if CONFIG_FREERTOS_SMP
CONFIG_FREERTOS_USE_TICK_HOOK
configUSE_TICK_HOOK
Found in: Component config > FreeRTOS > Kernel
Enables the tick hook (see configUSE_TICK_HOOK documentation for more details).
Note:
• The application must provide the hook function void vApplicationTickHook( void
);
• vApplicationTickHook() is called from FreeRTOS’s tick handling function xTaskIn-
crementTick()
• The FreeRTOS tick hook is NOT the same as the ESP-IDF Tick Interrupt Hook, but both can be
enabled simultaneously.
Default value:
• No (disabled)
CONFIG_FREERTOS_MAX_TASK_NAME_LEN
configMAX_TASK_NAME_LEN
Found in: Component config > FreeRTOS > Kernel
Sets the maximum number of characters for task names (see configMAX_TASK_NAME_LEN docu-
mentation for more details).
Note: For most uses, the default of 16 characters is sufficient.
Range:
• from 1 to 256
Default value:
• 16
CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY
configENABLE_BACKWARD_COMPATIBILITY
Found in: Component config > FreeRTOS > Kernel
Enable backward compatibility with APIs prior to FreeRTOS v8.0.0. (see configEN-
ABLE_BACKWARD_COMPATIBILITY documentation for more details).
Default value:
• No (disabled)
CONFIG_FREERTOS_TIMER_TASK_PRIORITY
configTIMER_TASK_PRIORITY
Found in: Component config > FreeRTOS > Kernel
Sets the timer task’s priority (see configTIMER_TASK_PRIORITY documentation for more details).
Range:
• from 1 to 25
Default value:
• 1
CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH
configTIMER_TASK_STACK_DEPTH
Found in: Component config > FreeRTOS > Kernel
Set the timer task’s stack size (see configTIMER_TASK_STACK_DEPTH documentation for more
details).
Range:
• from 1536 to 32768
Default value:
• 2048
CONFIG_FREERTOS_TIMER_QUEUE_LENGTH
configTIMER_QUEUE_LENGTH
Found in: Component config > FreeRTOS > Kernel
Set the timer task’s command queue length (see configTIMER_QUEUE_LENGTH documentation for
more details).
Range:
• from 5 to 20
Default value:
• 10
CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE
configQUEUE_REGISTRY_SIZE
Found in: Component config > FreeRTOS > Kernel
Set the size of the queue registry (see configQUEUE_REGISTRY_SIZE documentation for more de-
tails).
Note: A value of 0 will disable queue registry functionality
Range:
• from 0 to 20
Default value:
• 0
CONFIG_FREERTOS_USE_TRACE_FACILITY
configUSE_TRACE_FACILITY
Found in: Component config > FreeRTOS > Kernel
Enables additional structure members and functions to assist with execution visualization and tracing
(see configUSE_TRACE_FACILITY documentation for more details).
Default value:
• No (disabled)
CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS
configUSE_STATS_FORMATTING_FUNCTIONS
Found in: Component config > FreeRTOS > Kernel > CONFIG_FREERTOS_USE_TRACE_FACILITY
Set configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS to 1 to
include the vTaskList() and vTaskGetRunTimeStats() functions in the build (see confi-
gUSE_STATS_FORMATTING_FUNCTIONS documentation for more details).
Default value:
• No (disabled) if CONFIG_FREERTOS_USE_TRACE_FACILITY
CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID
Enable display of xCoreID in vTaskList
Found in: Component config > FreeRTOS > Kernel > CONFIG_FREERTOS_USE_TRACE_FACILITY >
CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS
If enabled, this will include an extra column when vTaskList is called to display the CoreID the task is
pinned to (0,1) or -1 if not pinned.
Default value:
• No (disabled) if CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS
CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS
configGENERATE_RUN_TIME_STATS
Found in: Component config > FreeRTOS > Kernel
Enables collection of run time statistics for each task (see configGENERATE_RUN_TIME_STATS
documentation for more details).
Note: The clock used for run time statistics can be configured in FREER-
TOS_RUN_TIME_STATS_CLK.
Default value:
• No (disabled)
CONFIG_FREERTOS_USE_TICKLESS_IDLE
configUSE_TICKLESS_IDLE
Found in: Component config > FreeRTOS > Kernel
If power management support is enabled, FreeRTOS will be able to put the system into light sleep
mode when no tasks need to run for a number of ticks. This number can be set using FREER-
TOS_IDLE_TIME_BEFORE_SLEEP option. This feature is also known as “automatic light sleep”
.
Note that timers created using esp_timer APIs may prevent the system from entering sleep mode,
even when no tasks need to run. To skip unnecessary wake-up initialize a timer with the
“skip_unhandled_events”option as true.
If disabled, automatic light sleep support will be disabled.
Default value:
• No (disabled) if CONFIG_PM_ENABLE
CONFIG_FREERTOS_IDLE_TIME_BEFORE_SLEEP
configEXPECTED_IDLE_TIME_BEFORE_SLEEP
Found in: Component config > FreeRTOS > Kernel > CONFIG_FREERTOS_USE_TICKLESS_IDLE
FreeRTOS will enter light sleep mode if no tasks need to run for this number of ticks.
Range:
• from 2 to 4294967295 if CONFIG_FREERTOS_USE_TICKLESS_IDLE
Default value:
• 3 if CONFIG_FREERTOS_USE_TICKLESS_IDLE
Port Contains:
• CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER
• CONFIG_FREERTOS_RUN_TIME_STATS_CLK
• CONFIG_FREERTOS_INTERRUPT_BACKTRACE
• CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK
• CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP
• CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT
• CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS
• CONFIG_FREERTOS_ASSERT_ON_UNTESTED_FUNCTION
• CONFIG_FREERTOS_ISR_STACKSIZE
• CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH
• CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH
• CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE
• CONFIG_FREERTOS_CORETIMER
• CONFIG_FREERTOS_FPU_IN_ISR
• CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER
CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER
Wrap task functions
Found in: Component config > FreeRTOS > Port
If enabled, all FreeRTOS task functions will be enclosed in a wrapper function. If a task function
mistakenly returns (i.e. does not delete), the call flow will return to the wrapper function. The wrapper
function will then log an error and abort the application. This option is also required for GDB backtraces
and C++ exceptions to work correctly inside top-level task functions.
Default value:
• Yes (enabled)
CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK
Enable stack overflow debug watchpoint
Found in: Component config > FreeRTOS > Port
FreeRTOS can check if a stack has overflown its bounds by checking either the value of the stack pointer
or by checking the integrity of canary bytes. (See FREERTOS_CHECK_STACKOVERFLOW for
more information.) These checks only happen on a context switch, and the situation that caused the stack
overflow may already be long gone by then. This option will use the last debug memory watchpoint to
allow breaking into the debugger (or panic’ing) as soon as any of the last 32 bytes on the stack of a
task are overwritten. The side effect is that using gdb, you effectively have one hardware watchpoint less
because the last one is overwritten as soon as a task switch happens.
Another consequence is that due to alignment requirements of the watchpoint, the usable stack size
decreases by up to 60 bytes. This is because the watchpoint region has to be aligned to its size and the
size for the stack watchpoint in IDF is 32 bytes.
This check only triggers if the stack overflow writes within 32 bytes near the end of the stack, rather
than overshooting further, so it is worth combining this approach with one of the other stack overflow
check methods.
When this watchpoint is hit, gdb will stop with a SIGTRAP message. When no JTAG OCD is attached,
esp-idf will panic on an unhandled debug exception.
Default value:
• No (disabled)
CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS
Enable thread local storage pointers deletion callbacks
Found in: Component config > FreeRTOS > Port
ESP-IDF provides users with the ability to free TLSP memory by registering TLSP deletion callbacks.
These callbacks are automatically called by FreeRTOS when a task is deleted. When this option is
turned on, the memory reserved for TLSPs in the TCB is doubled to make space for storing the deletion
callbacks. If the user does not wish to use TLSP deletion callbacks then this option could be turned off
to save space in the TCB memory.
Default value:
• Yes (enabled) if CONFIG_FREERTOS_SMP && CON-
FIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS > 0
CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP
Enable static task clean up hook
Found in: Component config > FreeRTOS > Port
Enable this option to make FreeRTOS call the static task clean up hook when a task is deleted.
Note: Users will need to provide a void vPortCleanUpTCB ( void \*pxTCB ) callback
Default value:
• No (disabled) if CONFIG_FREERTOS_SMP
CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER
Check that mutex semaphore is given by owner task
Found in: Component config > FreeRTOS > Port
If enabled, assert that when a mutex semaphore is given, the task giving the semaphore is the task which
is currently holding the mutex.
Default value:
• Yes (enabled)
CONFIG_FREERTOS_ISR_STACKSIZE
ISR stack size
Found in: Component config > FreeRTOS > Port
The interrupt handlers have their own stack. The size of the stack can be defined here. Each processor
has its own stack, so the total size occupied will be twice this.
Range:
• from 2096 to 32768 if ESP_COREDUMP_DATA_FORMAT_ELF
• from 1536 to 32768
Default value:
• 2096 if ESP_COREDUMP_DATA_FORMAT_ELF
• 1536
CONFIG_FREERTOS_INTERRUPT_BACKTRACE
Enable backtrace from interrupt to task context
Found in: Component config > FreeRTOS > Port
If this option is enabled, interrupt stack frame will be modified to point to the code of the interrupted
task as its return address. This helps the debugger (or the panic handler) show a backtrace from the
interrupt to the task which was interrupted. This also works for nested interrupts: higher level interrupt
stack can be traced back to the lower level interrupt. This option adds 4 instructions to the interrupt
dispatching code.
Default value:
• Yes (enabled)
CONFIG_FREERTOS_FPU_IN_ISR
Use float in Level 1 ISR
Found in: Component config > FreeRTOS > Port
When enabled, the usage of float type is allowed inside Level 1 ISRs. Note that usage of float types in
higher level interrupts is still not permitted.
Default value:
• No (disabled)
CONFIG_FREERTOS_CORETIMER
Tick timer source (Xtensa Only)
Found in: Component config > FreeRTOS > Port
FreeRTOS needs a timer with an associated interrupt to use as the main tick source to increase counters,
run timers and do pre-emptive multitasking with. There are multiple timers available to do this, with
different interrupt priorities.
Available options:
• Timer 0 (int 6, level 1) (FREERTOS_CORETIMER_0)
Select this to use timer 0
• Timer 1 (int 15, level 3) (FREERTOS_CORETIMER_1)
Select this to use timer 1
• SYSTIMER 0 (level 1) (FREERTOS_CORETIMER_SYSTIMER_LVL1)
Select this to use systimer with the 1 interrupt priority.
• SYSTIMER 0 (level 3) (FREERTOS_CORETIMER_SYSTIMER_LVL3)
Select this to use systimer with the 3 interrupt priority.
CONFIG_FREERTOS_RUN_TIME_STATS_CLK
Choose the clock source for run time stats
Found in: Component config > FreeRTOS > Port
Choose the clock source for FreeRTOS run time stats. Options are CPU0’s CPU Clock or the ESP
Timer. Both clock sources are 32 bits. The CPU Clock can run at a higher frequency hence provide a
finer resolution but will overflow much quicker. Note that run time stats are only valid until the clock
source overflows.
Available options:
• Use ESP TIMER for run time stats (FREERTOS_RUN_TIME_STATS_USING_ESP_TIMER)
ESP Timer will be used as the clock source for FreeRTOS run time stats. The ESP Timer
runs at a frequency of 1MHz regardless of Dynamic Frequency Scaling. Therefore the ESP
Timer will overflow in approximately 4290 seconds.
• Use CPU Clock for run time stats (FREERTOS_RUN_TIME_STATS_USING_CPU_CLK)
CPU Clock will be used as the clock source for the generation of run time stats. The CPU
Clock has a frequency dependent on ESP_DEFAULT_CPU_FREQ_MHZ and Dynamic Fre-
quency Scaling (DFS). Therefore the CPU Clock frequency can fluctuate between 80 to
240MHz. Run time stats generated using the CPU Clock represents the number of CPU
cycles each task is allocated and DOES NOT reflect the amount of time each task runs for
(as CPU clock frequency can change). If the CPU clock consistently runs at the maximum
frequency of 240MHz, it will overflow in approximately 17 seconds.
CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH
Place FreeRTOS functions into Flash
Found in: Component config > FreeRTOS > Port
When enabled the selected Non-ISR FreeRTOS functions will be placed into Flash memory instead of
IRAM. This saves up to 8KB of IRAM depending on which functions are used.
Default value:
• No (disabled)
CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH
Place task snapshot functions into flash
Found in: Component config > FreeRTOS > Port
When enabled, the functions related to snapshots, such as vTaskGetSnapshot or uxTaskGetSnapshotAll,
will be placed in flash. Note that if enabled, these functions cannot be called when cache is disabled.
Default value:
• No (disabled) if CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT && CON-
FIG_ESP_PANIC_HANDLER_IRAM
CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE
Tests compliance with Vanilla FreeRTOS port*_CRITICAL calls
Found in: Component config > FreeRTOS > Port
If enabled, context of port*_CRITICAL calls (ISR or Non-ISR) would be checked to be in compliance
with Vanilla FreeRTOS. e.g Calling port*_CRITICAL from ISR context would cause assert failure
Default value:
• No (disabled)
CONFIG_FREERTOS_ASSERT_ON_UNTESTED_FUNCTION
Halt when an SMP-untested function is called
Found in: Component config > FreeRTOS > Port
Some functions in FreeRTOS have not been thoroughly tested yet when moving to the SMP implemen-
tation of FreeRTOS. When this option is enabled, these functions will throw an assert().
Default value:
• Yes (enabled)
CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT
Enable task snapshot functions
Found in: Component config > FreeRTOS > Port
When enabled, the functions related to snapshots, such as vTaskGetSnapshot or uxTaskGetSnapshotAll,
are compiled and linked. Task snapshots are primarily used by GDB Stub and Core dump.
Default value:
• Yes (enabled)
CONFIG_HAL_DEFAULT_ASSERTION_LEVEL
Default HAL assertion level
Found in: Component config > Hardware Abstraction Layer (HAL) and Low Level (LL)
Set the assert behavior / level for HAL component. HAL component assert level can be set separately,
but the level can’t exceed the system assertion level. e.g. If the system assertion is disabled, then the
HAL assertion can’t be enabled either. If the system assertion is enable, then the HAL assertion can
still be disabled by this Kconfig option.
Available options:
• Same as system assertion level (HAL_ASSERTION_EQUALS_SYSTEM)
• Disabled (HAL_ASSERTION_DISABLE)
• Silent (HAL_ASSERTION_SILENT)
• Enabled (HAL_ASSERTION_ENABLE)
CONFIG_HAL_LOG_LEVEL
HAL layer log verbosity
Found in: Component config > Hardware Abstraction Layer (HAL) and Low Level (LL)
Specify how much output to see in HAL logs.
Available options:
• No output (HAL_LOG_LEVEL_NONE)
• Error (HAL_LOG_LEVEL_ERROR)
• Warning (HAL_LOG_LEVEL_WARN)
• Info (HAL_LOG_LEVEL_INFO)
• Debug (HAL_LOG_LEVEL_DEBUG)
• Verbose (HAL_LOG_LEVEL_VERBOSE)
CONFIG_HAL_SYSTIMER_USE_ROM_IMPL
Use ROM implementation of SysTimer HAL driver
Found in: Component config > Hardware Abstraction Layer (HAL) and Low Level (LL)
Enable this flag to use HAL functions from ROM instead of ESP-IDF.
If keeping this as “n”in your project, you will have less free IRAM. If making this as “y”in your
project, you will increase free IRAM, but you will lose the possibility to debug this module, and some
new features will be added and bugs will be fixed in the IDF source but cannot be synced to ROM.
Default value:
• Yes (enabled) if ESP_ROM_HAS_HAL_SYSTIMER
CONFIG_HAL_WDT_USE_ROM_IMPL
Use ROM implementation of WDT HAL driver
Found in: Component config > Hardware Abstraction Layer (HAL) and Low Level (LL)
Enable this flag to use HAL functions from ROM instead of ESP-IDF.
If keeping this as “n”in your project, you will have less free IRAM. If making this as “y”in your
project, you will increase free IRAM, but you will lose the possibility to debug this module, and some
new features will be added and bugs will be fixed in the IDF source but cannot be synced to ROM.
Default value:
• Yes (enabled) if ESP_ROM_HAS_HAL_WDT
CONFIG_HEAP_CORRUPTION_DETECTION
Heap corruption detection
Found in: Component config > Heap memory debugging
Enable heap poisoning features to detect heap corruption caused by out-of-bounds access to heap mem-
ory.
See the “Heap Memory Debugging”page of the IDF documentation for a description of each level of
heap corruption detection.
Available options:
• Basic (no poisoning) (HEAP_POISONING_DISABLED)
• Light impact (HEAP_POISONING_LIGHT)
• Comprehensive (HEAP_POISONING_COMPREHENSIVE)
CONFIG_HEAP_TRACING_DEST
Heap tracing
Found in: Component config > Heap memory debugging
Enables the heap tracing API defined in esp_heap_trace.h.
This function causes a moderate increase in IRAM code side and a minor increase in heap function
(malloc/free/realloc) CPU overhead, even when the tracing feature is not used. So it’s best to keep it
disabled unless tracing is being used.
Available options:
• Disabled (HEAP_TRACING_OFF)
• Standalone (HEAP_TRACING_STANDALONE)
• Host-based (HEAP_TRACING_TOHOST)
CONFIG_HEAP_TRACING_STACK_DEPTH
Heap tracing stack depth
Found in: Component config > Heap memory debugging
Number of stack frames to save when tracing heap operation callers.
More stack frames uses more memory in the heap trace buffer (and slows down allocation), but can
provide useful information.
CONFIG_HEAP_TASK_TRACKING
Enable heap task tracking
Found in: Component config > Heap memory debugging
Enables tracking the task responsible for each heap allocation.
This function depends on heap poisoning being enabled and adds four more bytes of overhead for each
block allocated.
CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS
Abort if memory allocation fails
Found in: Component config > Heap memory debugging
When enabled, if a memory allocation operation fails it will cause a system abort.
Default value:
• No (disabled)
CONFIG_HEAP_TLSF_USE_ROM_IMPL
Use ROM implementation of heap tlsf library
Found in: Component config > Heap memory debugging
Enable this flag to use heap functions from ROM instead of ESP-IDF.
If keeping this as “n”in your project, you will have less free IRAM. If making this as “y”in your
project, you will increase free IRAM, but you will lose the possibility to debug this module, and some
new features will be added and bugs will be fixed in the IDF source but cannot be synced to ROM.
Default value:
• Yes (enabled) if ESP_ROM_HAS_HEAP_TLSF
CONFIG_LOG_DEFAULT_LEVEL
Default log verbosity
Found in: Component config > Log output
Specify how much output to see in logs by default. You can set lower verbosity level at runtime using
esp_log_level_set function.
By default, this setting limits which log statements are compiled into the program. For example, selecting
“Warning”would mean that changing log level to “Debug”at runtime will not be possible. To allow
increasing log level above the default at runtime, see the next option.
Available options:
• No output (LOG_DEFAULT_LEVEL_NONE)
• Error (LOG_DEFAULT_LEVEL_ERROR)
• Warning (LOG_DEFAULT_LEVEL_WARN)
• Info (LOG_DEFAULT_LEVEL_INFO)
• Debug (LOG_DEFAULT_LEVEL_DEBUG)
• Verbose (LOG_DEFAULT_LEVEL_VERBOSE)
CONFIG_LOG_MAXIMUM_LEVEL
Maximum log verbosity
Found in: Component config > Log output
This config option sets the highest log verbosity that it’s possible to select at runtime by calling
esp_log_level_set(). This level may be higher than the default verbosity level which is set when the
app starts up.
This can be used enable debugging output only at a critical point, for a particular tag, or to minimize
startup time but then enable more logs once the firmware has loaded.
Note that increasing the maximum available log level will increase the firmware binary size.
This option only applies to logging from the app, the bootloader log level is fixed at compile time to the
separate “Bootloader log verbosity”setting.
Available options:
• Same as default (LOG_MAXIMUM_EQUALS_DEFAULT)
• Error (LOG_MAXIMUM_LEVEL_ERROR)
• Warning (LOG_MAXIMUM_LEVEL_WARN)
• Info (LOG_MAXIMUM_LEVEL_INFO)
• Debug (LOG_MAXIMUM_LEVEL_DEBUG)
• Verbose (LOG_MAXIMUM_LEVEL_VERBOSE)
CONFIG_LOG_COLORS
Use ANSI terminal colors in log output
Found in: Component config > Log output
Enable ANSI terminal color codes in bootloader output.
In order to view these, your terminal program must support ANSI color codes.
Default value:
• Yes (enabled)
CONFIG_LOG_TIMESTAMP_SOURCE
Log Timestamps
Found in: Component config > Log output
LWIP Contains:
• Checksums
• DHCP server
• CONFIG_LWIP_DHCP_OPTIONS_LEN
• CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID
• CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID
• CONFIG_LWIP_DHCP_DOES_ARP_CHECK
• CONFIG_LWIP_DHCP_RESTORE_LAST_IP
• CONFIG_LWIP_PPP_CHAP_SUPPORT
• CONFIG_LWIP_L2_TO_L3_COPY
• CONFIG_LWIP_IPV6_DHCP6
• CONFIG_LWIP_IP4_FRAG
• CONFIG_LWIP_IP6_FRAG
• CONFIG_LWIP_IP_FORWARD
• CONFIG_LWIP_NETBUF_RECVINFO
• CONFIG_LWIP_AUTOIP
• CONFIG_LWIP_IPV6
• CONFIG_LWIP_ENABLE_LCP_ECHO
• CONFIG_LWIP_ESP_LWIP_ASSERT
• CONFIG_LWIP_DEBUG
• CONFIG_LWIP_IRAM_OPTIMIZATION
• CONFIG_LWIP_STATS
• CONFIG_LWIP_TIMERS_ONDEMAND
• CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES
• CONFIG_LWIP_PPP_MPPE_SUPPORT
• CONFIG_LWIP_PPP_MSCHAP_SUPPORT
• CONFIG_LWIP_PPP_NOTIFY_PHASE_SUPPORT
• CONFIG_LWIP_PPP_PAP_SUPPORT
• CONFIG_LWIP_PPP_DEBUG_ON
• CONFIG_LWIP_PPP_SUPPORT
• CONFIG_LWIP_IP4_REASSEMBLY
• CONFIG_LWIP_IP6_REASSEMBLY
• CONFIG_LWIP_SLIP_SUPPORT
• CONFIG_LWIP_SO_LINGER
• CONFIG_LWIP_SO_RCVBUF
• CONFIG_LWIP_SO_REUSE
• CONFIG_LWIP_NETIF_STATUS_CALLBACK
• CONFIG_LWIP_TCPIP_CORE_LOCKING
• CONFIG_LWIP_NETIF_API
• Hooks
• ICMP
• CONFIG_LWIP_LOCAL_HOSTNAME
• LWIP RAW API
• CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS
• CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE
• CONFIG_LWIP_MAX_SOCKETS
• CONFIG_LWIP_BRIDGEIF_MAX_PORTS
• CONFIG_LWIP_NUM_NETIF_CLIENT_DATA
• CONFIG_LWIP_ESP_GRATUITOUS_ARP
• SNTP
• CONFIG_LWIP_USE_ONLY_LWIP_SELECT
• CONFIG_LWIP_NETIF_LOOPBACK
• TCP
• CONFIG_LWIP_TCPIP_TASK_AFFINITY
• CONFIG_LWIP_TCPIP_TASK_STACK_SIZE
• CONFIG_LWIP_TCPIP_RECVMBOX_SIZE
• UDP
• CONFIG_LWIP_IPV6_RDNSS_MAX_DNS_SERVERS
CONFIG_LWIP_LOCAL_HOSTNAME
Local netif hostname
Found in: Component config > LWIP
The default name this device will report to other devices on the network. Could be updated at runtime
with esp_netif_set_hostname()
Default value:
• “espressif”
CONFIG_LWIP_NETIF_API
Enable usage of standard POSIX APIs in LWIP
Found in: Component config > LWIP
If this feature is enabled, standard POSIX APIs: if_indextoname(), if_nametoindex() could be
used to convert network interface index to name instead of IDF specific esp-netif APIs (such as
esp_netif_get_netif_impl_name())
Default value:
• No (disabled)
CONFIG_LWIP_TCPIP_CORE_LOCKING
Enable tcpip core locking
Found in: Component config > LWIP
If Enable tcpip core locking,Creates a global mutex that is held during TCPIP thread operations.Can
be locked by client code to perform lwIP operations without changing into TCPIP thread using callbacks.
See LOCK_TCPIP_CORE() and UNLOCK_TCPIP_CORE().
If disable tcpip core locking,TCP IP will perform tasks through context switching.
Default value:
• No (disabled)
CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES
Enable mDNS queries in resolving host name
Found in: Component config > LWIP
If this feature is enabled, standard API such as gethostbyname support .local addresses by sending one
shot multicast mDNS query
Default value:
• Yes (enabled)
CONFIG_LWIP_L2_TO_L3_COPY
Enable copy between Layer2 and Layer3 packets
Found in: Component config > LWIP
If this feature is enabled, all traffic from layer2(WIFI Driver) will be copied to a new buffer before send-
ing it to layer3(LWIP stack), freeing the layer2 buffer. Please be notified that the total layer2 receiving
buffer is fixed and ESP32 currently supports 25 layer2 receiving buffer, when layer2 buffer runs out of
memory, then the incoming packets will be dropped in hardware. The layer3 buffer is allocated from
the heap, so the total layer3 receiving buffer depends on the available heap size, when heap runs out of
memory, no copy will be sent to layer3 and packet will be dropped in layer2. Please make sure you fully
understand the impact of this feature before enabling it.
Default value:
• No (disabled)
CONFIG_LWIP_IRAM_OPTIMIZATION
Enable LWIP IRAM optimization
Found in: Component config > LWIP
If this feature is enabled, some functions relating to RX/TX in LWIP will be put into IRAM, it can
improve UDP/TCP throughput by >10% for single core mode, it doesn’t help too much for dual core
mode. On the other hand, it needs about 10KB IRAM for these optimizations.
If this feature is disabled, all lwip functions will be put into FLASH.
Default value:
• No (disabled)
CONFIG_LWIP_TIMERS_ONDEMAND
Enable LWIP Timers on demand
Found in: Component config > LWIP
If this feature is enabled, IGMP and MLD6 timers will be activated only when joining groups or receiving
QUERY packets.
This feature will reduce the power consumption for applications which do not use IGMP and MLD6.
Default value:
• Yes (enabled)
CONFIG_LWIP_MAX_SOCKETS
Max number of open sockets
Found in: Component config > LWIP
Sockets take up a certain amount of memory, and allowing fewer sockets to be open at the same time
conserves memory. Specify the maximum amount of sockets here. The valid value is from 1 to 16.
Range:
• from 1 to 16
Default value:
• 10
CONFIG_LWIP_USE_ONLY_LWIP_SELECT
Support LWIP socket select() only (DEPRECATED)
Found in: Component config > LWIP
This option is deprecated. Do not use this option, use VFS_SUPPORT_SELECT instead.
Default value:
• No (disabled)
CONFIG_LWIP_SO_LINGER
Enable SO_LINGER processing
Found in: Component config > LWIP
Enabling this option allows SO_LINGER processing. l_onoff = 1,l_linger can set the timeout.
If l_linger=0, When a connection is closed, TCP will terminate the connection. This means that TCP
will discard any data packets stored in the socket send buffer and send an RST to the peer.
If l_linger!=0,Then closesocket() calls to block the process until the remaining data packets has been
sent or timed out.
Default value:
• No (disabled)
CONFIG_LWIP_SO_REUSE
Enable SO_REUSEADDR option
Found in: Component config > LWIP
Enabling this option allows binding to a port which remains in TIME_WAIT.
Default value:
• Yes (enabled)
CONFIG_LWIP_SO_REUSE_RXTOALL
SO_REUSEADDR copies broadcast/multicast to all matches
Found in: Component config > LWIP > CONFIG_LWIP_SO_REUSE
Enabling this option means that any incoming broadcast or multicast packet will be copied to all of the
local sockets that it matches (may be more than one if SO_REUSEADDR is set on the socket.)
This increases memory overhead as the packets need to be copied, however they are only copied per
matching socket. You can safely disable it if you don’t plan to receive broadcast or multicast traffic on
more than one socket at a time.
Default value:
• Yes (enabled)
CONFIG_LWIP_SO_RCVBUF
Enable SO_RCVBUF option
Found in: Component config > LWIP
Enabling this option allows checking for available data on a netconn.
Default value:
• No (disabled)
CONFIG_LWIP_NETBUF_RECVINFO
Enable IP_PKTINFO option
Found in: Component config > LWIP
Enabling this option allows checking for the destination address of a received IPv4 Packet.
Default value:
• No (disabled)
CONFIG_LWIP_IP4_FRAG
Enable fragment outgoing IP4 packets
Found in: Component config > LWIP
Enabling this option allows fragmenting outgoing IP4 packets if their size exceeds MTU.
Default value:
• Yes (enabled)
CONFIG_LWIP_IP6_FRAG
Enable fragment outgoing IP6 packets
Found in: Component config > LWIP
Enabling this option allows fragmenting outgoing IP6 packets if their size exceeds MTU.
Default value:
• Yes (enabled)
CONFIG_LWIP_IP4_REASSEMBLY
Enable reassembly incoming fragmented IP4 packets
Found in: Component config > LWIP
Enabling this option allows reassemblying incoming fragmented IP4 packets.
Default value:
• No (disabled)
CONFIG_LWIP_IP6_REASSEMBLY
Enable reassembly incoming fragmented IP6 packets
Found in: Component config > LWIP
Enabling this option allows reassemblying incoming fragmented IP6 packets.
Default value:
• No (disabled)
CONFIG_LWIP_IP_FORWARD
Enable IP forwarding
Found in: Component config > LWIP
Enabling this option allows packets forwarding across multiple interfaces.
Default value:
• No (disabled)
CONFIG_LWIP_IPV4_NAPT
Enable NAT (new/experimental)
Found in: Component config > LWIP > CONFIG_LWIP_IP_FORWARD
Enabling this option allows Network Address and Port Translation.
Default value:
• No (disabled) if CONFIG_LWIP_IP_FORWARD
CONFIG_LWIP_STATS
Enable LWIP statistics
Found in: Component config > LWIP
Enabling this option allows LWIP statistics
Default value:
• No (disabled)
CONFIG_LWIP_ESP_GRATUITOUS_ARP
Send gratuitous ARP periodically
Found in: Component config > LWIP
Enable this option allows to send gratuitous ARP periodically.
This option solve the compatibility issues.If the ARP table of the AP is old, and the AP doesn’t send
ARP request to update it’s ARP table, this will lead to the STA sending IP packet fail. Thus we send
gratuitous ARP periodically to let AP update it’s ARP table.
Default value:
• Yes (enabled)
CONFIG_LWIP_GARP_TMR_INTERVAL
GARP timer interval(seconds)
Found in: Component config > LWIP > CONFIG_LWIP_ESP_GRATUITOUS_ARP
Set the timer interval for gratuitous ARP. The default value is 60s
Default value:
• 60
CONFIG_LWIP_TCPIP_RECVMBOX_SIZE
TCPIP task receive mail box size
Found in: Component config > LWIP
Set TCPIP task receive mail box size. Generally bigger value means higher throughput but more memory.
The value should be bigger than UDP/TCP mail box size.
Range:
• from 6 to 64 if CONFIG_LWIP_WND_SCALE
• from 6 to 1024 if CONFIG_LWIP_WND_SCALE
Default value:
• 32
CONFIG_LWIP_DHCP_DOES_ARP_CHECK
DHCP: Perform ARP check on any offered address
Found in: Component config > LWIP
Enabling this option performs a check (via ARP request) if the offered IP address is not already in use
by another host on the network.
Default value:
• Yes (enabled)
CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID
DHCP: Disable Use of HW address as client identification
Found in: Component config > LWIP
This option could be used to disable DHCP client identification with its MAC address. (Client id is used
by DHCP servers to uniquely identify clients and are included in the DHCP packets as an option 61) Set
this option to “y”in order to exclude option 61 from DHCP packets.
Default value:
• No (disabled)
CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID
DHCP: Disable Use of vendor class identification
Found in: Component config > LWIP
This option could be used to disable DHCP client vendor class identification. Set this option to “y”in
order to exclude option 60 from DHCP packets.
Default value:
• Yes (enabled)
CONFIG_LWIP_DHCP_RESTORE_LAST_IP
DHCP: Restore last IP obtained from DHCP server
Found in: Component config > LWIP
When this option is enabled, DHCP client tries to re-obtain last valid IP address obtained from DHCP
server. Last valid DHCP configuration is stored in nvs and restored after reset/power-up. If IP is still
available, there is no need for sending discovery message to DHCP server and save some time.
Default value:
• No (disabled)
CONFIG_LWIP_DHCP_OPTIONS_LEN
DHCP total option length
Found in: Component config > LWIP
Set total length of outgoing DHCP option msg. Generally bigger value means it can carry more options
and values. If your code meets LWIP_ASSERT due to option value is too long. Please increase the
LWIP_DHCP_OPTIONS_LEN value.
Range:
• from 68 to 255
Default value:
• 68
• 108
CONFIG_LWIP_NUM_NETIF_CLIENT_DATA
Number of clients store data in netif
Found in: Component config > LWIP
Number of clients that may store data in client_data member array of struct netif.
Range:
• from 0 to 256
Default value:
• 0
CONFIG_LWIP_DHCPS
DHCPS: Enable IPv4 Dynamic Host Configuration Protocol Server (DHCPS)
Found in: Component config > LWIP > DHCP server
Enabling this option allows the device to run the DHCP server (to dynamically assign IPv4 addresses to
clients).
Default value:
• Yes (enabled)
CONFIG_LWIP_DHCPS_LEASE_UNIT
Multiplier for lease time, in seconds
Found in: Component config > LWIP > DHCP server > CONFIG_LWIP_DHCPS
The DHCP server is calculating lease time multiplying the sent and received times by this number of
seconds per unit. The default is 60, that equals one minute.
Range:
• from 1 to 3600
Default value:
• 60
CONFIG_LWIP_DHCPS_MAX_STATION_NUM
Maximum number of stations
Found in: Component config > LWIP > DHCP server > CONFIG_LWIP_DHCPS
The maximum number of DHCP clients that are connected to the server. After this number is exceeded,
DHCP server removes of the oldest device from it’s address pool, without notification.
Range:
• from 1 to 64
Default value:
• 8
CONFIG_LWIP_AUTOIP
Enable IPV4 Link-Local Addressing (AUTOIP)
Found in: Component config > LWIP
Enabling this option allows the device to self-assign an address in the 169.256/16 range if none is assigned
statically or via DHCP.
CONFIG_LWIP_AUTOIP_TRIES
DHCP Probes before self-assigning IPv4 LL address
Found in: Component config > LWIP > CONFIG_LWIP_AUTOIP
DHCP client will send this many probes before self-assigning a link local address.
From LWIP help: “This can be set as low as 1 to get an AutoIP address very quickly, but you should
be prepared to handle a changing IP address when DHCP overrides AutoIP.”(In the case of ESP-IDF,
this means multiple SYSTEM_EVENT_STA_GOT_IP events.)
Range:
• from 1 to 100 if CONFIG_LWIP_AUTOIP
Default value:
• 2 if CONFIG_LWIP_AUTOIP
CONFIG_LWIP_AUTOIP_MAX_CONFLICTS
Max IP conflicts before rate limiting
Found in: Component config > LWIP > CONFIG_LWIP_AUTOIP
If the AUTOIP functionality detects this many IP conflicts while self-assigning an address, it will go into
a rate limited mode.
Range:
• from 1 to 100 if CONFIG_LWIP_AUTOIP
Default value:
• 9 if CONFIG_LWIP_AUTOIP
CONFIG_LWIP_AUTOIP_RATE_LIMIT_INTERVAL
Rate limited interval (seconds)
Found in: Component config > LWIP > CONFIG_LWIP_AUTOIP
If rate limiting self-assignment requests, wait this long between each request.
Range:
• from 5 to 120 if CONFIG_LWIP_AUTOIP
Default value:
• 20 if CONFIG_LWIP_AUTOIP
CONFIG_LWIP_IPV6
Enable IPv6
Found in: Component config > LWIP
Enable IPv6 function. If not use IPv6 function, set this option to n. If disabling LWIP_IPV6 then some
other components (coap and asio) will no longer be available.
Default value:
• Yes (enabled)
CONFIG_LWIP_IPV6_AUTOCONFIG
Enable IPV6 stateless address autoconfiguration (SLAAC)
Found in: Component config > LWIP > CONFIG_LWIP_IPV6
Enabling this option allows the devices to IPV6 stateless address autoconfiguration (SLAAC).
See RFC 4862.
Default value:
• No (disabled)
CONFIG_LWIP_IPV6_NUM_ADDRESSES
Number of IPv6 addresses on each network interface
Found in: Component config > LWIP > CONFIG_LWIP_IPV6
The maximum number of IPv6 addresses on each interface. Any additional addresses will be discarded.
Default value:
• 3
CONFIG_LWIP_IPV6_FORWARD
Enable IPv6 forwarding between interfaces
Found in: Component config > LWIP > CONFIG_LWIP_IPV6
Forwarding IPv6 packets between interfaces is only required when acting as a router.
Default value:
• No (disabled)
CONFIG_LWIP_IPV6_RDNSS_MAX_DNS_SERVERS
Use IPv6 Router Advertisement Recursive DNS Server Option
Found in: Component config > LWIP
Use IPv6 Router Advertisement Recursive DNS Server Option (as per RFC 6106) to copy a defined
maximum number of DNS servers to the DNS module. Set this option to a number of desired DNS
servers advertised in the RA protocol. This feature is disabled when set to 0.
Default value:
• 0 if CONFIG_LWIP_IPV6_AUTOCONFIG
CONFIG_LWIP_IPV6_DHCP6
Enable DHCPv6 stateless address autoconfiguration
Found in: Component config > LWIP
Enable DHCPv6 for IPv6 stateless address autoconfiguration. Note that the dhcpv6 client has to be
started using dhcp6_enable_stateless(netif); Note that the stateful address autoconfiguration is not sup-
ported.
Default value:
• No (disabled) if CONFIG_LWIP_IPV6_AUTOCONFIG
CONFIG_LWIP_NETIF_STATUS_CALLBACK
Enable status callback for network interfaces
Found in: Component config > LWIP
Enable callbacks when the network interface is up/down and addresses are changed.
Default value:
• No (disabled)
CONFIG_LWIP_NETIF_LOOPBACK
Support per-interface loopback
Found in: Component config > LWIP
Enabling this option means that if a packet is sent with a destination address equal to the interface’s
own IP address, it will “loop back”and be received by this interface. Disabling this option disables
support of loopback interface in lwIP
Default value:
• Yes (enabled)
Contains:
• CONFIG_LWIP_LOOPBACK_MAX_PBUFS
CONFIG_LWIP_LOOPBACK_MAX_PBUFS
Max queued loopback packets per interface
Found in: Component config > LWIP > CONFIG_LWIP_NETIF_LOOPBACK
Configure the maximum number of packets which can be queued for loopback on a given interface.
Reducing this number may cause packets to be dropped, but will avoid filling memory with queued
packet data.
Range:
• from 0 to 16
Default value:
• 8
TCP Contains:
• CONFIG_LWIP_TCP_WND_DEFAULT
• CONFIG_LWIP_TCP_SND_BUF_DEFAULT
• CONFIG_LWIP_TCP_RECVMBOX_SIZE
• CONFIG_LWIP_TCP_RTO_TIME
• CONFIG_LWIP_MAX_ACTIVE_TCP
• CONFIG_LWIP_MAX_LISTENING_TCP
• CONFIG_LWIP_TCP_MAXRTX
• CONFIG_LWIP_TCP_SYNMAXRTX
• CONFIG_LWIP_TCP_MSL
• CONFIG_LWIP_TCP_MSS
• CONFIG_LWIP_TCP_OVERSIZE
• CONFIG_LWIP_TCP_QUEUE_OOSEQ
• CONFIG_LWIP_WND_SCALE
• CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION
• CONFIG_LWIP_TCP_TMR_INTERVAL
CONFIG_LWIP_MAX_ACTIVE_TCP
Maximum active TCP Connections
Found in: Component config > LWIP > TCP
The maximum number of simultaneously active TCP connections. The practical maximum limit is
determined by available heap memory at runtime.
Changing this value by itself does not substantially change the memory usage of LWIP, except for pre-
venting new TCP connections after the limit is reached.
Range:
• from 1 to 1024
Default value:
• 16
CONFIG_LWIP_MAX_LISTENING_TCP
Maximum listening TCP Connections
Found in: Component config > LWIP > TCP
The maximum number of simultaneously listening TCP connections. The practical maximum limit is
determined by available heap memory at runtime.
Changing this value by itself does not substantially change the memory usage of LWIP, except for pre-
venting new listening TCP connections after the limit is reached.
Range:
• from 1 to 1024
Default value:
• 16
CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION
TCP high speed retransmissions
Found in: Component config > LWIP > TCP
Speed up the TCP retransmission interval. If disabled, it is recommended to change the number of SYN
retransmissions to 6, and TCP initial rto time to 3000.
Default value:
• Yes (enabled)
CONFIG_LWIP_TCP_MAXRTX
Maximum number of retransmissions of data segments
Found in: Component config > LWIP > TCP
Set maximum number of retransmissions of data segments.
Range:
• from 3 to 12
Default value:
• 12
CONFIG_LWIP_TCP_SYNMAXRTX
Maximum number of retransmissions of SYN segments
Found in: Component config > LWIP > TCP
Set maximum number of retransmissions of SYN segments.
Range:
• from 3 to 12
Default value:
• 6
• 12
CONFIG_LWIP_TCP_MSS
Maximum Segment Size (MSS)
Found in: Component config > LWIP > TCP
Set maximum segment size for TCP transmission.
Can be set lower to save RAM, the default value 1460(ipv4)/1440(ipv6) will give best throughput. IPv4
TCP_MSS Range: 576 <= TCP_MSS <= 1460 IPv6 TCP_MSS Range: 1220<= TCP_mSS <= 1440
Range:
• from 536 to 1460
Default value:
• 1440
CONFIG_LWIP_TCP_TMR_INTERVAL
TCP timer interval(ms)
Found in: Component config > LWIP > TCP
Set TCP timer interval in milliseconds.
Can be used to speed connections on bad networks. A lower value will redeliver unacked packets faster.
Default value:
• 250
CONFIG_LWIP_TCP_MSL
Maximum segment lifetime (MSL)
Found in: Component config > LWIP > TCP
Set maximum segment lifetime in in milliseconds.
Default value:
• 60000
CONFIG_LWIP_TCP_SND_BUF_DEFAULT
Default send buffer size
Found in: Component config > LWIP > TCP
Set default send buffer size for new TCP sockets.
Per-socket send buffer size can be changed at runtime with lwip_setsockopt(s, TCP_SNDBUF, …).
This value must be at least 2x the MSS size, and the default is 4x the default MSS size.
Setting a smaller default SNDBUF size can save some RAM, but will decrease performance.
Range:
• from 2440 to 65535 if CONFIG_LWIP_WND_SCALE
• from 2440 to 1024000 if CONFIG_LWIP_WND_SCALE
Default value:
• 5744
CONFIG_LWIP_TCP_WND_DEFAULT
Default receive window size
Found in: Component config > LWIP > TCP
Set default TCP receive window size for new TCP sockets.
Per-socket receive window size can be changed at runtime with lwip_setsockopt(s, TCP_WINDOW, …
).
Setting a smaller default receive window size can save some RAM, but will significantly decrease per-
formance.
Range:
• from 2440 to 65535 if CONFIG_LWIP_WND_SCALE
• from 2440 to 1024000 if CONFIG_LWIP_WND_SCALE
Default value:
• 5744
CONFIG_LWIP_TCP_RECVMBOX_SIZE
Default TCP receive mail box size
Found in: Component config > LWIP > TCP
Set TCP receive mail box size. Generally bigger value means higher throughput but more
memory. The recommended value is: LWIP_TCP_WND_DEFAULT/TCP_MSS + 2, e.g. if
LWIP_TCP_WND_DEFAULT=14360, TCP_MSS=1436, then the recommended receive mail box
size is (14360/1436 + 2) = 12.
TCP receive mail box is a per socket mail box, when the application receives packets from TCP
socket, LWIP core firstly posts the packets to TCP receive mail box and the application then fetches
the packets from mail box. It means LWIP can caches maximum LWIP_TCP_RECCVMBOX_SIZE
packets for each TCP socket, so the maximum possible cached TCP packets for all TCP sockets is
LWIP_TCP_RECCVMBOX_SIZE multiples the maximum TCP socket number. In other words, the
bigger LWIP_TCP_RECVMBOX_SIZE means more memory. On the other hand, if the receiv mail
box is too small, the mail box may be full. If the mail box is full, the LWIP drops the packets. So
generally we need to make sure the TCP receive mail box is big enough to avoid packet drop between
LWIP core and application.
Range:
• from 6 to 64 if CONFIG_LWIP_WND_SCALE
• from 6 to 1024 if CONFIG_LWIP_WND_SCALE
Default value:
• 6
CONFIG_LWIP_TCP_QUEUE_OOSEQ
Queue incoming out-of-order segments
Found in: Component config > LWIP > TCP
Queue incoming out-of-order segments for later use.
Disable this option to save some RAM during TCP sessions, at the expense of increased retransmissions
if segments arrive out of order.
Default value:
• Yes (enabled)
CONFIG_LWIP_TCP_SACK_OUT
Support sending selective acknowledgements
Found in: Component config > LWIP > TCP > CONFIG_LWIP_TCP_QUEUE_OOSEQ
TCP will support sending selective acknowledgements (SACKs).
Default value:
• No (disabled)
CONFIG_LWIP_TCP_OVERSIZE
Pre-allocate transmit PBUF size
Found in: Component config > LWIP > TCP
Allows enabling “oversize”allocation of TCP transmission pbufs ahead of time, which can reduce the
length of pbuf chains used for transmission.
This will not make a difference to sockets where Nagle’s algorithm is disabled.
Default value of MSS is fine for most applications, 25% MSS may save some RAM when only trans-
mitting small amounts of data. Disabled will have worst performance and fragmentation characteristics,
but uses least RAM overall.
Available options:
• MSS (LWIP_TCP_OVERSIZE_MSS)
• 25% MSS (LWIP_TCP_OVERSIZE_QUARTER_MSS)
• Disabled (LWIP_TCP_OVERSIZE_DISABLE)
CONFIG_LWIP_WND_SCALE
Support TCP window scale
Found in: Component config > LWIP > TCP
Enable this feature to support TCP window scaling.
Default value:
• No (disabled) if CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP
CONFIG_LWIP_TCP_RCV_SCALE
Set TCP receiving window scaling factor
Found in: Component config > LWIP > TCP > CONFIG_LWIP_WND_SCALE
Enable this feature to support TCP window scaling.
Range:
• from 0 to 14 if CONFIG_LWIP_WND_SCALE
Default value:
• 0 if CONFIG_LWIP_WND_SCALE
CONFIG_LWIP_TCP_RTO_TIME
Default TCP rto time
Found in: Component config > LWIP > TCP
Set default TCP rto time for a reasonable initial rto. In bad network environment, recommend set value
of rto time to 1500.
Default value:
• 3000
• 1500
UDP Contains:
• CONFIG_LWIP_UDP_RECVMBOX_SIZE
• CONFIG_LWIP_MAX_UDP_PCBS
CONFIG_LWIP_MAX_UDP_PCBS
Maximum active UDP control blocks
Found in: Component config > LWIP > UDP
The maximum number of active UDP “connections”(ie UDP sockets sending/receiving data). The
practical maximum limit is determined by available heap memory at runtime.
Range:
• from 1 to 1024
Default value:
• 16
CONFIG_LWIP_UDP_RECVMBOX_SIZE
Default UDP receive mail box size
Found in: Component config > LWIP > UDP
Set UDP receive mail box size. The recommended value is 6.
UDP receive mail box is a per socket mail box, when the application receives packets from UDP
socket, LWIP core firstly posts the packets to UDP receive mail box and the application then fetches
the packets from mail box. It means LWIP can caches maximum UDP_RECCVMBOX_SIZE pack-
ets for each UDP socket, so the maximum possible cached UDP packets for all UDP sockets is
UDP_RECCVMBOX_SIZE multiples the maximum UDP socket number. In other words, the big-
ger UDP_RECVMBOX_SIZE means more memory. On the other hand, if the receiv mail box is too
small, the mail box may be full. If the mail box is full, the LWIP drops the packets. So generally we
need to make sure the UDP receive mail box is big enough to avoid packet drop between LWIP core
and application.
Range:
• from 6 to 64
Default value:
• 6
Checksums Contains:
• CONFIG_LWIP_CHECKSUM_CHECK_ICMP
• CONFIG_LWIP_CHECKSUM_CHECK_IP
• CONFIG_LWIP_CHECKSUM_CHECK_UDP
CONFIG_LWIP_CHECKSUM_CHECK_IP
Enable LWIP IP checksums
Found in: Component config > LWIP > Checksums
Enable checksum checking for received IP messages
Default value:
• No (disabled)
CONFIG_LWIP_CHECKSUM_CHECK_UDP
Enable LWIP UDP checksums
Found in: Component config > LWIP > Checksums
Enable checksum checking for received UDP messages
Default value:
• No (disabled)
CONFIG_LWIP_CHECKSUM_CHECK_ICMP
Enable LWIP ICMP checksums
Found in: Component config > LWIP > Checksums
Enable checksum checking for received ICMP messages
Default value:
• Yes (enabled)
CONFIG_LWIP_TCPIP_TASK_STACK_SIZE
TCP/IP Task Stack Size
Found in: Component config > LWIP
Configure TCP/IP task stack size, used by LWIP to process multi-threaded TCP/IP operations. Setting
this stack too small will result in stack overflow crashes.
Range:
• from 2048 to 65536
Default value:
• 3072
CONFIG_LWIP_TCPIP_TASK_AFFINITY
TCP/IP task affinity
Found in: Component config > LWIP
Allows setting LwIP tasks affinity, i.e. whether the task is pinned to CPU0, pinned to CPU1, or allowed
to run on any CPU. Currently this applies to “TCP/IP”task and “Ping”task.
Available options:
• No affinity (LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY)
• CPU0 (LWIP_TCPIP_TASK_AFFINITY_CPU0)
• CPU1 (LWIP_TCPIP_TASK_AFFINITY_CPU1)
CONFIG_LWIP_PPP_SUPPORT
Enable PPP support (new/experimental)
Found in: Component config > LWIP
Enable PPP stack. Now only PPP over serial is possible.
PPP over serial support is experimental and unsupported.
Default value:
• No (disabled)
Contains:
• CONFIG_LWIP_PPP_ENABLE_IPV6
CONFIG_LWIP_PPP_ENABLE_IPV6
Enable IPV6 support for PPP connections (IPV6CP)
Found in: Component config > LWIP > CONFIG_LWIP_PPP_SUPPORT
Enable IPV6 support in PPP for the local link between the DTE (processor) and DCE (modem). There
are some modems which do not support the IPV6 addressing in the local link. If they are requested for
IPV6CP negotiation, they may time out. This would in turn fail the configuration for the whole link. If
your modem is not responding correctly to PPP Phase Network, try to disable IPV6 support.
Default value:
• Yes (enabled) if CONFIG_LWIP_PPP_SUPPORT && CONFIG_LWIP_IPV6
CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE
Max number of IPv6 packets to queue during MAC resolution
Found in: Component config > LWIP
Config max number of IPv6 packets to queue during MAC resolution.
Range:
• from 3 to 20
Default value:
• 3
CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS
Max number of entries in IPv6 neighbor cache
Found in: Component config > LWIP
Config max number of entries in IPv6 neighbor cache
Range:
• from 3 to 10
Default value:
• 5
CONFIG_LWIP_PPP_NOTIFY_PHASE_SUPPORT
Enable Notify Phase Callback
Found in: Component config > LWIP
Enable to set a callback which is called on change of the internal PPP state machine.
Default value:
• No (disabled) if CONFIG_LWIP_PPP_SUPPORT
CONFIG_LWIP_PPP_PAP_SUPPORT
Enable PAP support
Found in: Component config > LWIP
Enable Password Authentication Protocol (PAP) support
Default value:
• No (disabled) if CONFIG_LWIP_PPP_SUPPORT
CONFIG_LWIP_PPP_CHAP_SUPPORT
Enable CHAP support
Found in: Component config > LWIP
Enable Challenge Handshake Authentication Protocol (CHAP) support
Default value:
• No (disabled) if CONFIG_LWIP_PPP_SUPPORT
CONFIG_LWIP_PPP_MSCHAP_SUPPORT
Enable MSCHAP support
Found in: Component config > LWIP
Enable Microsoft version of the Challenge-Handshake Authentication Protocol (MSCHAP) support
Default value:
• No (disabled) if CONFIG_LWIP_PPP_SUPPORT
CONFIG_LWIP_PPP_MPPE_SUPPORT
Enable MPPE support
Found in: Component config > LWIP
Enable Microsoft Point-to-Point Encryption (MPPE) support
Default value:
• No (disabled) if CONFIG_LWIP_PPP_SUPPORT
CONFIG_LWIP_ENABLE_LCP_ECHO
Enable LCP ECHO
Found in: Component config > LWIP
Enable LCP echo keepalive requests
Default value:
• No (disabled) if CONFIG_LWIP_PPP_SUPPORT
CONFIG_LWIP_LCP_ECHOINTERVAL
Echo interval (s)
Found in: Component config > LWIP > CONFIG_LWIP_ENABLE_LCP_ECHO
Interval in seconds between keepalive LCP echo requests, 0 to disable.
Range:
• from 0 to 1000000 if CONFIG_LWIP_ENABLE_LCP_ECHO
Default value:
• 3 if CONFIG_LWIP_ENABLE_LCP_ECHO
CONFIG_LWIP_LCP_MAXECHOFAILS
Maximum echo failures
Found in: Component config > LWIP > CONFIG_LWIP_ENABLE_LCP_ECHO
Number of consecutive unanswered echo requests before failure is indicated.
Range:
• from 0 to 100000 if CONFIG_LWIP_ENABLE_LCP_ECHO
Default value:
• 3 if CONFIG_LWIP_ENABLE_LCP_ECHO
CONFIG_LWIP_PPP_DEBUG_ON
Enable PPP debug log output
Found in: Component config > LWIP
Enable PPP debug log output
Default value:
• No (disabled) if CONFIG_LWIP_PPP_SUPPORT
CONFIG_LWIP_SLIP_SUPPORT
Enable SLIP support (new/experimental)
Found in: Component config > LWIP
Enable SLIP stack. Now only SLIP over serial is possible.
SLIP over serial support is experimental and unsupported.
Default value:
• No (disabled)
Contains:
• CONFIG_LWIP_SLIP_DEBUG_ON
CONFIG_LWIP_SLIP_DEBUG_ON
Enable SLIP debug log output
Found in: Component config > LWIP > CONFIG_LWIP_SLIP_SUPPORT
Enable SLIP debug log output
Default value:
• No (disabled) if CONFIG_LWIP_SLIP_SUPPORT
ICMP Contains:
• CONFIG_LWIP_ICMP
• CONFIG_LWIP_BROADCAST_PING
• CONFIG_LWIP_MULTICAST_PING
CONFIG_LWIP_ICMP
ICMP: Enable ICMP
Found in: Component config > LWIP > ICMP
Enable ICMP module for check network stability
Default value:
• Yes (enabled)
CONFIG_LWIP_MULTICAST_PING
Respond to multicast pings
Found in: Component config > LWIP > ICMP
Default value:
• No (disabled)
CONFIG_LWIP_BROADCAST_PING
Respond to broadcast pings
Found in: Component config > LWIP > ICMP
Default value:
• No (disabled)
CONFIG_LWIP_MAX_RAW_PCBS
Maximum LWIP RAW PCBs
Found in: Component config > LWIP > LWIP RAW API
The maximum number of simultaneously active LWIP RAW protocol control blocks. The practical
maximum limit is determined by available heap memory at runtime.
Range:
• from 1 to 1024
Default value:
• 16
SNTP Contains:
• CONFIG_LWIP_SNTP_MAX_SERVERS
• CONFIG_LWIP_SNTP_UPDATE_DELAY
• CONFIG_LWIP_DHCP_GET_NTP_SRV
CONFIG_LWIP_SNTP_MAX_SERVERS
Maximum number of NTP servers
Found in: Component config > LWIP > SNTP
Set maximum number of NTP servers used by LwIP SNTP module. First argument of
sntp_setserver/sntp_setservername functions is limited to this value.
Range:
• from 1 to 16
Default value:
• 1
CONFIG_LWIP_DHCP_GET_NTP_SRV
Request NTP servers from DHCP
Found in: Component config > LWIP > SNTP
If enabled, LWIP will add‘NTP’to Parameter-Request Option sent via DHCP-request. DHCP server
might reply with an NTP server address in option 42. SNTP callback for such replies should be set
accordingly (see sntp_servermode_dhcp() func.)
Default value:
• No (disabled)
CONFIG_LWIP_DHCP_MAX_NTP_SERVERS
Maximum number of NTP servers aquired via DHCP
Found in: Component config > LWIP > SNTP > CONFIG_LWIP_DHCP_GET_NTP_SRV
Set maximum number of NTP servers aquired via DHCP-offer. Should be less or equal to “Maximum
number of NTP servers”, any extra servers would be just ignored.
Range:
• from 1 to 16 if CONFIG_LWIP_DHCP_GET_NTP_SRV
Default value:
• 1 if CONFIG_LWIP_DHCP_GET_NTP_SRV
CONFIG_LWIP_SNTP_UPDATE_DELAY
Request interval to update time (ms)
Found in: Component config > LWIP > SNTP
This option allows you to set the time update period via SNTP. Default is 1 hour. Must not be below 15
seconds by specification. (SNTPv4 RFC 4330 enforces a minimum update time of 15 seconds).
Range:
• from 15000 to 4294967295
Default value:
• 3600000
CONFIG_LWIP_BRIDGEIF_MAX_PORTS
Maximum number of bridge ports
Found in: Component config > LWIP
Set maximum number of ports a bridge can consists of.
Range:
• from 1 to 63
Default value:
• 7
CONFIG_LWIP_ESP_LWIP_ASSERT
Enable LWIP ASSERT checks
Found in: Component config > LWIP
Enable this option keeps LWIP assertion checks enabled. It is recommended to keep this option enabled.
If asserts are disabled for the entire project, they are also disabled for LWIP and this option is ignored.
Default value:
• Yes (enabled) if COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE
Hooks Contains:
• CONFIG_LWIP_HOOK_ND6_GET_GW
• CONFIG_LWIP_HOOK_IP6_INPUT
• CONFIG_LWIP_HOOK_IP6_ROUTE
• CONFIG_LWIP_HOOK_NETCONN_EXTERNAL_RESOLVE
• CONFIG_LWIP_HOOK_TCP_ISN
CONFIG_LWIP_HOOK_TCP_ISN
TCP ISN Hook
Found in: Component config > LWIP > Hooks
Enables to define a TCP ISN hook to randomize initial sequence number in TCP connection. The default
TCP ISN algorithm used in IDF (standardized in RFC 6528) produces ISN by combining an MD5 of
the new TCP id and a stable secret with the current time. This is because the lwIP implementation
(tcp_next_iss) is not very strong, as it does not take into consideration any platform specific entropy
source.
Set to LWIP_HOOK_TCP_ISN_CUSTOM to provide custom implementation. Set to
LWIP_HOOK_TCP_ISN_NONE to use lwIP implementation.
Available options:
• No hook declared (LWIP_HOOK_TCP_ISN_NONE)
• Default implementation (LWIP_HOOK_TCP_ISN_DEFAULT)
• Custom implementation (LWIP_HOOK_TCP_ISN_CUSTOM)
CONFIG_LWIP_HOOK_IP6_ROUTE
IPv6 route Hook
Found in: Component config > LWIP > Hooks
Enables custom IPv6 route hook. Setting this to “default”provides weak implementation stub that
could be overwritten in application code. Setting this to “custom”provides hook’s declaration only
and expects the application to implement it.
Available options:
• No hook declared (LWIP_HOOK_IP6_ROUTE_NONE)
• Default (weak) implementation (LWIP_HOOK_IP6_ROUTE_DEFAULT)
• Custom implementation (LWIP_HOOK_IP6_ROUTE_CUSTOM)
CONFIG_LWIP_HOOK_ND6_GET_GW
IPv6 get gateway Hook
Found in: Component config > LWIP > Hooks
Enables custom IPv6 route hook. Setting this to “default”provides weak implementation stub that
could be overwritten in application code. Setting this to “custom”provides hook’s declaration only
and expects the application to implement it.
Available options:
• No hook declared (LWIP_HOOK_ND6_GET_GW_NONE)
• Default (weak) implementation (LWIP_HOOK_ND6_GET_GW_DEFAULT)
• Custom implementation (LWIP_HOOK_ND6_GET_GW_CUSTOM)
CONFIG_LWIP_HOOK_NETCONN_EXTERNAL_RESOLVE
Netconn external resolve Hook
Found in: Component config > LWIP > Hooks
Enables custom DNS resolve hook. Setting this to “default”provides weak implementation stub that
could be overwritten in application code. Setting this to “custom”provides hook’s declaration only
and expects the application to implement it.
Available options:
• No hook declared (LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE)
• Default (weak) implementation (LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT)
• Custom implementation (LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM)
CONFIG_LWIP_HOOK_IP6_INPUT
IPv6 packet input
Found in: Component config > LWIP > Hooks
Enables custom IPv6 packet input. Setting this to “default”provides weak implementation stub that
could be overwritten in application code. Setting this to “custom”provides hook’s declaration only
and expects the application to implement it.
Available options:
• No hook declared (LWIP_HOOK_IP6_INPUT_NONE)
• Default (weak) implementation (LWIP_HOOK_IP6_INPUT_DEFAULT)
• Custom implementation (LWIP_HOOK_IP6_INPUT_CUSTOM)
CONFIG_LWIP_DEBUG
Enable LWIP Debug
Found in: Component config > LWIP
Enabling this option allows different kinds of lwIP debug output.
All lwIP debug features increase the size of the final binary.
Default value:
• No (disabled)
Contains:
• CONFIG_LWIP_API_LIB_DEBUG
• CONFIG_LWIP_BRIDGEIF_FDB_DEBUG
• CONFIG_LWIP_BRIDGEIF_FW_DEBUG
• CONFIG_LWIP_BRIDGEIF_DEBUG
• CONFIG_LWIP_DHCP_DEBUG
• CONFIG_LWIP_DHCP_STATE_DEBUG
• CONFIG_LWIP_DNS_DEBUG
• CONFIG_LWIP_ETHARP_DEBUG
• CONFIG_LWIP_ICMP_DEBUG
• CONFIG_LWIP_ICMP6_DEBUG
• CONFIG_LWIP_IP_DEBUG
• CONFIG_LWIP_IP6_DEBUG
• CONFIG_LWIP_NETIF_DEBUG
• CONFIG_LWIP_PBUF_DEBUG
• CONFIG_LWIP_SNTP_DEBUG
• CONFIG_LWIP_SOCKETS_DEBUG
• CONFIG_LWIP_TCP_DEBUG
• CONFIG_LWIP_DEBUG_ESP_LOG
CONFIG_LWIP_DEBUG_ESP_LOG
Route LWIP debugs through ESP_LOG interface
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Enabling this option routes all enabled LWIP debugs through ESP_LOGD.
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_NETIF_DEBUG
Enable netif debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_PBUF_DEBUG
Enable pbuf debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_ETHARP_DEBUG
Enable etharp debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_API_LIB_DEBUG
Enable api lib debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_SOCKETS_DEBUG
Enable socket debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_IP_DEBUG
Enable IP debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_ICMP_DEBUG
Enable ICMP debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG && CONFIG_LWIP_ICMP
CONFIG_LWIP_DHCP_STATE_DEBUG
Enable DHCP state tracking
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_DHCP_DEBUG
Enable DHCP debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_IP6_DEBUG
Enable IP6 debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_ICMP6_DEBUG
Enable ICMP6 debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_TCP_DEBUG
Enable TCP debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_SNTP_DEBUG
Enable SNTP debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_DNS_DEBUG
Enable DNS debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_BRIDGEIF_DEBUG
Enable bridge generic debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_BRIDGEIF_FDB_DEBUG
Enable bridge FDB debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
CONFIG_LWIP_BRIDGEIF_FW_DEBUG
Enable bridge forwarding debug messages
Found in: Component config > LWIP > CONFIG_LWIP_DEBUG
Default value:
• No (disabled) if CONFIG_LWIP_DEBUG
mbedTLS Contains:
• CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN
• Certificate Bundle
• Certificates
• CONFIG_MBEDTLS_CHACHA20_C
• CONFIG_MBEDTLS_DHM_C
• CONFIG_MBEDTLS_ECP_C
• CONFIG_MBEDTLS_ECDH_C
• CONFIG_MBEDTLS_ECJPAKE_C
• CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED
• CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED
• CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED
• CONFIG_MBEDTLS_CMAC_C
• CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED
• CONFIG_MBEDTLS_ECDSA_DETERMINISTIC
• CONFIG_MBEDTLS_HARDWARE_AES
• CONFIG_MBEDTLS_HARDWARE_ECC
• CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN
• CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY
• CONFIG_MBEDTLS_HARDWARE_MPI
• CONFIG_MBEDTLS_HARDWARE_SHA
• CONFIG_MBEDTLS_DEBUG
• CONFIG_MBEDTLS_ECP_RESTARTABLE
• CONFIG_MBEDTLS_HAVE_TIME
• CONFIG_MBEDTLS_RIPEMD160_C
• CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED
• CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED
• CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED
• CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED
• CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED
• CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED
• CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED
• CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED
• CONFIG_MBEDTLS_SHA512_C
• CONFIG_MBEDTLS_THREADING_C
• CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI
• CONFIG_MBEDTLS_HKDF_C
• mbedTLS v3.x related
• CONFIG_MBEDTLS_MEM_ALLOC_MODE
• CONFIG_MBEDTLS_ECP_NIST_OPTIM
• CONFIG_MBEDTLS_POLY1305_C
• CONFIG_MBEDTLS_SECURITY_RISKS
• CONFIG_MBEDTLS_SSL_ALPN
• CONFIG_MBEDTLS_SSL_PROTO_DTLS
• CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1
• CONFIG_MBEDTLS_SSL_PROTO_TLS1_2
• CONFIG_MBEDTLS_SSL_RENEGOTIATION
• Symmetric Ciphers
• TLS Key Exchange Methods
• CONFIG_MBEDTLS_SSL_MAX_CONTENT_LEN
• CONFIG_MBEDTLS_TLS_MODE
• CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS
• CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS
• CONFIG_MBEDTLS_ROM_MD5
• CONFIG_MBEDTLS_DYNAMIC_BUFFER
CONFIG_MBEDTLS_MEM_ALLOC_MODE
Memory allocation strategy
Found in: Component config > mbedTLS
Allocation strategy for mbedTLS, essentially provides ability to allocate all required dynamic allocations
from,
• Internal DRAM memory only
• External SPIRAM memory only
• Either internal or external memory based on default malloc() behavior in ESP-IDF
• Custom allocation mode, by overwriting calloc()/free() using mbedtls_platform_set_calloc_free()
function
• Internal IRAM memory wherever applicable else internal DRAM
Recommended mode here is always internal (*), since that is most preferred from security perspective.
But if application requirement does not allow sufficient free internal memory then alternate mode can
be selected.
(*) In case of ESP32-S2/ESP32-S3, hardware allows encryption of external SPIRAM contents provided
hardware flash encryption feature is enabled. In that case, using external SPIRAM allocation strategy is
also safe choice from security perspective.
Available options:
• Internal memory (MBEDTLS_INTERNAL_MEM_ALLOC)
• External SPIRAM (MBEDTLS_EXTERNAL_MEM_ALLOC)
• Default alloc mode (MBEDTLS_DEFAULT_MEM_ALLOC)
• Custom alloc mode (MBEDTLS_CUSTOM_MEM_ALLOC)
CONFIG_MBEDTLS_SSL_MAX_CONTENT_LEN
TLS maximum message content length
Found in: Component config > mbedTLS
Maximum TLS message length (in bytes) supported by mbedTLS.
16384 is the default and this value is required to comply fully with TLS standards.
However you can set a lower value in order to save RAM. This is safe if the other end of the connection
supports Maximum Fragment Length Negotiation Extension (max_fragment_length, see RFC6066) or
you know for certain that it will never send a message longer than a certain number of bytes.
If the value is set too low, symptoms are a failed TLS handshake or a return value of
MBEDTLS_ERR_SSL_INVALID_RECORD (-0x7200).
Range:
• from 512 to 16384
Default value:
• 16384
CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN
Asymmetric in/out fragment length
Found in: Component config > mbedTLS
If enabled, this option allows customizing TLS in/out fragment length in asymmetric way. Please note
that enabling this with default values saves 12KB of dynamic memory per TLS connection.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN
TLS maximum incoming fragment length
Found in: Component config > mbedTLS > CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN
This defines maximum incoming fragment length, overriding default maximum content length
(MBEDTLS_SSL_MAX_CONTENT_LEN).
Range:
• from 512 to 16384
Default value:
• 16384
CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN
TLS maximum outgoing fragment length
Found in: Component config > mbedTLS > CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN
This defines maximum outgoing fragment length, overriding default maximum content length
(MBEDTLS_SSL_MAX_CONTENT_LEN).
Range:
• from 512 to 16384
Default value:
• 4096
CONFIG_MBEDTLS_DYNAMIC_BUFFER
Using dynamic TX/RX buffer
Found in: Component config > mbedTLS
Using dynamic TX/RX buffer. After enabling this option, mbedTLS will allocate TX buffer when need
to send data and then free it if all data is sent, allocate RX buffer when need to receive data and then
free it when all data is used or read by upper layer.
By default, when SSL is initialized, mbedTLS also allocate TX and RX buffer with the default value
of “MBEDTLS_SSL_OUT_CONTENT_LEN”or “MBEDTLS_SSL_IN_CONTENT_LEN”, so
to save more heap, users can set the options to be an appropriate value.
Default value:
• No (disabled) if CONFIG_MBEDTLS_SSL_PROTO_DTLS && CON-
FIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH
CONFIG_MBEDTLS_DYNAMIC_FREE_CONFIG_DATA
Free private key and DHM data after its usage
Found in: Component config > mbedTLS > CONFIG_MBEDTLS_DYNAMIC_BUFFER
Free private key and DHM data after its usage in handshake process.
The option will decrease heap cost when handshake, but also lead to problem:
Becasue all certificate, private key and DHM data are freed so users should register certificate and private
key to ssl config object again.
Default value:
• No (disabled) if CONFIG_MBEDTLS_DYNAMIC_BUFFER
CONFIG_MBEDTLS_DYNAMIC_FREE_CA_CERT
Free SSL CA certificate after its usage
Found in: Component config > mbedTLS > CONFIG_MBEDTLS_DYNAMIC_BUFFER > CON-
FIG_MBEDTLS_DYNAMIC_FREE_CONFIG_DATA
Free CA certificate after its usage in the handshake process. This option will decrease the heap footprint
for the TLS handshake, but may lead to a problem: If the respective ssl object needs to perform the TLS
handshake again, the CA certificate should once again be registered to the ssl object.
Default value:
• Yes (enabled) if CONFIG_MBEDTLS_DYNAMIC_FREE_CONFIG_DATA
CONFIG_MBEDTLS_DEBUG
Enable mbedTLS debugging
Found in: Component config > mbedTLS
Enable mbedTLS debugging functions at compile time.
If this option is enabled, you can include “mbedtls/esp_debug.h”and call
mbedtls_esp_enable_debug_log() at runtime in order to enable mbedTLS debug output via the
ESP log mechanism.
Default value:
• No (disabled)
CONFIG_MBEDTLS_DEBUG_LEVEL
Set mbedTLS debugging level
Found in: Component config > mbedTLS > CONFIG_MBEDTLS_DEBUG
Set mbedTLS debugging level
Available options:
• Warning (MBEDTLS_DEBUG_LEVEL_WARN)
• Info (MBEDTLS_DEBUG_LEVEL_INFO)
• Debug (MBEDTLS_DEBUG_LEVEL_DEBUG)
• Verbose (MBEDTLS_DEBUG_LEVEL_VERBOSE)
CONFIG_MBEDTLS_SSL_PROTO_TLS1_3
Support TLS 1.3 protocol
Found in: Component config > mbedTLS > mbedTLS v3.x related
Default value:
• No (disabled) if CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE && CON-
FIG_MBEDTLS_DYNAMIC_BUFFER
CONFIG_MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE
Enable TLS 1.3 middlebox compatibility mode
Found in: Component config > mbedTLS > mbedTLS v3.x related > CON-
FIG_MBEDTLS_SSL_PROTO_TLS1_3
Default value:
• Yes (enabled) if CONFIG_MBEDTLS_SSL_PROTO_TLS1_3
CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH
Variable SSL buffer length
Found in: Component config > mbedTLS > mbedTLS v3.x related
This enables the SSL buffer to be resized automatically based on the negotiated maximum fragment
length in each direction.
Default value:
• No (disabled)
CONFIG_MBEDTLS_ECDH_LEGACY_CONTEXT
Use a backward compatible ECDH context (Experimental)
Found in: Component config > mbedTLS > mbedTLS v3.x related
Use the legacy ECDH context format. Define this option only if you enable
MBEDTLS_ECP_RESTARTABLE or if you want to access ECDH context fields directly.
Default value:
• No (disabled) if CONFIG_MBEDTLS_ECDH_C && CON-
FIG_MBEDTLS_ECP_RESTARTABLE
CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK
Enable trusted certificate callbacks
Found in: Component config > mbedTLS > mbedTLS v3.x related
Enables users to configure the set of trusted certificates through a callback instead of a linked list.
See mbedTLS documentation for required API and more details.
Default value:
• No (disabled)
CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION
Enable serialization of the TLS context structures
Found in: Component config > mbedTLS > mbedTLS v3.x related
Enable serialization of the TLS context structures This is a local optimization in handling a single, po-
tentially long-lived connection.
See mbedTLS documentation for required API and more details. Disabling this option will save some
code size.
Default value:
• No (disabled)
CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE
Keep peer certificate after handshake completion
Found in: Component config > mbedTLS > mbedTLS v3.x related
Keep the peer’s certificate after completion of the handshake. Disabling this option will save about
4kB of heap and some code size.
See mbedTLS documentation for required API and more details.
Default value:
• Yes (enabled) if MBEDTLS_DYNAMIC_FREE_PEER_CERT
CONFIG_MBEDTLS_SSL_DTLS_CONNECTION_ID
Support for the DTLS Connection ID extension
Found in: Component config > mbedTLS > mbedTLS v3.x related > DTLS-based configurations
Enable support for the DTLS Connection ID extension which allows to identify DTLS connections across
changes in the underlying transport. The Connection ID extension is still in draft state. Refer: version
draft-ietf-tls-dtls-connection-id-05
Default value:
• No (disabled) if CONFIG_MBEDTLS_SSL_PROTO_DTLS
CONFIG_MBEDTLS_SSL_CID_IN_LEN_MAX
Maximum length of CIDs used for incoming DTLS messages
Found in: Component config > mbedTLS > mbedTLS v3.x related > DTLS-based configurations > CON-
FIG_MBEDTLS_SSL_DTLS_CONNECTION_ID
Maximum length of CIDs used for incoming DTLS messages
Range:
• from 0 to 32 if CONFIG_MBEDTLS_SSL_DTLS_CONNECTION_ID
Default value:
• 32 if CONFIG_MBEDTLS_SSL_DTLS_CONNECTION_ID
CONFIG_MBEDTLS_SSL_CID_OUT_LEN_MAX
Maximum length of CIDs used for outgoing DTLS messages
Found in: Component config > mbedTLS > mbedTLS v3.x related > DTLS-based configurations > CON-
FIG_MBEDTLS_SSL_DTLS_CONNECTION_ID
Maximum length of CIDs used for outgoing DTLS messages
Range:
• from 0 to 32 if CONFIG_MBEDTLS_SSL_DTLS_CONNECTION_ID
Default value:
• 32 if CONFIG_MBEDTLS_SSL_DTLS_CONNECTION_ID
CONFIG_MBEDTLS_SSL_CID_PADDING_GRANULARITY
Record plaintext padding (for DTLS 1.2)
Found in: Component config > mbedTLS > mbedTLS v3.x related > DTLS-based configurations > CON-
FIG_MBEDTLS_SSL_DTLS_CONNECTION_ID
Controls the use of record plaintext padding when using the Connection ID extension in DTLS 1.2.
The padding will always be chosen so that the length of the padded plaintext is a multiple of the value
of this option.
Notes: A value of 1 means that no padding will be used for outgoing records. On systems lacking
division instructions, a power of two should be preferred.
Range:
• from 0 to 32 if CONFIG_MBEDTLS_SSL_DTLS_CONNECTION_ID
Default value:
• 16 if CONFIG_MBEDTLS_SSL_DTLS_CONNECTION_ID
CONFIG_MBEDTLS_SSL_DTLS_SRTP
Enable support for negotiation of DTLS-SRTP (RFC 5764)
Found in: Component config > mbedTLS > mbedTLS v3.x related > DTLS-based configurations
Enable support for negotiation of DTLS-SRTP (RFC 5764) through the use_srtp extension.
See mbedTLS documentation for required API and more details. Disabling this option will save some
code size.
Default value:
• No (disabled) if CONFIG_MBEDTLS_SSL_PROTO_DTLS
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
Enable trusted root certificate bundle
Found in: Component config > mbedTLS > Certificate Bundle
Enable support for large number of default root certificates
When enabled this option allows user to store default as well as customer specific root certificates in
compressed format rather than storing full certificate. For the root certificates the public key and the
subject name will be stored.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_DEFAULT_CERTIFICATE_BUNDLE
Default certificate bundle options
Found in: Component config > mbedTLS > Certificate Bundle > CON-
FIG_MBEDTLS_CERTIFICATE_BUNDLE
Available options:
• Use the full default certificate bundle (MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL)
• Use only the most common certificates from the default bundles
(MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN)
Use only the most common certificates from the default bundles, reducing the size with 50%,
while still having around 99% coverage.
• Do not use the default certificate bundle (MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE)
CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE
Add custom certificates to the default bundle
Found in: Component config > mbedTLS > Certificate Bundle > CON-
FIG_MBEDTLS_CERTIFICATE_BUNDLE
Default value:
• No (disabled)
CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE_PATH
Custom certificate bundle path
Found in: Component config > mbedTLS > Certificate Bundle > CON-
FIG_MBEDTLS_CERTIFICATE_BUNDLE > CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE
Name of the custom certificate directory or file. This path is evaluated relative to the project root direc-
tory.
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS
Maximum no of certificates allowed in certificate bundle
Found in: Component config > mbedTLS > Certificate Bundle > CON-
FIG_MBEDTLS_CERTIFICATE_BUNDLE
Default value:
• 200
CONFIG_MBEDTLS_ECP_RESTARTABLE
Enable mbedTLS ecp restartable
Found in: Component config > mbedTLS
Enable “non-blocking”ECC operations that can return early and be resumed.
Default value:
• No (disabled)
CONFIG_MBEDTLS_CMAC_C
Enable CMAC mode for block ciphers
Found in: Component config > mbedTLS
Enable the CMAC (Cipher-based Message Authentication Code) mode for block ciphers.
Default value:
• No (disabled)
CONFIG_MBEDTLS_HARDWARE_AES
Enable hardware AES acceleration
Found in: Component config > mbedTLS
Enable hardware accelerated AES encryption & decryption.
Note that if the ESP32 CPU is running at 240MHz, hardware AES does not offer any speed boost over
software AES.
Default value:
• Yes (enabled) if SPIRAM_CACHE_WORKAROUND_STRATEGY_DUPLDST
CONFIG_MBEDTLS_HARDWARE_GCM
Enable partially hardware accelerated GCM
Found in: Component config > mbedTLS > CONFIG_MBEDTLS_HARDWARE_AES
Enable partially hardware accelerated GCM. GHASH calculation is still done in software.
If MBEDTLS_HARDWARE_GCM is disabled and MBEDTLS_HARDWARE_AES is enabled then
mbedTLS will still use the hardware accelerated AES block operation, but on a single block at a time.
Default value:
• Yes (enabled) if SOC_AES_SUPPORT_GCM && CONFIG_MBEDTLS_HARDWARE_AES
CONFIG_MBEDTLS_HARDWARE_MPI
Enable hardware MPI (bignum) acceleration
Found in: Component config > mbedTLS
Enable hardware accelerated multiple precision integer operations.
Hardware accelerated multiplication, modulo multiplication, and modular exponentiation for up to
SOC_RSA_MAX_BIT_LEN bit results.
These operations are used by RSA.
Default value:
• Yes (enabled) if SPIRAM_CACHE_WORKAROUND_STRATEGY_DUPLDST
CONFIG_MBEDTLS_HARDWARE_SHA
Enable hardware SHA acceleration
Found in: Component config > mbedTLS
Enable hardware accelerated SHA1, SHA256, SHA384 & SHA512 in mbedTLS.
Due to a hardware limitation, on the ESP32 hardware acceleration is only guaranteed if SHA digests
are calculated one at a time. If more than one SHA digest is calculated at the same time, one will be
calculated fully in hardware and the rest will be calculated (at least partially calculated) in software. This
happens automatically.
SHA hardware acceleration is faster than software in some situations but slower in others. You should
benchmark to find the best setting for you.
Default value:
• Yes (enabled) if SPIRAM_CACHE_WORKAROUND_STRATEGY_DUPLDST
CONFIG_MBEDTLS_HARDWARE_ECC
Enable hardware ECC acceleration
Found in: Component config > mbedTLS
Enable hardware accelerated ECC point multiplication and point verification for points on curve
SECP192R1 and SECP256R1 in mbedTLS
Default value:
• Yes (enabled) if SOC_ECC_SUPPORTED
CONFIG_MBEDTLS_ECC_OTHER_CURVES_SOFT_FALLBACK
Fallback to software implementation for curves not supported in hardware
Found in: Component config > mbedTLS > CONFIG_MBEDTLS_HARDWARE_ECC
Fallback to software implementation of ECC point multiplication and point verification for curves not
supported in hardware.
Default value:
• Yes (enabled) if CONFIG_MBEDTLS_HARDWARE_ECC
CONFIG_MBEDTLS_ROM_MD5
Use MD5 implementation in ROM
Found in: Component config > mbedTLS
Use ROM MD5 in mbedTLS.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN
Enable hardware ECDSA sign acceleration when using ATECC608A
Found in: Component config > mbedTLS
This option enables hardware acceleration for ECDSA sign function, only when using ATECC608A
cryptoauth chip (integrated with ESP32-WROOM-32SE)
Default value:
• No (disabled)
CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY
Enable hardware ECDSA verify acceleration when using ATECC608A
Found in: Component config > mbedTLS
This option enables hardware acceleration for ECDSA sign function, only when using ATECC608A
cryptoauth chip (integrated with ESP32-WROOM-32SE)
Default value:
• No (disabled)
CONFIG_MBEDTLS_HAVE_TIME
Enable mbedtls time support
Found in: Component config > mbedTLS
Enable use of time.h functions (time() and gmtime()) by mbedTLS.
This option doesn’t require the system time to be correct, but enables functionality that requires relative
timekeeping - for example periodic expiry of TLS session tickets or session cache entries.
Disabling this option will save some firmware size, particularly if the rest of the firmware doesn’t call
any standard timekeeeping functions.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_PLATFORM_TIME_ALT
Enable mbedtls time support: platform-specific
Found in: Component config > mbedTLS > CONFIG_MBEDTLS_HAVE_TIME
Enabling this config will provide users with a function “mbedtls_platform_set_time()”that allows to
set an alternative time function pointer.
Default value:
• No (disabled)
CONFIG_MBEDTLS_HAVE_TIME_DATE
Enable mbedtls certificate expiry check
Found in: Component config > mbedTLS > CONFIG_MBEDTLS_HAVE_TIME
Enables X.509 certificate expiry checks in mbedTLS.
If this option is disabled (default) then X.509 certificate “valid from”and “valid to”timestamp fields
are ignored.
If this option is enabled, these fields are compared with the current system date and time. The time
is retrieved using the standard time() and gmtime() functions. If the certificate is not valid for the
current system time then verification will fail with code MBEDTLS_X509_BADCERT_FUTURE or
MBEDTLS_X509_BADCERT_EXPIRED.
Enabling this option requires adding functionality in the firmware to set the system clock to a valid
timestamp before using TLS. The recommended way to do this is via ESP-IDF’s SNTP functionality,
but any method can be used.
In the case where only a small number of certificates are trusted by the device, please carefully consider
the tradeoffs of enabling this option. There may be undesired consequences, for example if all trusted
certificates expire while the device is offline and a TLS connection is required to update. Or if an issue
with the SNTP server means that the system time is invalid for an extended period after a reset.
Default value:
• No (disabled)
CONFIG_MBEDTLS_ECDSA_DETERMINISTIC
Enable deterministic ECDSA
Found in: Component config > mbedTLS
Standard ECDSA is“fragile”in the sense that lack of entropy when signing may result in a compromise
of the long-term signing key.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_SHA512_C
Enable the SHA-384 and SHA-512 cryptographic hash algorithms
Found in: Component config > mbedTLS
Enable MBEDTLS_SHA512_C adds support for SHA-384 and SHA-512.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_TLS_MODE
TLS Protocol Role
Found in: Component config > mbedTLS
mbedTLS can be compiled with protocol support for the TLS server, TLS client, or both server and
client.
Reducing the number of TLS roles supported saves code size.
Available options:
• Server & Client (MBEDTLS_TLS_SERVER_AND_CLIENT)
• Server (MBEDTLS_TLS_SERVER_ONLY)
• Client (MBEDTLS_TLS_CLIENT_ONLY)
• None (MBEDTLS_TLS_DISABLED)
CONFIG_MBEDTLS_PSK_MODES
Enable pre-shared-key ciphersuites
Found in: Component config > mbedTLS > TLS Key Exchange Methods
Enable to show configuration for different types of pre-shared-key TLS authentatication methods.
Leaving this options disabled will save code size if they are not used.
Default value:
• No (disabled)
CONFIG_MBEDTLS_KEY_EXCHANGE_PSK
Enable PSK based ciphersuite modes
Found in: Component config > mbedTLS > TLS Key Exchange Methods > CON-
FIG_MBEDTLS_PSK_MODES
Enable to support symmetric key PSK (pre-shared-key) TLS key exchange modes.
Default value:
• No (disabled) if CONFIG_MBEDTLS_PSK_MODES
CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_PSK
Enable DHE-PSK based ciphersuite modes
Found in: Component config > mbedTLS > TLS Key Exchange Methods > CON-
FIG_MBEDTLS_PSK_MODES
Enable to support Diffie-Hellman PSK (pre-shared-key) TLS authentication modes.
Default value:
• Yes (enabled) if CONFIG_MBEDTLS_PSK_MODES && CONFIG_MBEDTLS_DHM_C
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_PSK
Enable ECDHE-PSK based ciphersuite modes
Found in: Component config > mbedTLS > TLS Key Exchange Methods > CON-
FIG_MBEDTLS_PSK_MODES
Enable to support Elliptic-Curve-Diffie-Hellman PSK (pre-shared-key) TLS authentication modes.
Default value:
• Yes (enabled) if CONFIG_MBEDTLS_PSK_MODES && CONFIG_MBEDTLS_ECDH_C
CONFIG_MBEDTLS_KEY_EXCHANGE_RSA_PSK
Enable RSA-PSK based ciphersuite modes
Found in: Component config > mbedTLS > TLS Key Exchange Methods > CON-
FIG_MBEDTLS_PSK_MODES
Enable to support RSA PSK (pre-shared-key) TLS authentication modes.
Default value:
• Yes (enabled) if CONFIG_MBEDTLS_PSK_MODES
CONFIG_MBEDTLS_KEY_EXCHANGE_RSA
Enable RSA-only based ciphersuite modes
Found in: Component config > mbedTLS > TLS Key Exchange Methods
Enable to support ciphersuites with prefix TLS-RSA-WITH-
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_RSA
Enable DHE-RSA based ciphersuite modes
Found in: Component config > mbedTLS > TLS Key Exchange Methods
Enable to support ciphersuites with prefix TLS-DHE-RSA-WITH-
Default value:
• Yes (enabled) if CONFIG_MBEDTLS_DHM_C
CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE
Support Elliptic Curve based ciphersuites
Found in: Component config > mbedTLS > TLS Key Exchange Methods
Enable to show Elliptic Curve based ciphersuite mode options.
Disabling all Elliptic Curve ciphersuites saves code size and can give slightly faster TLS handshakes,
provided the server supports RSA-only ciphersuite modes.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA
Enable ECDHE-RSA based ciphersuite modes
Found in: Component config > mbedTLS > TLS Key Exchange Methods > CON-
FIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE
Enable to support ciphersuites with prefix TLS-ECDHE-RSA-WITH-
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA
Enable ECDHE-ECDSA based ciphersuite modes
Found in: Component config > mbedTLS > TLS Key Exchange Methods > CON-
FIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE
Enable to support ciphersuites with prefix TLS-ECDHE-RSA-WITH-
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA
Enable ECDH-ECDSA based ciphersuite modes
Found in: Component config > mbedTLS > TLS Key Exchange Methods > CON-
FIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE
Enable to support ciphersuites with prefix TLS-ECDHE-RSA-WITH-
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA
Enable ECDH-RSA based ciphersuite modes
Found in: Component config > mbedTLS > TLS Key Exchange Methods > CON-
FIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE
Enable to support ciphersuites with prefix TLS-ECDHE-RSA-WITH-
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_KEY_EXCHANGE_ECJPAKE
Enable ECJPAKE based ciphersuite modes
Found in: Component config > mbedTLS > TLS Key Exchange Methods
Enable to support ciphersuites with prefix TLS-ECJPAKE-WITH-
Default value:
• No (disabled) if CONFIG_MBEDTLS_ECJPAKE_C && CON-
FIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED
CONFIG_MBEDTLS_SSL_RENEGOTIATION
Support TLS renegotiation
Found in: Component config > mbedTLS
The two main uses of renegotiation are (1) refresh keys on long-lived connections and (2) client authen-
tication after the initial handshake. If you don’t need renegotiation, disabling it will save code size and
reduce the possibility of abuse/vulnerability.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_SSL_PROTO_TLS1_2
Support TLS 1.2 protocol
Found in: Component config > mbedTLS
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1
Support GM/T SSL 1.1 protocol
Found in: Component config > mbedTLS
Provisions for GM/T SSL 1.1 support
Default value:
• No (disabled)
CONFIG_MBEDTLS_SSL_PROTO_DTLS
Support DTLS protocol (all versions)
Found in: Component config > mbedTLS
Requires TLS 1.2 to be enabled for DTLS 1.2
Default value:
• No (disabled)
CONFIG_MBEDTLS_SSL_ALPN
Support ALPN (Application Layer Protocol Negotiation)
Found in: Component config > mbedTLS
Disabling this option will save some code size if it is not needed.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS
TLS: Client Support for RFC 5077 SSL session tickets
Found in: Component config > mbedTLS
Client support for RFC 5077 session tickets. See mbedTLS documentation for more details. Disabling
this option will save some code size.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS
TLS: Server Support for RFC 5077 SSL session tickets
Found in: Component config > mbedTLS
Server support for RFC 5077 session tickets. See mbedTLS documentation for more details. Disabling
this option will save some code size.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_AES_C
AES block cipher
Found in: Component config > mbedTLS > Symmetric Ciphers
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_CAMELLIA_C
Camellia block cipher
Found in: Component config > mbedTLS > Symmetric Ciphers
Default value:
• No (disabled)
CONFIG_MBEDTLS_DES_C
DES block cipher (legacy, insecure)
Found in: Component config > mbedTLS > Symmetric Ciphers
Enables the DES block cipher to support 3DES-based TLS ciphersuites.
3DES is vulnerable to the Sweet32 attack and should only be enabled if absolutely necessary.
Default value:
• No (disabled)
CONFIG_MBEDTLS_BLOWFISH_C
Blowfish block cipher (read help)
Found in: Component config > mbedTLS > Symmetric Ciphers
Enables the Blowfish block cipher (not used for TLS sessions.)
The Blowfish cipher is not used for mbedTLS TLS sessions but can be used for other purposes. Read
up on the limitations of Blowfish (including Sweet32) before enabling.
Default value:
• No (disabled)
CONFIG_MBEDTLS_XTEA_C
XTEA block cipher
Found in: Component config > mbedTLS > Symmetric Ciphers
Enables the XTEA block cipher.
Default value:
• No (disabled)
CONFIG_MBEDTLS_CCM_C
CCM (Counter with CBC-MAC) block cipher modes
Found in: Component config > mbedTLS > Symmetric Ciphers
Enable Counter with CBC-MAC (CCM) modes for AES and/or Camellia ciphers.
Disabling this option saves some code size.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_GCM_C
GCM (Galois/Counter) block cipher modes
Found in: Component config > mbedTLS > Symmetric Ciphers
Enable Galois/Counter Mode for AES and/or Camellia ciphers.
This option is generally faster than CCM.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_NIST_KW_C
NIST key wrapping (KW) and KW padding (KWP)
Found in: Component config > mbedTLS > Symmetric Ciphers
Enable NIST key wrapping and key wrapping padding.
Default value:
• No (disabled)
CONFIG_MBEDTLS_RIPEMD160_C
Enable RIPEMD-160 hash algorithm
Found in: Component config > mbedTLS
Enable the RIPEMD-160 hash algorithm.
Default value:
• No (disabled)
Certificates Contains:
• CONFIG_MBEDTLS_PEM_PARSE_C
• CONFIG_MBEDTLS_PEM_WRITE_C
• CONFIG_MBEDTLS_X509_CRL_PARSE_C
• CONFIG_MBEDTLS_X509_CSR_PARSE_C
CONFIG_MBEDTLS_PEM_PARSE_C
Read & Parse PEM formatted certificates
Found in: Component config > mbedTLS > Certificates
Enable decoding/parsing of PEM formatted certificates.
If your certificates are all in the simpler DER format, disabling this option will save some code size.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_PEM_WRITE_C
Write PEM formatted certificates
Found in: Component config > mbedTLS > Certificates
Enable writing of PEM formatted certificates.
If writing certificate data only in DER format, disabling this option will save some code size.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_X509_CRL_PARSE_C
X.509 CRL parsing
Found in: Component config > mbedTLS > Certificates
Support for parsing X.509 Certifificate Revocation Lists.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_X509_CSR_PARSE_C
X.509 CSR parsing
Found in: Component config > mbedTLS > Certificates
Support for parsing X.509 Certifificate Signing Requests
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_ECP_C
Elliptic Curve Ciphers
Found in: Component config > mbedTLS
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_DHM_C
Diffie-Hellman-Merkle key exchange (DHM)
Found in: Component config > mbedTLS
Enable DHM. Needed to use DHE-xxx TLS ciphersuites.
Note that the security of Diffie-Hellman key exchanges depends on a suitable prime being used for the
exchange. Please see detailed warning text about this in file mbedtls/dhm.h file.
Default value:
• No (disabled)
CONFIG_MBEDTLS_ECDH_C
Elliptic Curve Diffie-Hellman (ECDH)
Found in: Component config > mbedTLS
Enable ECDH. Needed to use ECDHE-xxx TLS ciphersuites.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_ECDSA_C
Elliptic Curve DSA
Found in: Component config > mbedTLS > CONFIG_MBEDTLS_ECDH_C
Enable ECDSA. Needed to use ECDSA-xxx TLS ciphersuites.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_ECJPAKE_C
Elliptic curve J-PAKE
Found in: Component config > mbedTLS
Enable ECJPAKE. Needed to use ECJPAKE-xxx TLS ciphersuites.
Default value:
• No (disabled)
CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED
Enable SECP192R1 curve
Found in: Component config > mbedTLS
Enable support for SECP192R1 Elliptic Curve.
Default value:
• Yes (enabled) if (CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN || CON-
FIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY) && CONFIG_MBEDTLS_ECP_C
CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED
Enable SECP224R1 curve
Found in: Component config > mbedTLS
Enable support for SECP224R1 Elliptic Curve.
Default value:
• Yes (enabled) if (CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN || CON-
FIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY) && CONFIG_MBEDTLS_ECP_C
CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED
Enable SECP256R1 curve
Found in: Component config > mbedTLS
Enable support for SECP256R1 Elliptic Curve.
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED
Enable SECP384R1 curve
Found in: Component config > mbedTLS
Enable support for SECP384R1 Elliptic Curve.
Default value:
• Yes (enabled) if (CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN || CON-
FIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY) && CONFIG_MBEDTLS_ECP_C
CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED
Enable SECP521R1 curve
Found in: Component config > mbedTLS
Enable support for SECP521R1 Elliptic Curve.
Default value:
• Yes (enabled) if (CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN || CON-
FIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY) && CONFIG_MBEDTLS_ECP_C
CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED
Enable SECP192K1 curve
Found in: Component config > mbedTLS
Enable support for SECP192K1 Elliptic Curve.
Default value:
• Yes (enabled) if (CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN || CON-
FIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY) && CONFIG_MBEDTLS_ECP_C
CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED
Enable SECP224K1 curve
Found in: Component config > mbedTLS
Enable support for SECP224K1 Elliptic Curve.
Default value:
• Yes (enabled) if (CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN || CON-
FIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY) && CONFIG_MBEDTLS_ECP_C
CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED
Enable SECP256K1 curve
Found in: Component config > mbedTLS
Enable support for SECP256K1 Elliptic Curve.
Default value:
• Yes (enabled) if (CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN || CON-
FIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY) && CONFIG_MBEDTLS_ECP_C
CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED
Enable BP256R1 curve
Found in: Component config > mbedTLS
support for DP Elliptic Curve.
Default value:
• Yes (enabled) if (CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN || CON-
FIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY) && CONFIG_MBEDTLS_ECP_C
CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED
Enable BP384R1 curve
Found in: Component config > mbedTLS
support for DP Elliptic Curve.
Default value:
• Yes (enabled) if (CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN || CON-
FIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY) && CONFIG_MBEDTLS_ECP_C
CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED
Enable BP512R1 curve
Found in: Component config > mbedTLS
support for DP Elliptic Curve.
Default value:
• Yes (enabled) if (CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN || CON-
FIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY) && CONFIG_MBEDTLS_ECP_C
CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED
Enable CURVE25519 curve
Found in: Component config > mbedTLS
Enable support for CURVE25519 Elliptic Curve.
Default value:
• Yes (enabled) if (CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN || CON-
FIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY) && CONFIG_MBEDTLS_ECP_C
CONFIG_MBEDTLS_ECP_NIST_OPTIM
NIST ‘modulo p’optimisations
Found in: Component config > mbedTLS
NIST ‘modulo p’optimisations increase Elliptic Curve operation performance.
Disabling this option saves some code size.
# end of Elliptic Curve options
Default value:
• Yes (enabled)
CONFIG_MBEDTLS_POLY1305_C
Poly1305 MAC algorithm
Found in: Component config > mbedTLS
Enable support for Poly1305 MAC algorithm.
Default value:
• No (disabled)
CONFIG_MBEDTLS_CHACHA20_C
Chacha20 stream cipher
Found in: Component config > mbedTLS
Enable support for Chacha20 stream cipher.
Default value:
• No (disabled)
CONFIG_MBEDTLS_CHACHAPOLY_C
ChaCha20-Poly1305 AEAD algorithm
Found in: Component config > mbedTLS > CONFIG_MBEDTLS_CHACHA20_C
Enable support for ChaCha20-Poly1305 AEAD algorithm.
Default value:
• No (disabled) if CONFIG_MBEDTLS_CHACHA20_C && CON-
FIG_MBEDTLS_POLY1305_C
CONFIG_MBEDTLS_HKDF_C
HKDF algorithm (RFC 5869)
Found in: Component config > mbedTLS
Enable support for the Hashed Message Authentication Code (HMAC)-based key derivation function
(HKDF).
Default value:
• No (disabled)
CONFIG_MBEDTLS_THREADING_C
Enable the threading abstraction layer
Found in: Component config > mbedTLS
If you do intend to use contexts between threads, you will need to enable this layer to prevent race
conditions.
Default value:
• No (disabled)
CONFIG_MBEDTLS_THREADING_ALT
Enable threading alternate implementation
Found in: Component config > mbedTLS > CONFIG_MBEDTLS_THREADING_C
Enable threading alt to allow your own alternate threading implementation.
Default value:
• Yes (enabled) if CONFIG_MBEDTLS_THREADING_C
CONFIG_MBEDTLS_THREADING_PTHREAD
Enable threading pthread implementation
Found in: Component config > mbedTLS > CONFIG_MBEDTLS_THREADING_C
Enable the pthread wrapper layer for the threading layer.
Default value:
• No (disabled) if CONFIG_MBEDTLS_THREADING_C
CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI
Fallback to software implementation for larger MPI values
Found in: Component config > mbedTLS
Fallback to software implementation for RSA key lengths larger than SOC_RSA_MAX_BIT_LEN. If
this is not active then the ESP will be unable to process keys greater than SOC_RSA_MAX_BIT_LEN.
Default value:
• No (disabled)
CONFIG_MBEDTLS_SECURITY_RISKS
Show configurations with potential security risks
Found in: Component config > mbedTLS
Default value:
• No (disabled)
Contains:
• CONFIG_MBEDTLS_ALLOW_UNSUPPORTED_CRITICAL_EXT
CONFIG_MBEDTLS_ALLOW_UNSUPPORTED_CRITICAL_EXT
X.509 CRT parsing with unsupported critical extensions
Found in: Component config > mbedTLS > CONFIG_MBEDTLS_SECURITY_RISKS
Allow the X.509 certificate parser to load certificates with unsupported critical extensions
Default value:
• No (disabled) if CONFIG_MBEDTLS_SECURITY_RISKS
CONFIG_MQTT_PROTOCOL_311
Enable MQTT protocol 3.1.1
Found in: Component config > ESP-MQTT Configurations
If not, this library will use MQTT protocol 3.1
Default value:
• Yes (enabled)
CONFIG_MQTT_TRANSPORT_SSL
Enable MQTT over SSL
Found in: Component config > ESP-MQTT Configurations
Enable MQTT transport over SSL with mbedtls
Default value:
• Yes (enabled)
CONFIG_MQTT_TRANSPORT_WEBSOCKET
Enable MQTT over Websocket
Found in: Component config > ESP-MQTT Configurations
Enable MQTT transport over Websocket.
Default value:
• Yes (enabled)
CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE
Enable MQTT over Websocket Secure
Found in: Component config > ESP-MQTT Configurations > CON-
FIG_MQTT_TRANSPORT_WEBSOCKET
Enable MQTT transport over Websocket Secure.
Default value:
• Yes (enabled)
CONFIG_MQTT_MSG_ID_INCREMENTAL
Use Incremental Message Id
Found in: Component config > ESP-MQTT Configurations
Set this to true for the message id (2.3.1 Packet Identifier) to be generated as an incremental number
rather then a random value (used by default)
Default value:
• No (disabled)
CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED
Skip publish if disconnected
Found in: Component config > ESP-MQTT Configurations
Set this to true to avoid publishing (enqueueing messages) if the client is disconnected. The
MQTT client tries to publish all messages by default, even in the disconnected state (where
the qos1 and qos2 packets are stored in the internal outbox to be published later) The
MQTT_SKIP_PUBLISH_IF_DISCONNECTED option allows applications to override this behaviour
and not enqueue publish packets in the disconnected state.
Default value:
• No (disabled)
CONFIG_MQTT_REPORT_DELETED_MESSAGES
Report deleted messages
Found in: Component config > ESP-MQTT Configurations
Set this to true to post events for all messages which were deleted from the outbox before being correctly
sent and confirmed.
Default value:
• No (disabled)
CONFIG_MQTT_USE_CUSTOM_CONFIG
MQTT Using custom configurations
Found in: Component config > ESP-MQTT Configurations
Custom MQTT configurations.
Default value:
• No (disabled)
CONFIG_MQTT_TCP_DEFAULT_PORT
Default MQTT over TCP port
Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG
Default MQTT over TCP port
Default value:
• 1883 if CONFIG_MQTT_USE_CUSTOM_CONFIG
CONFIG_MQTT_SSL_DEFAULT_PORT
Default MQTT over SSL port
Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG
Default MQTT over SSL port
Default value:
• 8883 if CONFIG_MQTT_USE_CUSTOM_CONFIG && CONFIG_MQTT_TRANSPORT_SSL
CONFIG_MQTT_WS_DEFAULT_PORT
Default MQTT over Websocket port
Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG
Default MQTT over Websocket port
Default value:
• 80 if CONFIG_MQTT_USE_CUSTOM_CONFIG && CON-
FIG_MQTT_TRANSPORT_WEBSOCKET
CONFIG_MQTT_WSS_DEFAULT_PORT
Default MQTT over Websocket Secure port
Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG
Default MQTT over Websocket Secure port
Default value:
• 443 if CONFIG_MQTT_USE_CUSTOM_CONFIG && CON-
FIG_MQTT_TRANSPORT_WEBSOCKET && CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE
CONFIG_MQTT_BUFFER_SIZE
Default MQTT Buffer Size
Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG
This buffer size using for both transmit and receive
Default value:
• 1024 if CONFIG_MQTT_USE_CUSTOM_CONFIG
CONFIG_MQTT_TASK_STACK_SIZE
MQTT task stack size
Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG
MQTT task stack size
Default value:
• 6144 if CONFIG_MQTT_USE_CUSTOM_CONFIG
CONFIG_MQTT_DISABLE_API_LOCKS
Disable API locks
Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG
Default config employs API locks to protect internal structures. It is possible to disable these locks if
the user code doesn’t access MQTT API from multiple concurrent tasks
Default value:
• No (disabled) if CONFIG_MQTT_USE_CUSTOM_CONFIG
CONFIG_MQTT_TASK_PRIORITY
MQTT task priority
Found in: Component config > ESP-MQTT Configurations > CONFIG_MQTT_USE_CUSTOM_CONFIG
MQTT task priority. Higher number denotes higher priority.
Default value:
• 5 if CONFIG_MQTT_USE_CUSTOM_CONFIG
CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED
Enable MQTT task core selection
Found in: Component config > ESP-MQTT Configurations
This will enable core selection
CONFIG_MQTT_TASK_CORE_SELECTION
Core to use ?
Found in: Component config > ESP-MQTT Configurations > CON-
FIG_MQTT_TASK_CORE_SELECTION_ENABLED
Available options:
• Core 0 (MQTT_USE_CORE_0)
• Core 1 (MQTT_USE_CORE_1)
CONFIG_MQTT_CUSTOM_OUTBOX
Enable custom outbox implementation
Found in: Component config > ESP-MQTT Configurations
Set to true if a specific implementation of message outbox is needed (e.g. persistent outbox in NVM
or similar). Note: Implementation of the custom outbox must be added to the mqtt component.
These CMake commands could be used to append the custom implementation to lib-mqtt sources:
idf_component_get_property(mqtt mqtt COMPONENT_LIB) set_property(TARGET ${mqtt} PROP-
ERTY SOURCES ${PROJECT_DIR}/custom_outbox.c APPEND)
Default value:
• No (disabled)
CONFIG_MQTT_OUTBOX_EXPIRED_TIMEOUT_MS
Outbox message expired timeout[ms]
Found in: Component config > ESP-MQTT Configurations
Messages which stays in the outbox longer than this value before being published will be discarded.
Default value:
• 30000 if CONFIG_MQTT_USE_CUSTOM_CONFIG
Newlib Contains:
• CONFIG_NEWLIB_NANO_FORMAT
• CONFIG_NEWLIB_STDIN_LINE_ENDING
• CONFIG_NEWLIB_STDOUT_LINE_ENDING
• CONFIG_NEWLIB_TIME_SYSCALL
CONFIG_NEWLIB_STDOUT_LINE_ENDING
Line ending for UART output
Found in: Component config > Newlib
This option allows configuring the desired line endings sent to UART when a newline (‘n’, LF) appears
on stdout. Three options are possible:
CRLF: whenever LF is encountered, prepend it with CR
LF: no modification is applied, stdout is sent as is
CR: each occurence of LF is replaced with CR
This option doesn’t affect behavior of the UART driver (drivers/uart.h).
Available options:
• CRLF (NEWLIB_STDOUT_LINE_ENDING_CRLF)
• LF (NEWLIB_STDOUT_LINE_ENDING_LF)
• CR (NEWLIB_STDOUT_LINE_ENDING_CR)
CONFIG_NEWLIB_STDIN_LINE_ENDING
Line ending for UART input
Found in: Component config > Newlib
This option allows configuring which input sequence on UART produces a newline (‘n’, LF) on stdin.
Three options are possible:
CRLF: CRLF is converted to LF
LF: no modification is applied, input is sent to stdin as is
CR: each occurence of CR is replaced with LF
This option doesn’t affect behavior of the UART driver (drivers/uart.h).
Available options:
• CRLF (NEWLIB_STDIN_LINE_ENDING_CRLF)
• LF (NEWLIB_STDIN_LINE_ENDING_LF)
• CR (NEWLIB_STDIN_LINE_ENDING_CR)
CONFIG_NEWLIB_NANO_FORMAT
Enable ‘nano’formatting options for printf/scanf family
Found in: Component config > Newlib
ESP32 ROM contains parts of newlib C library, including printf/scanf family of functions. These func-
tions have been compiled with so-called“nano”formatting option. This option doesn’t support 64-bit
integer formats and C99 features, such as positional arguments.
For more details about “nano”formatting option, please see newlib readme file, search for ‘–enable-
newlib-nano-formatted-io’: https://sourceware.org/newlib/README
If this option is enabled, build system will use functions available in ROM, reducing the application
binary size. Functions available in ROM run faster than functions which run from flash. Functions
available in ROM can also run when flash instruction cache is disabled.
If you need 64-bit integer formatting support or C99 features, keep this option disabled.
CONFIG_NEWLIB_TIME_SYSCALL
Timers used for gettimeofday function
Found in: Component config > Newlib
This setting defines which hardware timers are used to implement‘gettimeofday’and‘time’functions
in C library.
• If both high-resolution (systimer for all targets except ESP32) and RTC timers are used,
timekeeping will continue in deep sleep. Time will be reported at 1 microsecond resolution.
This is the default, and the recommended option.
• If only high-resolution timer (systimer) is used, gettimeofday will provide time at microsec-
ond resolution. Time will not be preserved when going into deep sleep mode.
• If only RTC timer is used, timekeeping will continue in deep sleep, but time will be measured
at 6.(6) microsecond resolution. Also the gettimeofday function itself may take longer to run.
• If no timers are used, gettimeofday and time functions return -1 and set errno to ENOSYS.
• When RTC is used for timekeeping, two RTC_STORE registers are used to keep time in
deep sleep mode.
Available options:
• RTC and high-resolution timer (NEWLIB_TIME_SYSCALL_USE_RTC_HRT)
• RTC (NEWLIB_TIME_SYSCALL_USE_RTC)
• High-resolution timer (NEWLIB_TIME_SYSCALL_USE_HRT)
• None (NEWLIB_TIME_SYSCALL_USE_NONE)
NVS Contains:
• CONFIG_NVS_ENCRYPTION
• CONFIG_NVS_COMPATIBLE_PRE_V4_3_ENCRYPTION_FLAG
• CONFIG_NVS_ASSERT_ERROR_CHECK
CONFIG_NVS_ENCRYPTION
Enable NVS encryption
Found in: Component config > NVS
This option enables encryption for NVS. When enabled, AES-XTS is used to encrypt the complete NVS
data, except the page headers. It requires XTS encryption keys to be stored in an encrypted partition.
This means enabling flash encryption is a pre-requisite for this feature.
Default value:
• Yes (enabled) if CONFIG_SECURE_FLASH_ENC_ENABLED
CONFIG_NVS_COMPATIBLE_PRE_V4_3_ENCRYPTION_FLAG
NVS partition encrypted flag compatible with ESP-IDF before v4.3
Found in: Component config > NVS
Enabling this will ignore “encrypted”flag for NVS partitions. NVS encryption scheme is different
than hardware flash encryption and hence it is not recommended to have “encrypted”flag for NVS
partitions. This was not being checked in pre v4.3 IDF. Hence, if you have any devices where this flag
is kept enabled in partition table then enabling this config will allow to have same behavior as pre v4.3
IDF.
CONFIG_NVS_ASSERT_ERROR_CHECK
Use assertions for error checking
Found in: Component config > NVS
This option switches error checking type between assertions (y) or return codes (n).
Default value:
• No (disabled)
OpenThread Contains:
• CONFIG_OPENTHREAD_ENABLED
CONFIG_OPENTHREAD_ENABLED
OpenThread
Found in: Component config > OpenThread
Select this option to enable OpenThread and show the submenu with OpenThread configuration choices.
Default value:
• No (disabled)
CONFIG_OPENTHREAD_RADIO_TYPE
Config the Thread radio type
Found in: Component config > OpenThread > CONFIG_OPENTHREAD_ENABLED
Configure how OpenThread connects to the 15.4 radio
Available options:
• Native 15.4 radio (OPENTHREAD_RADIO_NATIVE)
Select this to use the native 15.4 radio.
• Connect via UART (OPENTHREAD_RADIO_SPINEL_UART)
Select this to connect to a Radio Co-Processor via UART.
CONFIG_OPENTHREAD_DEVICE_TYPE
Config the Thread device type
Found in: Component config > OpenThread > CONFIG_OPENTHREAD_ENABLED
OpenThread can be configured to different device types (FTD, MTD, Radio)
Available options:
• Full Thread Device (OPENTHREAD_FTD)
Select this to enable Full Thread Device which can act as router and leader in a Thread net-
work.
• Minimal Thread Device (OPENTHREAD_MTD)
Select this to enable Minimal Thread Device which can only act as end device in a Thread
network. This will reduce the code size of the OpenThread stack.
• Radio Only Device (OPENTHREAD_RADIO)
Select this to enable Radio Only Device which can only forward 15.4 packets to the host. The
OpenThread stack will be run on the host and OpenThread will have minimal footprint on the
radio only device.
CONFIG_OPENTHREAD_DIAG
Enable diag
Found in: Component config > OpenThread > CONFIG_OPENTHREAD_ENABLED
Select this option to enable Diag in OpenThread. This will enable diag mode and a series of diag com-
mands in the OpenThread command line. These commands allow users to manipulate low-level features
of the storage and 15.4 radio.
Default value:
• Yes (enabled) if CONFIG_OPENTHREAD_ENABLED
CONFIG_OPENTHREAD_COMMISSIONER
Enable Commissioner
Found in: Component config > OpenThread > CONFIG_OPENTHREAD_ENABLED
Select this option to enable commissioner in OpenThread. This will enable the device to act as a com-
missioner in the Thread network. A commissioner checks the pre-shared key from a joining device
with the Thread commissioning protocol and shares the network parameter with the joining device upon
success.
Default value:
• No (disabled) if CONFIG_OPENTHREAD_ENABLED
CONFIG_OPENTHREAD_JOINER
Enable Joiner
Found in: Component config > OpenThread > CONFIG_OPENTHREAD_ENABLED
Select this option to enable Joiner in OpenThread. This allows a device to join the Thread network with
a pre-shared key using the Thread commissioning protocol.
Default value:
• No (disabled) if CONFIG_OPENTHREAD_ENABLED
CONFIG_OPENTHREAD_SRP_CLIENT
Enable SRP Client
Found in: Component config > OpenThread > CONFIG_OPENTHREAD_ENABLED
Select this option to enable SRP Client in OpenThread. This allows a device to register SRP services to
SRP Server.
Default value:
• No (disabled) if CONFIG_OPENTHREAD_ENABLED
CONFIG_OPENTHREAD_BORDER_ROUTER
Enable Border Router
Found in: Component config > OpenThread > CONFIG_OPENTHREAD_ENABLED
Select this option to enable border router features in OpenThread.
Default value:
• No (disabled) if CONFIG_OPENTHREAD_ENABLED
CONFIG_OPENTHREAD_NUM_MESSAGE_BUFFERS
The number of openthread message buffers
Found in: Component config > OpenThread > CONFIG_OPENTHREAD_ENABLED
Range:
• from 50 to 100 if CONFIG_OPENTHREAD_ENABLED
Default value:
• 65 if CONFIG_OPENTHREAD_ENABLED
Protocomm Contains:
• CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0
• CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1
• CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0
Support protocomm security version 0 (no security)
Found in: Component config > Protocomm
Enable support of security version 0. Disabling this option saves some code size. Consult the Enabling
protocomm security version section of the Protocomm documentation in ESP-IDF Programming guide
for more details.
Default value:
• Yes (enabled)
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1
Support protocomm security version 1 (Curve25519 key exchange + AES-CTR encryption/decryption)
Found in: Component config > Protocomm
Enable support of security version 1. Disabling this option saves some code size. Consult the Enabling
protocomm security version section of the Protocomm documentation in ESP-IDF Programming guide
for more details.
Default value:
• Yes (enabled)
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2
Support protocomm security version 2 (SRP6a-based key exchange + AES-GCM encryp-
tion/decryption)
Found in: Component config > Protocomm
Enable support of security version 2. Disabling this option saves some code size. Consult the Enabling
protocomm security version section of the Protocomm documentation in ESP-IDF Programming guide
for more details.
Default value:
• No (disabled)
PThreads Contains:
• CONFIG_PTHREAD_TASK_NAME_DEFAULT
• CONFIG_PTHREAD_TASK_CORE_DEFAULT
• CONFIG_PTHREAD_TASK_PRIO_DEFAULT
• CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT
• CONFIG_PTHREAD_STACK_MIN
CONFIG_PTHREAD_TASK_PRIO_DEFAULT
Default task priority
Found in: Component config > PThreads
Priority used to create new tasks with default pthread parameters.
Range:
• from 0 to 255
Default value:
• 5
CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT
Default task stack size
Found in: Component config > PThreads
Stack size used to create new tasks with default pthread parameters.
Default value:
• 3072
CONFIG_PTHREAD_STACK_MIN
Minimum allowed pthread stack size
Found in: Component config > PThreads
Minimum allowed pthread stack size set in attributes passed to pthread_create
Default value:
• 768
CONFIG_PTHREAD_TASK_CORE_DEFAULT
Default pthread core affinity
Found in: Component config > PThreads
The default core to which pthreads are pinned.
Available options:
• No affinity (PTHREAD_DEFAULT_CORE_NO_AFFINITY)
• Core 0 (PTHREAD_DEFAULT_CORE_0)
• Core 1 (PTHREAD_DEFAULT_CORE_1)
CONFIG_PTHREAD_TASK_NAME_DEFAULT
Default name of pthreads
Found in: Component config > PThreads
The default name of pthreads.
Default value:
• “pthread”
• CONFIG_SPI_FLASH_VERIFY_WRITE
• CONFIG_SPI_FLASH_DANGEROUS_WRITE
CONFIG_SPI_FLASH_VERIFY_WRITE
Verify SPI flash writes
Found in: Component config > SPI Flash driver
If this option is enabled, any time SPI flash is written then the data will be read back and verified. This
can catch hardware problems with SPI flash, or flash which was not erased before verification.
Default value:
• No (disabled)
CONFIG_SPI_FLASH_LOG_FAILED_WRITE
Log errors if verification fails
Found in: Component config > SPI Flash driver > CONFIG_SPI_FLASH_VERIFY_WRITE
If this option is enabled, if SPI flash write verification fails then a log error line will be written with the
address, expected & actual values. This can be useful when debugging hardware SPI flash problems.
Default value:
• No (disabled) if CONFIG_SPI_FLASH_VERIFY_WRITE
CONFIG_SPI_FLASH_WARN_SETTING_ZERO_TO_ONE
Log warning if writing zero bits to ones
Found in: Component config > SPI Flash driver > CONFIG_SPI_FLASH_VERIFY_WRITE
If this option is enabled, any SPI flash write which tries to set zero bits in the flash to ones will log a
warning. Such writes will not result in the requested data appearing identically in flash once written, as
SPI NOR flash can only set bits to one when an entire sector is erased. After erasing, individual bits can
only be written from one to zero.
Note that some software (such as SPIFFS) which is aware of SPI NOR flash may write one bits as an
optimisation, relying on the data in flash becoming a bitwise AND of the new data and any existing data.
Such software will log spurious warnings if this option is enabled.
Default value:
• No (disabled) if CONFIG_SPI_FLASH_VERIFY_WRITE
CONFIG_SPI_FLASH_ENABLE_COUNTERS
Enable operation counters
Found in: Component config > SPI Flash driver
This option enables the following APIs:
• spi_flash_reset_counters
• spi_flash_dump_counters
• spi_flash_get_counters
These APIs may be used to collect performance data for spi_flash APIs and to help understand behaviour
of libraries which use SPI flash.
Default value:
• 0
CONFIG_SPI_FLASH_ROM_DRIVER_PATCH
Enable SPI flash ROM driver patched functions
Found in: Component config > SPI Flash driver
Enable this flag to use patched versions of SPI flash ROM driver functions. This option should be
enabled, if any one of the following is true: (1) need to write to flash on ESP32-D2WD; (2) main SPI
flash is connected to non-default pins; (3) main SPI flash chip is manufactured by ISSI.
Default value:
• Yes (enabled)
CONFIG_SPI_FLASH_DANGEROUS_WRITE
Writing to dangerous flash regions
Found in: Component config > SPI Flash driver
SPI flash APIs can optionally abort or return a failure code if erasing or writing addresses that fall at
the beginning of flash (covering the bootloader and partition table) or that overlap the app partition that
contains the running app.
It is not recommended to ever write to these regions from an IDF app, and this check prevents logic
errors or corrupted firmware memory from damaging these regions.
Note that this feature *does not* check calls to the esp_rom_xxx SPI flash ROM functions. These
functions should not be called directly from IDF applications.
Available options:
• Aborts (SPI_FLASH_DANGEROUS_WRITE_ABORTS)
• Fails (SPI_FLASH_DANGEROUS_WRITE_FAILS)
• Allowed (SPI_FLASH_DANGEROUS_WRITE_ALLOWED)
CONFIG_SPI_FLASH_SHARE_SPI1_BUS
Support other devices attached to SPI1 bus
Found in: Component config > SPI Flash driver
Each SPI bus needs a lock for arbitration among devices. This allows multiple devices on a same bus,
but may reduce the speed of esp_flash driver access to the main flash chip.
If you only need to use esp_flash driver to access the main flash chip, disable this option, and the lock
will be bypassed on SPI1 bus. Otherwise if extra devices are needed to attach to SPI1 bus, enable this
option.
Default value:
• No (disabled)
CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE
Bypass a block erase and always do sector erase
Found in: Component config > SPI Flash driver
Some flash chips can have very high “max”erase times, especially for block erase (32KB or 64KB).
This option allows to bypass “block erase”and always do sector erase commands. This will be much
slower overall in most cases, but improves latency for other code to run.
Default value:
• No (disabled)
CONFIG_SPI_FLASH_YIELD_DURING_ERASE
Enables yield operation during flash erase
Found in: Component config > SPI Flash driver
This allows to yield the CPUs between erase commands. Prevents starvation of other tasks. Please use
this configuration together with SPI\_FLASH\_ERASE\_YIELD\_DURATION\_MS and SPI\
_FLASH\_ERASE\_YIELD\_TICKS after carefully checking flash datasheet to avoid a watchdog
timeout. For more information, please check SPI Flash API reference documenation under section OS
Function.
Default value:
• Yes (enabled)
CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS
Duration of erasing to yield CPUs (ms)
Found in: Component config > SPI Flash driver > CONFIG_SPI_FLASH_YIELD_DURING_ERASE
If a duration of one erase command is large then it will yield CPUs after finishing a current command.
Default value:
• 20
CONFIG_SPI_FLASH_ERASE_YIELD_TICKS
CPU release time (tick) for an erase operation
Found in: Component config > SPI Flash driver > CONFIG_SPI_FLASH_YIELD_DURING_ERASE
Defines how many ticks will be before returning to continue a erasing.
Default value:
• 1
CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE
Flash write chunk size
Found in: Component config > SPI Flash driver
Flash write is broken down in terms of multiple (smaller) write operations. This configuration options
helps to set individual write chunk size, smaller value here ensures that cache (and non-IRAM resident
interrupts) remains disabled for shorter duration.
Range:
• from 256 to 8192
Default value:
• 8192
CONFIG_SPI_FLASH_SIZE_OVERRIDE
Override flash size in bootloader header by ESPTOOLPY_FLASHSIZE
Found in: Component config > SPI Flash driver
SPI Flash driver uses the flash size configured in bootloader header by default. Enable this option to
override flash size with latest ESPTOOLPY_FLASHSIZE value from the app header if the size in the
bootloader header is incorrect.
Default value:
• No (disabled)
CONFIG_SPI_FLASH_CHECK_ERASE_TIMEOUT_DISABLED
Flash timeout checkout disabled
Found in: Component config > SPI Flash driver
This option is helpful if you are using a flash chip whose timeout is quite large or unpredictable.
Default value:
• No (disabled)
CONFIG_SPI_FLASH_OVERRIDE_CHIP_DRIVER_LIST
Override default chip driver list
Found in: Component config > SPI Flash driver
This option allows the chip driver list to be customized, instead of using the default list provided by
ESP-IDF.
When this option is enabled, the default list is no longer compiled or linked. Instead, the de-
fault_registered_chips structure must be provided by the user.
See example: custom_chip_driver under examples/storage for more details.
Default value:
• No (disabled)
CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC
Enable sending reset when brownout for XMC flash chips
Found in: Component config > SPI Flash driver > SPI Flash behavior when brownout
When this option is selected, the patch will be enabled for XMC. Follow the recommended flow by XMC
for better stability.
DO NOT DISABLE UNLESS YOU KNOW WHAT YOU ARE DOING.
Default value:
• Yes (enabled)
CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP
ISSI
Found in: Component config > SPI Flash driver > Auto-detect flash chips
Enable this to support auto detection of ISSI chips if chip vendor not directly given by chip\_drv
member of the chip struct. This adds support for variant chips, however will extend detecting time.
Default value:
• Yes (enabled)
CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP
MXIC
Found in: Component config > SPI Flash driver > Auto-detect flash chips
Enable this to support auto detection of MXIC chips if chip vendor not directly given by chip\_drv
member of the chip struct. This adds support for variant chips, however will extend detecting time.
Default value:
• Yes (enabled)
CONFIG_SPI_FLASH_SUPPORT_GD_CHIP
GigaDevice
Found in: Component config > SPI Flash driver > Auto-detect flash chips
Enable this to support auto detection of GD (GigaDevice) chips if chip vendor not directly given by
chip\_drv member of the chip struct. If you are using Wrover modules, please don’t disable this,
otherwise your flash may not work in 4-bit mode.
This adds support for variant chips, however will extend detecting time and image size. Note that the
default chip driver supports the GD chips with product ID 60H.
Default value:
• Yes (enabled)
CONFIG_SPI_FLASH_SUPPORT_WINBOND_CHIP
Winbond
Found in: Component config > SPI Flash driver > Auto-detect flash chips
Enable this to support auto detection of Winbond chips if chip vendor not directly given by chip\_drv
member of the chip struct. This adds support for variant chips, however will extend detecting time.
Default value:
• Yes (enabled)
CONFIG_SPI_FLASH_SUPPORT_BOYA_CHIP
BOYA
Found in: Component config > SPI Flash driver > Auto-detect flash chips
Enable this to support auto detection of BOYA chips if chip vendor not directly given by chip\_drv
member of the chip struct. This adds support for variant chips, however will extend detecting time.
Default value:
• No (disabled)
• Yes (enabled)
CONFIG_SPI_FLASH_SUPPORT_TH_CHIP
TH
Found in: Component config > SPI Flash driver > Auto-detect flash chips
Enable this to support auto detection of TH chips if chip vendor not directly given by chip\_drv
member of the chip struct. This adds support for variant chips, however will extend detecting time.
Default value:
• No (disabled)
• Yes (enabled)
CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE
Enable encrypted partition read/write operations
Found in: Component config > SPI Flash driver
This option enables flash read/write operations to encrypted partition/s. This option is kept enabled
irrespective of state of flash encryption feature. However, in case application is not using flash encryption
feature and is in need of some additional memory from IRAM region (~1KB) then this config can be
disabled.
Default value:
• Yes (enabled)
CONFIG_SPIFFS_MAX_PARTITIONS
Maximum Number of Partitions
Found in: Component config > SPIFFS Configuration
Define maximum number of partitions that can be mounted.
Range:
• from 1 to 10
Default value:
• 3
CONFIG_SPIFFS_CACHE
Enable SPIFFS Cache
Found in: Component config > SPIFFS Configuration > SPIFFS Cache Configuration
Enables/disable memory read caching of nucleus file system operations.
Default value:
• Yes (enabled)
CONFIG_SPIFFS_CACHE_WR
Enable SPIFFS Write Caching
Found in: Component config > SPIFFS Configuration > SPIFFS Cache Configuration > CON-
FIG_SPIFFS_CACHE
Enables memory write caching for file descriptors in hydrogen.
Default value:
• Yes (enabled)
CONFIG_SPIFFS_CACHE_STATS
Enable SPIFFS Cache Statistics
Found in: Component config > SPIFFS Configuration > SPIFFS Cache Configuration > CON-
FIG_SPIFFS_CACHE
Enable/disable statistics on caching. Debug/test purpose only.
Default value:
• No (disabled)
CONFIG_SPIFFS_PAGE_CHECK
Enable SPIFFS Page Check
Found in: Component config > SPIFFS Configuration
Always check header of each accessed page to ensure consistent state. If enabled it will increase number
of reads from flash, especially if cache is disabled.
Default value:
• Yes (enabled)
CONFIG_SPIFFS_GC_MAX_RUNS
Set Maximum GC Runs
Found in: Component config > SPIFFS Configuration
Define maximum number of GC runs to perform to reach desired free pages.
Range:
• from 1 to 10000
Default value:
• 10
CONFIG_SPIFFS_GC_STATS
Enable SPIFFS GC Statistics
Found in: Component config > SPIFFS Configuration
Enable/disable statistics on gc. Debug/test purpose only.
Default value:
• No (disabled)
CONFIG_SPIFFS_PAGE_SIZE
SPIFFS logical page size
Found in: Component config > SPIFFS Configuration
Logical page size of SPIFFS partition, in bytes. Must be multiple of flash page size (which is usually 256
bytes). Larger page sizes reduce overhead when storing large files, and improve filesystem performance
when reading large files. Smaller page sizes reduce overhead when storing small (< page size) files.
Range:
• from 256 to 1024
Default value:
• 256
CONFIG_SPIFFS_OBJ_NAME_LEN
Set SPIFFS Maximum Name Length
Found in: Component config > SPIFFS Configuration
Object name maximum length. Note that this length include the zero-termination character, meaning
maximum string of characters can at most be SPIFFS_OBJ_NAME_LEN - 1.
SPIFFS_OBJ_NAME_LEN + SPIFFS_META_LENGTH should not exceed SPIFFS_PAGE_SIZE -
64.
Range:
• from 1 to 256
Default value:
• 32
CONFIG_SPIFFS_FOLLOW_SYMLINKS
Enable symbolic links for image creation
Found in: Component config > SPIFFS Configuration
If this option is enabled, symbolic links are taken into account during partition image creation.
Default value:
• No (disabled)
CONFIG_SPIFFS_USE_MAGIC
Enable SPIFFS Filesystem Magic
Found in: Component config > SPIFFS Configuration
Enable this to have an identifiable spiffs filesystem. This will look for a magic in all sectors to determine
if this is a valid spiffs system or not at mount time.
Default value:
• Yes (enabled)
CONFIG_SPIFFS_USE_MAGIC_LENGTH
Enable SPIFFS Filesystem Length Magic
Found in: Component config > SPIFFS Configuration > CONFIG_SPIFFS_USE_MAGIC
If this option is enabled, the magic will also be dependent on the length of the filesystem. For exam-
ple, a filesystem configured and formatted for 4 megabytes will not be accepted for mounting with a
configuration defining the filesystem as 2 megabytes.
Default value:
• Yes (enabled)
CONFIG_SPIFFS_META_LENGTH
Size of per-file metadata field
Found in: Component config > SPIFFS Configuration
This option sets the number of extra bytes stored in the file header. These bytes can be used in an
application-specific manner. Set this to at least 4 bytes to enable support for saving file modification
time.
SPIFFS_OBJ_NAME_LEN + SPIFFS_META_LENGTH should not exceed SPIFFS_PAGE_SIZE -
64.
Default value:
• 4
CONFIG_SPIFFS_USE_MTIME
Save file modification time
Found in: Component config > SPIFFS Configuration
If enabled, then the first 4 bytes of per-file metadata will be used to store file modification time (mtime),
accessible through stat/fstat functions. Modification time is updated when the file is opened.
Default value:
• Yes (enabled)
CONFIG_SPIFFS_MTIME_WIDE_64_BITS
The time field occupies 64 bits in the image instead of 32 bits
Found in: Component config > SPIFFS Configuration
If this option is not set, the time field is 32 bits (up to 2106 year), otherwise it is 64 bits and make sure
it matches SPIFFS_META_LENGTH. If the chip already has the spiffs image with the time field = 32
bits then this option cannot be applied in this case. Erase it first before using this option. To resolve the
Y2K38 problem for the spiffs, use a toolchain with 64-bit time_t support.
Default value:
• No (disabled) if CONFIG_SPIFFS_META_LENGTH >= 8
CONFIG_SPIFFS_DBG
Enable general SPIFFS debug
Found in: Component config > SPIFFS Configuration > Debug Configuration
Enabling this option will print general debug mesages to the console.
Default value:
• No (disabled)
CONFIG_SPIFFS_API_DBG
Enable SPIFFS API debug
Found in: Component config > SPIFFS Configuration > Debug Configuration
Enabling this option will print API debug mesages to the console.
Default value:
• No (disabled)
CONFIG_SPIFFS_GC_DBG
Enable SPIFFS Garbage Cleaner debug
Found in: Component config > SPIFFS Configuration > Debug Configuration
Enabling this option will print GC debug mesages to the console.
Default value:
• No (disabled)
CONFIG_SPIFFS_CACHE_DBG
Enable SPIFFS Cache debug
Found in: Component config > SPIFFS Configuration > Debug Configuration
Enabling this option will print cache debug mesages to the console.
Default value:
• No (disabled)
CONFIG_SPIFFS_CHECK_DBG
Enable SPIFFS Filesystem Check debug
Found in: Component config > SPIFFS Configuration > Debug Configuration
Enabling this option will print Filesystem Check debug mesages to the console.
Default value:
• No (disabled)
CONFIG_SPIFFS_TEST_VISUALISATION
Enable SPIFFS Filesystem Visualization
Found in: Component config > SPIFFS Configuration > Debug Configuration
Enable this option to enable SPIFFS_vis function in the API.
Default value:
• No (disabled)
Websocket Contains:
• CONFIG_WS_TRANSPORT
CONFIG_WS_TRANSPORT
Enable Websocket Transport
Found in: Component config > TCP Transport > Websocket
Enable support for creating websocket transport.
Default value:
• Yes (enabled)
CONFIG_WS_BUFFER_SIZE
Websocket transport buffer size
Found in: Component config > TCP Transport > Websocket > CONFIG_WS_TRANSPORT
Size of the buffer used for constructing the HTTP Upgrade request during connect
Default value:
• 1024
CONFIG_WS_DYNAMIC_BUFFER
Using dynamic websocket transport buffer
Found in: Component config > TCP Transport > Websocket > CONFIG_WS_TRANSPORT
If enable this option, websocket transport buffer will be freed after connection succeed to save more
heap.
Default value:
• No (disabled)
CONFIG_ULP_COPROC_ENABLED
Enable Ultra Low Power (ULP) Co-processor
Found in: Component config > Ultra Low Power (ULP) Co-processor
Enable this feature if you plan to use the ULP Co-processor. Once this option is enabled, further ULP
co-processor configuration will appear in the menu.
Default value:
• No (disabled)
CONFIG_ULP_COPROC_TYPE
ULP Co-processor type
Found in: Component config > Ultra Low Power (ULP) Co-processor > CON-
FIG_ULP_COPROC_ENABLED
Choose the ULP Coprocessor type: ULP FSM (Finite State Machine) or ULP RISC-V. Please note that
ESP32 only supports ULP FSM.
Available options:
• ULP FSM (Finite State Machine) (ULP_COPROC_TYPE_FSM)
• ULP RISC-V (ULP_COPROC_TYPE_RISCV)
CONFIG_ULP_COPROC_RESERVE_MEM
RTC slow memory reserved for coprocessor
Found in: Component config > Ultra Low Power (ULP) Co-processor > CON-
FIG_ULP_COPROC_ENABLED
Bytes of memory to reserve for ULP Co-processor firmware & data. Data is reserved at the beginning
of RTC slow memory.
Range:
• from 32 to 8176 if CONFIG_ULP_COPROC_ENABLED
Default value:
• 512 if CONFIG_ULP_COPROC_ENABLED
CONFIG_UNITY_ENABLE_FLOAT
Support for float type
Found in: Component config > Unity unit testing library
If not set, assertions on float arguments will not be available.
Default value:
• Yes (enabled)
CONFIG_UNITY_ENABLE_DOUBLE
Support for double type
Found in: Component config > Unity unit testing library
If not set, assertions on double arguments will not be available.
Default value:
• Yes (enabled)
CONFIG_UNITY_ENABLE_64BIT
Support for 64-bit integer types
Found in: Component config > Unity unit testing library
If not set, assertions on 64-bit integer types will always fail. If this feature is enabled, take care not
to pass pointers (which are 32 bit) to UNITY_ASSERT_EQUAL, as that will cause pointer-to-int-cast
warnings.
Default value:
• No (disabled)
CONFIG_UNITY_ENABLE_COLOR
Colorize test output
Found in: Component config > Unity unit testing library
If set, Unity will colorize test results using console escape sequences.
Default value:
• No (disabled)
CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER
Include ESP-IDF test registration/running helpers
Found in: Component config > Unity unit testing library
If set, then the following features will be available:
• TEST_CASE macro which performs automatic registration of test functions
• Functions to run registered test functions: unity_run_all_tests, unity_run_tests_with_filter,
unity_run_single_test_by_name.
• Interactive menu which lists test cases and allows choosing the tests to be run, available via
unity_run_menu function.
Disable if a different test registration mechanism is used.
Default value:
• Yes (enabled)
CONFIG_UNITY_ENABLE_FIXTURE
Include Unity test fixture
Found in: Component config > Unity unit testing library
If set, unity_fixture.h header file and associated source files are part of the build. These provide an
optional set of macros and functions to implement test groups.
Default value:
• No (disabled)
CONFIG_UNITY_ENABLE_BACKTRACE_ON_FAIL
Print a backtrace when a unit test fails
Found in: Component config > Unity unit testing library
If set, the unity framework will print the backtrace information before jumping back to the test menu.
The jumping is usually occurs in assert functions such as TEST_ASSERT, TEST_FAIL etc.
Default value:
• No (disabled)
CONFIG_VFS_SUPPORT_IO
Provide basic I/O functions
Found in: Component config > Virtual file system
If enabled, the following functions are provided by the VFS component.
open, close, read, write, pread, pwrite, lseek, fstat, fsync, ioctl, fcntl
Filesystem drivers can then be registered to handle these functions for specific paths.
Disabling this option can save memory when the support for these functions is not required.
Note that the following functions can still be used with socket file descriptors when this option is disabled:
close, read, write, ioctl, fcntl.
Default value:
• Yes (enabled)
CONFIG_VFS_SUPPORT_DIR
Provide directory related functions
Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO
If enabled, the following functions are provided by the VFS component.
stat, link, unlink, rename, utime, access, truncate, rmdir, mkdir, opendir, closedir, readdir, readdir_r,
seekdir, telldir, rewinddir
Filesystem drivers can then be registered to handle these functions for specific paths.
Disabling this option can save memory when the support for these functions is not required.
Default value:
• Yes (enabled)
CONFIG_VFS_SUPPORT_SELECT
Provide select function
Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO
If enabled, select function is provided by the VFS component, and can be used on peripheral file de-
scriptors (such as UART) and sockets at the same time.
If disabled, the default select implementation will be provided by LWIP for sockets only.
Disabling this option can reduce code size if support for “select”on UART file descriptors is not
required.
Default value:
• Yes (enabled) if CONFIG_VFS_SUPPORT_IO && CON-
FIG_LWIP_USE_ONLY_LWIP_SELECT
CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT
Suppress select() related debug outputs
Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO > CON-
FIG_VFS_SUPPORT_SELECT
Select() related functions might produce an unconveniently lot of debug outputs when one sets the default
log level to DEBUG or higher. It is possible to suppress these debug outputs by enabling this option.
Default value:
• Yes (enabled)
CONFIG_VFS_SUPPORT_TERMIOS
Provide termios.h functions
Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO
Disabling this option can save memory when the support for termios.h is not required.
Default value:
• Yes (enabled)
CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS
Host FS: Maximum number of the host filesystem mount points
Found in: Component config > Virtual file system > CONFIG_VFS_SUPPORT_IO > Host File System I/O
(Semihosting)
Define maximum number of host filesystem mount points.
Default value:
• 1
CONFIG_WL_SECTOR_SIZE
Wear Levelling library sector size
Found in: Component config > Wear Levelling
Sector size used by wear levelling library. You can set default sector size or size that will fit to the flash
device sector size.
With sector size set to 4096 bytes, wear levelling library is more efficient. However if FAT filesystem is
used on top of wear levelling library, it will need more temporary storage: 4096 bytes for each mounted
filesystem and 4096 bytes for each opened file.
With sector size set to 512 bytes, wear levelling library will perform more operations with flash memory,
but less RAM will be used by FAT filesystem library (512 bytes for the filesystem and 512 bytes for each
file opened).
Available options:
• 512 (WL_SECTOR_SIZE_512)
• 4096 (WL_SECTOR_SIZE_4096)
CONFIG_WL_SECTOR_MODE
Sector store mode
Found in: Component config > Wear Levelling
Specify the mode to store data into flash:
• In Performance mode a data will be stored to the RAM and then stored back to the flash. Compared
to the Safety mode, this operation is faster, but if power will be lost when erase sector operation is
in progress, then the data from complete flash device sector will be lost.
• In Safety mode data from complete flash device sector will be read from flash, modified, and then
stored back to flash. Compared to the Performance mode, this operation is slower, but if power is
lost during erase sector operation, then the data from full flash device sector will not be lost.
Available options:
• Perfomance (WL_SECTOR_MODE_PERF)
• Safety (WL_SECTOR_MODE_SAFE)
CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES
Max Wi-Fi Scan Result Entries
Found in: Component config > Wi-Fi Provisioning Manager
This sets the maximum number of entries of Wi-Fi scan results that will be kept by the provisioning
manager
Range:
• from 1 to 255
Default value:
• 16
CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT
Provisioning auto-stop timeout
Found in: Component config > Wi-Fi Provisioning Manager
Time (in seconds) after which the Wi-Fi provisioning manager will auto-stop after connecting to a Wi-Fi
network successfully.
Range:
• from 5 to 600
Default value:
• 30
CONFIG_WIFI_PROV_BLE_BONDING
Enable BLE bonding
Found in: Component config > Wi-Fi Provisioning Manager
This option is applicable only when provisioning transport is BLE.
Default value:
• Yes (enabled) if CONFIG_BT_ENABLED
CONFIG_WIFI_PROV_BLE_SEC_CONN
Enable BLE Secure connection flag
Found in: Component config > Wi-Fi Provisioning Manager
Used to enable Secure connection support when provisioning transport is BLE.
Default value:
CONFIG_WIFI_PROV_BLE_FORCE_ENCRYPTION
Force Link Encryption during characteristic Read / Write
Found in: Component config > Wi-Fi Provisioning Manager
Used to enforce link encryption when attempting to read / write characteristic
Default value:
• Yes (enabled)
Supplicant Contains:
• CONFIG_WPA_TESTING_OPTIONS
• CONFIG_WPA_WPS_SOFTAP_REGISTRAR
• CONFIG_WPA_11KV_SUPPORT
• CONFIG_WPA_11R_SUPPORT
• CONFIG_WPA_DPP_SUPPORT
• CONFIG_WPA_MBO_SUPPORT
• CONFIG_WPA_SUITE_B_192
• CONFIG_WPA_WAPI_PSK
• CONFIG_WPA_DEBUG_PRINT
• CONFIG_WPA_WPS_STRICT
• CONFIG_WPA_MBEDTLS_CRYPTO
CONFIG_WPA_MBEDTLS_CRYPTO
Use MbedTLS crypto APIs
Found in: Component config > Supplicant
Select this option to use MbedTLS crypto APIs which utilize hardware acceleration.
Default value:
• Yes (enabled)
CONFIG_WPA_MBEDTLS_TLS_CLIENT
Use MbedTLS TLS client for WiFi Enterprise connection
Found in: Component config > Supplicant > CONFIG_WPA_MBEDTLS_CRYPTO
Select this option to use MbedTLS TLS client for WPA2 enterprise connection. Please note that from
MbedTLS-3.0 onwards, MbedTLS does not support SSL-3.0 TLS-v1.0, TLS-v1.1 versions. Incase your
server is using one of these version, it is advisable to update your server. Please disable this option for
compatibilty with older TLS versions.
Default value:
• Yes (enabled)
CONFIG_WPA_WAPI_PSK
Enable WAPI PSK support
Found in: Component config > Supplicant
Select this option to enable WAPI-PSK which is a Chinese National Standard Encryption for Wireless
LANs (GB 15629.11-2003).
Default value:
• No (disabled)
CONFIG_WPA_SUITE_B_192
Enable NSA suite B support with 192 bit key
Found in: Component config > Supplicant
Select this option to enable 192 bit NSA suite-B. This is necessary to support WPA3 192 bit security.
Default value:
• No (disabled)
CONFIG_WPA_DEBUG_PRINT
Print debug messages from WPA Supplicant
Found in: Component config > Supplicant
Select this option to print logging information from WPA supplicant, this includes handshake information
and key hex dumps depending on the project logging level.
Enabling this could increase the build size ~60kb depending on the project logging level.
Default value:
• No (disabled)
CONFIG_WPA_TESTING_OPTIONS
Add DPP testing code
Found in: Component config > Supplicant
Select this to enable unity test for DPP.
Default value:
• No (disabled)
CONFIG_WPA_WPS_STRICT
Strictly validate all WPS attributes
Found in: Component config > Supplicant
Select this option to enable validate each WPS attribute rigorously. Disabling this add the workaorunds
with various APs. Enabling this may cause inter operability issues with some APs.
Default value:
• No (disabled)
CONFIG_WPA_11KV_SUPPORT
Enable 802.11k, 802.11v APIs Support
Found in: Component config > Supplicant
Select this option to enable 802.11k 802.11v APIs(RRM and BTM support). Only APIs which are
helpful for network assisted roaming are supported for now. Enable this option with BTM and RRM
enabled in sta config to make device ready for network assisted roaming. BTM: BSS transition man-
agement enables an AP to request a station to transition to a specific AP, or to indicate to a station a
set of preferred APs. RRM: Radio measurements enable STAs to understand the radio environment,
it enables STAs to observe and gather data on radio link performance and on the radio environment.
Current implementation adds beacon report, link measurement, neighbor report.
Default value:
• No (disabled)
CONFIG_WPA_SCAN_CACHE
Keep scan results in cache
Found in: Component config > Supplicant > CONFIG_WPA_11KV_SUPPORT
Keep scan results in cache, if not enabled, those will be flushed immediately.
Default value:
• No (disabled) if CONFIG_WPA_11KV_SUPPORT
CONFIG_WPA_MBO_SUPPORT
Enable Multi Band Operation Certification Support
Found in: Component config > Supplicant
Select this option to enable WiFi Multiband operation certification support.
Default value:
• No (disabled)
CONFIG_WPA_DPP_SUPPORT
Enable DPP support
Found in: Component config > Supplicant
Select this option to enable WiFi Easy Connect Support.
Default value:
• No (disabled)
CONFIG_WPA_11R_SUPPORT
Enable 802.11R (Fast Transition) Support
Found in: Component config > Supplicant
Select this option to enable WiFi Fast Transition Support.
Default value:
• No (disabled)
CONFIG_WPA_WPS_SOFTAP_REGISTRAR
Add WPS Registrar support in SoftAP mode
Found in: Component config > Supplicant
Select this option to enable WPS registrar support in softAP mode.
Default value:
• No (disabled)
• CONFIG_A2DP_ENABLE (CONFIG_BT_A2DP_ENABLE)
• CONFIG_A2D_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_A2D_TRACE_LEVEL)
– CONFIG_A2D_TRACE_LEVEL_NONE
– CONFIG_A2D_TRACE_LEVEL_ERROR
– CONFIG_A2D_TRACE_LEVEL_WARNING
– CONFIG_A2D_TRACE_LEVEL_API
– CONFIG_A2D_TRACE_LEVEL_EVENT
– CONFIG_A2D_TRACE_LEVEL_DEBUG
– CONFIG_A2D_TRACE_LEVEL_VERBOSE
• CONFIG_ADC2_DISABLE_DAC (CONFIG_ADC_DISABLE_DAC)
• CONFIG_APPL_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_APPL_TRACE_LEVEL)
– CONFIG_APPL_TRACE_LEVEL_NONE
– CONFIG_APPL_TRACE_LEVEL_ERROR
– CONFIG_APPL_TRACE_LEVEL_WARNING
– CONFIG_APPL_TRACE_LEVEL_API
– CONFIG_APPL_TRACE_LEVEL_EVENT
– CONFIG_APPL_TRACE_LEVEL_DEBUG
– CONFIG_APPL_TRACE_LEVEL_VERBOSE
• CONFIG_APP_ANTI_ROLLBACK (CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK)
• CONFIG_APP_ROLLBACK_ENABLE (CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE)
• CONFIG_APP_SECURE_VERSION (CONFIG_BOOTLOADER_APP_SECURE_VERSION)
• CONFIG_APP_SECURE_VERSION_SIZE_EFUSE_FIELD (CONFIG_BOOTLOADER_APP_SEC_VER_SIZE_EFUSE_FIELD
• CONFIG_AVCT_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_AVCT_TRACE_LEVEL)
– CONFIG_AVCT_TRACE_LEVEL_NONE
– CONFIG_AVCT_TRACE_LEVEL_ERROR
– CONFIG_AVCT_TRACE_LEVEL_WARNING
– CONFIG_AVCT_TRACE_LEVEL_API
– CONFIG_AVCT_TRACE_LEVEL_EVENT
– CONFIG_AVCT_TRACE_LEVEL_DEBUG
– CONFIG_AVCT_TRACE_LEVEL_VERBOSE
• CONFIG_AVDT_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_AVDT_TRACE_LEVEL)
– CONFIG_AVDT_TRACE_LEVEL_NONE
– CONFIG_AVDT_TRACE_LEVEL_ERROR
– CONFIG_AVDT_TRACE_LEVEL_WARNING
– CONFIG_AVDT_TRACE_LEVEL_API
– CONFIG_AVDT_TRACE_LEVEL_EVENT
– CONFIG_AVDT_TRACE_LEVEL_DEBUG
– CONFIG_AVDT_TRACE_LEVEL_VERBOSE
• CONFIG_AVRC_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_AVRC_TRACE_LEVEL)
– CONFIG_AVRC_TRACE_LEVEL_NONE
– CONFIG_AVRC_TRACE_LEVEL_ERROR
– CONFIG_AVRC_TRACE_LEVEL_WARNING
– CONFIG_AVRC_TRACE_LEVEL_API
– CONFIG_AVRC_TRACE_LEVEL_EVENT
– CONFIG_AVRC_TRACE_LEVEL_DEBUG
– CONFIG_AVRC_TRACE_LEVEL_VERBOSE
• CONFIG_BLE_ACTIVE_SCAN_REPORT_ADV_SCAN_RSP_INDIVIDUALLY (CON-
FIG_BT_BLE_ACT_SCAN_REP_ADV_SCAN)
• CONFIG_BLE_ADV_REPORT_DISCARD_THRSHOLD (CONFIG_BTDM_BLE_ADV_REPORT_DISCARD_THRSHOLD)
• CONFIG_BLE_ADV_REPORT_FLOW_CONTROL_NUM (CONFIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_NUM)
• CONFIG_BLE_ADV_REPORT_FLOW_CONTROL_SUPPORTED (CON-
FIG_BTDM_BLE_ADV_REPORT_FLOW_CTRL_SUPP)
• CONFIG_BLE_ESTABLISH_LINK_CONNECTION_TIMEOUT (CON-
FIG_BT_BLE_ESTAB_LINK_CONN_TOUT)
• CONFIG_BLE_HOST_QUEUE_CONGESTION_CHECK (CONFIG_BT_BLE_HOST_QUEUE_CONG_CHECK)
• CONFIG_BLE_MESH_GATT_PROXY (CONFIG_BLE_MESH_GATT_PROXY_SERVER)
• CONFIG_BLE_MESH_SCAN_DUPLICATE_EN (CONFIG_BTDM_BLE_MESH_SCAN_DUPL_EN)
• CONFIG_BLE_SCAN_DUPLICATE (CONFIG_BTDM_BLE_SCAN_DUPL)
• CONFIG_BLE_SMP_ENABLE (CONFIG_BT_BLE_SMP_ENABLE)
• CONFIG_BLUEDROID_MEM_DEBUG (CONFIG_BT_BLUEDROID_MEM_DEBUG)
• CONFIG_BLUEDROID_PINNED_TO_CORE_CHOICE (CONFIG_BT_BLUEDROID_PINNED_TO_CORE_CHOICE)
– CONFIG_BLUEDROID_PINNED_TO_CORE_0
– CONFIG_BLUEDROID_PINNED_TO_CORE_1
• CONFIG_BLUFI_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BLUFI_TRACE_LEVEL)
– CONFIG_BLUFI_TRACE_LEVEL_NONE
– CONFIG_BLUFI_TRACE_LEVEL_ERROR
– CONFIG_BLUFI_TRACE_LEVEL_WARNING
– CONFIG_BLUFI_TRACE_LEVEL_API
– CONFIG_BLUFI_TRACE_LEVEL_EVENT
– CONFIG_BLUFI_TRACE_LEVEL_DEBUG
– CONFIG_BLUFI_TRACE_LEVEL_VERBOSE
• CONFIG_BNEP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BNEP_TRACE_LEVEL)
• CONFIG_BROWNOUT_DET (CONFIG_ESP_BROWNOUT_DET)
• CONFIG_BROWNOUT_DET_LVL_SEL (CONFIG_ESP_BROWNOUT_DET_LVL_SEL)
– CONFIG_BROWNOUT_DET_LVL_SEL_0
– CONFIG_BROWNOUT_DET_LVL_SEL_1
– CONFIG_BROWNOUT_DET_LVL_SEL_2
– CONFIG_BROWNOUT_DET_LVL_SEL_3
– CONFIG_BROWNOUT_DET_LVL_SEL_4
– CONFIG_BROWNOUT_DET_LVL_SEL_5
– CONFIG_BROWNOUT_DET_LVL_SEL_6
– CONFIG_BROWNOUT_DET_LVL_SEL_7
• CONFIG_BTC_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BTC_TRACE_LEVEL)
– CONFIG_BTC_TRACE_LEVEL_NONE
– CONFIG_BTC_TRACE_LEVEL_ERROR
– CONFIG_BTC_TRACE_LEVEL_WARNING
– CONFIG_BTC_TRACE_LEVEL_API
– CONFIG_BTC_TRACE_LEVEL_EVENT
– CONFIG_BTC_TRACE_LEVEL_DEBUG
– CONFIG_BTC_TRACE_LEVEL_VERBOSE
• CONFIG_BTC_TASK_STACK_SIZE (CONFIG_BT_BTC_TASK_STACK_SIZE)
• CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN (CONFIG_BTDM_CTRL_BLE_MAX_CONN)
• CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN (CON-
FIG_BTDM_CTRL_BR_EDR_MAX_ACL_CONN)
• CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN (CON-
FIG_BTDM_CTRL_BR_EDR_MAX_SYNC_CONN)
• CONFIG_BTDM_CONTROLLER_FULL_SCAN_SUPPORTED (CON-
FIG_BTDM_CTRL_FULL_SCAN_SUPPORTED)
• CONFIG_BTDM_CONTROLLER_HCI_MODE_CHOICE (CONFIG_BTDM_CTRL_HCI_MODE_CHOICE)
– CONFIG_BTDM_CONTROLLER_HCI_MODE_VHCI
– CONFIG_BTDM_CONTROLLER_HCI_MODE_UART_H4
• CONFIG_BTDM_CONTROLLER_MODE (CONFIG_BTDM_CTRL_MODE)
– CONFIG_BTDM_CONTROLLER_MODE_BLE_ONLY
– CONFIG_BTDM_CONTROLLER_MODE_BR_EDR_ONLY
– CONFIG_BTDM_CONTROLLER_MODE_BTDM
• CONFIG_BTDM_CONTROLLER_MODEM_SLEEP (CONFIG_BTDM_CTRL_MODEM_SLEEP)
• CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE_CHOICE (CON-
FIG_BTDM_CTRL_PINNED_TO_CORE_CHOICE)
• CONFIG_BTH_LOG_SDP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_SDP_TRACE_LEVEL)
– CONFIG_SDP_TRACE_LEVEL_NONE
– CONFIG_SDP_TRACE_LEVEL_ERROR
– CONFIG_SDP_TRACE_LEVEL_WARNING
– CONFIG_SDP_TRACE_LEVEL_API
– CONFIG_SDP_TRACE_LEVEL_EVENT
– CONFIG_SDP_TRACE_LEVEL_DEBUG
– CONFIG_SDP_TRACE_LEVEL_VERBOSE
• CONFIG_BTIF_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BTIF_TRACE_LEVEL)
– CONFIG_BTIF_TRACE_LEVEL_NONE
– CONFIG_BTIF_TRACE_LEVEL_ERROR
– CONFIG_BTIF_TRACE_LEVEL_WARNING
– CONFIG_BTIF_TRACE_LEVEL_API
– CONFIG_BTIF_TRACE_LEVEL_EVENT
– CONFIG_BTIF_TRACE_LEVEL_DEBUG
– CONFIG_BTIF_TRACE_LEVEL_VERBOSE
• CONFIG_BTM_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_BTM_TRACE_LEVEL)
– CONFIG_BTM_TRACE_LEVEL_NONE
– CONFIG_BTM_TRACE_LEVEL_ERROR
– CONFIG_BTM_TRACE_LEVEL_WARNING
– CONFIG_BTM_TRACE_LEVEL_API
– CONFIG_BTM_TRACE_LEVEL_EVENT
– CONFIG_BTM_TRACE_LEVEL_DEBUG
– CONFIG_BTM_TRACE_LEVEL_VERBOSE
• CONFIG_BTU_TASK_STACK_SIZE (CONFIG_BT_BTU_TASK_STACK_SIZE)
• CONFIG_BT_NIMBLE_MSYS1_BLOCK_COUNT (CONFIG_BT_NIMBLE_MSYS_1_BLOCK_COUNT)
• CONFIG_BT_NIMBLE_TASK_STACK_SIZE (CONFIG_BT_NIMBLE_HOST_TASK_STACK_SIZE)
• CONFIG_CLASSIC_BT_ENABLED (CONFIG_BT_CLASSIC_ENABLED)
• CONFIG_CONSOLE_UART (CONFIG_ESP_CONSOLE_UART)
– CONFIG_CONSOLE_UART_DEFAULT
– CONFIG_CONSOLE_UART_CUSTOM
– CONFIG_CONSOLE_UART_NONE, CONFIG_ESP_CONSOLE_UART_NONE
• CONFIG_CONSOLE_UART_BAUDRATE (CONFIG_ESP_CONSOLE_UART_BAUDRATE)
• CONFIG_CONSOLE_UART_NUM (CONFIG_ESP_CONSOLE_UART_NUM)
– CONFIG_CONSOLE_UART_CUSTOM_NUM_0
– CONFIG_CONSOLE_UART_CUSTOM_NUM_1
• CONFIG_CONSOLE_UART_RX_GPIO (CONFIG_ESP_CONSOLE_UART_RX_GPIO)
• CONFIG_CONSOLE_UART_TX_GPIO (CONFIG_ESP_CONSOLE_UART_TX_GPIO)
• CONFIG_CXX_EXCEPTIONS (CONFIG_COMPILER_CXX_EXCEPTIONS)
• CONFIG_CXX_EXCEPTIONS_EMG_POOL_SIZE (CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE)
• CONFIG_DUPLICATE_SCAN_CACHE_SIZE (CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE)
• CONFIG_EFUSE_SECURE_VERSION_EMULATE (CONFIG_BOOTLOADER_EFUSE_SECURE_VERSION_EMULATE)
• CONFIG_ENABLE_STATIC_TASK_CLEAN_UP_HOOK (CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP)
• CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TMO (CON-
FIG_APPTRACE_ONPANIC_HOST_FLUSH_TMO)
• CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX (CONFIG_APPTRACE_PENDING_DATA_SIZE_MAX)
• CONFIG_ESP32_APPTRACE_POSTMORTEM_FLUSH_TRAX_THRESH (CON-
FIG_APPTRACE_POSTMORTEM_FLUSH_THRESH)
• CONFIG_ESP32_COMPATIBLE_PRE_V2_1_BOOTLOADERS (CON-
FIG_APP_COMPATIBLE_PRE_V2_1_BOOTLOADERS)
• CONFIG_ESP32_COMPATIBLE_PRE_V3_1_BOOTLOADERS (CON-
FIG_APP_COMPATIBLE_PRE_V3_1_BOOTLOADERS)
• CONFIG_ESP32_CORE_DUMP_DECODE (CONFIG_ESP_COREDUMP_DECODE)
– CONFIG_ESP32_CORE_DUMP_DECODE_INFO
– CONFIG_ESP32_CORE_DUMP_DECODE_DISABLE
• CONFIG_ESP32_CORE_DUMP_MAX_TASKS_NUM (CONFIG_ESP_COREDUMP_MAX_TASKS_NUM)
• CONFIG_ESP32_CORE_DUMP_STACK_SIZE (CONFIG_ESP_COREDUMP_STACK_SIZE)
• CONFIG_ESP32_CORE_DUMP_UART_DELAY (CONFIG_ESP_COREDUMP_UART_DELAY)
• CONFIG_ESP32_DEBUG_STUBS_ENABLE (CONFIG_ESP_DEBUG_STUBS_ENABLE)
• CONFIG_ESP32_GCOV_ENABLE (CONFIG_APPTRACE_GCOV_ENABLE)
• CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE (CON-
FIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE)
• CONFIG_ESP32_PHY_DEFAULT_INIT_IF_INVALID (CONFIG_ESP_PHY_DEFAULT_INIT_IF_INVALID)
• CONFIG_ESP32_PHY_INIT_DATA_ERROR (CONFIG_ESP_PHY_INIT_DATA_ERROR)
• CONFIG_ESP32_PHY_INIT_DATA_IN_PARTITION (CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION)
• CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER (CONFIG_ESP_PHY_MAX_WIFI_TX_POWER)
• CONFIG_ESP32_PTHREAD_STACK_MIN (CONFIG_PTHREAD_STACK_MIN)
• CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT (CONFIG_PTHREAD_TASK_CORE_DEFAULT)
– CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY
– CONFIG_ESP32_DEFAULT_PTHREAD_CORE_0
– CONFIG_ESP32_DEFAULT_PTHREAD_CORE_1
• CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT (CONFIG_PTHREAD_TASK_NAME_DEFAULT)
• CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT (CONFIG_PTHREAD_TASK_PRIO_DEFAULT)
• CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT (CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT)
• CONFIG_ESP32_REDUCE_PHY_TX_POWER (CONFIG_ESP_PHY_REDUCE_TX_POWER)
• CONFIG_ESP32_RTC_XTAL_BOOTSTRAP_CYCLES (CONFIG_ESP_SYSTEM_RTC_EXT_XTAL_BOOTSTRAP_CYCLES)
• CONFIG_ESP32_SUPPORT_MULTIPLE_PHY_INIT_DATA_BIN (CON-
FIG_ESP_PHY_MULTIPLE_INIT_DATA_BIN)
• CONFIG_ESP_GRATUITOUS_ARP (CONFIG_LWIP_ESP_GRATUITOUS_ARP)
• CONFIG_ESP_SYSTEM_PD_FLASH (CONFIG_ESP_SLEEP_POWER_DOWN_FLASH)
• CONFIG_EVENT_LOOP_PROFILING (CONFIG_ESP_EVENT_LOOP_PROFILING)
• CONFIG_FLASH_ENCRYPTION_ENABLED (CONFIG_SECURE_FLASH_ENC_ENABLED)
• CONFIG_FLASH_ENCRYPTION_UART_BOOTLOADER_ALLOW_CACHE (CON-
FIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_CACHE)
• CONFIG_FLASH_ENCRYPTION_UART_BOOTLOADER_ALLOW_DECRYPT (CON-
FIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_DEC)
• CONFIG_FLASH_ENCRYPTION_UART_BOOTLOADER_ALLOW_ENCRYPT (CON-
FIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_ENC)
• CONFIG_GAP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_GAP_TRACE_LEVEL)
– CONFIG_GAP_TRACE_LEVEL_NONE
– CONFIG_GAP_TRACE_LEVEL_ERROR
– CONFIG_GAP_TRACE_LEVEL_WARNING
– CONFIG_GAP_TRACE_LEVEL_API
– CONFIG_GAP_TRACE_LEVEL_EVENT
– CONFIG_GAP_TRACE_LEVEL_DEBUG
– CONFIG_GAP_TRACE_LEVEL_VERBOSE
• CONFIG_GARP_TMR_INTERVAL (CONFIG_LWIP_GARP_TMR_INTERVAL)
• CONFIG_GATTC_CACHE_NVS_FLASH (CONFIG_BT_GATTC_CACHE_NVS_FLASH)
• CONFIG_GATTC_ENABLE (CONFIG_BT_GATTC_ENABLE)
• CONFIG_GATTS_ENABLE (CONFIG_BT_GATTS_ENABLE)
• CONFIG_GATTS_SEND_SERVICE_CHANGE_MODE (CONFIG_BT_GATTS_SEND_SERVICE_CHANGE_MODE)
– CONFIG_GATTS_SEND_SERVICE_CHANGE_MANUAL
– CONFIG_GATTS_SEND_SERVICE_CHANGE_AUTO
• CONFIG_GATT_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_GATT_TRACE_LEVEL)
– CONFIG_GATT_TRACE_LEVEL_NONE
– CONFIG_GATT_TRACE_LEVEL_ERROR
– CONFIG_GATT_TRACE_LEVEL_WARNING
– CONFIG_GATT_TRACE_LEVEL_API
– CONFIG_GATT_TRACE_LEVEL_EVENT
– CONFIG_GATT_TRACE_LEVEL_DEBUG
– CONFIG_GATT_TRACE_LEVEL_VERBOSE
• CONFIG_GDBSTUB_MAX_TASKS (CONFIG_ESP_GDBSTUB_MAX_TASKS)
• CONFIG_GDBSTUB_SUPPORT_TASKS (CONFIG_ESP_GDBSTUB_SUPPORT_TASKS)
• CONFIG_HCI_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_HCI_TRACE_LEVEL)
– CONFIG_HCI_TRACE_LEVEL_NONE
– CONFIG_HCI_TRACE_LEVEL_ERROR
– CONFIG_HCI_TRACE_LEVEL_WARNING
– CONFIG_HCI_TRACE_LEVEL_API
– CONFIG_HCI_TRACE_LEVEL_EVENT
– CONFIG_HCI_TRACE_LEVEL_DEBUG
– CONFIG_HCI_TRACE_LEVEL_VERBOSE
• CONFIG_HFP_AUDIO_DATA_PATH (CONFIG_BT_HFP_AUDIO_DATA_PATH)
– CONFIG_HFP_AUDIO_DATA_PATH_PCM
– CONFIG_HFP_AUDIO_DATA_PATH_HCI
• CONFIG_HFP_ENABLE (CONFIG_BT_HFP_ENABLE)
• CONFIG_HFP_ROLE (CONFIG_BT_HFP_ROLE)
– CONFIG_HFP_CLIENT_ENABLE
– CONFIG_HFP_AG_ENABLE
• CONFIG_HID_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_HID_TRACE_LEVEL)
– CONFIG_HID_TRACE_LEVEL_NONE
– CONFIG_HID_TRACE_LEVEL_ERROR
– CONFIG_HID_TRACE_LEVEL_WARNING
– CONFIG_HID_TRACE_LEVEL_API
– CONFIG_HID_TRACE_LEVEL_EVENT
– CONFIG_HID_TRACE_LEVEL_DEBUG
– CONFIG_HID_TRACE_LEVEL_VERBOSE
• CONFIG_INT_WDT (CONFIG_ESP_INT_WDT)
• CONFIG_INT_WDT_CHECK_CPU1 (CONFIG_ESP_INT_WDT_CHECK_CPU1)
• CONFIG_INT_WDT_TIMEOUT_MS (CONFIG_ESP_INT_WDT_TIMEOUT_MS)
• CONFIG_IPC_TASK_STACK_SIZE (CONFIG_ESP_IPC_TASK_STACK_SIZE)
• CONFIG_L2CAP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_L2CAP_TRACE_LEVEL)
– CONFIG_L2CAP_TRACE_LEVEL_NONE
– CONFIG_L2CAP_TRACE_LEVEL_ERROR
– CONFIG_L2CAP_TRACE_LEVEL_WARNING
– CONFIG_L2CAP_TRACE_LEVEL_API
– CONFIG_L2CAP_TRACE_LEVEL_EVENT
– CONFIG_L2CAP_TRACE_LEVEL_DEBUG
– CONFIG_L2CAP_TRACE_LEVEL_VERBOSE
• CONFIG_L2_TO_L3_COPY (CONFIG_LWIP_L2_TO_L3_COPY)
• CONFIG_LOG_BOOTLOADER_LEVEL (CONFIG_BOOTLOADER_LOG_LEVEL)
– CONFIG_LOG_BOOTLOADER_LEVEL_NONE
– CONFIG_LOG_BOOTLOADER_LEVEL_ERROR
– CONFIG_LOG_BOOTLOADER_LEVEL_WARN
– CONFIG_LOG_BOOTLOADER_LEVEL_INFO
– CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG
– CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE
• CONFIG_MAIN_TASK_STACK_SIZE (CONFIG_ESP_MAIN_TASK_STACK_SIZE)
• CONFIG_MCA_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_MCA_TRACE_LEVEL)
– CONFIG_MCA_TRACE_LEVEL_NONE
– CONFIG_MCA_TRACE_LEVEL_ERROR
– CONFIG_MCA_TRACE_LEVEL_WARNING
– CONFIG_MCA_TRACE_LEVEL_API
– CONFIG_MCA_TRACE_LEVEL_EVENT
– CONFIG_MCA_TRACE_LEVEL_DEBUG
– CONFIG_MCA_TRACE_LEVEL_VERBOSE
• CONFIG_MCPWM_ISR_IN_IRAM (CONFIG_MCPWM_ISR_IRAM_SAFE)
• CONFIG_MESH_DUPLICATE_SCAN_CACHE_SIZE (CONFIG_BTDM_MESH_DUPL_SCAN_CACHE_SIZE)
• CONFIG_NIMBLE_ACL_BUF_COUNT (CONFIG_BT_NIMBLE_ACL_BUF_COUNT)
• CONFIG_NIMBLE_ACL_BUF_SIZE (CONFIG_BT_NIMBLE_ACL_BUF_SIZE)
• CONFIG_NIMBLE_ATT_PREFERRED_MTU (CONFIG_BT_NIMBLE_ATT_PREFERRED_MTU)
• CONFIG_NIMBLE_CRYPTO_STACK_MBEDTLS (CONFIG_BT_NIMBLE_CRYPTO_STACK_MBEDTLS)
• CONFIG_NIMBLE_DEBUG (CONFIG_BT_NIMBLE_DEBUG)
• CONFIG_NIMBLE_GAP_DEVICE_NAME_MAX_LEN (CONFIG_BT_NIMBLE_GAP_DEVICE_NAME_MAX_LEN)
• CONFIG_NIMBLE_HCI_EVT_BUF_SIZE (CONFIG_BT_NIMBLE_HCI_EVT_BUF_SIZE)
• CONFIG_NIMBLE_HCI_EVT_HI_BUF_COUNT (CONFIG_BT_NIMBLE_HCI_EVT_HI_BUF_COUNT)
• CONFIG_NIMBLE_HCI_EVT_LO_BUF_COUNT (CONFIG_BT_NIMBLE_HCI_EVT_LO_BUF_COUNT)
• CONFIG_NIMBLE_HS_FLOW_CTRL (CONFIG_BT_NIMBLE_HS_FLOW_CTRL)
• CONFIG_NIMBLE_HS_FLOW_CTRL_ITVL (CONFIG_BT_NIMBLE_HS_FLOW_CTRL_ITVL)
• CONFIG_NIMBLE_HS_FLOW_CTRL_THRESH (CONFIG_BT_NIMBLE_HS_FLOW_CTRL_THRESH)
• CONFIG_NIMBLE_HS_FLOW_CTRL_TX_ON_DISCONNECT (CON-
FIG_BT_NIMBLE_HS_FLOW_CTRL_TX_ON_DISCONNECT)
• CONFIG_NIMBLE_L2CAP_COC_MAX_NUM (CONFIG_BT_NIMBLE_L2CAP_COC_MAX_NUM)
• CONFIG_NIMBLE_MAX_BONDS (CONFIG_BT_NIMBLE_MAX_BONDS)
• CONFIG_NIMBLE_MAX_CCCDS (CONFIG_BT_NIMBLE_MAX_CCCDS)
• CONFIG_NIMBLE_MAX_CONNECTIONS (CONFIG_BT_NIMBLE_MAX_CONNECTIONS)
• CONFIG_NIMBLE_MEM_ALLOC_MODE (CONFIG_BT_NIMBLE_MEM_ALLOC_MODE)
– CONFIG_NIMBLE_MEM_ALLOC_MODE_INTERNAL
– CONFIG_NIMBLE_MEM_ALLOC_MODE_EXTERNAL
– CONFIG_NIMBLE_MEM_ALLOC_MODE_DEFAULT
• CONFIG_NIMBLE_MESH (CONFIG_BT_NIMBLE_MESH)
• CONFIG_NIMBLE_MESH_DEVICE_NAME (CONFIG_BT_NIMBLE_MESH_DEVICE_NAME)
• CONFIG_NIMBLE_MESH_FRIEND (CONFIG_BT_NIMBLE_MESH_FRIEND)
• CONFIG_NIMBLE_MESH_GATT_PROXY (CONFIG_BT_NIMBLE_MESH_GATT_PROXY)
• CONFIG_NIMBLE_MESH_LOW_POWER (CONFIG_BT_NIMBLE_MESH_LOW_POWER)
• CONFIG_NIMBLE_MESH_PB_ADV (CONFIG_BT_NIMBLE_MESH_PB_ADV)
• CONFIG_NIMBLE_MESH_PB_GATT (CONFIG_BT_NIMBLE_MESH_PB_GATT)
• CONFIG_NIMBLE_MESH_PROV (CONFIG_BT_NIMBLE_MESH_PROV)
• CONFIG_NIMBLE_MESH_PROXY (CONFIG_BT_NIMBLE_MESH_PROXY)
• CONFIG_NIMBLE_MESH_RELAY (CONFIG_BT_NIMBLE_MESH_RELAY)
• CONFIG_NIMBLE_NVS_PERSIST (CONFIG_BT_NIMBLE_NVS_PERSIST)
• CONFIG_NIMBLE_PINNED_TO_CORE_CHOICE (CONFIG_BT_NIMBLE_PINNED_TO_CORE_CHOICE)
– CONFIG_NIMBLE_PINNED_TO_CORE_0
– CONFIG_NIMBLE_PINNED_TO_CORE_1
• CONFIG_NIMBLE_ROLE_BROADCASTER (CONFIG_BT_NIMBLE_ROLE_BROADCASTER)
• CONFIG_NIMBLE_ROLE_CENTRAL (CONFIG_BT_NIMBLE_ROLE_CENTRAL)
• CONFIG_NIMBLE_ROLE_OBSERVER (CONFIG_BT_NIMBLE_ROLE_OBSERVER)
• CONFIG_NIMBLE_ROLE_PERIPHERAL (CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
• CONFIG_NIMBLE_RPA_TIMEOUT (CONFIG_BT_NIMBLE_RPA_TIMEOUT)
• CONFIG_NIMBLE_SM_LEGACY (CONFIG_BT_NIMBLE_SM_LEGACY)
• CONFIG_NIMBLE_SM_SC (CONFIG_BT_NIMBLE_SM_SC)
• CONFIG_NIMBLE_SM_SC_DEBUG_KEYS (CONFIG_BT_NIMBLE_SM_SC_DEBUG_KEYS)
• CONFIG_NIMBLE_SVC_GAP_APPEARANCE (CONFIG_BT_NIMBLE_SVC_GAP_APPEARANCE)
• CONFIG_NIMBLE_SVC_GAP_DEVICE_NAME (CONFIG_BT_NIMBLE_SVC_GAP_DEVICE_NAME)
• CONFIG_NIMBLE_TASK_STACK_SIZE (CONFIG_BT_NIMBLE_HOST_TASK_STACK_SIZE)
• CONFIG_NO_BLOBS (CONFIG_APP_NO_BLOBS)
• CONFIG_NUMBER_OF_UNIVERSAL_MAC_ADDRESS (CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES)
– CONFIG_TWO_UNIVERSAL_MAC_ADDRESS
– CONFIG_FOUR_UNIVERSAL_MAC_ADDRESS
• CONFIG_OPTIMIZATION_ASSERTION_LEVEL (CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL)
– CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED
– CONFIG_OPTIMIZATION_ASSERTIONS_SILENT
– CONFIG_OPTIMIZATION_ASSERTIONS_DISABLED
• CONFIG_OPTIMIZATION_COMPILER (CONFIG_COMPILER_OPTIMIZATION)
– CONFIG_OPTIMIZATION_LEVEL_DEBUG, CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG
– CONFIG_OPTIMIZATION_LEVEL_RELEASE, CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE
• CONFIG_OSI_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_OSI_TRACE_LEVEL)
– CONFIG_OSI_TRACE_LEVEL_NONE
– CONFIG_OSI_TRACE_LEVEL_ERROR
– CONFIG_OSI_TRACE_LEVEL_WARNING
– CONFIG_OSI_TRACE_LEVEL_API
– CONFIG_OSI_TRACE_LEVEL_EVENT
– CONFIG_OSI_TRACE_LEVEL_DEBUG
– CONFIG_OSI_TRACE_LEVEL_VERBOSE
• CONFIG_OTA_ALLOW_HTTP (CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP)
• CONFIG_PAN_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_PAN_TRACE_LEVEL)
– CONFIG_PAN_TRACE_LEVEL_NONE
– CONFIG_PAN_TRACE_LEVEL_ERROR
– CONFIG_PAN_TRACE_LEVEL_WARNING
– CONFIG_PAN_TRACE_LEVEL_API
– CONFIG_PAN_TRACE_LEVEL_EVENT
– CONFIG_PAN_TRACE_LEVEL_DEBUG
– CONFIG_PAN_TRACE_LEVEL_VERBOSE
• CONFIG_POST_EVENTS_FROM_IRAM_ISR (CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR)
• CONFIG_POST_EVENTS_FROM_ISR (CONFIG_ESP_EVENT_POST_FROM_ISR)
• CONFIG_PPP_CHAP_SUPPORT (CONFIG_LWIP_PPP_CHAP_SUPPORT)
• CONFIG_PPP_DEBUG_ON (CONFIG_LWIP_PPP_DEBUG_ON)
• CONFIG_PPP_MPPE_SUPPORT (CONFIG_LWIP_PPP_MPPE_SUPPORT)
• CONFIG_PPP_MSCHAP_SUPPORT (CONFIG_LWIP_PPP_MSCHAP_SUPPORT)
• CONFIG_PPP_NOTIFY_PHASE_SUPPORT (CONFIG_LWIP_PPP_NOTIFY_PHASE_SUPPORT)
• CONFIG_PPP_PAP_SUPPORT (CONFIG_LWIP_PPP_PAP_SUPPORT)
• CONFIG_PPP_SUPPORT (CONFIG_LWIP_PPP_SUPPORT)
• CONFIG_REDUCE_PHY_TX_POWER (CONFIG_ESP_PHY_REDUCE_TX_POWER)
• CONFIG_RFCOMM_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL)
– CONFIG_RFCOMM_TRACE_LEVEL_NONE
– CONFIG_RFCOMM_TRACE_LEVEL_ERROR
– CONFIG_RFCOMM_TRACE_LEVEL_WARNING
– CONFIG_RFCOMM_TRACE_LEVEL_API
– CONFIG_RFCOMM_TRACE_LEVEL_EVENT
– CONFIG_RFCOMM_TRACE_LEVEL_DEBUG
– CONFIG_RFCOMM_TRACE_LEVEL_VERBOSE
• CONFIG_SCAN_DUPLICATE_TYPE (CONFIG_BTDM_SCAN_DUPL_TYPE)
– CONFIG_SCAN_DUPLICATE_BY_DEVICE_ADDR
– CONFIG_SCAN_DUPLICATE_BY_ADV_DATA
– CONFIG_SCAN_DUPLICATE_BY_ADV_DATA_AND_DEVICE_ADDR
• CONFIG_SEMIHOSTFS_MAX_MOUNT_POINTS (CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS)
• CONFIG_SMP_INITIAL_TRACE_LEVEL (CONFIG_BT_LOG_SMP_TRACE_LEVEL)
– CONFIG_SMP_TRACE_LEVEL_NONE
– CONFIG_SMP_TRACE_LEVEL_ERROR
– CONFIG_SMP_TRACE_LEVEL_WARNING
– CONFIG_SMP_TRACE_LEVEL_API
– CONFIG_SMP_TRACE_LEVEL_EVENT
– CONFIG_SMP_TRACE_LEVEL_DEBUG
– CONFIG_SMP_TRACE_LEVEL_VERBOSE
• CONFIG_SMP_SLAVE_CON_PARAMS_UPD_ENABLE (CONFIG_BT_SMP_SLAVE_CON_PARAMS_UPD_ENABLE)
• CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS (CONFIG_SPI_FLASH_DANGEROUS_WRITE)
– CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS
– CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS
– CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED
• CONFIG_STACK_CHECK_MODE (CONFIG_COMPILER_STACK_CHECK_MODE)
– CONFIG_STACK_CHECK_NONE
– CONFIG_STACK_CHECK_NORM
– CONFIG_STACK_CHECK_STRONG
– CONFIG_STACK_CHECK_ALL
• CONFIG_SUPPORT_TERMIOS (CONFIG_VFS_SUPPORT_TERMIOS)
• CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT (CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT)
• CONFIG_SW_COEXIST_ENABLE (CONFIG_ESP32_WIFI_SW_COEXIST_ENABLE)
• CONFIG_SYSTEM_EVENT_QUEUE_SIZE (CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE)
• CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE (CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE)
• CONFIG_SYSVIEW_BUF_WAIT_TMO (CONFIG_APPTRACE_SV_BUF_WAIT_TMO)
• CONFIG_SYSVIEW_ENABLE (CONFIG_APPTRACE_SV_ENABLE)
• CONFIG_SYSVIEW_EVT_IDLE_ENABLE (CONFIG_APPTRACE_SV_EVT_IDLE_ENABLE)
• CONFIG_SYSVIEW_EVT_ISR_ENTER_ENABLE (CONFIG_APPTRACE_SV_EVT_ISR_ENTER_ENABLE)
• CONFIG_SYSVIEW_EVT_ISR_EXIT_ENABLE (CONFIG_APPTRACE_SV_EVT_ISR_EXIT_ENABLE)
• CONFIG_SYSVIEW_EVT_ISR_TO_SCHEDULER_ENABLE (CONFIG_APPTRACE_SV_EVT_ISR_TO_SCHED_ENABLE)
• CONFIG_SYSVIEW_EVT_OVERFLOW_ENABLE (CONFIG_APPTRACE_SV_EVT_OVERFLOW_ENABLE)
• CONFIG_SYSVIEW_EVT_TASK_CREATE_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_CREATE_ENABLE)
• CONFIG_SYSVIEW_EVT_TASK_START_EXEC_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_START_EXEC_ENABL
• CONFIG_SYSVIEW_EVT_TASK_START_READY_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_START_READY_ENA
• CONFIG_SYSVIEW_EVT_TASK_STOP_EXEC_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_STOP_EXEC_ENABLE)
• CONFIG_SYSVIEW_EVT_TASK_STOP_READY_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_STOP_READY_ENABL
• CONFIG_SYSVIEW_EVT_TASK_TERMINATE_ENABLE (CONFIG_APPTRACE_SV_EVT_TASK_TERMINATE_ENABLE)
• CONFIG_SYSVIEW_EVT_TIMER_ENTER_ENABLE (CONFIG_APPTRACE_SV_EVT_TIMER_ENTER_ENABLE)
• CONFIG_SYSVIEW_EVT_TIMER_EXIT_ENABLE (CONFIG_APPTRACE_SV_EVT_TIMER_EXIT_ENABLE)
• CONFIG_SYSVIEW_MAX_TASKS (CONFIG_APPTRACE_SV_MAX_TASKS)
• CONFIG_SYSVIEW_TS_SOURCE (CONFIG_APPTRACE_SV_TS_SOURCE)
– CONFIG_SYSVIEW_TS_SOURCE_CCOUNT
– CONFIG_SYSVIEW_TS_SOURCE_ESP_TIMER
• CONFIG_TASK_WDT (CONFIG_ESP_TASK_WDT)
• CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0 (CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0)
• CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1 (CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1)
• CONFIG_TASK_WDT_PANIC (CONFIG_ESP_TASK_WDT_PANIC)
• CONFIG_TASK_WDT_TIMEOUT_S (CONFIG_ESP_TASK_WDT_TIMEOUT_S)
• CONFIG_TCPIP_RECVMBOX_SIZE (CONFIG_LWIP_TCPIP_RECVMBOX_SIZE)
• CONFIG_TCPIP_TASK_AFFINITY (CONFIG_LWIP_TCPIP_TASK_AFFINITY)
– CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY
– CONFIG_TCPIP_TASK_AFFINITY_CPU0
– CONFIG_TCPIP_TASK_AFFINITY_CPU1
• CONFIG_TCPIP_TASK_STACK_SIZE (CONFIG_LWIP_TCPIP_TASK_STACK_SIZE)
• CONFIG_TCP_MAXRTX (CONFIG_LWIP_TCP_MAXRTX)
• CONFIG_TCP_MSL (CONFIG_LWIP_TCP_MSL)
• CONFIG_TCP_MSS (CONFIG_LWIP_TCP_MSS)
• CONFIG_TCP_OVERSIZE (CONFIG_LWIP_TCP_OVERSIZE)
– CONFIG_TCP_OVERSIZE_MSS
– CONFIG_TCP_OVERSIZE_QUARTER_MSS
– CONFIG_TCP_OVERSIZE_DISABLE
• CONFIG_TCP_QUEUE_OOSEQ (CONFIG_LWIP_TCP_QUEUE_OOSEQ)
• CONFIG_TCP_RECVMBOX_SIZE (CONFIG_LWIP_TCP_RECVMBOX_SIZE)
• CONFIG_TCP_SND_BUF_DEFAULT (CONFIG_LWIP_TCP_SND_BUF_DEFAULT)
• CONFIG_TCP_SYNMAXRTX (CONFIG_LWIP_TCP_SYNMAXRTX)
• CONFIG_TCP_WND_DEFAULT (CONFIG_LWIP_TCP_WND_DEFAULT)
• CONFIG_TIMER_QUEUE_LENGTH (CONFIG_FREERTOS_TIMER_QUEUE_LENGTH)
• CONFIG_TIMER_TASK_PRIORITY (CONFIG_FREERTOS_TIMER_TASK_PRIORITY)
• CONFIG_TIMER_TASK_STACK_DEPTH (CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH)
• CONFIG_TIMER_TASK_STACK_SIZE (CONFIG_ESP_TIMER_TASK_STACK_SIZE)
• CONFIG_UDP_RECVMBOX_SIZE (CONFIG_LWIP_UDP_RECVMBOX_SIZE)
• CONFIG_WARN_WRITE_STRINGS (CONFIG_COMPILER_WARN_WRITE_STRINGS)
Overview
Protocol Communication (protocomm) component manages secure sessions and provides framework for multiple
transports. The application can also use protocomm layer directly to have application specific extensions for the
provisioning (or non-provisioning) use cases.
Following features are available for provisioning :
• Communication security at application level -
– protocomm_security0 (no security)
– protocomm_security1 (Curve25519 key exchange + AES-CTR encryption/decryption)
Protocomm component provides project configuration menu to enable/disable support of respective security versions.
The respective configuration options can be found as follows:
• Support protocomm security version 0 (no security): CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0
(this option is enabled by default)
• Support protocomm security version 1 (Curve25519 key exchange + AES-CTR encryption/decryption): CON-
FIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1 (this option is enabled by default)
• Support protocomm security version 2 (SRP6a-based key exchange + AES-GCM encryption/decryption):
CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2
Note: Enabling multiple security versions allow to control them dynamically but also increases firmware size.
return ESP_OK;
}
static const char sec2_salt[] = {0xf7, 0x5f, 0xe2, 0xbe, 0xba, 0x7c, 0x81,
,→ 0xcd};
static const char sec2_verifier[] = {0xbf, 0x86, 0xce, 0x63, 0x8a, 0xbb,␣
,→0x7e, 0x2f, 0x38, 0xa8, 0x19, 0x1b, 0x35,
0x08, 0xef, 0xaf, 0xa5, 0x94, 0x4b, 0xcb, 0xe1, 0xce, 0x59, 0x2a,␣
,→0xe8, 0x7b, 0x27, 0xc8, 0x72, 0x26, 0x71, 0xde,
0xb2, 0xf2, 0x80, 0x02, 0xdd, 0x11, 0xf0, 0x38, 0x0e, 0x95, 0x25,␣
,→0x00, 0xcf, 0xb3, 0x3f, 0xf0, 0x73, 0x2a, 0x25,
0x03, 0xe8, 0x51, 0x72, 0xef, 0x6d, 0x3e, 0x14, 0xb9, 0x2e, 0x9f,␣
,→0x2a, 0x90, 0x9e, 0x26, 0xb6, 0x3e, 0xc7, 0xe4,
0x9f, 0xe3, 0x20, 0xce, 0x28, 0x7c, 0xbf, 0x89, 0x50, 0xc9, 0xb6,␣
,→0xec, 0xdd, 0x81, 0x18, 0xf1, 0x1a, 0xd9, 0x7a,
0x21, 0x99, 0xf1, 0xee, 0x71, 0x2f, 0xcc, 0x93, 0x16, 0x34, 0x0c,␣
,→0x79, 0x46, 0x23, 0xe4, 0x32, 0xec, 0x2d, 0x9e,
0x18, 0xa6, 0xb9, 0xbb, 0x0a, 0xcf, 0xc4, 0xa8, 0x32, 0xc0, 0x1c,␣
,→0x32, 0xa3, 0x97, 0x66, 0xf8, 0x30, 0xb2, 0xda,
0xf9, 0x8d, 0xc3, 0x72, 0x72, 0x5f, 0xe5, 0xee, 0xc3, 0x5c, 0x24,␣
,→0xc8, 0xdd, 0x54, 0x49, 0xfc, 0x12, 0x91, 0x81,
0x9c, 0xc3, 0xac, 0x64, 0x5e, 0xd6, 0x41, 0x88, 0x2f, 0x23, 0x66,␣
,→0xc8, 0xac, 0xb0, 0x35, 0x0b, 0xf6, 0x9c, 0x88,
0x6f, 0xac, 0xe1, 0xf4, 0xca, 0xc9, 0x07, 0x04, 0x11, 0xda, 0x90,␣
,→0x42, 0xa9, 0xf1, 0x97, 0x3d, 0x94, 0x65, 0xe4,
0xfb, 0x52, 0x22, 0x3b, 0x7a, 0x7b, 0x9e, 0xe9, 0xee, 0x1c, 0x44,␣
,→0xd0, 0x73, 0x72, 0x2a, 0xca, 0x85, 0x19, 0x4a,
0x60, 0xce, 0x0a, 0xc8, 0x7d, 0x57, 0xa4, 0xf8, 0x77, 0x22, 0xc1,␣
,→0xa5, 0xfa, 0xfb, 0x7b, 0x91, 0x3b, 0xfe, 0x87,
0x5f, 0xfe, 0x05, 0xd2, 0xd6, 0xd3, 0x74, 0xe5, 0x2e, 0x68, 0x79,␣
,→0x34, 0x70, 0x40, 0x12, 0xa8, 0xe1, 0xb4, 0x6c,
0xaa, 0x46, 0x73, 0xcd, 0x8d, 0x17, 0x72, 0x67, 0x32, 0x42, 0xdc,␣
,→0x10, 0xd3, 0x71, 0x7e, 0x8b, 0x00, 0x46, 0x9b,
0x0a, 0xe9, 0xb4, 0x0f, 0xeb, 0x70, 0x52, 0xdd, 0x0a, 0x1c, 0x7e,␣
,→0x2e, 0xb0, 0x61, 0xa6, 0xe1, 0xa3, 0x34, 0x4b,
0x2a, 0x3c, 0xc4, 0x5d, 0x42, 0x05, 0x58, 0x25, 0xd3, 0xca, 0x96,␣
,→0x5c, 0xb9, 0x52, 0xf9, 0xe9, 0x80, 0x75, 0x3d,
0xc8, 0x9f, 0xc7, 0xb2, 0xaa, 0x95, 0x2e, 0x76, 0xb3, 0xe1, 0x48,␣
,→0xc1, 0x0a, 0xa1, 0x0a, 0xe8, 0xaf, 0x41, 0x28,
0xd2, 0x16, 0xe1, 0xa6, 0xd0, 0x73, 0x51, 0x73, 0x79, 0x98, 0xd9,␣
,→0xb9, 0x00, 0x50, 0xa2, 0x4d, 0x99, 0x18, 0x90,
0x70, 0x27, 0xe7, 0x8d, 0x56, 0x45, 0x34, 0x1f, 0xb9, 0x30, 0xda,␣
,→0xec, 0x4a, 0x08, 0x27, 0x9f, 0xfa, 0x59, 0x2e,
0x36, 0x77, 0x00, 0xe2, 0xb6, 0xeb, 0xd1, 0x56, 0x50, 0x8e};
/* Create Security2 params object from salt and verifier. It must be␣
,→valid
* throughout the scope of protocomm endpoint. This need not be␣
,→static,
return ESP_OK;
}
* removal */
const static protocomm_security1_params_t sec1_params = {
.data = (const uint8_t *) strdup(pop_string),
.len = strlen(pop_string)
};
/* Endpoint UUIDs */
protocomm_ble_name_uuid_t nu_lookup_table[] = {
{"security_endpoint", 0xFF51},
{"echo_req_endpoint", 0xFF52}
};
.nu_lookup = nu_lookup_table
};
return pc;
}
protocomm_delete(pc);
}
API Reference
Header File
• components/protocomm/include/common/protocomm.h
Functions
protocomm_t *protocomm_new(void)
Create a new protocomm instance.
This API will return a new dynamically allocated protocomm instance with all elements of the protocomm_t
structure initialized to NULL.
Returns
• protocomm_t* : On success
• NULL : No memory for allocating new instance
void protocomm_delete(protocomm_t *pc)
Delete a protocomm instance.
This API will deallocate a protocomm instance that was created using protocomm_new().
Parameters pc –[in] Pointer to the protocomm instance to be deleted
esp_err_t protocomm_add_endpoint(protocomm_t *pc, const char *ep_name, protocomm_req_handler_t h,
void *priv_data)
Add endpoint request handler for a protocomm instance.
This API will bind an endpoint handler function to the specified endpoint name, along with any private data
that needs to be pass to the handler at the time of call.
Note:
• An endpoint must be bound to a valid protocomm instance, created using protocomm_new().
• This function internally calls the registered add_endpoint() function of the selected transport which
is a member of the protocomm_t instance structure.
Parameters
• pc –[in] Pointer to the protocomm instance
• ep_name –[in] Endpoint identifier(name) string
• h –[in] Endpoint handler function
• priv_data –[in] Pointer to private data to be passed as a parameter to the handler
function on call. Pass NULL if not needed.
Returns
• ESP_OK : Success
• ESP_FAIL : Error adding endpoint / Endpoint with this name already exists
• ESP_ERR_NO_MEM : Error allocating endpoint resource
• ESP_ERR_INVALID_ARG : Null instance/name/handler arguments
Note:
• This function internally calls the registered remove_endpoint() function which is a member of the
protocomm_t instance structure.
Parameters
• pc –[in] Pointer to the protocomm instance
• ep_name –[in] Endpoint identifier(name) string
Returns
• ESP_OK : Success
• ESP_ERR_NOT_FOUND : Endpoint with specified name doesn’t exist
• ESP_ERR_INVALID_ARG : Null instance/name arguments
Note:
• An endpoint must be bound to a valid protocomm instance, created using protocomm_new().
Parameters
• pc –[in] Pointer to the protocomm instance
• session_id –[in] Unique ID for a communication session
Returns
• ESP_OK : Request handled successfully
• ESP_ERR_NO_MEM : Error allocating internal resource
• ESP_ERR_INVALID_ARG : Null instance/name arguments
Note:
• An endpoint must be bound to a valid protocomm instance, created using protocomm_new().
Parameters
• pc –[in] Pointer to the protocomm instance
• session_id –[in] Unique ID for a communication session
Returns
• ESP_OK : Request handled successfully
• ESP_ERR_INVALID_ARG : Null instance/name arguments
Note:
• An endpoint must be bound to a valid protocomm instance, created using protocomm_new().
• Resulting output buffer must be deallocated by the caller.
Parameters
• pc –[in] Pointer to the protocomm instance
• ep_name –[in] Endpoint identifier(name) string
• session_id –[in] Unique ID for a communication session
• inbuf –[in] Input buffer contains input request data which is to be processed by the
registered handler
• inlen –[in] Length of the input buffer
• outbuf –[out] Pointer to internally allocated output buffer, where the resulting response
data output from the registered handler is to be stored
• outlen –[out] Buffer length of the allocated output buffer
Returns
• ESP_OK : Request handled successfully
• ESP_FAIL : Internal error in execution of registered handler
• ESP_ERR_NO_MEM : Error allocating internal resource
• ESP_ERR_NOT_FOUND : Endpoint with specified name doesn’t exist
• ESP_ERR_INVALID_ARG : Null instance/name arguments
Note:
• An endpoint must be bound to a valid protocomm instance, created using protocomm_new().
• The choice of security can be any protocomm_security_t instance. Choices proto-
comm_security0 and protocomm_security1 and protocomm_security2 are readily
available.
Parameters
• pc –[in] Pointer to the protocomm instance
• ep_name –[in] Endpoint identifier(name) string
• sec –[in] Pointer to endpoint security instance
• sec_params –[in] Pointer to security params (NULL if not needed) The pointer
should contain the security params struct of appropriate security version. For proto-
comm security version 1 and 2 sec_params should contain pointer to struct of type proto-
comm_security1_params_t and protocmm_security2_params_t respectively.
Returns
• ESP_OK : Success
• ESP_FAIL : Error adding endpoint / Endpoint with this name already exists
• ESP_ERR_INVALID_STATE : Security endpoint already set
Note:
• An endpoint must be bound to a valid protocomm instance, created using protocomm_new().
Parameters
• pc –[in] Pointer to the protocomm instance
• ep_name –[in] Endpoint identifier(name) string
• version –[in] Version identifier(name) string
Returns
• ESP_OK : Success
• ESP_FAIL : Error adding endpoint / Endpoint with this name already exists
• ESP_ERR_INVALID_STATE : Version endpoint already set
• ESP_ERR_NO_MEM : Error allocating endpoint resource
• ESP_ERR_INVALID_ARG : Null instance/name/handler arguments
Type Definitions
typedef esp_err_t (*protocomm_req_handler_t)(uint32_t session_id, const uint8_t *inbuf, ssize_t inlen,
uint8_t **outbuf, ssize_t *outlen, void *priv_data)
Function prototype for protocomm endpoint handler.
Header File
• components/protocomm/include/security/protocomm_security.h
Structures
struct protocomm_security1_params
Protocomm Security 1 parameters: Proof Of Possession.
Public Members
uint16_t len
Length (in bytes) of the proof of possession data
struct protocomm_security2_params
Protocomm Security 2 parameters: Salt and Verifier.
Public Members
uint16_t salt_len
Length (in bytes) of the salt
uint16_t verifier_len
Length (in bytes) of the verifier
struct protocomm_security
Protocomm security object structure.
The member functions are used for implementing secure protocomm sessions.
Note: This structure should not have any dynamic members to allow re-entrancy
Public Members
int ver
Unique version number of security implementation
Type Definitions
Note: This structure should not have any dynamic members to allow re-entrancy
Header File
• components/protocomm/include/security/protocomm_security0.h
Header File
• components/protocomm/include/security/protocomm_security1.h
Header File
• components/protocomm/include/transports/protocomm_httpd.h
Functions
esp_err_t protocomm_httpd_start(protocomm_t *pc, const protocomm_httpd_config_t *config)
Start HTTPD protocomm transport.
This API internally creates a framework to allow endpoint registration and security configuration for the pro-
tocomm.
Note: This is a singleton. ie. Protocomm can have multiple instances, but only one instance can be bound to
an HTTP transport layer.
Parameters
• pc –[in] Protocomm instance pointer obtained from protocomm_new()
• config –[in] Pointer to config structure for initializing HTTP server
Returns
• ESP_OK : Success
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_NOT_SUPPORTED : Transport layer bound to another protocomm instance
• ESP_ERR_INVALID_STATE : Transport layer already bound to this protocomm in-
stance
• ESP_ERR_NO_MEM : Memory allocation for server resource failed
• ESP_ERR_HTTPD_* : HTTP server error on start
esp_err_t protocomm_httpd_stop(protocomm_t *pc)
Stop HTTPD protocomm transport.
This API cleans up the HTTPD transport protocomm and frees all the handlers registered with the protocomm.
Parameters pc –[in] Same protocomm instance that was passed to protocomm_httpd_start()
Returns
• ESP_OK : Success
• ESP_ERR_INVALID_ARG : Null / incorrect protocomm instance pointer
Unions
union protocomm_httpd_config_data_t
#include <protocomm_httpd.h> Protocomm HTTPD Configuration Data
Public Members
void *handle
HTTP Server Handle, if ext_handle_provided is set to true
protocomm_http_server_config_t config
HTTP Server Configuration, if a server is not already active
Structures
struct protocomm_http_server_config_t
Config parameters for protocomm HTTP server.
Public Members
uint16_t port
Port on which the HTTP server will listen
size_t stack_size
Stack size of server task, adjusted depending upon stack usage of endpoint handler
unsigned task_priority
Priority of server task
struct protocomm_httpd_config_t
Config parameters for protocomm HTTP server.
Public Members
bool ext_handle_provided
Flag to indicate of an external HTTP Server Handle has been provided. In such as case, protocomm will
use the same HTTP Server and not start a new one internally.
protocomm_httpd_config_data_t data
Protocomm HTTPD Configuration Data
Macros
PROTOCOMM_HTTPD_DEFAULT_CONFIG()
Header File
• components/protocomm/include/transports/protocomm_ble.h
Functions
esp_err_t protocomm_ble_start(protocomm_t *pc, const protocomm_ble_config_t *config)
Start Bluetooth Low Energy based transport layer for provisioning.
Initialize and start required BLE service for provisioning. This includes the initialization for characteris-
tics/service for BLE.
Parameters
• pc –[in] Protocomm instance pointer obtained from protocomm_new()
• config –[in] Pointer to config structure for initializing BLE
Returns
• ESP_OK : Success
• ESP_FAIL : Simple BLE start error
• ESP_ERR_NO_MEM : Error allocating memory for internal resources
• ESP_ERR_INVALID_STATE : Error in ble config
• ESP_ERR_INVALID_ARG : Null arguments
Note: You might want to optionally reclaim memory from Bluetooth. Refer to the documentation of
esp_bt_mem_release in that case.
Structures
struct name_uuid
This structure maps handler required by protocomm layer to UUIDs which are used to uniquely identify BLE
characteristics from a smartphone or a similar client device.
Public Members
uint16_t uuid
UUID to be assigned to the BLE characteristic which is mapped to the handler
struct protocomm_ble_config
Config parameters for protocomm BLE service.
Public Members
char device_name[MAX_BLE_DEVNAME_LEN]
BLE device name being broadcast at the time of provisioning
uint8_t service_uuid[BLE_UUID128_VAL_LENGTH]
128 bit UUID of the provisioning service
uint8_t *manufacturer_data
BLE device manufacturer data pointer in advertisement
ssize_t manufacturer_data_len
BLE device manufacturer data length in advertisement
ssize_t nu_lookup_count
Number of entries in the Name-UUID lookup table
protocomm_ble_name_uuid_t *nu_lookup
Pointer to the Name-UUID lookup table
unsigned ble_bonding
BLE bonding
unsigned ble_sm_sc
BLE security flag
Macros
MAX_BLE_DEVNAME_LEN
BLE device name cannot be larger than this value 31 bytes (max scan response size) - 1 byte (length) - 1 byte
(type) = 29 bytes
BLE_UUID128_VAL_LENGTH
MAX_BLE_MANUFACTURER_DATA_LEN
Theoretically, the limit for max manufacturer length remains same as BLE device name i.e. 31 bytes (max
scan response size) - 1 byte (length) - 1 byte (type) = 29 bytes However, manufacturer data goes along with
BLE device name in scan response. So, it is important to understand the actual length should be smaller than
(29 - (BLE device name length) - 2).
Type Definitions
Overview
Unified provisioning support in the ESP-IDF provides an extensible mechanism to the developers to configure the
device with the Wi-Fi credentials and/or other custom configuration using various transports and different security
schemes. Depending on the use-case it provides a complete and ready solution for Wi-Fi network provisioning
along with example iOS and Android applications. Or developers can extend the device-side and phone-app side
implementations to accommodate their requirements for sending additional configuration data. Following are the
important features of this implementation.
1. Extensible Protocol: The protocol is completely flexible and it offers the ability for the developers to send custom
configuration in the provisioning process. The data representation too is left to the application to decide.
2. Transport Flexibility: The protocol can work on Wi-Fi (SoftAP + HTTP server) or on BLE as a transport
protocol. The framework provides an ability to add support for any other transport easily as long as command-
response behaviour can be supported on the transport.
3. Security Scheme Flexibility: It’s understood that each use-case may require different security scheme to secure
the data that is exchanged in the provisioning process. Some applications may work with SoftAP that’s WPA2
protected or BLE with “just-works”security. Or the applications may consider the transport to be insecure
and may want application level security. The unified provisioning framework allows application to choose the
security as deemed suitable.
4. Compact Data Representation: The protocol uses Google Protobufs as a data representation for session setup
and Wi-Fi provisioning. They provide a compact data representation and ability to parse the data in multiple
programming languages in native format. Please note that this data representation is not forced on application
specific data and the developers may choose the representation of their choice.
Deciding on Transport
Unified provisioning subsystem supports Wi-Fi (SoftAP+HTTP server) and BLE (GATT based) transport schemes.
Following points need to be considered while selecting the best possible transport for provisioning.
1. BLE based transport has an advantage that in the provisioning process, the BLE communication channel stays
intact between the device and the client. That provides reliable provisioning feedback.
2. BLE based provisioning implementation makes the user-experience better from the phone apps as on Android
and iOS both, the phone app can discover and connect to the device without requiring user to go out of the
phone app
3. BLE transport however consumes ~110KB memory at runtime. If the product does not use the BLE or BT
functionality after provisioning is done, almost all the memory can be reclaimed back and can be added into
the heap.
4. SoftAP based transport is highly interoperable; however as the same radio is shared between SoftAP and Station
interface, the transport is not reliable in the phase when the Wi-Fi connection to external AP is attempted. Also,
the client may roam back to different network when the SoftAP changes the channel at the time of Station
connection.
5. SoftAP transport does not require much additional memory for the Wi-Fi use-cases
6. SoftAP based provisioning requires the phone app user to go to“System Settings”to connect to Wi-Fi network
hosted by the device in case of iOS. The discovery (scanning) as well as connection API is not available for
the iOS applications.
Deciding on Security
Depending on the transport and other constraints the security scheme needs to be selected by the application devel-
opers. Following considerations need to be given from the provisioning security perspective: 1. The configuration
data sent from the client to the device and the response has to be secured. 2. The client should authenticate the device
it is connected to. 3. The device manufacturer may choose proof-of-possession - a unique per device secret to be
entered on the provisioning client as a security measure to make sure that the user can provisions the device in the
possession.
There are two levels of security schemes. The developer may select one or combination depending on requirements.
1. Transport Security: SoftAP provisioning may choose WPA2 protected security with unique per-device
passphrase. Per-device unique passphrase can also act as a proof-of-possession. For BLE, “just-works”
security can be used as a transport level security after understanding the level of security it provides.
2. Application Security: The unified provisioning subsystem provides application level security (security1) that
provides data protection and authentication (through proof-of-possession) if the application does not use the
transport level security or if the transport level security is not sufficient for the use-case.
Device Discovery
The advertisement and device discovery is left to the application and depending on the protocol chosen, the phone
apps and device firmware application can choose appropriate method to advertise and discovery.
For the SoftAP+HTTP transport, typically the SSID (network name) of the AP hosted by the device can be used for
discovery.
For the BLE transport device name or primary service included in the advertisement or combination of both can be
used for discovery.
Architecture
It relies on the base layer called Protocol Communication (Protocol Communication) which provides a framework
for security schemes and transport mechanisms. Wi-Fi Provisioning layer uses Protocomm to provide simple call-
backs to the application for setting the configuration and getting the Wi-Fi status. The application has control over
implementation of these callbacks. In addition application can directly use protocomm to register custom handlers.
Application creates a protocomm instance which is mapped to a specific transport and specific security scheme. Each
transport in the protocomm has a concept of an“end-point”which corresponds to logical channel for communication
for specific type of information. For example security handshake happens on a different endpoint than the Wi-Fi
configuration endpoint. Each end-point is identified using a string and depending on the transport internal represen-
tation of the end-point changes. In case of SoftAP+HTTP transport the end-point corresponds to URI whereas in
case of BLE the end-point corresponds to GATT characteristic with specific UUID. Developers can create custom
end-points and implement handler for the data that is received or sent over the same end-point.
Security Schemes
a. Authorized - Proof of Possession (PoP) string used to authorize session and derive shared key
b. No Auth (Null PoP) - Shared key derived through key exchange only
3. Security2 - SRP6a-based shared key derivation and AES256-GCM mode encryption of the data.
Note: The respective security schemes need to be enabled through the project configuration menu. Please refer
to the Enabling protocom security version section in Protocol Communication (Protocol Communication) for more
details.
Security1 Scheme
Note: We shall soon migrate to Security2 scheme as the default scheme in our examples as it provides
enhanced security. This change shall be done once we have our phone apps (Android/iOS) upgraded to handle
Security2 scheme.
Security2 Scheme
Security2 scheme is based on the Secure Remote Password (SRP6a) protocol - RFC 5054. The protocol requires the
Salt and Verifier to be generated beforehand with help of the identifying username I and the plaintext password p.
The Salt and Verifier are then stored on ESP32. - The password p and username I are to be provided to the Phone
App (Provisioning entity) by suitable means for example QR code sticker.
Security2 scheme details are shown in the below sequence diagram -
Sample Code
Please refer to Protocol Communication and Wi-Fi Provisioning for API guides and code snippets on example usage.
Application implementation can be found as an example under provisioning.
Provisioning Tools
Provisioning applications are available for various platforms, along with source code:
• Android:
– BLE Provisioning app on Play Store.
– SoftAP Provisioning app on Play Store.
– Source code on GitHub: esp-idf-provisioning-android.
• iOS:
– BLE Provisioning app on app store.
– SoftAP Provisioning app on app Store.
– Source code on GitHub: esp-idf-provisioning-ios.
• Linux/MacOS/Windows : tools/esp_prov (a python based command line tool for provisioning)
The phone applications offer simple UI and thus more user centric, while the command line application is useful as
a debugging tool for developers.
Overview
This component provides APIs that control Wi-Fi provisioning service for receiving and configuring Wi-Fi cre-
dentials over SoftAP or BLE transport via secure Protocol Communication (protocomm) sessions. The set of
wifi_prov_mgr_ APIs help in quickly implementing a provisioning service having necessary features with min-
imal amount of code and sufficient flexibility.
Initialization wifi_prov_mgr_init() is called to configure and initialize the provisioning manager and thus
this must be called prior to invoking any other wifi_prov_mgr_ APIs. Note that the manager relies on other com-
ponents of IDF, namely NVS, TCP/IP, Event Loop and Wi-Fi (and optionally mDNS), hence these must be initialized
beforehand. The manager can be de-initialized at any moment by making a call to wifi_prov_mgr_deinit().
wifi_prov_mgr_config_t config = {
.scheme = wifi_prov_scheme_ble,
.scheme_event_handler = WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM
};
ESP_ERROR_CHECK( wifi_prov_mgr_init(config) );
The configuration structure wifi_prov_mgr_config_t has a few fields to specify the behavior desired of the
manager :
• scheme : This is used to specify the provisioning scheme. Each scheme corresponds to one of the
modes of transport supported by protocomm. Hence, we have three options :
– wifi_prov_scheme_ble : BLE transport and GATT Server for handling provisioning
commands
– wifi_prov_scheme_softap : Wi-Fi SoftAP transport and HTTP Server for handling
provisioning commands
– wifi_prov_scheme_console : Serial transport and console for handling provisioning
commands
• scheme_event_handler : An event handler defined along with scheme. Choosing appropriate
scheme specific event handler allows the manager to take care of certain matters automatically.
Presently this is not used for either SoftAP or Console based provisioning, but is very convenient
for BLE. To understand how, we must recall that Bluetooth requires quite some amount of memory
to function and once provisioning is finished, the main application may want to reclaim back this
memory (or part of it, if it needs to use either BLE or classic BT). Also, upon every future re-
boot of a provisioned device, this reclamation of memory needs to be performed again. To reduce
this complication in using wifi_prov_scheme_ble, the scheme specific handlers have been
defined, and depending upon the chosen handler, the BLE / classic BT / BTDM memory will be
freed automatically when the provisioning manager is de-initialized. The available options are:
– WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM - Free both classic BT
and BLE (BTDM) memory. Used when main application doesn’t require Bluetooth at all.
– WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BLE - Free only BLE memory.
Used when main application requires classic BT.
– WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BT - Free only classic BT. Used
when main application requires BLE. In this case freeing happens right when the manager is
initialized.
– WIFI_PROV_EVENT_HANDLER_NONE - Don’t use any scheme specific handler. Used
when provisioning scheme is not BLE (i.e. SoftAP or Console), or when main application
wants to handle the memory reclaiming on its own, or needs both BLE and classic BT to
function.
• app_event_handler (Deprecated) : It is now recommended to catch WIFI_PROV_EVENT``s
that are emitted to the default event loop handler. See definition
of ``wifi_prov_cb_event_t for the list of events that are generated by the provisioning
service. Here is an excerpt showing some of the provisioning events:
static void event_handler(void* arg, esp_event_base_t event_base,
int event_id, void* event_data)
{
if (event_base == WIFI_PROV_EVENT) {
switch (event_id) {
case WIFI_PROV_START:
ESP_LOGI(TAG, "Provisioning started");
break;
case WIFI_PROV_CRED_RECV: {
wifi_sta_config_t *wifi_sta_cfg = (wifi_sta_config_t␣
,→*)event_data;
(*reason == WIFI_PROV_STA_AUTH_ERROR) ?
"Wi-Fi station authentication failed" : "Wi-Fi␣
,→access-point not found");
break;
}
case WIFI_PROV_CRED_SUCCESS:
ESP_LOGI(TAG, "Provisioning successful");
break;
case WIFI_PROV_END:
/* De-initialize manager once provisioning is finished */
wifi_prov_mgr_deinit();
break;
default:
break;
}
}
}
Check Provisioning State Whether device is provisioned or not can be checked at runtime by calling
wifi_prov_mgr_is_provisioned(). This internally checks if the Wi-Fi credentials are stored in NVS.
Note that presently manager does not have its own NVS namespace for storage of Wi-Fi credentials, instead it relies
on the esp_wifi_ APIs to set and get the credentials stored in NVS from the default location.
If provisioning state needs to be reset, any of the following approaches may be taken :
• the associated part of NVS partition has to be erased manually
• main application must implement some logic to call esp_wifi_ APIs for erasing the credentials
at runtime
• main application must implement some logic to force start the provisioning irrespective of the
provisioning state
Start Provisioning Service At the time of starting provisioning we need to specify a service name and the corre-
sponding key. These translate to :
• Wi-Fi SoftAP SSID and passphrase, respectively, when scheme is wifi_prov_scheme_softap
• BLE Device name (service key is ignored) when scheme is wifi_prov_scheme_ble
Also, since internally the manager uses protocomm, we have the option of choosing one of the security features
provided by it :
• Security 1 is secure communication which consists of a prior handshake involving X25519 key exchange along
with authentication using a proof of possession (pop), followed by AES-CTR for encryption/decryption of
subsequent messages
• Security 0 is simply plain text communication. In this case the pop is simply ignored
See Provisioning for details about the security features.
const char *service_name = "my_device";
const char *service_key = "password";
The provisioning service will automatically finish only if it receives valid Wi-Fi AP credentials followed by success-
fully connection of device to the AP (IP obtained). Regardless of that, the provisioning service can be stopped at any
moment by making a call to wifi_prov_mgr_stop_provisioning().
Note: If the device fails to connect with the provided credentials, it won’t accept new credentials anymore, but
the provisioning service will keep on running (only to convey failure to the client), until the device is restarted. Upon
restart the provisioning state will turn out to be true this time (as credentials will be found in NVS), but device will
again fail to connect with those same credentials (unless an AP with the matching credentials somehow does become
available). This situation can be fixed by resetting the credentials in NVS or force starting the provisioning service.
This has been explained above in Check Provisioning State.
Waiting For Completion Typically, the main application will wait for the provisioning to finish, then de-initialize
the manager to free up resources and finally start executing its own logic.
There are two ways for making this possible. The simpler way is to use a blocking call to
wifi_prov_mgr_wait().
// Start provisioning service
ESP_ERROR_CHECK( wifi_prov_mgr_start_provisioning(security, pop, service_
,→name, service_key) );
The other way is to use the default event loop handler to catch WIFI_PROV_EVENT``s and call
:cpp:func:`wifi_prov_mgr_deinit()` when event ID is ``WIFI_PROV_END:
static void event_handler(void* arg, esp_event_base_t event_base,
int event_id, void* event_data)
{
if (event_base == WIFI_PROV_EVENT && event_id == WIFI_PROV_END) {
/* De-initialize manager once provisioning is finished */
wifi_prov_mgr_deinit();
}
}
User Side Implementation When the service is started, the device to be provisioned is identified by the advertised
service name which, depending upon the selected transport, is either the BLE device name or the SoftAP SSID.
When using SoftAP transport, for allowing service discovery, mDNS must be initialized before starting provisioning.
In this case the hostname set by the main application is used, and the service type is internally set to _esp_wifi_prov.
When using BLE transport, a custom 128 bit UUID should be set using
wifi_prov_scheme_ble_set_service_uuid(). This UUID will be included in the BLE advertisement
and will correspond to the primary GATT service that provides provisioning endpoints as GATT characteristics.
Each GATT characteristic will be formed using the primary service UUID as base, with different auto assigned 12th
and 13th bytes (assume counting starts from 0th byte). Since, an endpoint characteristic UUID is auto assigned, it
shouldn’t be used to identify the endpoint. Instead, client side applications should identify the endpoints by reading
the User Characteristic Description (0x2901) descriptor for each characteristic, which contains the endpoint name
of the characteristic. For example, if the service UUID is set to 55cc035e-fb27-4f80-be02-3c60828b7451, each
endpoint characteristic will be assigned a UUID like 55cc____-fb27-4f80-be02-3c60828b7451, with unique values
at the 12th and 13th bytes.
Once connected to the device, the provisioning related protocomm endpoints can be identified as follows :
Immediately after connecting, the client application may fetch the version / capabilities information from the proto-ver
endpoint. All communications to this endpoint are un-encrypted, hence necessary information (that may be relevant
for deciding compatibility) can be retrieved before establishing a secure session. The response is in JSON format
and looks like : prov: { ver: v1.1, cap: [no_pop] }, my_app: { ver: 1.345,
cap: [cloud, local_ctrl] },..... Here label prov provides provisioning service version (ver) and
capabilities (cap). For now, only no_pop capability is supported, which indicates that the service doesn’t require
proof of possession for authentication. Any application related version / capabilities will be given by other labels (like
my_app in this example). These additional fields are set using wifi_prov_mgr_set_app_info().
User side applications need to implement the signature handshaking required for establishing and authenticating secure
protocomm sessions as per the security scheme configured for use (this is not needed when manager is configured to
use protocomm security 0).
See Unified Provisioning for more details about the secure handshake and encryption used. Applications must use the
.proto files found under protocomm/proto, which define the Protobuf message structures supported by prov-session
endpoint.
Once a session is established, Wi-Fi credentials are configured using the following set of wifi_config commands,
serialized as Protobuf messages (the corresponding .proto files can be found under wifi_provisioning/proto) :
• get_status - For querying the Wi-Fi connection status. The device will respond with a status which will be
one of connecting / connected / disconnected. If status is disconnected, a disconnection reason will also be
included in the status response.
• set_config - For setting the Wi-Fi connection credentials
• apply_config - For applying the credentials saved during set_config and start the Wi-Fi station
After session establishment, client can also request Wi-Fi scan results from the device. The results returned is a list
of AP SSIDs, sorted in descending order of signal strength. This allows client applications to display APs nearby
to the device at the time of provisioning, and users can select one of the SSIDs and provide the password which is
then sent using the wifi_config commands described above. The wifi_scan endpoint supports the following protobuf
commands :
• scan_start - For starting Wi-Fi scan with various options :
– blocking (input) - If true, the command returns only when the scanning is finished
– passive (input) - If true scan is started in passive mode (this may be slower) instead of active mode
– group_channels (input) - This specifies whether to scan all channels in one go (when zero) or perform
scanning of channels in groups, with 120ms delay between scanning of consecutive groups, and the value
of this parameter sets the number of channels in each group. This is useful when transport mode is
SoftAP, where scanning all channels in one go may not give the Wi-Fi driver enough time to send out
beacons, and hence may cause disconnection with any connected stations. When scanning in groups, the
manager will wait for atleast 120ms after completing scan on a group of channels, and thus allow the
driver to send out the beacons. For example, given that the total number of Wi-Fi channels is 14, then
setting group_channels to 4, will create 5 groups, with each group having 3 channels, except the last one
which will have 14 % 3 = 2 channels. So, when scan is started, the first 3 channels will be scanned,
followed by a 120ms delay, and then the next 3 channels, and so on, until all the 14 channels have been
scanned. One may need to adjust this parameter as having only few channels in a group may slow down
the overall scan time, while having too many may again cause disconnection. Usually a value of 4 should
work for most cases. Note that for any other mode of transport, e.g. BLE, this can be safely set to 0, and
hence achieve the fastest overall scanning time.
– period_ms (input) - Scan parameter specifying how long to wait on each channel
• scan_status - Gives the status of scanning process :
– scan_finished (output) - When scan has finished this returns true
– result_count (output) - This gives the total number of results obtained till now. If scan is yet happening
this number will keep on updating
• scan_result - For fetching scan results. This can be called even if scan is still on going
– start_index (input) - Starting index from where to fetch the entries from the results list
– count (input) - Number of entries to fetch from the starting index
– entries (output) - List of entries returned. Each entry consists of ssid, channel and rssi information
Additional Endpoints In case users want to have some additional protocomm endpoints customized to their re-
quirements, this is done in two steps. First is creation of an endpoint with a specific name, and the second step is
the registration of a handler for this endpoint. See protocomm for the function signature of an endpoint handler.
A custom endpoint must be created after initialization and before starting the provisioning service. Whereas, the
protocomm handler is registered for this endpoint only after starting the provisioning service.
wifi_prov_mgr_init(config);
wifi_prov_mgr_endpoint_create("custom-endpoint");
wifi_prov_mgr_start_provisioning(security, pop, service_name, service_
,→key);
wifi_prov_mgr_endpoint_register("custom-endpoint", custom_ep_handler,␣
,→custom_ep_data);
When / How To Stop Provisioning Service? The default behavior is that once the device successfully connects
using the Wi-Fi credentials set by the apply_config command, the provisioning service will be stopped (and BLE
/ SoftAP turned off) automatically after responding to the next get_status command. If get_status command is not
received by the device, the service will be stopped after a 30s timeout.
On the other hand, if device was not able to connect using the provided Wi-Fi credentials, due to incorrect SSID /
passphrase, the service will keep running, and get_status will keep responding with disconnected status and reason for
disconnection. Any further attempts to provide another set of Wi-Fi credentials, will be rejected. These credentials
will be preserved, unless the provisioning service is force started, or NVS erased.
If this default behavior is not desired, it can be disabled by calling wifi_prov_mgr_disable_auto_stop().
Now the provisioning service will only be stopped after an explicit call to
wifi_prov_mgr_stop_provisioning(), which returns immediately after scheduling a task for stopping
the service. The service stops after a certain delay and WIFI_PROV_END event gets emitted. This delay is specified
by the argument to wifi_prov_mgr_disable_auto_stop().
The customized behavior is useful for applications which want the provisioning service to be stopped some
time after the Wi-Fi connection is successfully established. For example, if the application requires the de-
vice to connect to some cloud service and obtain another set of credentials, and exchange this credentials
over a custom protocomm endpoint, then after successfully doing so stop the provisioning service by calling
wifi_prov_mgr_stop_provisioning() inside the protocomm handler itself. The right amount of de-
lay ensures that the transport resources are freed only after the response from the protocomm handler reaches the
client side application.
Application Examples
Provisioning Tools
Provisioning applications are available for various platforms, along with source code:
• Android:
– BLE Provisioning app on Play Store.
– SoftAP Provisioning app on Play Store.
– Source code on GitHub: esp-idf-provisioning-android.
• iOS:
– BLE Provisioning app on app store.
– SoftAP Provisioning app on app Store.
– Source code on GitHub: esp-idf-provisioning-ios.
• Linux/MacOS/Windows : tools/esp_prov (a python based command line tool for provisioning)
The phone applications offer simple UI and thus more user centric, while the command line application is useful as
a debugging tool for developers.
API Reference
Header File
• components/wifi_provisioning/include/wifi_provisioning/manager.h
Functions
esp_err_t wifi_prov_mgr_init(wifi_prov_mgr_config_t config)
Initialize provisioning manager instance.
Configures the manager and allocates internal resources
Configuration specifies the provisioning scheme (transport) and event handlers
Event WIFI_PROV_INIT is emitted right after initialization is complete
Parameters config –[in] Configuration structure
Returns
• ESP_OK : Success
• ESP_FAIL : Fail
void wifi_prov_mgr_deinit(void)
Stop provisioning (if running) and release resource used by the manager.
Event WIFI_PROV_DEINIT is emitted right after de-initialization is finished
If provisioning service is still active when this API is called, it first stops the service, hence emitting
WIFI_PROV_END, and then performs the de-initialization
Note: This API will start provisioning service even if device is found to be already provisioned, i.e.
wifi_prov_mgr_is_provisioned() yields true
Parameters
• security –[in] Specify which protocomm security scheme to use :
– WIFI_PROV_SECURITY_0 : For no security
– WIFI_PROV_SECURITY_1 : x25519 secure handshake for session establishment fol-
lowed by AES-CTR encryption of provisioning messages
– WIFI_PROV_SECURITY_2: SRP6a based authentication and key exchange followed
by AES-GCM encryption/decryption of provisioning messages
• wifi_prov_sec_params –[in] Pointer to security params (NULL if not
needed). This is not needed for protocomm security 0 This pointer should hold
the struct of type wifi_prov_security1_params_t for protocomm security 1 and
wifi_prov_security2_params_t for protocomm security 2 respectively.
• service_name –[in] Unique name of the service. This translates to:
– Wi-Fi SSID when provisioning mode is softAP
– Device name when provisioning mode is BLE
• service_key –[in] Key required by client to access the service (NULL if not needed).
This translates to:
– Wi-Fi password when provisioning mode is softAP
– ignored when provisioning mode is BLE
Returns
void wifi_prov_mgr_stop_provisioning(void)
Stop provisioning service.
If provisioning service is active, this API will initiate a process to stop the service and return. Once the service
actually stops, the event WIFI_PROV_END will be emitted.
If wifi_prov_mgr_deinit() is called without calling this API first, it will automatically stop the provisioning
service and emit the WIFI_PROV_END, followed by WIFI_PROV_DEINIT, before returning.
This API will generally be used along with wifi_prov_mgr_disable_auto_stop() in the scenario when the main
application has registered its own endpoints, and wishes that the provisioning service is stopped only when
some protocomm command from the client side application is received.
Calling this API inside an endpoint handler, with sufficient cleanup_delay, will allow the response / acknowl-
edgment to be sent successfully before the underlying protocomm service is stopped.
Cleaup_delay is set when calling wifi_prov_mgr_disable_auto_stop(). If not specified, it defaults to 1000ms.
For straightforward cases, using this API is usually not necessary as provisioning is stopped automatically once
WIFI_PROV_CRED_SUCCESS is emitted. Stopping is delayed (maximum 30 seconds) thus allowing the
client side application to query for Wi-Fi state, i.e. after receiving the first query and sending Wi-Fi state
connected response the service is stopped immediately.
void wifi_prov_mgr_wait(void)
Wait for provisioning service to finish.
Calling this API will block until provisioning service is stopped i.e. till event WIFI_PROV_END is emitted.
This will not block if provisioning is not started or not initialized.
esp_err_t wifi_prov_mgr_disable_auto_stop(uint32_t cleanup_delay)
Disable auto stopping of provisioning service upon completion.
By default, once provisioning is complete, the provisioning service is automatically stopped, and all endpoints
(along with those registered by main application) are deactivated.
This API is useful in the case when main application wishes to close provisioning service only after it receives
some protocomm command from the client side app. For example, after connecting to Wi-Fi, the device may
want to connect to the cloud, and only once that is successfully, the device is said to be fully configured. But,
then it is upto the main application to explicitly call wifi_prov_mgr_stop_provisioning() later when the device
is fully configured and the provisioning service is no longer required.
Parameters cleanup_delay –[in] Sets the delay after which the actual cleanup of transport
related resources is done after a call to wifi_prov_mgr_stop_provisioning() returns. Minimum
allowed value is 100ms. If not specified, this will default to 1000ms.
Returns
• ESP_OK : Success
• ESP_ERR_INVALID_STATE : Manager not initialized or provisioning service already
started
esp_err_t wifi_prov_mgr_set_app_info(const char *label, const char *version, const char **capabilities,
size_t total_capabilities)
Set application version and capabilities in the JSON data returned by proto-ver endpoint.
This function can be called multiple times, to specify information about the various application specific services
running on the device, identified by unique labels.
The provisioning service itself registers an entry in the JSON data, by the label “prov”, containing only
provisioning service version and capabilities. Application services should use a label other than “prov”so as
not to overwrite this.
Parameters
• label –[in] String indicating the application name.
• version –[in] String indicating the application version. There is no constraint on format.
• capabilities –[in] Array of strings with capabilities. These could be used by the
client side app to know the application registered endpoint capabilities
• total_capabilities –[in] Size of capabilities array
Returns
• ESP_OK : Success
• ESP_ERR_INVALID_STATE : Manager not initialized or provisioning service already
started
• ESP_ERR_NO_MEM : Failed to allocate memory for version string
• ESP_ERR_INVALID_ARG : Null argument
Note: Additional endpoints can be used for configuring client provided parameters other than Wi-Fi creden-
tials, that are necessary for the main application and hence must be set prior to starting the application
Note: After session establishment, the additional endpoints must be targeted first by the client side applica-
tion before sending Wi-Fi configuration, because once Wi-Fi configuration finishes the provisioning service is
stopped and hence all endpoints are unregistered
Note: This API can only be called AFTER provisioning has started
Note: Additional endpoints can be used for configuring client provided parameters other than Wi-Fi creden-
tials, that are necessary for the main application and hence must be set prior to starting the application
Note: After session establishment, the additional endpoints must be targeted first by the client side applica-
tion before sending Wi-Fi configuration, because once Wi-Fi configuration finishes the provisioning service is
stopped and hence all endpoints are unregistered
Parameters
• ep_name –[in] Name of the endpoint
• handler –[in] Endpoint handler function
• user_ctx –[in] User data
Returns
• ESP_OK : Success
• ESP_FAIL : Failure
esp_err_t wifi_prov_mgr_reset_provisioning(void)
Reset Wi-Fi provisioning config.
Calling this API will restore WiFi stack persistent settings to default values.
Returns
• ESP_OK : Reset provisioning config successfully
• ESP_FAIL : Failed to reset provisioning config
esp_err_t wifi_prov_mgr_reset_sm_state_on_failure(void)
Reset internal state machine and clear provisioned credentials.
This API can be used to restart provisioning in case invalid credentials are entered.
Returns
• ESP_OK : Reset provisioning state machine successfully
• ESP_FAIL : Failed to reset provisioning state machine
• ESP_ERR_INVALID_STATE : Manager not initialized
Structures
struct wifi_prov_event_handler_t
Event handler that is used by the manager while provisioning service is active.
Public Members
wifi_prov_cb_func_t event_cb
Callback function to be executed on provisioning events
void *user_data
User context data to pass as parameter to callback function
struct wifi_prov_scheme
Structure for specifying the provisioning scheme to be followed by the manager.
Public Members
void *(*new_config)(void)
Function which is to be called by the manager to generate a new configuration for the provisioning service,
that is to be passed to prov_start()
wifi_mode_t wifi_mode
Sets mode of operation of Wi-Fi during provisioning This is set to :
• WIFI_MODE_APSTA for SoftAP transport
• WIFI_MODE_STA for BLE transport
struct wifi_prov_mgr_config_t
Structure for specifying the manager configuration.
Public Members
wifi_prov_scheme_t scheme
Provisioning scheme to use. Following schemes are already available:
• wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server
• wifi_prov_scheme_softap : for provisioning over SoftAP transport + HTTP server + mDNS (op-
tional)
• wifi_prov_scheme_console : for provisioning over Serial UART transport + Console (for debugging)
wifi_prov_event_handler_t scheme_event_handler
Event handler required by the scheme for incorporating scheme specific behavior while provi-
sioning manager is running. Various options may be provided by the scheme for setting this
field. Use WIFI_PROV_EVENT_HANDLER_NONE when not used. When using scheme
wifi_prov_scheme_ble, the following options are available:
• WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM
• WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BLE
• WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BT
wifi_prov_event_handler_t app_event_handler
Event handler that can be set for the purpose of incorporating application specific behavior. Use
WIFI_PROV_EVENT_HANDLER_NONE when not used.
Macros
WIFI_PROV_EVENT_HANDLER_NONE
Event handler can be set to none if not used.
Type Definitions
Enumerations
enum wifi_prov_cb_event_t
Events generated by manager.
These events are generated in order of declaration and, for the stretch of time between initialization and de-
initialization of the manager, each event is signaled only once
Values:
enumerator WIFI_PROV_INIT
Emitted when the manager is initialized
enumerator WIFI_PROV_START
Indicates that provisioning has started
enumerator WIFI_PROV_CRED_RECV
Emitted when Wi-Fi AP credentials are received via protocomm endpoint wifi_config. The event
data in this case is a pointer to the corresponding wifi_sta_config_t structure
enumerator WIFI_PROV_CRED_FAIL
Emitted when device fails to connect to the AP of which the credentials were received earlier on event
WIFI_PROV_CRED_RECV. The event data in this case is a pointer to the disconnection reason code
with type wifi_prov_sta_fail_reason_t
enumerator WIFI_PROV_CRED_SUCCESS
Emitted when device successfully connects to the AP of which the credentials were received earlier on
event WIFI_PROV_CRED_RECV
enumerator WIFI_PROV_END
Signals that provisioning service has stopped
enumerator WIFI_PROV_DEINIT
Signals that manager has been de-initialized
enum wifi_prov_security
Security modes supported by the Provisioning Manager.
These are same as the security modes provided by protocomm
Values:
enumerator WIFI_PROV_SECURITY_0
No security (plain-text communication)
enumerator WIFI_PROV_SECURITY_1
This secure communication mode consists of X25519 key exchange
• proof of possession (pop) based authentication
• AES-CTR encryption
enumerator WIFI_PROV_SECURITY_2
This secure communication mode consists of SRP6a based authentication and key exchange
• AES-GCM encryption/decryption
Header File
• components/wifi_provisioning/include/wifi_provisioning/scheme_ble.h
Functions
void wifi_prov_scheme_ble_event_cb_free_btdm(void *user_data, wifi_prov_cb_event_t event,
void *event_data)
void wifi_prov_scheme_ble_event_cb_free_ble(void *user_data, wifi_prov_cb_event_t event, void
*event_data)
Note: The data being pointed to by the argument must be valid atleast till provisioning is started. Upon start,
the manager will store an internal copy of this UUID, and this data can be freed or invalidated afterwords.
Note: It is important to understand that length of custom manufacturer data should be within limits. The
manufacturer data goes into scan response along with BLE device name. By default, BLE device name length
is of 11 Bytes, however it can vary as per application use case. So, one has to honour the scan response data
size limits i.e. (mfg_data_len + 2) < 31 - (device_name_length + 2 ). If the mfg_data length exceeds this limit,
the length will be truncated.
Parameters
• mfg_data –[in] Custom manufacturer data
• mfg_data_len –[in] Manufacturer data length
Returns
• ESP_OK : Success
• ESP_ERR_INVALID_ARG : Null argument
Macros
WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM
WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BLE
WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BT
Header File
• components/wifi_provisioning/include/wifi_provisioning/scheme_softap.h
Functions
void wifi_prov_scheme_softap_set_httpd_handle(void *handle)
Provide HTTPD Server handle externally.
Useful in cases wherein applications need the webserver for some different operations, and do not want the wifi
provisioning component to start/stop a new instance.
Header File
• components/wifi_provisioning/include/wifi_provisioning/scheme_console.h
Header File
• components/wifi_provisioning/include/wifi_provisioning/wifi_config.h
Functions
esp_err_t wifi_prov_config_data_handler(uint32_t session_id, const uint8_t *inbuf, ssize_t inlen,
uint8_t **outbuf, ssize_t *outlen, void *priv_data)
Handler for receiving and responding to requests from master.
This is to be registered as the wifi_config endpoint handler (protocomm proto-
comm_req_handler_t) using protocomm_add_endpoint()
Structures
struct wifi_prov_sta_conn_info_t
WiFi STA connected status information.
Public Members
char ip_addr[IP4ADDR_STRLEN_MAX]
IP Address received by station
char bssid[6]
BSSID of the AP to which connection was estalished
char ssid[33]
SSID of the to which connection was estalished
uint8_t channel
Channel of the AP
uint8_t auth_mode
Authorization mode of the AP
struct wifi_prov_config_get_data_t
WiFi status data to be sent in response to get_status request from master.
Public Members
wifi_prov_sta_state_t wifi_state
WiFi state of the station
wifi_prov_sta_fail_reason_t fail_reason
Reason for disconnection (valid only when wifi_state is WIFI_STATION_DISCONNECTED)
wifi_prov_sta_conn_info_t conn_info
Connection information (valid only when wifi_state is WIFI_STATION_CONNECTED)
struct wifi_prov_config_set_data_t
WiFi config data received by slave during set_config request from master.
Public Members
char ssid[33]
SSID of the AP to which the slave is to be connected
char password[64]
Password of the AP
char bssid[6]
BSSID of the AP
uint8_t channel
Channel of the AP
struct wifi_prov_config_handlers
Internal handlers for receiving and responding to protocomm requests from master.
This is to be passed as priv_data for protocomm request handler (refer to
wifi_prov_config_data_handler()) when calling protocomm_add_endpoint().
Public Members
wifi_prov_ctx_t *ctx
Context pointer to be passed to above handler functions upon invocation
Type Definitions
Enumerations
enum wifi_prov_sta_state_t
WiFi STA status for conveying back to the provisioning master.
Values:
enumerator WIFI_PROV_STA_CONNECTING
enumerator WIFI_PROV_STA_CONNECTED
enumerator WIFI_PROV_STA_DISCONNECTED
enum wifi_prov_sta_fail_reason_t
WiFi STA connection fail reason.
Values:
enumerator WIFI_PROV_STA_AUTH_ERROR
enumerator WIFI_PROV_STA_AP_NOT_FOUND
Code examples for above API are provided in the provisioning directory of ESP-IDF examples.
Code example for above API is provided in wifi/smart_config.
Code example for above API is provided in wifi/wifi_easy_connect/dpp-enrollee.
ESP-IDF uses the FatFs library to work with FAT filesystems. FatFs resides in the fatfs component. Although the
library can be used directly, many of its features can be accessed via VFS using the C standard library and POSIX
API functions.
Additionally, FatFs has been modified to support the runtime pluggable disk I/O layer. This allows mapping of FatFs
drives to physical disks at runtime.
The header file fatfs/vfs/esp_vfs_fat.h defines the functions for connecting FatFs and VFS.
The function esp_vfs_fat_register() allocates a FATFS structure and registers a given path prefix in VFS.
Subsequent operations on files starting with this prefix are forwarded to FatFs APIs.
The function esp_vfs_fat_unregister_path() deletes the registration with VFS, and frees the FATFS
structure.
Most applications use the following workflow when working with esp_vfs_fat_ functions:
1. Call esp_vfs_fat_register() to specify:
• Path prefix where to mount the filesystem (e.g., "/sdcard", "/spiflash")
• FatFs drive number
Note: This function doesn’t mount the drive into FATFS, it just connects POSIX and C standard library IO
function with FATFS. You need to mount desired drive into FATFS separately.
Parameters
• base_path –path prefix where FATFS should be registered
• fat_drive –FATFS drive specification; if only one drive is used, can be an empty string
• max_files –maximum number of files which can be open at the same time
• out_fs –[out] pointer to FATFS structure which can be used for FATFS f_mount call
is returned via this argument.
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if esp_vfs_fat_register was already called
• ESP_ERR_NO_MEM if not enough memory or too many VFSes already registered
Note: FATFS structure returned by esp_vfs_fat_register is destroyed after this call. Make sure to call f_mount
function to unmount it before calling esp_vfs_fat_unregister_ctx. Difference between this function and the one
above is that this one will release the correct drive, while the one above will release the last registered one
Parameters base_path –path prefix where FATFS is registered. This is the same used when
esp_vfs_fat_register was called
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if FATFS is not registered in VFS
Note: Use this API to mount a card through SDSPI is deprecated. Please call
esp_vfs_fat_sdspi_mount() instead for that case.
Parameters
• base_path –path where partition should be registered (e.g. “/sdcard”)
• host_config –Pointer to structure describing SDMMC host. When using SD-
MMC peripheral, this structure can be initialized using SDMMC_HOST_DEFAULT()
macro. When using SPI peripheral, this structure can be initialized using SD-
SPI_HOST_DEFAULT() macro.
• slot_config –Pointer to structure with slot configuration. For SDMMC pe-
ripheral, pass a pointer to sdmmc_slot_config_t structure initialized using SD-
MMC_SLOT_CONFIG_DEFAULT.
• mount_config –pointer to structure with extra parameters for mounting FATFS
• out_card –[out] if not NULL, pointer to the card information structure will be returned
via this argument
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called
• ESP_ERR_NO_MEM if memory can not be allocated
• ESP_FAIL if partition can not be mounted
• other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers
esp_err_t esp_vfs_fat_sdmmc_unmount(void)
Unmount FAT filesystem and release resources acquired using esp_vfs_fat_sdmmc_mount.
Deprecated:
Use esp_vfs_fat_sdcard_unmount() instead.
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount hasn’t been called
Note: This function try to attach the new SD SPI device to the bus specified in host_config. Make sure the
SPI bus specified in host_config->slot have been initialized by spi_bus_initialize() before.
Parameters
• base_path –path where partition should be registered (e.g. “/sdcard”)
• host_config_input –Pointer to structure describing SDMMC host. This structure
can be initialized using SDSPI_HOST_DEFAULT() macro.
• slot_config –Pointer to structure with slot configuration. For SPI pe-
ripheral, pass a pointer to sdspi_device_config_t structure initialized using SD-
SPI_DEVICE_CONFIG_DEFAULT().
• mount_config –pointer to structure with extra parameters for mounting FATFS
• out_card –[out] If not NULL, pointer to the card information structure will be returned
via this argument. It is suggested to hold this handle and use it to unmount the card later
if needed. Otherwise it’s not suggested to use more than one card at the same time and
unmount one of them in your application.
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called
• ESP_ERR_NO_MEM if memory can not be allocated
• ESP_FAIL if partition can not be mounted
• other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers
struct esp_vfs_fat_mount_config_t
Configuration arguments for esp_vfs_fat_sdmmc_mount and esp_vfs_fat_spiflash_mount_rw_wl functions.
Public Members
bool format_if_mount_failed
If FAT partition can not be mounted, and this parameter is true, create partition table and format the
filesystem.
int max_files
Max number of open files.
size_t allocation_unit_size
If format_if_mount_failed is set, and mount fails, format the card with given allocation unit size. Must
be a power of 2, between sector size and 128 * sector size. For SD cards, sector size is always 512 bytes.
For wear_levelling, sector size is determined by CONFIG_WL_SECTOR_SIZE option.
Using larger allocation unit size will result in higher read/write performance and higher overhead when
storing small files.
Setting this field to 0 will result in allocation unit set to the sector size.
bool disk_status_check_enable
Enables real ff_disk_status function implementation for SD cards (ff_sdmmc_status). Possibly slows
down IO performance.
Try to enable if you need to handle situations when SD cards are not unmounted properly before physical
removal or you are experiencing issues with SD cards.
Doesn’t do anything for other memory storage media.
esp_err_t esp_vfs_fat_sdcard_unmount(const char *base_path, sdmmc_card_t *card)
Unmount an SD card from the FAT filesystem and release resources acquired using
esp_vfs_fat_sdmmc_mount() or esp_vfs_fat_sdspi_mount()
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if the card argument is unregistered
• ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount hasn’t been called
• finds the partition with defined partition_label. Partition label should be configured in the partition table.
• mounts FAT partition using FATFS library
• registers FATFS library with VFS, with prefix given by base_prefix variable
Note: Wear levelling is not used when FAT is mounted in read-only mode using this function.
Parameters
• base_path –path where FATFS partition should be mounted (e.g. “/spiflash”)
• partition_label –label of the partition which should be used
• mount_config –pointer to structure with extra parameters for mounting FATFS
Returns
• ESP_OK on success
• ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with
given label
• ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_ro was already called for
the same partition
• ESP_ERR_NO_MEM if memory can not be allocated
• ESP_FAIL if partition can not be mounted
• other error codes from SPI flash driver, or FATFS drivers
FatFs has been extended with API functions that register the disk I/O driver at runtime.
These APIs provide implementation of disk I/O functions for SD/MMC cards and can be registered for the given
FatFs drive number using the function ff_diskio_register_sdmmc().
void ff_diskio_register(BYTE pdrv, const ff_diskio_impl_t *discio_impl)
Register or unregister diskio driver for given drive number.
When FATFS library calls one of disk_xxx functions for driver number pdrv, corresponding function in dis-
cio_impl for given pdrv will be called.
Parameters
• pdrv –drive number
• discio_impl –pointer to ff_diskio_impl_t structure with diskio functions or NULL to
unregister and free previously registered drive
struct ff_diskio_impl_t
Structure of pointers to disk IO driver functions.
See FatFs documentation for details about these functions
Public Members
DRESULT (*read)(unsigned char pdrv, unsigned char *buff, uint32_t sector, unsigned count)
sector read function
DRESULT (*write)(unsigned char pdrv, const unsigned char *buff, uint32_t sector, unsigned count)
sector write function
We provide a partition generator for FatFs (wl_fatfsgen.py) which is integrated into the build system and could be
easily used in the user project.
The tool is used to create filesystem images on a host and populate it with content of the specified host folder.
The script is based on the partition generator (fatfsgen.py). Apart from generating partition, it can also initialize wear
levelling.
The latest version supports both short and long file names, FAT12 and FAT16. The long file names are limited to
255 characters and can contain multiple periods (.) characters within the filename and additional characters +, ,, ;,
=, [ and ].
Build System Integration with FatFs Partition Generator It is possible to invoke FatFs generator directly from
the CMake build system by calling fatfs_create_spiflash_image:
If you prefer generating partition without wear levelling support, you can use
fatfs_create_rawflash_image:
2. base_dir - the directory that will be encoded to FatFs partition and optionally flashed into the device. Beware
that you have to specify the suitable size of the partition in the partition table.
3. flag FLASH_IN_PROJECT - optionally, users can have the image automatically flashed together with the app
binaries, partition tables, etc. on idf.py flash -p <PORT> by specifying FLASH_IN_PROJECT.
For example:
If FLASH_IN_PROJECT is not specified, the image will still be generated, but you will have to flash it manually
using esptool.py or a custom build system target.
For an example, see storage/fatfsgen.
Introduction
This utility is designed to create instances of factory NVS partition images on a per-device basis for mass manufac-
turing purposes. The NVS partition images are created from CSV files containing user-provided configurations and
values.
Please note that this utility only creates manufacturing binary images which then need to be flashed onto your devices
using:
• esptool.py
• Flash Download tool (available on Windows only).Just download it, unzip, and follow the instructions inside
the doc folder.
• Direct flash programming using custom production tools.
Prerequisites
Note:
Before using this utility, please make sure that:
• The path to Python is added to the PATH environment variable.
• You have installed the packages from requirement.txt, the file in the root of the esp-idf directory.
Workflow
Note: The first line in this file should always be the namespace entry.
Each line should have three parameters: key,type,encoding, separated by a comma. If the REPEAT tag is
present, the value corresponding to this key in the master value CSV file will be the same for all devices.
Please refer to README of the NVS Partition Generator utility for detailed description of each parameter.
Below is a sample example of such a configuration file:
app,namespace,
firmware_key,data,hex2bin
serial_no,data,string,REPEAT
device_no,data,i32
Note:
Make sure there are no spaces:
• before and after ‘,’
• at the end of each line in a CSV file
This file contains details of the devices to be flashed. Each line in this file corresponds to a device instance.
The data in the master value CSV file has the following format:
key1,key2,key3,.....
value1,value2,value3,....
Note: The first line in the file should always contain the key names. All the keys from the configuration file should
be present here in the same order. This file can have additional columns (keys). The additional keys will be treated
as metadata and would not be part of the final binary files.
Each line should contain the value of the corresponding keys, separated by a comma. If the key has the REPEAT
tag, its corresponding value must be entered in the second line only. Keep the entry empty for this value in the
following lines.
The description of this parameter is as follows:
value Data value
Data value is the value of data corresponding to the key.
Below is a sample example of a master value CSV file:
id,firmware_key,serial_no,device_no
1,1a2b3c4d5e6faabb,A1,101
2,1a2b3c4d5e6fccdd,,102
3,1a2b3c4d5e6feeff,,103
Note: If the ‘REPEAT’tag is present, a new master value CSV file will be created in the same folder as the input
Master CSV File with the values inserted at each line for the key with the ‘REPEAT’tag.
This utility creates intermediate CSV files which are used as input for the NVS partition utility to generate the binary
files.
The format of this intermediate CSV file is as follows:
key,type,encoding,value
key,namespace, ,
key1,type1,encoding1,value1
key2,type2,encoding2,value2
An instance of an intermediate CSV file will be created for each device on an individual basis.
Usage:
Optional Arguments:
Commands:
Run mfg_gen.py {command} -h for additional help
Positional Arguments:
Parameter Description
conf Path to configuration csv file to parse
values Path to values csv file to parse
prefix | Unique name for each output filename prefix
size | Size of NVS partition in bytes
(must be multiple of 4096)
Optional Arguments:
Parameter Description
-h, –help show this help message and exit
–fileid Unique file identifier(any key in values file) for each filename suffix (Default: nu-
FILEID meric value(1,2,3…)
–version Set multipage blob version. Version 1 - Multipage blob support disabled. Version
{1,2} 2 - Multipage blob support enabled. Default: Version 2
–keygen Generates key for encrypting NVS partition
–inputkey IN- File having key for encrypting NVS partition
PUTKEY
–outdir OUT- Output directory to store files created (Default: current directory)
DIR
You can run the utility to generate factory images for each device using the command below. A sample CSV file is
provided with the utility:
The master value CSV file should have the path in the file type relative to the directory from which you are running
the utility.
To generate encrypted factory images for each device:
You can run the utility to encrypt factory images for each device using the command below. A sample CSV file is
provided with the utility:
• Encrypt by allowing the utility to generate encryption keys:
Parameter Description
-h, –help show this help message and exit
–keyfile KEYFILE Path to output encryption keys file
–outdir OUTDIR Output directory to store files created. (Default: current directory)
You can run the utility to generate only encryption keys using the command below:
Generated encryption key binary file can further be used to encrypt factory images created on the per device basis.
The default numeric value: 1,2,3…of the fileid argument corresponds to each line bearing device instance values
in the master value CSV file.
While running the manufacturing utility, the following folders will be created in the specified outdir directory:
• bin/ for storing the generated binary files
• csv/ for storing the generated intermediate CSV files
• keys/ for storing encryption keys (when generating encrypted factory images)
Introduction
Non-volatile storage (NVS) library is designed to store key-value pairs in flash. This section introduces some concepts
used by NVS.
Underlying storage Currently, NVS uses a portion of main flash memory through the esp_partition API. The
library uses all the partitions with data type and nvs subtype. The application can choose to use the partition
with the label nvs through the nvs_open() API function or any other partition by specifying its name using the
nvs_open_from_partition() API function.
Future versions of this library may have other storage backends to keep data in another flash chip (SPI or I2C), RTC,
FRAM, etc.
Note: if an NVS partition is truncated (for example, when the partition table layout is changed), its contents should
be erased. ESP-IDF build system provides a idf.py erase-flash target to erase all contents of the flash chip.
Note: NVS works best for storing many small values, rather than a few large values of the type‘string’and‘blob’
. If you need to store large blobs or strings, consider using the facilities provided by the FAT filesystem on top of the
wear levelling library.
Keys and values NVS operates on key-value pairs. Keys are ASCII strings; the maximum key length is currently
15 characters. Values can have one of the following types:
• integer types: uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t,
int64_t
• zero-terminated string
Note: String values are currently limited to 4000 bytes. This includes the null terminator. Blob values are limited
to 508,000 bytes or 97.6% of the partition size - 4000 bytes, whichever is lower.
Namespaces To mitigate potential conflicts in key names between different components, NVS assigns each key-
value pair to one of namespaces. Namespace names follow the same rules as key names, i.e., the maximum length
is 15 characters. Namespace name is specified in the nvs_open() or nvs_open_from_partition call.
This call returns an opaque handle, which is used in subsequent calls to the nvs_get_*, nvs_set_*, and
nvs_commit() functions. This way, a handle is associated with a namespace, and key names will not collide
with same names in other namespaces. Please note that the namespaces with the same name in different NVS parti-
tions are considered as separate namespaces.
NVS iterators Iterators allow to list key-value pairs stored in NVS, based on specified partition name, namespace,
and data type.
There are the following functions available:
• nvs_entry_find() creates an opaque handle, which is used in subsequent calls to the
nvs_entry_next() and nvs_entry_info() functions.
• nvs_entry_next() advances an iterator to the next key-value pair.
• nvs_entry_info() returns information about each key-value pair
In general, all iterators obtained via nvs_entry_find() have to be released using
nvs_release_iterator(), which also tolerates NULL iterators. nvs_entry_find() and
nvs_entry_next() will set the given iterator to NULL or a valid iterator in all cases except a parameter
error occured (i.e., return ESP_ERR_NVS_NOT_FOUND). In case of a parameter error, the given iterator will not
be modified. Hence, it is best practice to initialize the iterator to NULL before calling nvs_entry_find() to
avoid complicated error checking before releasing the iterator.
Security, tampering, and robustness NVS is not directly compatible with the ESP32 flash encryption system.
However, data can still be stored in encrypted form if NVS encryption is used together with ESP32 flash encryption.
Please refer to NVS Encryption for more details.
If NVS encryption is not used, it is possible for anyone with physical access to the flash chip to alter, erase, or add
key-value pairs. With NVS encryption enabled, it is not possible to alter or add a key-value pair and get recognized
as a valid pair without knowing corresponding NVS encryption keys. However, there is no tamper-resistance against
the erase operation.
The library does try to recover from conditions when flash memory is in an inconsistent state. In particular, one
should be able to power off the device at any point and time and then power it back on. This should not result in loss
of data, except for the new key-value pair if it was being written at the moment of powering off. The library should
also be able to initialize properly with any random data present in flash memory.
NVS Encryption
Data stored in NVS partitions can be encrypted using AES-XTS in the manner similar to the one mentioned in disk
encryption standard IEEE P1619. For the purpose of encryption, each entry is treated as one sector and relative
address of the entry (w.r.t. partition-start) is fed to the encryption algorithm as sector-number. The NVS Encryption
can be enabled by enabling CONFIG_NVS_ENCRYPTION. The keys required for NVS encryption are stored in yet
another partition, which is protected using Flash Encryption. Therefore, enabling Flash Encryption is a prerequisite
for NVS encryption.
The NVS Encryption is enabled by default when Flash Encryption is enabled. This is done because Wi-Fi driver
stores credentials (like SSID and passphrase) in the default NVS partition. It is important to encrypt them as default
choice if platform level encryption is already enabled.
For using NVS encryption, the partition table must contain the NVS key partition. Two partition tables containing the
NVS key partition are provided for NVS encryption under the partition table option (menuconfig->Partition Table).
They can be selected with the project configuration menu (idf.py menuconfig). Please refer to the example
security/flash_encryption for how to configure and use NVS encryption feature.
+-----------+--------------+-------------+----+
| XTS encryption key (32) |
+---------------------------------------------+
| XTS tweak key (32) |
+---------------------------------------------+
| CRC32 (4) |
+---------------------------------------------+
The XTS encryption keys in the NVS key partition can be generated in one of the following two ways.
1. Generate the keys on the ESP chip:
When NVS encryption is enabled the nvs_flash_init() API function can be used to ini-
tialize the encrypted default NVS partition. The API function internally generates the XTS en-
cryption keys on the ESP chip. The API function finds the first NVS key partition. Then the
API function automatically generates and stores the NVS keys in that partition by making use of
the nvs_flash_generate_keys() API function provided by nvs_flash/include/nvs_flash.h.
New keys are generated and stored only when the respective key partition is empty. The same key
partition can then be used to read the security configurations for initializing a custom encrypted
NVS partition with help of nvs_flash_secure_init_partition().
The API functions nvs_flash_secure_init() and nvs_flash_secure_init_partition()
do not generate the keys internally. When these API functions are used for initial-
izing encrypted NVS partitions, the keys can be generated after startup using the
nvs_flash_generate_keys() API function provided by nvs_flash.h. The API
function will then write those keys onto the key-partition in encrypted form.
2. Use pre-generated key partition:
This option will be required by the user when keys in the NVS key partition are not generated by the
application. The NVS key partition containing the XTS encryption keys can be generated with the
help of NVS Partition Generator Utility. Then the user can store the pre generated key partition on
the flash with help of the following two commands:
i) Build and flash the partition table
ii) Store the keys in the NVS key partition (on the flash) with the help of parttool.py (see Partition
Tool section in partition-tables for more details)
,→-input NVS_KEY_PARTITION_FILE
Note: If the device is encrypted in flash encryption development mode and you want to renew the
NVS key partition, you need to advice parttool.py to encrypt the NVS key partition and you also need
to give it a pointer to the unencrypted partition table in your build directory (build/partition_table)
since the partition table on the device is encrypted, too. You can use the following command:
,→-input NVS_KEY_PARTITION_FILE
Since the key partition is marked as encrypted and Flash Encryption is enabled, the bootloader will encrypt this
partition using flash encryption key on the first boot.
It is possible for an application to use different keys for different NVS partitions and thereby have multiple key-
partitions. However, it is a responsibility of the application to provide correct key-partition/keys for the purpose of
encryption/decryption.
Encrypted Read/Write The same NVS API functions nvs_get_* or nvs_set_* can be used for reading of,
and writing to an encrypted nvs partition as well.
Encrypt the default NVS partition: To enable encryption for the default NVS partition no additional steps are
necessary. When CONFIG_NVS_ENCRYPTION is enabled, the nvs_flash_init() API function internally per-
forms some additional steps using the first NVS key partition found to enable encryption for the default NVS partition
(refer to the API documentation for more details). Alternatively, nvs_flash_secure_init() API function
can also be used to enable encryption for the default NVS partition.
Encrypt a custom NVS partition: To enable encryption for a custom NVS par-
tition, nvs_flash_secure_init_partition() API function is used instead of
nvs_flash_init_partition().
When nvs_flash_secure_init() and nvs_flash_secure_init_partition() API functions are
used, the applications are expected to follow the steps below in order to perform NVS read/write operations with
encryption enabled.
1. Find key partition and NVS data partition using esp_partition_find* API functions.
2. Populate the nvs_sec_cfg_t struct using the nvs_flash_read_security_cfg() or
nvs_flash_generate_keys() API functions.
3. Initialise NVS flash partition using the nvs_flash_secure_init() or
nvs_flash_secure_init_partition() API functions.
4. Open a namespace using the nvs_open() or nvs_open_from_partition() API functions.
5. Perform NVS read/write operations using nvs_get_* or nvs_set_*.
6. Deinitialise an NVS partition using nvs_flash_deinit().
This utility helps generate NVS partition binary files which can be flashed separately on a dedicated partition via a
flashing utility. Key-value pairs to be flashed onto the partition can be provided via a CSV file. For more details,
please refer to NVS Partition Generator Utility.
Application Example
You can find code examples in the storage directory of ESP-IDF examples:
storage/nvs_rw_value
Demonstrates how to read a single integer value from, and write it to NVS.
The value checked in this example holds the number of the ESP32 module restarts. The value’s function
as a counter is only possible due to its storing in NVS.
The example also shows how to check if a read / write operation was successful, or if a certain value
has not been initialized in NVS. The diagnostic procedure is provided in plain text to help you track the
program flow and capture any issues on the way.
storage/nvs_rw_blob
Demonstrates how to read a single integer value and a blob (binary large object), and write them to NVS
to preserve this value between ESP32 module restarts.
• value - tracks the number of the ESP32 module soft and hard restarts.
• blob - contains a table with module run times. The table is read from NVS to dynamically allocated
RAM. A new run time is added to the table on each manually triggered soft restart, and then the
added run time is written to NVS. Triggering is done by pulling down GPIO0.
The example also shows how to implement the diagnostic procedure to check if the read / write operation
was successful.
storage/nvs_rw_value_cxx
This example does exactly the same as storage/nvs_rw_value, except that it uses the C++ NVS handle
class.
Internals
Log of key-value pairs NVS stores key-value pairs sequentially, with new key-value pairs being added at the end.
When a value of any given key has to be updated, a new key-value pair is added at the end of the log and the old
key-value pair is marked as erased.
Pages and entries NVS library uses two main entities in its operation: pages and entries. Page is a logical structure
which stores a portion of the overall log. Logical page corresponds to one physical sector of flash memory. Pages
which are in use have a sequence number associated with them. Sequence numbers impose an ordering on pages.
Higher sequence numbers correspond to pages which were created later. Each page can be in one of the following
states:
Empty/uninitialized Flash storage for the page is empty (all bytes are 0xff). Page is not used to store any data at
this point and does not have a sequence number.
Active Flash storage is initialized, page header has been written to flash, page has a valid sequence number. Page
has some empty entries and data can be written there. No more than one page can be in this state at any given
moment.
Full Flash storage is in a consistent state and is filled with key-value pairs. Writing new key-value pairs into this
page is not possible. It is still possible to mark some key-value pairs as erased.
Erasing Non-erased key-value pairs are being moved into another page so that the current page can be erased. This
is a transient state, i.e., page should never stay in this state at the time when any API call returns. In case of a
sudden power off, the move-and-erase process will be completed upon the next power-on.
Corrupted Page header contains invalid data, and further parsing of page data was canceled. Any items previously
written into this page will not be accessible. The corresponding flash sector will not be erased immediately and
will be kept along with sectors in uninitialized state for later use. This may be useful for debugging.
Mapping from flash sectors to logical pages does not have any particular order. The library will inspect sequence
numbers of pages found in each flash sector and organize pages in a list based on these numbers.
Structure of a page For now, we assume that flash sector size is 4096 bytes and that ESP32 flash encryption
hardware operates on 32-byte blocks. It is possible to introduce some settings configurable at compile-time (e.g., via
menuconfig) to accommodate flash chips with different sector sizes (although it is not clear if other components in
the system, e.g., SPI flash driver and SPI flash cache can support these other sizes).
Page consists of three parts: header, entry state bitmap, and entries themselves. To be compatible with ESP32 flash
encryption, the entry size is 32 bytes. For integer types, an entry holds one key-value pair. For strings and blobs, an
entry holds part of key-value pair (more on that in the entry structure description).
The following diagram illustrates the page structure. Numbers in parentheses indicate the size of each part in bytes.
+-----------+--------------+-------------+-------------------------+
| State (4) | Seq. no. (4) | version (1) | Unused (19) | CRC32 (4) | Header (32)
+-----------+--------------+-------------+-------------------------+
| Entry state bitmap (32) |
+------------------------------------------------------------------+
| Entry 0 (32) |
+------------------------------------------------------------------+
| Entry 1 (32) |
+------------------------------------------------------------------+
/ /
/ /
+------------------------------------------------------------------+
| Entry 125 (32) |
+------------------------------------------------------------------+
Page header and entry state bitmap are always written to flash unencrypted. Entries are encrypted if flash encryption
feature of ESP32 is used.
Page state values are defined in such a way that changing state is possible by writing 0 into some of the bits. Therefore
it is not necessary to erase the page to change its state unless that is a change to the erased state.
The version field in the header reflects the NVS format version used. For backward compatibility reasons, it is
decremented for every version upgrade starting at 0xff (i.e., 0xff for version-1, 0xfe for version-2 and so on).
CRC32 value in the header is calculated over the part which does not include a state value (bytes 4 to 28). The unused
part is currently filled with 0xff bytes.
The following sections describe the structure of entry state bitmap and entry itself.
Entry and entry state bitmap Each entry can be in one of the following three states represented with two bits in
the entry state bitmap. The final four bits in the bitmap (256 - 2 * 126) are not used.
Empty (2’b11) Nothing is written into the specific entry yet. It is in an uninitialized state (all bytes are 0xff).
Written (2’b10) A key-value pair (or part of key-value pair which spans multiple entries) has been written into
the entry.
Erased (2’b00) A key-value pair in this entry has been discarded. Contents of this entry will not be parsed any-
more.
Structure of entry For values of primitive types (currently integers from 1 to 8 bytes long), entry holds one key-
value pair. For string and blob types, entry holds part of the whole key-value pair. For strings, in case when a
key-value pair spans multiple entries, all entries are stored in the same page. Blobs are allowed to span over multiple
pages by dividing them into smaller chunks. For tracking these chunks, an additional fixed length metadata entry is
stored called “blob index”. Earlier formats of blobs are still supported (can be read and modified). However, once
the blobs are modified, they are stored using the new format.
+--------+----------+----------+----------------+-----------+---------------+------
,→----+
| NS (1) | Type (1) | Span (1) | ChunkIndex (1) | CRC32 (4) | Key (16) | Data␣
,→(8) |
+--------+----------+----------+----------------+-----------+---------------+------
,→----+
Primitive +------------------------------
,→ --+
+--------> | Data (8) ␣
,→ |
| Types +------------------------------
,→ --+
+-> Fixed length --
| | +---------+--------------+-----
,→----------+-------+
|
| +----------+---------+-----------+
+-> Variable length --> | Size (2) | Rsv (2) | CRC32 (4) |
(Strings, Blob Data) +----------+---------+-----------+
Namespaces As mentioned above, each key-value pair belongs to one of the namespaces. Namespace identifiers
(strings) are stored as keys of key-value pairs in namespace with index 0. Values corresponding to these keys are
indexes of these namespaces.
+-------------------------------------------+
| NS=0 Type=uint8_t Key="wifi" Value=1 | Entry describing namespace "wifi"
+-------------------------------------------+
| NS=1 Type=uint32_t Key="channel" Value=6 | Key "channel" in namespace "wifi"
(continues on next page)
Item hash list To reduce the number of reads from flash memory, each member of the Page class maintains a list
of pairs: item index; item hash. This list makes searches much quicker. Instead of iterating over all entries, reading
them from flash one at a time, Page::findItem first performs a search for the item hash in the hash list. This gives the
item index within the page if such an item exists. Due to a hash collision, it is possible that a different item will be
found. This is handled by falling back to iteration over items in flash.
Each node in the hash list contains a 24-bit hash and 8-bit item index. Hash is calculated based on item namespace,
key name, and ChunkIndex. CRC32 is used for calculation; the result is truncated to 24 bits. To reduce the overhead
for storing 32-bit entries in a linked list, the list is implemented as a double-linked list of arrays. Each array holds
29 entries, for the total size of 128 bytes, together with linked list pointers and a 32-bit count field. The minimum
amount of extra RAM usage per page is therefore 128 bytes; maximum is 640 bytes.
API Reference
Header File
• components/nvs_flash/include/nvs_flash.h
Functions
esp_err_t nvs_flash_init(void)
Initialize the default NVS partition.
This API initialises the default NVS partition. The default NVS partition is the one that is labeled “nvs”in
the partition table.
When “NVS_ENCRYPTION”is enabled in the menuconfig, this API enables the NVS encryption for the
default NVS partition as follows
a. Read security configurations from the first NVS key partition listed in the partition table. (NVS key
partition is any “data”type partition which has the subtype value set to “nvs_keys”)
b. If the NVS key partiton obtained in the previous step is empty, generate and store new keys in that NVS
key partiton.
c. Internally call “nvs_flash_secure_init()”with the security configurations obtained/generated in the pre-
vious steps.
Post initialization NVS read/write APIs remain the same irrespective of NVS encryption.
Returns
• ESP_OK if storage was successfully initialized.
• ESP_ERR_NVS_NO_FREE_PAGES if the NVS storage contains no empty pages (which
may happen if NVS partition was truncated)
• ESP_ERR_NOT_FOUND if no partition with label“nvs”is found in the partition table
• ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures
• one of the error codes from the underlying flash storage driver
• error codes from nvs_flash_read_security_cfg API (when“NVS_ENCRYPTION”is en-
abled).
• error codes from nvs_flash_generate_keys API (when “NVS_ENCRYPTION”is en-
abled).
• error codes from nvs_flash_secure_init_partition API (when “NVS_ENCRYPTION”is
enabled) .
Note: If the partition is initialized, this function first de-initializes it. Afterwards, the partition has to be
initialized again to be used.
Returns
• ESP_OK on success
• ESP_ERR_NOT_FOUND if there is no NVS partition labeled “nvs”in the partition
table
• different error in case de-initialization fails (shouldn’t happen)
Note: If the partition is initialized, this function first de-initializes it. Afterwards, the partition has to be
initialized again to be used.
Parameters part_name –[in] Name (label) of the partition which should be erased
Returns
• ESP_OK on success
• ESP_ERR_NOT_FOUND if there is no NVS partition with the specified name in the
partition table
• different error in case de-initialization fails (shouldn’t happen)
Note: If the partition is initialized, this function first de-initializes it. Afterwards, the partition has to be
initialized again to be used.
Parameters partition –[in] pointer to a partition obtained by the ESP partition API.
Returns
• ESP_OK on success
• ESP_ERR_NOT_FOUND if there is no partition with the specified parameters in the
partition table
• ESP_ERR_INVALID_ARG in case partition is NULL
• one of the error codes from the underlying flash storage driver
• one of the error codes from the underlying flash storage driver
esp_err_t nvs_flash_generate_keys(const esp_partition_t *partition, nvs_sec_cfg_t *cfg)
Generate and store NVS keys in the provided esp partition.
Parameters
• partition –[in] Pointer to partition structure obtained using esp_partition_find_first
or esp_partition_get. Must be non-NULL.
• cfg –[out] Pointer to nvs security configuration structure. Pointer must be non-NULL.
Generated keys will be populated in this structure.
Returns -ESP_OK, if cfg was read successfully; -ESP_INVALID_ARG, if partition or cfg; -or
error codes from esp_partition_write/erase APIs.
esp_err_t nvs_flash_read_security_cfg(const esp_partition_t *partition, nvs_sec_cfg_t *cfg)
Read NVS security configuration from a partition.
Parameters
• partition –[in] Pointer to partition structure obtained using esp_partition_find_first
or esp_partition_get. Must be non-NULL.
• cfg –[out] Pointer to nvs security configuration structure. Pointer must be non-NULL.
Returns -ESP_OK, if cfg was read successfully; -ESP_INVALID_ARG, if partition or cfg; -
ESP_ERR_NVS_KEYS_NOT_INITIALIZED, if the partition is not yet written with keys.
-ESP_ERR_NVS_CORRUPT_KEY_PART, if the partition containing keys is found to be
corrupt -or error codes from esp_partition_read API.
Structures
struct nvs_sec_cfg_t
Key for encryption and decryption.
Public Members
uint8_t eky[NVS_KEY_SIZE]
XTS encryption and decryption key
uint8_t tky[NVS_KEY_SIZE]
XTS tweak key
Macros
NVS_KEY_SIZE
Header File
• components/nvs_flash/include/nvs.h
Functions
esp_err_t nvs_set_i8(nvs_handle_t handle, const char *key, int8_t value)
set int8_t value for given key
Set value for the key, given its name. Note that the actual storage will not be updated until nvs_commit is
called.
Parameters
• handle –[in] Handle obtained from nvs_open function. Handles that were opened read
only cannot be used.
• key –[in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) charac-
ters. Shouldn’t be empty.
• value –[in] The value to set.
Returns
• ESP_OK if value was set successfully
• ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only
if NVS assertion checks are disabled)
• ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL
• ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only
• ESP_ERR_NVS_INVALID_NAME if key name doesn’t satisfy constraints
• ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the underlying
storage to save the value
• ESP_ERR_NVS_REMOVE_FAILED if the value wasn’t updated because flash write
operation has failed. The value was written however, and update will be finished after
re-initialization of nvs, provided that flash operation doesn’t fail again.
esp_err_t nvs_set_u8(nvs_handle_t handle, const char *key, uint8_t value)
set uint8_t value for given key
This function is the same as nvs_set_i8 except for the data type.
esp_err_t nvs_set_i16(nvs_handle_t handle, const char *key, int16_t value)
set int16_t value for given key
This function is the same as nvs_set_i8 except for the data type.
esp_err_t nvs_set_u16(nvs_handle_t handle, const char *key, uint16_t value)
set uint16_t value for given key
This function is the same as nvs_set_i8 except for the data type.
esp_err_t nvs_set_i32(nvs_handle_t handle, const char *key, int32_t value)
set int32_t value for given key
This function is the same as nvs_set_i8 except for the data type.
esp_err_t nvs_set_u32(nvs_handle_t handle, const char *key, uint32_t value)
set uint32_t value for given key
This function is the same as nvs_set_i8 except for the data type.
esp_err_t nvs_set_i64(nvs_handle_t handle, const char *key, int64_t value)
set int64_t value for given key
This function is the same as nvs_set_i8 except for the data type.
esp_err_t nvs_set_u64(nvs_handle_t handle, const char *key, uint64_t value)
set uint64_t value for given key
This function is the same as nvs_set_i8 except for the data type.
esp_err_t nvs_set_str(nvs_handle_t handle, const char *key, const char *value)
set string for given key
Set value for the key, given its name. Note that the actual storage will not be updated until nvs_commit is
called.
Parameters
• handle –[in] Handle obtained from nvs_open function. Handles that were opened read
only cannot be used.
• key –[in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) charac-
ters. Shouldn’t be empty.
• value –[in] The value to set. For strings, the maximum length (including null character)
is 4000 bytes, if there is one complete page free for writing. This decreases, however, if
the free space is fragmented.
Returns
• ESP_OK if value was set successfully
• ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL
• ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only
• ESP_ERR_NVS_INVALID_NAME if key name doesn’t satisfy constraints
• ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the underlying
storage to save the value
• ESP_ERR_NVS_REMOVE_FAILED if the value wasn’t updated because flash write
operation has failed. The value was written however, and update will be finished after
re-initialization of nvs, provided that flash operation doesn’t fail again.
• ESP_ERR_NVS_VALUE_TOO_LONG if the string value is too long
esp_err_t nvs_get_i8(nvs_handle_t handle, const char *key, int8_t *out_value)
get int8_t value for given key
These functions retrieve value for the key, given its name. If key does not exist, or the requested variable type
doesn’t match the type which was used when setting a value, an error is returned.
In case of any error, out_value is not modified.
out_value has to be a pointer to an already allocated variable of the given type.
Parameters
• handle –[in] Handle obtained from nvs_open function.
• key –[in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) charac-
ters. Shouldn’t be empty.
• out_value –Pointer to the output value. May be NULL for nvs_get_str and
nvs_get_blob, in this case required length will be returned in length argument.
Returns
• ESP_OK if the value was retrieved successfully
• ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only
if NVS assertion checks are disabled)
• ESP_ERR_NVS_NOT_FOUND if the requested key doesn’t exist
• ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL
• ESP_ERR_NVS_INVALID_NAME if key name doesn’t satisfy constraints
• ESP_ERR_NVS_INVALID_LENGTH if length is not sufficient to store data
size_t required_size;
nvs_get_str(my_handle, "server_name", NULL, &required_size);
char* server_name = malloc(required_size);
nvs_get_str(my_handle, "server_name", server_name, &required_size);
Parameters
• handle –[in] Handle obtained from nvs_open function.
• key –[in] Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) charac-
ters. Shouldn’t be empty.
• out_value –[out] Pointer to the output value. May be NULL for nvs_get_str and
nvs_get_blob, in this case required length will be returned in length argument.
• length –[inout] A non-zero pointer to the variable holding the length of out_value. In
case out_value a zero, will be set to the length required to hold the value. In case out_value
is not zero, will be set to the actual length of the value written. For nvs_get_str this includes
zero terminator.
Returns
• ESP_OK if the value was retrieved successfully
• ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only
if NVS assertion checks are disabled)
• ESP_ERR_NVS_NOT_FOUND if the requested key doesn’t exist
• ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL
• ESP_ERR_NVS_INVALID_NAME if key name doesn’t satisfy constraints
• ESP_ERR_NVS_INVALID_LENGTH if length is not sufficient to store data
esp_err_t nvs_get_blob(nvs_handle_t handle, const char *key, void *out_value, size_t *length)
get blob value for given key
This function behaves the same as nvs_get_str, except for the data type.
esp_err_t nvs_open(const char *namespace_name, nvs_open_mode_t open_mode, nvs_handle_t *out_handle)
Open non-volatile storage with a given namespace from the default NVS partition.
Multiple internal ESP-IDF and third party application modules can store their key-value pairs in the NVS
module. In order to reduce possible conflicts on key names, each module can use its own namespace. The
default NVS partition is the one that is labelled “nvs”in the partition table.
Parameters
• namespace_name –[in] Namespace name. Maximum length is
(NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn’t be empty.
• open_mode –[in] NVS_READWRITE or NVS_READONLY. If NVS_READONLY,
will open a handle for reading only. All write requests will be rejected for this handle.
• out_handle –[out] If successful (return code is zero), handle will be returned in this
argument.
Returns
• ESP_OK if storage handle was opened successfully
• ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only
if NVS assertion checks are disabled)
• ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized
• ESP_ERR_NVS_PART_NOT_FOUND if the partition with label “nvs”is not found
• ESP_ERR_NVS_NOT_FOUND id namespace doesn’t exist yet and mode is
NVS_READONLY
• ESP_ERR_NVS_INVALID_NAME if namespace name doesn’t satisfy constraints
• ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures
• other error codes from the underlying storage driver
esp_err_t nvs_open_from_partition(const char *part_name, const char *namespace_name,
nvs_open_mode_t open_mode, nvs_handle_t *out_handle)
Open non-volatile storage with a given namespace from specified partition.
The behaviour is same as nvs_open() API. However this API can operate on a specified NVS partition
instead of default NVS partition. Note that the specified partition must be registered with NVS using
nvs_flash_init_partition() API.
Parameters
• part_name –[in] Label (name) of the partition of interest for object read/write/erase
• namespace_name –[in] Namespace name. Maximum length is
(NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn’t be empty.
• open_mode –[in] NVS_READWRITE or NVS_READONLY. If NVS_READONLY,
will open a handle for reading only. All write requests will be rejected for this handle.
• out_handle –[out] If successful (return code is zero), handle will be returned in this
argument.
Returns
• ESP_OK if storage handle was opened successfully
• ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only
if NVS assertion checks are disabled)
• ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized
• ESP_ERR_NVS_PART_NOT_FOUND if the partition with specified name is not found
• ESP_FAIL if there is an internal error; most likely due to corrupted NVS partition (only
if NVS assertion checks are disabled)
• ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL
• ESP_ERR_NVS_READ_ONLY if handle was opened as read only
• other error codes from the underlying storage driver
esp_err_t nvs_commit(nvs_handle_t handle)
Write any pending changes to non-volatile storage.
After setting any values, nvs_commit() must be called to ensure changes are written to non-volatile storage.
Individual implementations may write to storage at other times, but this is not guaranteed.
Parameters handle –[in] Storage handle obtained with nvs_open. Handles that were opened
read only cannot be used.
Returns
• ESP_OK if the changes have been written successfully
• ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL
• other error codes from the underlying storage driver
void nvs_close(nvs_handle_t handle)
Close the storage handle and free any allocated resources.
This function should be called for each handle opened with nvs_open once the handle is not in use any more.
Closing the handle may not automatically write the changes to nonvolatile storage. This has to be done explicitly
using nvs_commit function. Once this function is called on a handle, the handle should no longer be used.
Parameters handle –[in] Storage handle to close
esp_err_t nvs_get_stats(const char *part_name, nvs_stats_t *nvs_stats)
Fill structure nvs_stats_t. It provides info about used memory the partition.
This function calculates to runtime the number of used entries, free entries, total entries, and amount namespace
in partition.
nvs_stats_t nvs_stats;
nvs_get_stats(NULL, &nvs_stats);
printf("Count: UsedEntries = (%d), FreeEntries = (%d), AllEntries = (%d)\n",
nvs_stats.used_entries, nvs_stats.free_entries, nvs_stats.total_
,→entries);
Parameters
• part_name –[in] Partition name NVS in the partition table. If pass a NULL than will
use NVS_DEFAULT_PART_NAME (“nvs”).
• nvs_stats –[out] Returns filled structure nvs_states_t. It provides info about used
memory the partition.
Returns
• ESP_OK if the changes have been written successfully. Return param nvs_stats will be
filled.
• ESP_ERR_NVS_PART_NOT_FOUND if the partition with label“name”is not found.
Return param nvs_stats will be filled 0.
• ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized. Return
param nvs_stats will be filled 0.
• ESP_ERR_INVALID_ARG if nvs_stats equal to NULL.
• ESP_ERR_INVALID_STATE if there is page with the status of INVALID. Return param
nvs_stats will be filled not with correct values because not all pages will be counted. Count-
ing will be interrupted at the first INVALID page.
nvs_handle_t handle;
nvs_open("namespace1", NVS_READWRITE, &handle);
...
size_t used_entries;
size_t total_entries_namespace;
if(nvs_get_used_entry_count(handle, &used_entries) == ESP_OK){
// the total number of entries occupied by the namespace
total_entries_namespace = used_entries + 1;
}
Parameters
• handle –[in] Handle obtained from nvs_open function.
• used_entries –[out] Returns amount of used entries from a namespace.
Returns
• ESP_OK if the changes have been written successfully. Return param used_entries will
be filled valid value.
• ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized. Return
param used_entries will be filled 0.
• ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL. Return
param used_entries will be filled 0.
• ESP_ERR_INVALID_ARG if used_entries equal to NULL.
• Other error codes from the underlying storage driver. Return param used_entries will be
filled 0.
// Example of listing all the key-value pairs of any type under specified␣
,→partition and namespace
nvs_iterator_t it = NULL;
esp_err_t res = nvs_entry_find(<nvs_partition_name>, <namespace>, NVS_TYPE_
,→ANY, &it);
while(res == ESP_OK) {
nvs_entry_info_t info;
nvs_entry_info(it, &info); // Can omit error check if parameters are␣
,→guaranteed to be non-NULL
Parameters
• part_name –[in] Partition name
• namespace_name –[in] Set this value if looking for entries with a specific namespace.
Pass NULL otherwise.
• type –[in] One of nvs_type_t values.
Structures
struct nvs_entry_info_t
information about entry obtained from nvs_entry_info function
Public Members
char namespace_name[16]
Namespace to which key-value belong
char key[NVS_KEY_NAME_MAX_SIZE]
Key of stored key-value pair
nvs_type_t type
Type of stored key-value pair
struct nvs_stats_t
Public Members
size_t used_entries
Amount of used entries.
size_t free_entries
Amount of free entries.
size_t total_entries
Amount all available entries.
size_t namespace_count
Amount name space.
Macros
ESP_ERR_NVS_BASE
Starting number of error codes
ESP_ERR_NVS_NOT_INITIALIZED
The storage driver is not initialized
ESP_ERR_NVS_NOT_FOUND
A requested entry couldn’t be found or namespace doesn’t exist yet and mode is NVS_READONLY
ESP_ERR_NVS_TYPE_MISMATCH
The type of set or get operation doesn’t match the type of value stored in NVS
ESP_ERR_NVS_READ_ONLY
Storage handle was opened as read only
ESP_ERR_NVS_NOT_ENOUGH_SPACE
There is not enough space in the underlying storage to save the value
ESP_ERR_NVS_INVALID_NAME
Namespace name doesn’t satisfy constraints
ESP_ERR_NVS_INVALID_HANDLE
Handle has been closed or is NULL
ESP_ERR_NVS_REMOVE_FAILED
The value wasn’t updated because flash write operation has failed. The value was written however, and update
will be finished after re-initialization of nvs, provided that flash operation doesn’t fail again.
ESP_ERR_NVS_KEY_TOO_LONG
Key name is too long
ESP_ERR_NVS_PAGE_FULL
Internal error; never returned by nvs API functions
ESP_ERR_NVS_INVALID_STATE
NVS is in an inconsistent state due to a previous error. Call nvs_flash_init and nvs_open again, then retry.
ESP_ERR_NVS_INVALID_LENGTH
String or blob length is not sufficient to store data
ESP_ERR_NVS_NO_FREE_PAGES
NVS partition doesn’t contain any empty pages. This may happen if NVS partition was truncated. Erase the
whole partition and call nvs_flash_init again.
ESP_ERR_NVS_VALUE_TOO_LONG
Value doesn’t fit into the entry or string or blob length is longer than supported by the implementation
ESP_ERR_NVS_PART_NOT_FOUND
Partition with specified name is not found in the partition table
ESP_ERR_NVS_NEW_VERSION_FOUND
NVS partition contains data in new format and cannot be recognized by this version of code
ESP_ERR_NVS_XTS_ENCR_FAILED
XTS encryption failed while writing NVS entry
ESP_ERR_NVS_XTS_DECR_FAILED
XTS decryption failed while reading NVS entry
ESP_ERR_NVS_XTS_CFG_FAILED
XTS configuration setting failed
ESP_ERR_NVS_XTS_CFG_NOT_FOUND
XTS configuration not found
ESP_ERR_NVS_ENCR_NOT_SUPPORTED
NVS encryption is not supported in this version
ESP_ERR_NVS_KEYS_NOT_INITIALIZED
NVS key partition is uninitialized
ESP_ERR_NVS_CORRUPT_KEY_PART
NVS key partition is corrupt
ESP_ERR_NVS_WRONG_ENCRYPTION
NVS partition is marked as encrypted with generic flash encryption. This is forbidden since the NVS encryption
works differently.
ESP_ERR_NVS_CONTENT_DIFFERS
Internal error; never returned by nvs API functions. NVS key is different in comparison
NVS_DEFAULT_PART_NAME
Default partition name of the NVS partition in the partition table
NVS_PART_NAME_MAX_SIZE
maximum length of partition name (excluding null terminator)
NVS_KEY_NAME_MAX_SIZE
Maximum length of NVS key name (including null terminator)
Type Definitions
Enumerations
enum nvs_open_mode_t
Mode of opening the non-volatile storage.
Values:
enumerator NVS_READONLY
Read only
enumerator NVS_READWRITE
Read and write
enum nvs_type_t
Types of variables.
Values:
enumerator NVS_TYPE_U8
Type uint8_t
enumerator NVS_TYPE_I8
Type int8_t
enumerator NVS_TYPE_U16
Type uint16_t
enumerator NVS_TYPE_I16
Type int16_t
enumerator NVS_TYPE_U32
Type uint32_t
enumerator NVS_TYPE_I32
Type int32_t
enumerator NVS_TYPE_U64
Type uint64_t
enumerator NVS_TYPE_I64
Type int64_t
enumerator NVS_TYPE_STR
Type string
enumerator NVS_TYPE_BLOB
Type blob
enumerator NVS_TYPE_ANY
Must be last
Introduction
The utility nvs_flash/nvs_partition_generator/nvs_partition_gen.py creates a binary file based on key-value pairs pro-
vided in a CSV file. The binary file is compatible with NVS architecture defined in Non-Volatile Storage. This utility
is ideally suited for generating a binary blob, containing data specific to ODM/OEM, which can be flashed externally
at the time of device manufacturing. This allows manufacturers to generate many instances of the same application
firmware with customized parameters for each device, such as a serial number.
Prerequisites
Each line of a .csv file should contain 4 parameters, separated by a comma. The table below provides the description
for each of these parameters.
Note: The first line of the CSV file should always be the column header and it is not configurable.
Note:
Make sure there are no spaces:
• before and after ‘,’
• at the end of each line in a CSV file
When a namespace entry is encountered in a CSV file, each following entry will be treated as part of that namespace
until the next namespace entry is found. At this point, all the following entries will be treated as part of the new
namespace.
By default, binary blobs are allowed to span over multiple pages and are written in the format mentioned in Section
Structure of entry. If you intend to use an older format, the utility provides an option to disable this feature.
Encryption Support
The NVS Partition Generator utility also allows you to create an encrypted binary file. The utility uses the AES-XTS
encryption. Please refer to NVS Encryption for more details.
Decryption Support
This utility allows you to decrypt an encrypted NVS binary file. The utility uses an NVS binary file encrypted using
AES-XTS encryption. Please refer to NVS Encryption for more details.
Usage:
python nvs_partition_gen.py [-h] {generate,generate-key,encrypt,decrypt} ...
Optional Arguments:
+-----+------------+---------------------------------------------------------------
,→-------+
Commands:
Run nvs_partition_gen.py {command} -h for additional help
+-----+--------------+-------------------------------------------------------------
,→-------+
| Parameter | Description ␣
,→ |
+==============+======================================================================+
| input | Path to CSV file to parse ␣
,→ |
+--------------+----------------------------------------------------------
,→------------+
Optional Arguments:
+-----------------+-------------------------------------------------------
,→-------------+
| Parameter | Description ␣
,→ |
+=================+====================================================================+
| -h, --help | show this help message and exit ␣
,→ |
+-----------------+-------------------------------------------------------
,→-------------+
You can run the utility to generate NVS partition using the command below: A sample CSV file is provided with the
utility:
Optional Arguments:
+--------------------+----------------------------------------------------
,→------------------+
| Parameter | Description ␣
,→ |
+====================+======================================================================+
| -h, --help | show this help message and exit ␣
,→ |
+--------------------+----------------------------------------------------
,→------------------+
You can run the utility to generate only the encryption key partition using the command below:
python nvs_partition_gen.py generate-key
[--outdir OUTDIR]
input output size
Positional Arguments:
+--------------+----------------------------------------------------------
,→------------+
| Parameter | Description ␣
,→ |
+==============+======================================================================+
| input | Path to CSV file to parse ␣
,→ |
+--------------+----------------------------------------------------------
,→------------+
Optional Arguments:
+---------------------+---------------------------------------------------
,→-----------------+
| Parameter | Description ␣
,→ |
(continues on next page)
You can run the utility to encrypt NVS partition using the command below: A sample CSV file is provided with the
utility:
• Encrypt by allowing the utility to generate encryption keys:
python nvs_partition_gen.py encrypt sample_singlepage_blob.csv sample_encr.bin␣
,→0x3000 --keygen
• Encrypt by allowing the utility to generate encryption keys and store it in provided custom filename:
python nvs_partition_gen.py encrypt sample_singlepage_blob.csv sample_encr.bin␣
,→0x3000 --keygen --keyfile sample_keys.bin
Note: This newly created file having encryption keys in keys/ directory is compatible with NVS key-partition
structure. Refer to NVS key partition for more details.
Positional Arguments:
+--------------+----------------------------------------------------------
,→------------+
| Parameter | Description ␣
,→ |
+==============+======================================================================+
| input | Path to encrypted NVS partition file to parse ␣
,→ |
+--------------+----------------------------------------------------------
,→------------+
Optional Arguments:
+---------------------+---------------------------------------------------
,→-----------------+
| Parameter | Description ␣
,→ |
+=====================+====================================================================+
| -h, --help | show this help message and exit ␣
,→ |
+---------------------+---------------------------------------------------
,→-----------------+
You can run the utility to decrypt encrypted NVS partition using the command below:
Multipage Blob Support Disabled (Version 1): You can run the utility in this format by setting the version
parameter to 1, as shown below. A sample CSV file is provided with the utility:
Multipage Blob Support Enabled (Version 2): You can run the utility in this format by setting the version pa-
rameter to 2, as shown below. A sample CSV file is provided with the utility:
Note: When flashing the binary onto the device, make sure it is consistent with the application’s sdkconfig.
Caveats
• Utility does not check for duplicate keys and will write data pertaining to both keys. You need to make sure
that the keys are distinct.
• Once a new page is created, no data will be written in the space left on the previous page. Fields in the CSV
file need to be ordered in such a way as to optimize memory.
• 64-bit datatype is not yet supported.
Overview
The SD/SDIO/MMC driver currently supports SD memory, SDIO cards, and eMMC chips. This is a protocol level
driver built on top of SDMMC and SD SPI host drivers.
SDMMC and SD SPI host drivers (driver/include/driver/sdmmc_host.h and driver/include/driver/sdspi_host.h) pro-
vide API functions for:
• Sending commands to slave devices
• Sending and receiving data
• Handling error conditions within the bus
For functions used to initialize and configure:
Application Example
An example which combines the SDMMC driver with the FATFS library is provided in the storage/sd_card directory
of ESP-IDF examples. This example initializes the card, then writes and reads data from it using POSIX and C library
APIs. See README.md file in the example directory for more information.
Combo (memory + IO) cards The driver does not support SD combo cards. Combo cards are treated as IO cards.
Thread safety Most applications need to use the protocol layer only in one task. For this reason, the protocol layer
does not implement any kind of locking on the sdmmc_card_t structure, or when accessing SDMMC or SD SPI
host drivers. Such locking is usually implemented on a higher layer, e.g., in the filesystem driver.
The protocol layer is given the sdmmc_host_t structure. This structure describes the SD/MMC host driver, lists
its capabilities, and provides pointers to functions of the driver. The protocol layer stores card-specific information in
the sdmmc_card_t structure. When sending commands to the SD/MMC host driver, the protocol layer uses the
sdmmc_command_t structure to describe the command, arguments, expected return values, and data to transfer if
there is any.
Using API with eMMC chips From the protocol layer’s perspective, eMMC memory chips behave exactly like
SD memory cards. Even though eMMCs are chips and do not have a card form factor, the terminology for SD cards
can still be applied to eMMC due to the similarity of the protocol (sdmmc_card_t, sdmmc_card_init). Note that
eMMC chips cannot be used over SPI, which makes them incompatible with the SD SPI host driver.
To initialize eMMC memory and perform read/write operations, follow the steps listed for SD cards in the previous
section.
Using API with SDIO cards Initialization and the probing process are the same as with SD memory cards. The
only difference is in data transfer commands in SDIO mode.
During the card initialization and probing, performed with sdmmc_card_init(), the driver only configures the
following registers of the IO card:
1. The IO portion of the card is reset by setting RES bit in the I/O Abort (0x06) register.
2. If 4-line mode is enabled in host and slot configuration, the driver attempts to set the Bus width field in the Bus
Interface Control (0x07) register. If setting the filed is successful, which means that the slave supports 4-line
mode, the host is also switched to 4-line mode.
3. If high-speed mode is enabled in the host configuration, the SHS bit is set in the High Speed (0x13) register.
In particular, the driver does not set any bits in (1) I/O Enable and Int Enable registers, (2) I/O block sizes, etc.
Applications can set them by calling sdmmc_io_write_byte().
For card configuration and data transfer, choose the pair of functions relevant to your case from the table below.
SDIO interrupts can be enabled by the application using the function sdmmc_io_enable_int(). When using
SDIO in 1-line mode, the D1 line also needs to be connected to use SDIO interrupts.
If you want the application to wait until the SDIO interrupt occurs, use sdmmc_io_wait_int().
There is a component ESSL (ESP Serial Slave Link) to use if you are communicating with an ESP32 SDIO slave.
See ESP Serial Slave Link and example peripherals/sdio/host.
API Reference
Header File
• components/sdmmc/include/sdmmc_cmd.h
Functions
esp_err_t sdmmc_card_init(const sdmmc_host_t *host, sdmmc_card_t *out_card)
Probe and initialize SD/MMC card using given host
Note: Only SD cards (SDSC and SDHC/SDXC) are supported now. Support for MMC/eMMC cards will be
added later.
Parameters
• host –pointer to structure defining host controller
• out_card –pointer to structure which will receive information about the card when the
function completes
Returns
• ESP_OK on success
• One of the error codes from SDMMC host controller
void sdmmc_card_print_info(FILE *stream, const sdmmc_card_t *card)
Print information about the card to a stream.
Parameters
• stream –stream obtained using fopen or fdopen
• card –card information structure initialized using sdmmc_card_init
esp_err_t sdmmc_get_status(sdmmc_card_t *card)
Get status of SD/MMC card
Parameters card –pointer to card information structure previously initialized using sd-
mmc_card_init
Returns
• ESP_OK on success
• One of the error codes from SDMMC host controller
esp_err_t sdmmc_write_sectors(sdmmc_card_t *card, const void *src, size_t start_sector, size_t
sector_count)
Write given number of sectors to SD/MMC card
Parameters
• card –pointer to card information structure previously initialized using sdmmc_card_init
• src –pointer to data buffer to read data from; data size must be equal to sector_count *
card->csd.sector_size
• start_sector –sector where to start writing
• sector_count –number of sectors to write
Returns
• ESP_OK on success
• One of the error codes from SDMMC host controller
Note: When sdmmc_erase_sectors used with cards in SDSPI mode, it was observed that card requires re-init
after erase operation.
Parameters
• card –pointer to card information structure previously initialized using sdmmc_card_init
• start_sector –sector where to start erase
• sector_count –number of sectors to erase
• arg –erase command (CMD38) argument
Returns
• ESP_OK on success
• One of the error codes from SDMMC host controller
Note: Discard command has to precede sanitize operation. To discard, use MMC_DICARD_ARG with
sdmmc_erase_sectors argument
Parameters
• card –pointer to card information structure previously initialized using sdmmc_card_init
• timeout_ms –timeout value in milliseconds required to sanitize the selected range of
sectors.
Returns
• ESP_OK on success
• One of the error codes from SDMMC host controller
Parameters card –pointer to card information structure previously initialized using sd-
mmc_card_init
Returns
• ESP_OK on success
• ESP_ERR_NOT_SUPPORTED if the host controller does not support IO interrupts
esp_err_t sdmmc_io_wait_int(sdmmc_card_t *card, TickType_t timeout_ticks)
Block until an SDIO interrupt is received
Slave uses D1 line to signal interrupt condition to the host. This function can be used to wait for the interrupt.
Parameters
• card –pointer to card information structure previously initialized using sdmmc_card_init
• timeout_ticks –time to wait for the interrupt, in RTOS ticks
Returns
• ESP_OK if the interrupt is received
• ESP_ERR_NOT_SUPPORTED if the host controller does not support IO interrupts
• ESP_ERR_TIMEOUT if the interrupt does not happen in timeout_ticks
esp_err_t sdmmc_io_get_cis_data(sdmmc_card_t *card, uint8_t *out_buffer, size_t buffer_size, size_t
*inout_cis_size)
Get the data of CIS region of an SDIO card.
You may provide a buffer not sufficient to store all the CIS data. In this case, this function stores as much data
into your buffer as possible. Also, this function will try to get and return the size required for you.
Parameters
• card –pointer to card information structure previously initialized using sdmmc_card_init
• out_buffer –Output buffer of the CIS data
• buffer_size –Size of the buffer.
• inout_cis_size –Mandatory, pointer to a size, input and output.
– input: Limitation of maximum searching range, should be 0 or larger than buffer_size.
The function searches for CIS_CODE_END until this range. Set to 0 to search in-
finitely.
– output: The size required to store all the CIS data, if CIS_CODE_END is found.
Returns
• ESP_OK: on success
• ESP_ERR_INVALID_RESPONSE: if the card does not (correctly) support CIS.
• ESP_ERR_INVALID_SIZE: CIS_CODE_END found, but buffer_size is less than re-
quired size, which is stored in the inout_cis_size then.
• ESP_ERR_NOT_FOUND: if the CIS_CODE_END not found. Increase input value of
inout_cis_size or set it to 0, if you still want to search for the end; output value of in-
out_cis_size is invalid in this case.
• and other error code return from sdmmc_io_read_bytes
esp_err_t sdmmc_io_print_cis_info(uint8_t *buffer, size_t buffer_size, FILE *fp)
Parse and print the CIS information of an SDIO card.
Note: Not all the CIS codes and all kinds of tuples are supported. If you see some unresolved code, you can
add the parsing of these code in sdmmc_io.c and contribute to the IDF through the Github repository.
using sdmmc_card_init
Parameters
• buffer –Buffer to parse
• buffer_size –Size of the buffer.
• fp –File pointer to print to, set to NULL to print to stdout.
Returns
• ESP_OK: on success
Header File
• components/driver/include/driver/sdmmc_types.h
Structures
struct sdmmc_csd_t
Decoded values from SD card Card Specific Data register
Public Members
int csd_ver
CSD structure format
int mmc_ver
MMC version (for CID format)
int capacity
total number of sectors
int sector_size
sector size in bytes
int read_block_len
block length for reads
int card_command_class
Card Command Class for SD
int tr_speed
Max transfer speed
struct sdmmc_cid_t
Decoded values from SD card Card IDentification register
Public Members
int mfg_id
manufacturer identification number
int oem_id
OEM/product identification number
char name[8]
product name (MMC v1 has the longest)
int revision
product revision
int serial
product serial number
int date
manufacturing date
struct sdmmc_scr_t
Decoded values from SD Configuration Register Note: When new member is added, update reserved bits
accordingly
Public Members
uint32_t sd_spec
SD Physical layer specification version, reported by card
uint32_t erase_mem_state
data state on card after erase whether 0 or 1 (card vendor dependent)
uint32_t bus_width
bus widths supported by card: BIT(0) —1-bit bus, BIT(2) —4-bit bus
uint32_t reserved
reserved for future expansion
uint32_t rsvd_mnf
reserved for manufacturer usage
struct sdmmc_ssr_t
Decoded values from SD Status Register Note: When new member is added, update reserved bits accordingly
Public Members
uint32_t alloc_unit_kb
Allocation unit of the card, in multiples of kB (1024 bytes)
uint32_t erase_size_au
Erase size for the purpose of timeout calculation, in multiples of allocation unit
uint32_t cur_bus_width
SD current bus width
uint32_t discard_support
SD discard feature support
uint32_t fule_support
SD FULE (Full User Area Logical Erase) feature support
uint32_t erase_timeout
Timeout (in seconds) for erase of a single allocation unit
uint32_t erase_offset
Constant timeout offset (in seconds) for any erase operation
uint32_t reserved
reserved for future expansion
struct sdmmc_ext_csd_t
Decoded values of Extended Card Specific Data
Public Members
uint8_t rev
Extended CSD Revision
uint8_t power_class
Power class used by the card
uint8_t erase_mem_state
data state on card after erase whether 0 or 1 (card vendor dependent)
uint8_t sec_feature
secure data management features supported by the card
struct sdmmc_switch_func_rsp_t
SD SWITCH_FUNC response buffer
Public Members
struct sdmmc_command_t
SD/MMC command information
Public Members
uint32_t opcode
SD or MMC command index
uint32_t arg
SD/MMC command argument
sdmmc_response_t response
response buffer
void *data
buffer to send or read into
size_t datalen
length of data buffer
size_t blklen
block length
int flags
see below
esp_err_t error
error returned from transfer
uint32_t timeout_ms
response timeout, in milliseconds
struct sdmmc_host_t
SD/MMC Host description
This structure defines properties of SD/MMC host and functions of SD/MMC host which can be used by upper
layers.
Public Members
uint32_t flags
flags defining host properties
int slot
slot number, to be passed to host functions
int max_freq_khz
max frequency supported by the host
float io_voltage
I/O voltage used by the controller (voltage switching is not supported)
esp_err_t (*init)(void)
Host function to initialize the driver
esp_err_t (*deinit)(void)
host function to deinitialize the driver
int command_timeout_ms
timeout, in milliseconds, of a single command. Set to 0 to use the default value.
struct sdmmc_card_t
SD/MMC card information structure
Public Members
sdmmc_host_t host
Host with which the card is associated
uint32_t ocr
OCR (Operation Conditions Register) value
sdmmc_cid_t cid
decoded CID (Card IDentification) register value
sdmmc_response_t raw_cid
raw CID of MMC card to be decoded after the CSD is fetched in the data transfer mode
sdmmc_csd_t csd
decoded CSD (Card-Specific Data) register value
sdmmc_scr_t scr
decoded SCR (SD card Configuration Register) value
sdmmc_ssr_t ssr
decoded SSR (SD Status Register) value
sdmmc_ext_csd_t ext_csd
decoded EXT_CSD (Extended Card Specific Data) register value
uint16_t rca
RCA (Relative Card Address)
uint16_t max_freq_khz
Maximum frequency, in kHz, supported by the card
uint32_t is_mem
Bit indicates if the card is a memory card
uint32_t is_sdio
Bit indicates if the card is an IO card
uint32_t is_mmc
Bit indicates if the card is MMC
uint32_t num_io_functions
If is_sdio is 1, contains the number of IO functions on the card
uint32_t log_bus_width
log2(bus width supported by card)
uint32_t is_ddr
Card supports DDR mode
uint32_t reserved
Reserved for future expansion
Macros
SDMMC_HOST_FLAG_1BIT
host supports 1-line SD and MMC protocol
SDMMC_HOST_FLAG_4BIT
host supports 4-line SD and MMC protocol
SDMMC_HOST_FLAG_8BIT
host supports 8-line MMC protocol
SDMMC_HOST_FLAG_SPI
host supports SPI protocol
SDMMC_HOST_FLAG_DDR
host supports DDR mode for SD/MMC
SDMMC_HOST_FLAG_DEINIT_ARG
host deinit function called with the slot argument
SDMMC_FREQ_DEFAULT
SD/MMC Default speed (limited by clock divider)
SDMMC_FREQ_HIGHSPEED
SD High speed (limited by clock divider)
SDMMC_FREQ_PROBING
SD/MMC probing speed
SDMMC_FREQ_52M
MMC 52MHz speed
SDMMC_FREQ_26M
MMC 26MHz speed
Type Definitions
Enumerations
enum sdmmc_erase_arg_t
SD/MMC erase command(38) arguments SD: ERASE: Erase the write blocks, physical/hard erase.
DISCARD: Card may deallocate the discarded blocks partially or completely. After discard operation the
previously written data may be partially or fully read by the host depending on card implementation.
MMC: ERASE: Does TRIM, applies erase operation to write blocks instead of Erase Group.
DISCARD: The Discard function allows the host to identify data that is no longer required so that the device
can erase the data if necessary during background erase events. Applies to write blocks instead of Erase Group
After discard operation, the original data may be remained partially or fully accessible to the host dependent
on device.
Values:
enumerator SDMMC_ERASE_ARG
Erase operation on SD, Trim operation on MMC
enumerator SDMMC_DISCARD_ARG
Discard operation for SD/MMC
Overview
The spi_flash component contains API functions related to reading, writing, erasing, memory mapping for data in
the external flash. The spi_flash component also has higher-level API functions which work with partitions defined
in the partition table.
Different from the API before IDF v4.0, the functionality of esp_flash_* APIs is not limited to the“main”SPI flash
chip (the same SPI flash chip from which program runs). With different chip pointers, you can access external flash
chips connected to not only SPI0/1 but also other SPI buses like SPI2.
Note: Instead of going through the cache connected to the SPI0 peripheral, most esp_flash_* APIs go through other
SPI peripherals like SPI1, SPI2, etc. This makes them able to access not only the main flash, but also external flash.
However, due to limitations of the cache, operations through the cache are limited to the main flash. The address
range limitation for these operations are also on the cache side. The cache is not able to access external flash chips
or address range above its capabilities. These cache operations include: mmap, encrypted read/write, executing code
or access to variables in the flash.
Note: Flash APIs after ESP-IDF v4.0 are no longer atomic. If a write operation occurs during another on-going
read operation, and the flash addresses of both operations overlap, the data returned from the read operation may
contain both old data and new data (that was updated written by the write operation).
Note: Encrypted flash operations are only supported with the main flash chip (and not with other flash chips, that is
on SPI1 with different CS, or on other SPI buses). Reading through cache is only supported on the main flash, which
is determined by the HW.
Quad/Dual Mode Chips Features of different flashes are implemented in different ways and thus need speical
support. The fast/slow read and Dual mode (DOUT/DIO) of almost all 24-bits address flash chips are supported,
because they don’t need any vendor-specific commands.
Quad mode (QIO/QOUT) is supported on following chip types:
1. ISSI
2. GD
3. MXIC
4. FM
5. Winbond
6. XMC
7. BOYA
Optional Features
Optional features for flash Some features are not supported on all ESP chips and Flash chips. You can check the
list below for more information.
• Auto Suspend & Resume
• Flash unique ID
• High performance mode
• OPI flash support
• 32-bit Address Flash Chips
Note:
• The features listed above needs to be supported by both esp chips and flash chips.
• If you are using an official Espressif modules/SiP. Some of the modules/SiPs always support the feature, in this
case you can see these features listed in the datasheet. Otherwise please contact Espressif’s business team to
know if we can supply such products for you.
• If you are making your own modules with your own bought flash chips, and you need features listed above.
Please contact your vendor if they support the those features, and make sure that the chips can be supplied
continuously.
Attention: This document only shows that IDF code has supported the features of those flash chips. It’s not
a list of stable flash chips certified by Espressif. If you build your own hardware from flash chips with your own
brought flash chips (even with flash listed in this page), you need to validate the reliability of flash chips yourself.
Flash unique ID Unique ID is not flash id, which means flash has 64-Bit unique ID for each device. The instruction
to read the unique ID (4Bh) accesses a factory-set read-only 64-bit number that is unique to each flash device. This
ID number helps you to recognize each single device. Not all flash vendors support this feature. If you try to read the
unique ID on a chip which does not have this feature, the behavior is not determined. The support list is as follows.
ESP Chips Lists:
ALL
Flash Chips List:
1. ISSI
2. GD
3. TH
4. FM
5. Winbond
6. XMC
7. BOYA
High performance mode (HPM) means that the SPI1 and flash chip works under high frequency. Usually, when the
operating frequency of the flash is greater than 80MHz, it is considered that the flash works under HPM. As far as
we acknowledged, flash chips have more than two different coping strategies when flash work under HPM. For some
flash chips, HPM is controlled by high performance flag (HPF) in status register and for some flash chips, HPM is
controlled by dummy cycle bit.
For following conditions,IDF start code deals with HPM internally.
ESP Chips List:
1. ESP32S3
Attention: It is hard to create several strategies to cover all situations, so all flash chips using HPM need to be
supported explicitly. Therefore, if you try to use a flash not listed as supported under high performance mode, it
might cause some error. So, when you try to use the flash chip beyond supported list, please test properly.
OPI flash support OPI flash means that the flash chip supports octal peripheral interface, which has octal I/O pins.
Different octal flash has different configurations and different commands. Hence, it is necessary to carefully check
the support list.
ESP Chips List:
1. ESP32S3
Flash Chips List:
1. MX25UM25645G
32-bit Address Flash Chips Most NOR flash chips used by Espressif chips use 24-bits address, which can cover
16 MBytes memory. However, for larger memory (usually equal to or larger than 16 MBytes), flash uses a 32-bits
address to address larger memory. Regretfully, 32-bits address chips have vendor-specific commands, so we need to
support the chips one by one.
ESP Chips List:
ALL ESP Chips support this.
Flash Chips List:
1. W25Q256
2. GD25Q256
There are some features that are not supported by all flash chips, or not supported by all Espressif chips. These
features include:
• 32-bit address flash - usually means that the flash has higher capacity (equal to or larger than 16 MB) that needs
longer addresses.
• Flash unique ID - means that flash supports its unique 64-bits ID.
If you want to use these features, please ensure both ESP32 and ALL flash chips in your product support these
features. For more details, refer to Optional features for flash.
You may also customise your own flash chip driver. See Overriding Default Chip Drivers for more details.
Warning: Customizing SPI Flash Chip Drivers is considered an “expert”feature. Users should only do so at
their own risk. (See the notes below)
Overriding Default Chip Drivers During the SPI Flash driver’s initialization (i.e., esp_flash_init()),
there is a chip detection step during which the driver will iterate through a Default Chip Driver List and determine
which chip driver can properly support the currently connected flash chip. The Default Chip Drivers are provided by
the IDF, thus are updated in together with each IDF version. However IDF also allows users to customize their own
chip drivers.
Users should note the following when customizing chip drivers:
1. You may need to rely on some non-public IDF functions, which have slight possibility to change between IDF
versions. On the one hand, these changes may be useful bug fixes for your driver, on the other hand, they may
also be breaking changes (i.e., breaks your code).
2. Some IDF bug fixes to other chip drivers will not be automatically applied to your own custom chip drivers.
3. If the protection of flash is not handled properly, there may be some random reliability issues.
4. If you update to a newer IDF version that has support for more chips, you will have to manually add those new
chip drivers into your custom chip driver list. Otherwise the driver will only search for the drivers in custom
list you provided.
Steps For Creating Custom Chip Drivers and Overriding the IDF Default Driver List
1. Enable the CONFIG_SPI_FLASH_OVERRIDE_CHIP_DRIVER_LIST config option. This will prevent compila-
tion and linking of the Default Chip Driver List (default_registered_chips) provided by IDF. Instead, the linker
will search for the structure of the same name (default_registered_chips) that must be provided by the user.
2. Add a new component in your project, e.g. custom_chip_driver.
3. Copy the necessary chip driver files from the spi_flash component in IDF. This may include:
• spi_flash_chip_drivers.c (to provide the default_registered_chips structure)
• Any of the spi_flash_chip_*.c files that matches your own flash model best
• CMakeLists.txt and linker.lf files
Modify the files above properly.
Note:
• When writing your own flash chip driver, you can set your flash chip capabilities through
spi_flash_chip_***(vendor)_get_caps and points the function pointer get_chip_caps for protection to
the spi_flash_chip_***_get_caps function. The steps are as follows.
1. Please check whether your flash chip have the capabilities listed in spi_flash_caps_t by check-
ing the flash datasheet.
2. Write a function named spi_flash_chip_***(vendor)_get_caps. Take the example below as a
reference. (if the flash support suspend and read unique id).
3. Points the the pointer get_chip_caps (in spi_flash_chip_t) to the function mentioned above.
• You also can see how to implement this in the example storage/custom_flash_driver.
4. Add linking dependency from spi_flash component to the new custom_chip_driver component, by adding the
following lines after the idf_component_register, in the CMakeLists.txt file of the custom_chip_driver compo-
nent:
idf_component_get_property(spi_flash_lib spi_flash COMPONENT_LIB)
set_property(TARGET ${spi_flash_lib} APPEND PROPERTY INTER-
FACE_LINK_LIBRARIES $<LINK_ONLY:${COMPONENT_LIB}>)
5. The linker.lf is used to put every chip driver that you are going to use whilst cache is disabled into internal
RAM. See Linker Script Generation for more details. Make sure this file covers all the source files that you add.
6. Build your project, and you will see the new flash driver is used.
To use the esp_flash_* APIs, you need to initialise a flash chip on a certain SPI bus, as shown below:
1. Call spi_bus_initialize() to properly initialize an SPI bus. This function initializes the resources
(I/O, DMA, interrupts) shared among devices attached to this bus.
2. Call spi_bus_add_flash_device() to attach the flash device to the bus. This function allocates mem-
ory and fills the members for the esp_flash_t structure. The CS I/O is also initialized here.
3. Call esp_flash_init() to actually communicate with the chip. This will also detect the chip type, and
influence the following operations.
Note: Multiple flash chips can be attached to the same bus now.
This is the set of API functions for working with data in flash:
• esp_flash_read() reads data from flash to RAM
• esp_flash_write() writes data from RAM to flash
• esp_flash_erase_region() erases specific region of flash
• esp_flash_erase_chip() erases the whole flash
• esp_flash_get_chip_size() returns flash chip size, in bytes, as configured in menuconfig
Generally, try to avoid using the raw SPI flash functions to the “main”SPI flash chip in favour of partition-specific
functions.
The SPI flash size is configured by writing a field in the software bootloader image header, flashed at offset 0x1000.
By default, the SPI flash size is detected by esptool.py when this bootloader is written to flash, and the header
is updated with the correct size. Alternatively, it is possible to generate a fixed flash size by setting CON-
FIG_ESPTOOLPY_FLASHSIZE in the project configuration.
If it is necessary to override the configured flash size at runtime, it is possible to set the chip_size member of
the g_rom_flashchip structure. This size is used by esp_flash_* functions (in both software & ROM) to
check the bounds.
Concurrency Constraints for flash on SPI1 The SPI0/1 bus is shared between the instruction & data cache
(for firmware execution) and the SPI1 peripheral (controlled by the drivers including this SPI Flash driver). Hence,
operations to SPI1 will cause significant influence to the whole system. This kind of operations include calling SPI
Flash API or other drivers on SPI1 bus, any operations like read/write/erase or other user defined SPI operations,
regardless to the main flash or other SPI slave devices.
On ESP32, these caches must be disabled while reading/writing/erasing.
When the caches are disabled Under this condition, all CPUs should always execute code and access data from
internal RAM. The APIs documented in this file will disable the caches automatically and transparently.
The way that these APIs disable the caches will suspend all the other tasks. Besides, all non-IRAM-safe interrupts
will be disabled. The other core will be polling in a busy loop. These will be restored until the Flash operation
completes.
IRAM-Safe Interrupt Handlers For interrupt handlers which need to execute when the cache is disabled (e.g.,
for low latency operations), set the ESP_INTR_FLAG_IRAM flag when the interrupt handler is registered.
You must ensure that all data and functions accessed by these interrupt handlers, including the ones that handlers call,
are located in IRAM or DRAM. See How to place code in IRAM.
If a function or symbol is not correctly put into IRAM/DRAM, and the interrupt handler reads from the flash cache
during a flash operation, it will cause a crash due to Illegal Instruction exception (for code which should be in IRAM)
or garbage data to be read (for constant data which should be in DRAM).
Note: When working with strings in ISRs, it is not advised to use printf and other output functions. For debugging
purposes, use ESP_DRAM_LOGE() and similar macros when logging from ISRs. Make sure that both TAG and
format string are placed into DRAM in that case.
Non-IRAM-Safe Interrupt Handlers If the ESP_INTR_FLAG_IRAM flag is not set when registering, the in-
terrupt handler will not get executed when the caches are disabled. Once the caches are restored, the non-IRAM-safe
interrupts will be re-enabled. After this moment, the interrupt handler will run normally again. This means that as
long as caches are disabled, users won’t see the corresponding hardware event happening.
Attention: The SPI0/1 bus is shared between the instruction & data cache (for firmware execution) and the SPI1
peripheral (controlled by the drivers including this SPI flash driver). Hence, calling SPI Flash API on SPI1 bus
(including the main flash) will cause significant influence to the whole system. See Concurrency Constraints for
flash on SPI1 for more details.
ESP-IDF projects use a partition table to maintain information about various regions of SPI flash memory (bootloader,
various application binaries, data, filesystems). More information can be found in Partition Tables.
This component provides API functions to enumerate partitions found in the partition table and perform operations
on them. These functions are declared in esp_partition.h:
• esp_partition_find() checks a partition table for entries with specific type, returns an opaque iterator.
• esp_partition_get() returns a structure describing the partition for a given iterator.
• esp_partition_next() shifts the iterator to the next found partition.
• esp_partition_iterator_release() releases iterator returned by esp_partition_find.
• esp_partition_find_first() is a convenience function which returns the structure describing the
first partition found by esp_partition_find.
• esp_partition_read(), esp_partition_write(), esp_partition_erase_range()
are equivalent to esp_flash_read(), esp_flash_write(), esp_flash_erase_region(),
but operate within partition boundaries.
Note: Application code should mostly use these esp_partition_* API functions instead of lower level
esp_flash_* API functions. Partition table API functions do bounds checking and calculate correct offsets in
flash, based on data stored in a partition table.
It is possible to encrypt the contents of SPI flash and have it transparently decrypted by hardware.
Refer to the Flash Encryption documentation for more details.
ESP32 features memory hardware which allows regions of flash memory to be mapped into instruction and data
address spaces. This mapping works only for read operations. It is not possible to modify contents of flash memory
by writing to a mapped memory region.
Mapping happens in 64 KB pages. Memory mapping hardware can map flash into the data address space and the
instruction address space. See the technical reference manual for more details and limitations about memory mapping
hardware.
Note that some pages are used to map the application itself into memory, so the actual number of available pages
may be less than the capability of the hardware.
Reading data from flash using a memory mapped region is the only way to decrypt contents of flash when flash
encryption is enabled. Decryption is performed at the hardware level.
Memory mapping API are declared in spi_flash_mmap.h and esp_partition.h:
• spi_flash_mmap() maps a region of physical flash addresses into instruction space or data space of the
CPU.
• spi_flash_munmap() unmaps previously mapped region.
• esp_partition_mmap() maps part of a partition into the instruction space or data space of the CPU.
Differences between spi_flash_mmap() and esp_partition_mmap() are as follows:
• spi_flash_mmap() must be given a 64 KB aligned physical address.
• esp_partition_mmap() may be given any arbitrary offset within the partition. It will adjust the returned
pointer to mapped memory as necessary.
Note that since memory mapping happens in pages, it may be possible to read data outside of the partition provided
to esp_partition_mmap, regardless of the partition boundary.
The esp_flash_t structure holds chip data as well as three important parts of this API:
1. The host driver, which provides the hardware support to access the chip;
2. The chip driver, which provides compatibility service to different chips;
3. The OS functions, provide support of some OS functions (e.g. lock, delay) in different stages (1st/2nd boot, or
the app).
Host driver The host driver relies on an interface (spi_flash_host_driver_t) defined in the
spi_flash_types.h (in the hal/include/hal folder). This interface provides some common functions to
communicate with the chip.
In other files of the SPI HAL, some of these functions are implemented with existing ESP32 memory-spi function-
alities. However, due to the speed limitations of ESP32, the HAL layer cannot provide high-speed implementations
to some reading commands (so the support for it was dropped). The files (memspi_host_driver.h and .c)
implement the high-speed version of these commands with the common_command function provided in the HAL,
and wrap these functions as spi_flash_host_driver_t for upper layer to use.
You can also implement your own host driver, even with the GPIO. As long as all the functions in the
spi_flash_host_driver_t are implemented, the esp_flash API can access the flash regardless of the low-
level hardware.
Chip Driver The chip driver, defined in spi_flash_chip_driver.h, wraps basic functions provided by the
host driver for the API layer to use.
Some operations need some commands to be sent first, or read some status afterwards. Some chips need different
commands or values, or need special communication ways.
There is a type of chip called generic chip which stands for common chips. Other special chip drivers can be
developed on the base of the generic chip.
The chip driver relies on the host driver.
OS Functions Currently the OS function layer provides entries of a lock and delay.
The lock (see SPI Bus Lock) is used to resolve the conflicts among the access of devices on the same SPI bus, and the
SPI Flash chip access. E.g.
1. On SPI1 bus, the cache (used to fetch the data (code) in the Flash and PSRAM) should be disabled when the
flash chip on the SPI0/1 is being accessed.
2. On the other buses, the flash driver needs to disable the ISR registered by SPI Master driver, to avoid conflicts.
3. Some devices of SPI Master driver may require to use the bus monopolized during a period (especially when
the device doesn’t have a CS wire, or the wire is controlled by software like SDSPI driver).
The delay is used by some long operations which requires the master to wait or polling periodically.
The top API wraps these the chip driver and OS functions into an entire component, and also provides some argument
checking.
OS functions can also help to avoid a watchdog timeout when erasing large flash areas. During this time, the CPU is
occupied with the flash erasing task. This stops other tasks from being executed. Among these tasks is the idle task
to feed the watchdog timer (WDT). If the configuration option CONFIG_ESP_TASK_WDT_PANIC is selected and
the flash operation time is longer than the watchdog timeout period, the system will reboot.
It’s pretty hard to totally eliminate this risk, because the erasing time varies with different flash chips, making it hard
to be compatible in flash drivers. Therefore, users need to pay attention to it. Please use the following guidelines:
1. It is recommended to enable the CONFIG_SPI_FLASH_YIELD_DURING_ERASE option to allow the scheduler
to re-schedule during erasing flash memory. Besides, following parameters can also be used.
• Increase CONFIG_SPI_FLASH_ERASE_YIELD_TICKS or decrease CON-
FIG_SPI_FLASH_ERASE_YIELD_DURATION_MS in menuconfig.
• You can also increase CONFIG_ESP_TASK_WDT_TIMEOUT_S in menuconfig for a larger watchdog timeout
period. However, with larger watchdog timeout period, previously detected timeouts may no longer be detected.
2. Please be aware of the consequences of enabling the CONFIG_ESP_TASK_WDT_PANIC option when doing
long-running SPI flash operations which will trigger the panic handler when it times out. However, this option
can also help dealing with unexpected exceptions in your application. Please decide whether this is needed to
be enabled according to actual condition.
3. During your development, please carefully review the actual flash operation according to the specific require-
ments and time limits on erasing flash memory of your projects. Always allow reasonable redundancy based
on your specific product requirements when configuring the flash erasing timeout threshold, thus improving the
reliability of your product.
See Also
Implementation Details
In order to perform some flash operations, it is necessary to make sure that both CPUs are not running any code from
flash for the duration of the flash operation: - In a single-core setup, the SDK needs to disable interrupts or scheduler
before performing the flash operation. - In a dual-core setup, the SDK needs to make sure that both CPUs are not
running any code from flash.
When SPI flash API is called on CPU A (can be PRO or APP), start the spi_flash_op_block_func function
on CPU B using the esp_ipc_call API. This API wakes up a high priority task on CPU B and tells it to execute
a given function, in this case, spi_flash_op_block_func. This function disables cache on CPU B and signals
that the cache is disabled by setting the s_flash_op_can_start flag. Then the task on CPU A disables cache
as well and proceeds to execute flash operation.
While a flash operation is running, interrupts can still run on CPUs A and B. It is assumed that all interrupt code is
placed into RAM. Once the interrupt allocation API is added, a flag should be added to request the interrupt to be
disabled for the duration of a flash operations.
Once the flash operation is complete, the function on CPU A sets another flag, s_flash_op_complete, to let
the task on CPU B know that it can re-enable cache and release the CPU. Then the function on CPU A re-enables
the cache on CPU A as well and returns control to the calling code.
Additionally, all API functions are protected with a mutex (s_flash_op_mutex).
In a single core environment (CONFIG_FREERTOS_UNICORE enabled), you need to disable both caches, so that no
inter-CPU communication can take place.
Header File
• components/spi_flash/include/esp_flash_spi_init.h
Functions
esp_err_t spi_bus_add_flash_device(esp_flash_t **out_chip, const esp_flash_spi_device_config_t
*config)
Add a SPI Flash device onto the SPI bus.
The bus should be already initialized by spi_bus_initialization.
Parameters
• out_chip –Pointer to hold the initialized chip.
• config –Configuration of the chips to initialize.
Returns
• ESP_ERR_INVALID_ARG: out_chip is NULL, or some field in the config is invalid.
• ESP_ERR_NO_MEM: failed to allocate memory for the chip structures.
• ESP_OK: success.
esp_err_t spi_bus_remove_flash_device(esp_flash_t *chip)
Remove a SPI Flash device from the SPI bus.
Parameters chip –The flash device to remove.
Returns
• ESP_ERR_INVALID_ARG: The chip is invalid.
• ESP_OK: success.
Structures
struct esp_flash_spi_device_config_t
Configurations for the SPI Flash to init.
Public Members
spi_host_device_t host_id
Bus to use.
int cs_io_num
GPIO pin to output the CS signal.
esp_flash_io_mode_t io_mode
IO mode to read from the Flash.
int input_delay_ns
Input delay of the data pins, in ns. Set to 0 if unknown.
int cs_id
CS line ID, ignored when not host_id is not SPI1_HOST, or CON-
FIG_SPI_FLASH_SHARE_SPI1_BUS is enabled. In this case, the CS line used is automatically
assigned by the SPI bus lock.
int freq_mhz
The frequency of flash chip(MHZ)
Header File
• components/spi_flash/include/esp_flash.h
Functions
esp_err_t esp_flash_init(esp_flash_t *chip)
Initialise SPI flash chip interface.
This function must be called before any other API functions are called for this chip.
Note: Only the host and read_mode fields of the chip structure must be initialised before this function is
called. Other fields may be auto-detected if left set to zero or NULL.
Note: If the chip->drv pointer is NULL, chip chip_drv will be auto-detected based on its manufacturer &
product IDs. See esp_flash_registered_flash_drivers pointer for details of this process.
Parameters chip –Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substi-
tuted.
Returns ESP_OK on success, or a flash error code if initialisation fails.
bool esp_flash_chip_driver_initialized(const esp_flash_t *chip)
Check if appropriate chip driver is set.
Parameters chip –Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substi-
tuted.
Returns true if set, otherwise false.
ID is a 24-bit value. Lower 16 bits of ‘id’are the chip ID, upper 8 bits are the manufacturer ID.
Parameters
• chip –Pointer to identify flash chip. Must have been successfully initialised via
esp_flash_init()
• out_id –[out] Pointer to receive ID value.
Returns ESP_OK on success, or a flash error code if operation failed.
esp_err_t esp_flash_get_size(esp_flash_t *chip, uint32_t *out_size)
Detect flash size based on flash ID.
Note: Most flash chips use a common format for flash ID, where the lower 4 bits specify the size as a power
of 2. If the manufacturer doesn’t follow this convention, the size may be incorrectly detected.
Parameters
• chip –Pointer to identify flash chip. Must have been successfully initialised via
esp_flash_init()
• out_size –[out] Detected size in bytes.
Returns ESP_OK on success, or a flash error code if operation failed.
ID is a 64-bit value.
Parameters
• chip –Pointer to identify flash chip. Must have been successfully initialised via
esp_flash_init().
• out_id –[out] Pointer to receive unique ID value.
Returns
• ESP_OK on success, or a flash error code if operation failed.
• ESP_ERR_NOT_SUPPORTED if the chip doesn’t support read id.
esp_err_t esp_flash_erase_chip(esp_flash_t *chip)
Erase flash chip contents.
Parameters chip –Pointer to identify flash chip. Must have been successfully initialised via
esp_flash_init()
Returns
• ESP_OK on success,
• ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is
indicated by WREN = 1 after the command is sent.
• Other flash error code if operation failed.
esp_err_t esp_flash_erase_region(esp_flash_t *chip, uint32_t start, uint32_t len)
Erase a region of the flash chip.
Parameters
• chip –Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted.
Must have been successfully initialised via esp_flash_init()
• start –Address to start erasing flash. Must be sector aligned.
• len –Length of region to erase. Must also be sector aligned.
Returns
• ESP_OK on success,
• ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is
indicated by WREN = 1 after the command is sent.
• Other flash error code if operation failed.
esp_err_t esp_flash_get_chip_write_protect(esp_flash_t *chip, bool *write_protected)
Read if the entire chip is write protected.
Note: A correct result for this flag depends on the SPI flash chip model and chip_drv in use (via the ‘chip-
>drv’field).
Parameters
• chip –Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted.
Must have been successfully initialised via esp_flash_init()
• write_protected –[out] Pointer to boolean, set to the value of the write protect flag.
Returns ESP_OK on success, or a flash error code if operation failed.
Some SPI flash chips may require a power cycle before write protect status can be cleared. Otherwise, write
protection can be removed via a follow-up call to this function.
Note: Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the
‘chip->drv’field).
Parameters
• chip –Pointer to identify flash chip. If NULL, esp_flash_default_chip is substituted.
Must have been successfully initialised via esp_flash_init()
• write_protect –Boolean value for the write protect flag
Returns ESP_OK on success, or a flash error code if operation failed.
Note: Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the
‘chip->drv’field).
Parameters
• chip –Pointer to identify flash chip. Must have been successfully initialised via
esp_flash_init()
• out_regions –[out] Pointer to receive a pointer to the array of protectable regions of
the chip.
• out_num_regions –[out] Pointer to an integer receiving the count of protectable re-
gions in the array returned in ‘regions’.
Note: It is possible for this result to be false and write operations to still fail, if protection is enabled for the
entire chip.
Note: Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the
‘chip->drv’field).
Parameters
• chip –Pointer to identify flash chip. Must have been successfully initialised via
esp_flash_init()
• region –Pointer to a struct describing a protected region. This must match one of the
regions returned from esp_flash_get_protectable_regions(…).
• out_protected –[out] Pointer to a flag which is set based on the protected status for
this region.
Returns ESP_OK on success, or a flash error code if operation failed.
Note: It is possible for the region protection flag to be cleared and write operations to still fail, if protection
is enabled for the entire chip.
Note: Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the
‘chip->drv’field).
Parameters
• chip –Pointer to identify flash chip. Must have been successfully initialised via
esp_flash_init()
• region –Pointer to a struct describing a protected region. This must match one of the
regions returned from esp_flash_get_protectable_regions(…).
• protect –Write protection flag to set.
Returns ESP_OK on success, or a flash error code if operation failed.
Note: If on-chip flash encryption is used, this function returns raw (ie encrypted) data. Use the flash cache
to transparently decrypt data.
Parameters
esp_err_t esp_flash_write(esp_flash_t *chip, const void *buffer, uint32_t address, uint32_t length)
Write data to the SPI flash chip.
Note: Both address & length must be 16 byte aligned, as this is the encryption block size
Parameters
• chip –Pointer to identify flash chip. Must be NULL (the main flash chip). For other
chips, encrypted write is not supported.
• address –Address on flash to write to. 16 byte aligned. Must be previously erased (SPI
NOR flash can only write bits 1->0).
• buffer –Pointer to a buffer with the data to write.
• length –Length (in bytes) of data to write. 16 byte aligned.
Returns
• ESP_OK: on success
• ESP_ERR_NOT_SUPPORTED: encrypted write not supported for this chip.
• ESP_ERR_INVALID_ARG: Either the address, buffer or length is invalid.
Structures
struct esp_flash_region_t
Structure for describing a region of flash.
Public Members
uint32_t offset
Start address of this region.
uint32_t size
Size of the region.
struct esp_flash_os_functions_t
OS-level integration hooks for accessing flash chips inside a running OS.
It’s in the public header because some instances should be allocated statically in the startup code. May be
updated according to hardware version and new flash chip feature requirements, shouldn’t be treated as public
API.
For advanced developers, you may replace some of them with your implementations at your own risk.
Public Members
struct esp_flash_t
Structure to describe a SPI flash chip connected to the system.
Structure must be initialized before use (passed to esp_flash_init()). It’s in the public header because some
instances should be allocated statically in the startup code. May be updated according to hardware version and
new flash chip feature requirements, shouldn’t be treated as public API.
For advanced developers, you may replace some of them with your implementations at your own risk.
Public Members
spi_flash_host_inst_t *host
Pointer to hardware-specific “host_driver”structure. Must be initialized before used.
void *os_func_data
Pointer to argument for os-specific hooks. Left NULL and will be initialized with os_func.
esp_flash_io_mode_t read_mode
Configured SPI flash read mode. Set before esp_flash_init is called.
uint32_t size
Size of SPI flash in bytes. If 0, size will be detected during initialisation.
uint32_t chip_id
Detected chip id.
uint32_t busy
This flag is used to verify chip’s status.
uint32_t reserved_flags
reserved.
Macros
SPI_FLASH_YIELD_REQ_YIELD
SPI_FLASH_YIELD_REQ_SUSPEND
SPI_FLASH_YIELD_STA_RESUME
SPI_FLASH_OS_IS_ERASING_STATUS_FLAG
Type Definitions
Header File
• components/spi_flash/include/spi_flash_mmap.h
Functions
esp_err_t spi_flash_mmap(size_t src_addr, size_t size, spi_flash_mmap_memory_t memory, const void
**out_ptr, spi_flash_mmap_handle_t *out_handle)
Map region of flash memory into data or instruction address space.
This function allocates sufficient number of 64kB MMU pages and configures them to map the requested region
of flash memory into the address space. It may reuse MMU pages which already provide the required mapping.
As with any allocator, if mmap/munmap are heavily used then the address space may become fragmented. To
troubleshoot issues with page allocation, use spi_flash_mmap_dump() function.
Parameters
• src_addr –Physical address in flash where requested region starts. This address must
be aligned to 64kB boundary (SPI_FLASH_MMU_PAGE_SIZE)
• size –Size of region to be mapped. This size will be rounded up to a 64kB boundary
• memory –Address space where the region should be mapped (data or instruction)
• out_ptr –[out] Output, pointer to the mapped memory region
• out_handle –[out] Output, handle which should be used for spi_flash_munmap call
Returns ESP_OK on success, ESP_ERR_NO_MEM if pages can not be allocated
esp_err_t spi_flash_mmap_pages(const int *pages, size_t page_count, spi_flash_mmap_memory_t memory,
const void **out_ptr, spi_flash_mmap_handle_t *out_handle)
Map sequences of pages of flash memory into data or instruction address space.
This function allocates sufficient number of 64kB MMU pages and configures them to map the indicated pages
of flash memory contiguously into address space. In this respect, it works in a similar way as spi_flash_mmap()
but it allows mapping a (maybe non-contiguous) set of pages into a contiguous region of memory.
Parameters
• pages –An array of numbers indicating the 64kB pages in flash to be mapped contigu-
ously into memory. These indicate the indexes of the 64kB pages, not the byte-size ad-
dresses as used in other functions. Array must be located in internal memory.
• page_count –Number of entries in the pages array
• memory –Address space where the region should be mapped (instruction or data)
• out_ptr –[out] Output, pointer to the mapped memory region
• out_handle –[out] Output, handle which should be used for spi_flash_munmap call
Returns
• ESP_OK on success
• ESP_ERR_NO_MEM if pages can not be allocated
• ESP_ERR_INVALID_ARG if pagecount is zero or pages array is not in internal memory
void spi_flash_munmap(spi_flash_mmap_handle_t handle)
Release region previously obtained using spi_flash_mmap.
Note: Calling this function will not necessarily unmap memory region. Region will only be unmapped when
there are no other handles which reference this region. In case of partially overlapping regions it is possible
that memory will be unmapped partially.
void spi_flash_mmap_dump(void)
Display information about mapped regions.
This function lists handles obtained using spi_flash_mmap, along with range of pages allocated to each handle.
It also lists all non-zero entries of MMU table and corresponding reference counts.
uint32_t spi_flash_mmap_get_free_pages(spi_flash_mmap_memory_t memory)
get free pages number which can be mmap
This function will return number of free pages available in mmu table. This could be useful before calling
actual spi_flash_mmap (maps flash range to DCache or ICache memory) to check if there is sufficient space
available for mapping.
Parameters memory –memory type of MMU table free page
Returns number of free pages which can be mmaped
size_t spi_flash_cache2phys(const void *cached)
Given a memory address where flash is mapped, return the corresponding physical flash offset.
Cache address does not have have been assigned via spi_flash_mmap(), any address in memory mapped flash
space can be looked up.
Parameters cached –Pointer to flashed cached memory.
Returns
• SPI_FLASH_CACHE2PHYS_FAIL If cache address is outside flash cache region, or the
address is not mapped.
• Otherwise, returns physical offset in flash
const void *spi_flash_phys2cache(size_t phys_offs, spi_flash_mmap_memory_t memory)
Given a physical offset in flash, return the address where it is mapped in the memory space.
Physical address does not have to have been assigned via spi_flash_mmap(), any address in flash can be looked
up.
Note: Only the first matching cache address is returned. If MMU flash cache table is configured so multiple
entries point to the same physical address, there may be more than one cache address corresponding to that
physical address. It is also possible for a single physical address to be mapped to both the IROM and DROM
regions.
Note: This function doesn’t impose any alignment constraints, but if memory argument is
SPI_FLASH_MMAP_INST and phys_offs is not 4-byte aligned, then reading from the returned pointer will
result in a crash.
Parameters
• phys_offs –Physical offset in flash memory to look up.
• memory –Address space type to look up a flash cache address mapping for (instruction
or data)
Returns
• NULL if the physical address is invalid or not mapped to flash cache of the specified
memory type.
• Cached memory address (in IROM or DROM space) corresponding to phys_offs.
Macros
ESP_ERR_FLASH_OP_FAIL
This file contains spi_flash_mmap_xx APIs, mainly for doing memory mapping to an SPI0-connected
external Flash, as well as some helper functions to convert between virtual and physical address
ESP_ERR_FLASH_OP_TIMEOUT
SPI_FLASH_SEC_SIZE
SPI Flash sector size
SPI_FLASH_MMU_PAGE_SIZE
Flash cache MMU mapping page size
SPI_FLASH_CACHE2PHYS_FAIL
Type Definitions
Enumerations
enum spi_flash_mmap_memory_t
Enumeration which specifies memory space requested in an mmap call.
Values:
enumerator SPI_FLASH_MMAP_DATA
map to data memory (Vaddr0), allows byte-aligned access, 4 MB total
enumerator SPI_FLASH_MMAP_INST
map to instruction memory (Vaddr1-3), allows only 4-byte-aligned access, 11 MB total
Header File
• components/hal/include/hal/spi_flash_types.h
Structures
struct spi_flash_trans_t
Definition of a common transaction. Also holds the return value.
Public Members
uint8_t reserved
Reserved, must be 0.
uint8_t mosi_len
Output data length, in bytes.
uint8_t miso_len
Input data length, in bytes.
uint8_t address_bitlen
Length of address in bits, set to 0 if command does not need an address.
uint32_t address
Address to perform operation on.
uint8_t *miso_data
[out] Input data from slave, little endian
uint32_t flags
Flags for this transaction. Set to 0 for now.
uint16_t command
Command to send.
uint8_t dummy_bitlen
Basic dummy bits to use.
uint32_t io_mode
Flash working mode when SPI_FLASH_IGNORE_BASEIO is specified.
struct spi_flash_sus_cmd_conf
Configuration structure for the flash chip suspend feature.
Public Members
uint32_t sus_mask
SUS/SUS1/SUS2 bit in flash register.
uint32_t cmd_rdsr
Read flash status register(2) command.
uint32_t sus_cmd
Flash suspend command.
uint32_t res_cmd
Flash resume command.
uint32_t reserved
Reserved, set to 0.
struct spi_flash_encryption_t
Structure for flash encryption operations.
Public Members
void (*flash_encryption_enable)(void)
Enable the flash encryption.
void (*flash_encryption_disable)(void)
Disable the flash encryption.
Param address The destination address in flash for the write operation.
Param buffer Data for programming
Param size Size to program.
void (*flash_encryption_done)(void)
flash data encryption operation is done.
void (*flash_encryption_destroy)(void)
Destroy encrypted result
struct spi_flash_host_inst_t
SPI Flash Host driver instance
Public Members
struct spi_flash_host_driver_s
Host driver configuration and context structure.
Public Members
void (*program_page)(spi_flash_host_inst_t *host, const void *buffer, uint32_t address, uint32_t length)
Program a page of the flash. Check max_write_bytes for the maximum allowed writing length.
Macros
SPI_FLASH_TRANS_FLAG_CMD16
Send command of 16 bits.
SPI_FLASH_TRANS_FLAG_IGNORE_BASEIO
Not applying the basic io mode configuration for this transaction.
SPI_FLASH_TRANS_FLAG_BYTE_SWAP
Used for DTR mode, to swap the bytes of a pair of rising/falling edge.
SPI_FLASH_CONFIG_CONF_BITS
OR the io_mode with this mask, to enable the dummy output feature or replace the first several dummy bits
into address to meet the requirements of conf bits. (Used in DIO/QIO/OIO mode)
SPI_FLASH_OPI_FLAG
A flag for flash work in opi mode, the io mode below are opi, above are SPI/QSPI mode. DO NOT use this
value in any API.
SPI_FLASH_READ_MODE_MIN
Slowest io mode supported by ESP32, currently SlowRd.
Type Definitions
Enumerations
enum esp_flash_speed_s
SPI flash clock speed values, always refer to them by the enum rather than the actual value (more speed may
be appended into the list).
A strategy to select the maximum allowed speed is to enumerate from the ESP_FLSH_SPEED_MAX-1 or
highest frequency supported by your flash, and decrease the speed until the probing success.
Values:
enumerator ESP_FLASH_5MHZ
The flash runs under 5MHz.
enumerator ESP_FLASH_10MHZ
The flash runs under 10MHz.
enumerator ESP_FLASH_20MHZ
The flash runs under 20MHz.
enumerator ESP_FLASH_26MHZ
The flash runs under 26MHz.
enumerator ESP_FLASH_40MHZ
The flash runs under 40MHz.
enumerator ESP_FLASH_80MHZ
The flash runs under 80MHz.
enumerator ESP_FLASH_120MHZ
The flash runs under 120MHz, 120MHZ can only be used by main flash after timing tuning in system.
Do not use this directely in any API.
enumerator ESP_FLASH_SPEED_MAX
The maximum frequency supported by the host is ESP_FLASH_SPEED_MAX-1.
enum esp_flash_io_mode_t
Mode used for reading from SPI flash.
Values:
enumerator SPI_FLASH_SLOWRD
Data read using single I/O, some limits on speed.
enumerator SPI_FLASH_FASTRD
Data read using single I/O, no limit on speed.
enumerator SPI_FLASH_DOUT
Data read using dual I/O.
enumerator SPI_FLASH_DIO
Both address & data transferred using dual I/O.
enumerator SPI_FLASH_QOUT
Data read using quad I/O.
enumerator SPI_FLASH_QIO
Both address & data transferred using quad I/O.
enumerator SPI_FLASH_OPI_STR
Only support on OPI flash, flash read and write under STR mode.
enumerator SPI_FLASH_OPI_DTR
Only support on OPI flash, flash read and write under DTR mode.
enumerator SPI_FLASH_READ_MODE_MAX
The fastest io mode supported by the host is ESP_FLASH_READ_MODE_MAX-1.
Header File
• components/hal/include/hal/esp_flash_err.h
Macros
ESP_ERR_FLASH_NOT_INITIALISED
esp_flash_chip_t structure not correctly initialised by esp_flash_init().
ESP_ERR_FLASH_UNSUPPORTED_HOST
Requested operation isn’t supported via this host SPI bus (chip->spi field).
ESP_ERR_FLASH_UNSUPPORTED_CHIP
Requested operation isn’t supported by this model of SPI flash chip.
ESP_ERR_FLASH_PROTECTED
Write operation failed due to chip’s write protection being enabled.
Enumerations
enum [anonymous]
Values:
enumerator ESP_ERR_FLASH_SIZE_NOT_MATCH
The chip doesn’t have enough space for the current partition table.
enumerator ESP_ERR_FLASH_NO_RESPONSE
Chip did not respond to the command, or timed out.
Header File
• components/spi_flash/include/esp_partition.h
Functions
esp_partition_iterator_t esp_partition_find(esp_partition_type_t type, esp_partition_subtype_t subtype,
const char *label)
Find partition based on one or more parameters.
Parameters
• type –Partition type, one of esp_partition_type_t values or an 8-bit unsigned integer.
To find all partitions, no matter the type, use ESP_PARTITION_TYPE_ANY, and set
subtype argument to ESP_PARTITION_SUBTYPE_ANY.
• subtype –Partition subtype, one of esp_partition_subtype_t values or an 8-bit unsigned
integer. To find all partitions of given type, use ESP_PARTITION_SUBTYPE_ANY.
• label –(optional) Partition label. Set this value if looking for partition with a specific
name. Pass NULL otherwise.
Returns iterator which can be used to enumerate all the partitions found, or NULL if no
partitions were found. Iterator obtained through this function has to be released using
esp_partition_iterator_release when not used any more.
const esp_partition_t *esp_partition_find_first(esp_partition_type_t type, esp_partition_subtype_t
subtype, const char *label)
Find first partition based on one or more parameters.
Parameters
• type –Partition type, one of esp_partition_type_t values or an 8-bit unsigned integer.
To find all partitions, no matter the type, use ESP_PARTITION_TYPE_ANY, and set
subtype argument to ESP_PARTITION_SUBTYPE_ANY.
Note: Prior to writing to flash memory, make sure it has been erased with esp_partition_erase_range call.
Parameters
• partition –Pointer to partition structure obtained using esp_partition_find_first or
esp_partition_get. Must be non-NULL.
• dst_offset –Address where the data should be written, relative to the beginning of
the partition.
• src –Pointer to the source buffer. Pointer must be non-NULL and buffer must be at least
‘size’bytes long.
• size –Size of data to be written, in bytes.
Returns ESP_OK, if data was written successfully; ESP_ERR_INVALID_ARG, if dst_offset ex-
ceeds partition size; ESP_ERR_INVALID_SIZE, if write would go out of bounds of the par-
tition; or one of error codes from lower-level flash driver.
Note: This function is essentially the same as esp_partition_read() above. It just never decrypts
data but returns it as is.
Parameters
• partition –Pointer to partition structure obtained using esp_partition_find_first or
esp_partition_get. Must be non-NULL.
• dst –Pointer to the buffer where data should be stored. Pointer must be non-NULL and
buffer must be at least ‘size’bytes long.
• src_offset –Address of the data to be read, relative to the beginning of the partition.
• size –Size of data to be read, in bytes.
Returns ESP_OK, if data was read successfully; ESP_ERR_INVALID_ARG, if src_offset ex-
ceeds partition size; ESP_ERR_INVALID_SIZE, if read would go out of bounds of the par-
tition; or one of error codes from lower-level flash driver.
Before writing data to flash, corresponding region of flash needs to be erased. This can be done using
esp_partition_erase_range function.
Note: This function is essentially the same as esp_partition_write() above. It just never encrypts
data but writes it as is.
Note: Prior to writing to flash memory, make sure it has been erased with esp_partition_erase_range call.
Parameters
• partition –Pointer to partition structure obtained using esp_partition_find_first or
esp_partition_get. Must be non-NULL.
• dst_offset –Address where the data should be written, relative to the beginning of
the partition.
• src –Pointer to the source buffer. Pointer must be non-NULL and buffer must be at least
‘size’bytes long.
• size –Size of data to be written, in bytes.
Returns ESP_OK, if data was written successfully; ESP_ERR_INVALID_ARG, if dst_offset ex-
ceeds partition size; ESP_ERR_INVALID_SIZE, if write would go out of bounds of the par-
tition; or one of the error codes from lower-level flash driver.
• partition –[in] Pointer to info for partition containing app or data. (fields: address,
size and type, are required to be filled).
• sha_256 –[out] Returned SHA-256 digest for a given partition.
Returns
• ESP_OK: In case of successful operation.
• ESP_ERR_INVALID_ARG: The size was 0 or the sha_256 was NULL.
• ESP_ERR_NO_MEM: Cannot allocate memory for sha256 operation.
• ESP_ERR_IMAGE_INVALID: App partition doesn’t contain a valid app image.
• ESP_FAIL: An allocation error occurred.
bool esp_partition_check_identity(const esp_partition_t *partition_1, const esp_partition_t
*partition_2)
Check for the identity of two partitions by SHA-256 digest.
Parameters
• partition_1 –[in] Pointer to info for partition 1 containing app or data. (fields: ad-
dress, size and type, are required to be filled).
• partition_2 –[in] Pointer to info for partition 2 containing app or data. (fields: ad-
dress, size and type, are required to be filled).
Returns
• True: In case of the two firmware is equal.
• False: Otherwise
esp_err_t esp_partition_register_external(esp_flash_t *flash_chip, size_t offset, size_t size, const
char *label, esp_partition_type_t type,
esp_partition_subtype_t subtype, const esp_partition_t
**out_partition)
Register a partition on an external flash chip.
This API allows designating certain areas of external flash chips (identified by the esp_flash_t structure) as
partitions. This allows using them with components which access SPI flash through the esp_partition API.
Parameters
• flash_chip –Pointer to the structure identifying the flash chip
• offset –Address in bytes, where the partition starts
• size –Size of the partition in bytes
• label –Partition name
• type –One of the partition types (ESP_PARTITION_TYPE_*), or an integer.
Note that applications can not be booted from external flash chips, so using
ESP_PARTITION_TYPE_APP is not supported.
• subtype –One of the partition subtypes (ESP_PARTITION_SUBTYPE_*), or an in-
teger.
• out_partition –[out] Output, if non-NULL, receives the pointer to the resulting
esp_partition_t structure
Returns
• ESP_OK on success
• ESP_ERR_NO_MEM if memory allocation has failed
• ESP_ERR_INVALID_ARG if the new partition overlaps another partition on the same
flash chip
• ESP_ERR_INVALID_SIZE if the partition doesn’t fit into the flash chip size
esp_err_t esp_partition_deregister_external(const esp_partition_t *partition)
Deregister the partition previously registered using esp_partition_register_external.
Parameters partition –pointer to the partition structure obtained from
esp_partition_register_external,
Returns
• ESP_OK on success
• ESP_ERR_NOT_FOUND if the partition pointer is not found
• ESP_ERR_INVALID_ARG if the partition comes from the partition table
Structures
struct esp_partition_t
partition information structure
This is not the format in flash, that format is esp_partition_info_t.
However, this is the format used by this API.
Public Members
esp_flash_t *flash_chip
SPI flash chip on which the partition resides
esp_partition_type_t type
partition type (app/data)
esp_partition_subtype_t subtype
partition subtype
uint32_t address
starting address of the partition in flash
uint32_t size
size of the partition, in bytes
char label[17]
partition label, zero-terminated ASCII string
bool encrypted
flag is set to true if partition is encrypted
Macros
ESP_PARTITION_SUBTYPE_OTA(i)
Convenience macro to get esp_partition_subtype_t value for the i-th OTA partition.
Type Definitions
Enumerations
enum esp_partition_type_t
Partition type.
Note: Partition types with integer value 0x00-0x3F are reserved for partition types defined by ESP-IDF. Any
other integer value 0x40-0xFE can be used by individual applications, without restriction.
Values:
enumerator ESP_PARTITION_TYPE_APP
Application partition type.
enumerator ESP_PARTITION_TYPE_DATA
Data partition type.
enumerator ESP_PARTITION_TYPE_ANY
Used to search for partitions with any type.
enum esp_partition_subtype_t
Partition subtype.
Application-defined partition types (0x40-0xFE) can set any numeric subtype value.
Values:
enumerator ESP_PARTITION_SUBTYPE_APP_FACTORY
Factory application partition.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_MIN
Base for OTA partition subtypes.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_0
OTA partition 0.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_1
OTA partition 1.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_2
OTA partition 2.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_3
OTA partition 3.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_4
OTA partition 4.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_5
OTA partition 5.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_6
OTA partition 6.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_7
OTA partition 7.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_8
OTA partition 8.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_9
OTA partition 9.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_10
OTA partition 10.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_11
OTA partition 11.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_12
OTA partition 12.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_13
OTA partition 13.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_14
OTA partition 14.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_15
OTA partition 15.
enumerator ESP_PARTITION_SUBTYPE_APP_OTA_MAX
Max subtype of OTA partition.
enumerator ESP_PARTITION_SUBTYPE_APP_TEST
Test application partition.
enumerator ESP_PARTITION_SUBTYPE_DATA_OTA
OTA selection partition.
enumerator ESP_PARTITION_SUBTYPE_DATA_PHY
PHY init data partition.
enumerator ESP_PARTITION_SUBTYPE_DATA_NVS
NVS partition.
enumerator ESP_PARTITION_SUBTYPE_DATA_COREDUMP
COREDUMP partition.
enumerator ESP_PARTITION_SUBTYPE_DATA_NVS_KEYS
Partition for NVS keys.
enumerator ESP_PARTITION_SUBTYPE_DATA_EFUSE_EM
Partition for emulate eFuse bits.
enumerator ESP_PARTITION_SUBTYPE_DATA_UNDEFINED
Undefined (or unspecified) data partition.
enumerator ESP_PARTITION_SUBTYPE_DATA_ESPHTTPD
ESPHTTPD partition.
enumerator ESP_PARTITION_SUBTYPE_DATA_FAT
FAT partition.
enumerator ESP_PARTITION_SUBTYPE_DATA_SPIFFS
SPIFFS partition.
enumerator ESP_PARTITION_SUBTYPE_ANY
Used to search for partitions with any subtype.
Header File
• components/bootloader_support/include/esp_flash_encrypt.h
Functions
bool esp_flash_encryption_enabled(void)
Is flash encryption currently enabled in hardware?
Flash encryption is enabled if the FLASH_CRYPT_CNT efuse has an odd number of bits set.
Returns true if flash encryption is enabled.
esp_err_t esp_flash_encrypt_check_and_update(void)
bool esp_flash_encrypt_state(void)
Returns the Flash Encryption state and prints it.
Returns True - Flash Encryption is enabled False - Flash Encryption is not enabled
bool esp_flash_encrypt_initialized_once(void)
Checks if the first initialization was done.
If the first initialization was done then FLASH_CRYPT_CNT != 0
Returns true - the first initialization was done false - the first initialization was NOT done
esp_err_t esp_flash_encrypt_init(void)
The first initialization of Flash Encryption key and related eFuses.
Returns ESP_OK if all operations succeeded
esp_err_t esp_flash_encrypt_contents(void)
Encrypts flash content.
Returns ESP_OK if all operations succeeded
esp_err_t esp_flash_encrypt_enable(void)
Activates Flash encryption on the chip.
It burns FLASH_CRYPT_CNT eFuse based on the CONFIG_SECURE_FLASH_ENCRYPTION_MODE_RELEASE
option.
Returns ESP_OK if all operations succeeded
bool esp_flash_encrypt_is_write_protected(bool print_error)
Returns True if the write protection of FLASH_CRYPT_CNT is set.
Parameters print_error –Print error if it is write protected
Returns true - if FLASH_CRYPT_CNT is write protected
esp_err_t esp_flash_encrypt_region(uint32_t src_addr, size_t data_length)
Encrypt-in-place a block of flash sectors.
Parameters
• src_addr –Source offset in flash. Should be multiple of 4096 bytes.
• data_length –Length of data to encrypt in bytes. Will be rounded up to next multiple
of 4096 bytes.
Returns ESP_OK if all operations succeeded, ESP_ERR_FLASH_OP_FAIL if SPI flash fails,
ESP_ERR_FLASH_OP_TIMEOUT if flash times out.
void esp_flash_write_protect_crypt_cnt(void)
Write protect FLASH_CRYPT_CNT.
Intended to be called as a part of boot process if flash encryption is enabled but secure boot is not used. This
should protect against serial re-flashing of an unauthorised code in absence of secure boot.
Note: On ESP32 V3 only, write protecting FLASH_CRYPT_CNT will also prevent disabling UART Down-
load Mode. If both are wanted, call esp_efuse_disable_rom_download_mode() before calling this function.
esp_flash_enc_mode_t esp_get_flash_encryption_mode(void)
Return the flash encryption mode.
The API is called during boot process but can also be called by application to check the current flash encryption
mode of ESP32
Returns
void esp_flash_encryption_init_checks(void)
Check the flash encryption mode during startup.
• Correct any insecure flash encryption settings if hardware Secure Boot is enabled.
• Log warnings if the efuse config doesn’t match the project config in any way
Note: This function is called automatically during app startup, it doesn’t need to be called from the app.
esp_err_t esp_flash_encryption_enable_secure_features(void)
Set all secure eFuse features related to flash encryption.
Returns
• ESP_OK - Successfully
void esp_flash_encryption_set_release_mode(void)
Switches Flash Encryption from “Development”to “Release”.
If already in “Release”mode, the function will do nothing. If flash encryption efuse is not enabled yet then
abort. It burns:
• ”disable encrypt in dl mode”
• set FLASH_CRYPT_CNT efuse to max
Enumerations
enum esp_flash_enc_mode_t
Values:
enumerator ESP_FLASH_ENC_MODE_DISABLED
enumerator ESP_FLASH_ENC_MODE_DEVELOPMENT
enumerator ESP_FLASH_ENC_MODE_RELEASE
Overview
SPIFFS is a file system intended for SPI NOR flash devices on embedded targets. It supports wear levelling, file
system consistency checks, and more.
Notes
• Currently, SPIFFS does not support directories, it produces a flat structure. If SPIFFS is mounted under
/spiffs, then creating a file with the path /spiffs/tmp/myfile.txt will create a file called /tmp/
myfile.txt in SPIFFS, instead of myfile.txt in the directory /spiffs/tmp.
• It is not a real-time stack. One write operation might take much longer than another.
• For now, it does not detect or handle bad blocks.
• SPIFFS is able to reliably utilize only around 75% of assigned partition space.
• When the filesystem is running out of space, the garbage collector is trying to find free space by scanning the
filesystem multiple times, which can take up to several seconds per write function call, depending on required
space. This is caused by the SPIFFS design and the issue has been reported multiple times (e.g. here) and in
the official SPIFFS github repository. The issue can be partially mitigated by the SPIFFS configuration.
• Deleting a file does not always remove the whole file, which leaves unusable sections throughout the filesystem.
• When ESP32 experiences a power loss during a file system operation it could result in SPIFFS corruption.
However the file system still might be recovered via esp_spiffs_check function. More details in the
official SPIFFS FAQ <https://github.com/pellepl/spiffs/wiki/FAQ>.
Tools
spiffsgen.py spiffsgen.py is a write-only Python SPIFFS implementation used to create filesystem images from the
contents of a host folder. To use spiffsgen.py, open Terminal and run:
These optional arguments correspond to a possible SPIFFS build configuration. To generate the right image, please
make sure that you use the same arguments/configuration as were used to build SPIFFS. As a guide, the help output
indicates the SPIFFS build configuration to which the argument corresponds. In cases when these arguments are not
specified, the default values shown in the help output will be used.
When the image is created, it can be flashed using esptool.py or parttool.py.
Aside from invoking the spiffsgen.py standalone by manually running it from the command line
or a script, it is also possible to invoke spiffsgen.py directly from the build system by calling
spiffs_create_partition_image:
This is more convenient as the build configuration is automatically passed to the tool, ensuring that the generated image
is valid for that build. An example of this is while the image_size is required for the standalone invocation, only the
partition name is required when using spiffs_create_partition_image –the image size is automatically
obtained from the project’s partition table.
spiffs_create_partition_image must be called from one of the component CMakeLists.txt files.
Optionally, users can opt to have the image automatically flashed together with the app binaries, partition tables, etc.
on idf.py flash by specifying FLASH_IN_PROJECT. For example:
mkspiffs Another tool for creating SPIFFS partition images is mkspiffs. Similar to spiffsgen.py, it can be
used to create an image from a given folder and then flash that image using esptool.py
For that, you need to obtain the following parameters:
• Block Size: 4096 (standard for SPI Flash)
• Page Size: 256 (standard for SPI Flash)
• Image Size: Size of the partition in bytes (can be obtained from a partition table)
• Partition Offset: Starting address of the partition (can be obtained from a partition table)
To pack a folder into a 1-Megabyte image, run:
python esptool.py --chip esp32 --port [port] --baud [baud] write_flash -z 0x110000␣
,→spiffs.bin
Notes on which SPIFFS tool to use The two tools presented above offer very similar functionality. However,
there are reasons to prefer one over the other, depending on the use case.
Use spiffsgen.py in the following cases:
1. If you want to simply generate a SPIFFS image during the build. spiffsgen.py makes it very convenient
by providing functions/commands from the build system itself.
2. If the host has no C/C++ compiler available, because spiffsgen.py does not require compilation.
Use mkspiffs in the following cases:
1. If you need to unpack SPIFFS images in addition to image generation. For now, it is not possible with spiff-
sgen.py.
2. If you have an environment where a Python interpreter is not available, but a host compiler is available. Oth-
erwise, a pre-compiled mkspiffs binary can do the job. However, there is no build system integration for
mkspiffs and the user has to do the corresponding work: compiling mkspiffs during build (if a pre-
compiled binary is not used), creating build rules/targets for the output files, passing proper parameters to the
tool, etc.
See also
Application Example
An example of using SPIFFS is provided in the storage/spiffs directory. This example initializes and mounts a
SPIFFS partition, then writes and reads data from it using POSIX and C library APIs. See the README.md file in
the example directory for more information.
Header File
• components/spiffs/include/esp_spiffs.h
Functions
esp_err_t esp_vfs_spiffs_register(const esp_vfs_spiffs_conf_t *conf)
Register and mount SPIFFS to VFS with given path prefix.
Parameters conf –Pointer to esp_vfs_spiffs_conf_t configuration structure
Returns
• ESP_OK if success
• ESP_ERR_NO_MEM if objects could not be allocated
• ESP_ERR_INVALID_STATE if already mounted or partition is encrypted
• ESP_ERR_NOT_FOUND if partition for SPIFFS was not found
• ESP_FAIL if mount or format fails
Returns
• ESP_OK on success
• ESP_ERR_NOT_FINISHED if GC fails to reclaim the size given by size_to_gc
• ESP_ERR_INVALID_STATE if the partition is not mounted
• ESP_FAIL on all other errors
Structures
struct esp_vfs_spiffs_conf_t
Configuration structure for esp_vfs_spiffs_register.
Public Members
size_t max_files
Maximum files that could be open at the same time.
bool format_if_mount_failed
If true, it will format the file system if it fails to mount.
Overview
Virtual filesystem (VFS) component provides a unified interface for drivers which can perform operations on file-like
objects. These can be real filesystems (FAT, SPIFFS, etc.) or device drivers which provide a file-like interface.
This component allows C library functions, such as fopen and fprintf, to work with FS drivers. At a high level, each FS
driver is associated with some path prefix. When one of C library functions needs to open a file, the VFS component
searches for the FS driver associated with the file path and forwards the call to that driver. VFS also forwards read,
write, and other calls for the given file to the same FS driver.
For example, one can register a FAT filesystem driver with the /fat prefix and call fopen("/fat/file.txt",
"w"). The VFS component will then call the function open of the FAT driver and pass the argument /file.txt
to it together with appropriate mode flags. All subsequent calls to C library functions for the returned FILE* stream
will also be forwarded to the FAT driver.
FS registration
To register an FS driver, an application needs to define an instance of the esp_vfs_t structure and populate it with
function pointers to FS APIs:
esp_vfs_t myfs = {
.flags = ESP_VFS_FLAG_DEFAULT,
.write = &myfs_write,
.open = &myfs_open,
.fstat = &myfs_fstat,
.close = &myfs_close,
.read = &myfs_read,
};
Depending on the way how the FS driver declares its API functions, either read, write, etc., or read_p,
write_p, etc., should be used.
Case 1: API functions are declared without an extra context pointer (the FS driver is a singleton):
// In definition of esp_vfs_t:
.flags = ESP_VFS_FLAG_DEFAULT,
.write = &myfs_write,
// ... other members initialized
Case 2: API functions are declared with an extra context pointer (the FS driver supports multiple instances):
ssize_t myfs_write(myfs_t* fs, int fd, const void * data, size_t size);
// In definition of esp_vfs_t:
.flags = ESP_VFS_FLAG_CONTEXT_PTR,
.write_p = &myfs_write,
// ... other members initialized
// When registering FS, pass the FS context pointer into the third argument
// (hypothetical myfs_mount function is used for illustrative purposes)
myfs_t* myfs_inst1 = myfs_mount(partition1->offset, partition1->size);
ESP_ERROR_CHECK(esp_vfs_register("/data1", &myfs, myfs_inst1));
Non-socket VFS drivers If you want to use select() with a file descriptor belonging to a non-socket VFS
driver, then you need to register the driver with functions start_select() and end_select() similarly to
the following example:
// In definition of esp_vfs_t:
.start_select = &uart_start_select,
.end_select = &uart_end_select,
// ... other members initialized
start_select() is called for setting up the environment for detection of read/write/error conditions on file
descriptors belonging to the given VFS driver.
end_select() is called to stop/deinitialize/free the environment which was setup by start_select().
Note: end_select() might be called without a previous start_select() call in some rare circumstances.
end_select() should fail gracefully if this is the case (i.e., should not crash but return an error instead).
Please refer to the reference implementation for the UART peripheral in vfs/vfs_uart.c and most particularly to the
functions esp_vfs_dev_uart_register(), uart_start_select(), and uart_end_select()
for more information.
Please check the following examples that demonstrate the use of select() with VFS file descriptors:
• peripherals/uart/uart_select
• system/select
Socket VFS drivers A socket VFS driver is using its own internal implementation of select() and non-socket
VFS drivers notify it upon read/write/error conditions.
A socket VFS driver needs to be registered with the following functions defined:
// In definition of esp_vfs_t:
.socket_select = &lwip_select,
.get_socket_select_semaphore = &lwip_get_socket_select_semaphore,
.stop_socket_select = &lwip_stop_socket_select,
.stop_socket_select_isr = &lwip_stop_socket_select_isr,
// ... other members initialized
socket_select() is the internal implementation of select() for the socket driver. It works only with file
descriptors belonging to the socket VFS.
get_socket_select_semaphore() returns the signalization object (semaphore) which will be used in non-
socket drivers to stop the waiting in socket_select().
stop_socket_select() call is used to stop the waiting in socket_select() by passing the object returned
by get_socket_select_semaphore().
stop_socket_select_isr() has the same functionality as stop_socket_select() but it can be used
from ISR.
Please see lwip/port/esp32/vfs_lwip.c for a reference socket driver implementation using LWIP.
Note: If you use select() for socket file descriptors only then you can disable the CON-
FIG_VFS_SUPPORT_SELECT option to reduce the code size and improve performance. You should not change
the socket driver during an active select() call or you might experience some undefined behavior.
Paths
Each registered FS has a path prefix associated with it. This prefix can be considered as a “mount point”of this
partition.
In case when mount points are nested, the mount point with the longest matching path prefix is used when opening
the file. For instance, suppose that the following filesystems are registered in VFS:
• FS 1 on /data
• FS 2 on /data/static
Then:
• FS 1 will be used when opening a file called /data/log.txt
• FS 2 will be used when opening a file called /data/static/index.html
• Even if /index.html" does not exist in FS 2, FS 1 will not be searched for /static/index.html.
As a general rule, mount point names must start with the path separator (/) and must contain at least one character
after path separator. However, an empty mount point name is also supported and might be used in cases when an
application needs to provide a“fallback”filesystem or to override VFS functionality altogether. Such filesystem will
be used if no prefix matches the path given.
VFS does not handle dots (.) in path names in any special way. VFS does not treat .. as a reference to the parent
directory. In the above example, using a path /data/static/../log.txt will not result in a call to FS 1 to
open /log.txt. Specific FS drivers (such as FATFS) might handle dots in file names differently.
When opening files, the FS driver receives only relative paths to files. For example:
1. The myfs driver is registered with /data as a path prefix.
2. The application calls fopen("/data/config.json", ...).
3. The VFS component calls myfs_open("/config.json", ...).
4. The myfs driver opens the /config.json file.
VFS does not impose any limit on total file path length, but it does limit the FS path prefix to ESP_VFS_PATH_MAX
characters. Individual FS drivers may have their own filename length limitations.
File descriptors
File descriptors are small positive integers from 0 to FD_SETSIZE - 1, where FD_SETSIZE is defined in newlib’
s sys/types.h. The largest file descriptors (configured by CONFIG_LWIP_MAX_SOCKETS) are reserved for
sockets. The VFS component contains a lookup-table called s_fd_table for mapping global file descriptors to
VFS driver indexes registered in the s_vfs array.
If the menuconfig option UART for console output is not set to None, then stdin, stdout, and stderr
are configured to read from, and write to, a UART. It is possible to use UART0 or UART1 for standard IO. By default,
UART0 is used with 115200 baud rate; TX pin is GPIO1; RX pin is GPIO3. These parameters can be changed in
menuconfig.
Writing to stdout or stderr will send characters to the UART transmit FIFO. Reading from stdin will retrieve
characters from the UART receive FIFO.
By default, VFS uses simple functions for reading from and writing to UART. Writes busy-wait until all data is put
into UART FIFO, and reads are non-blocking, returning only the data present in the FIFO. Due to this non-blocking
read behavior, higher level C library calls, such as fscanf("%d\n", &var);, might not have desired results.
Applications which use the UART driver can instruct VFS to use the driver’s interrupt driven, blocking read and write
functions instead. This can be done using a call to the esp_vfs_dev_uart_use_driver function. It is also
possible to revert to the basic non-blocking functions using a call to esp_vfs_dev_uart_use_nonblocking.
VFS also provides an optional newline conversion feature for input and output. Internally, most applications send
and receive lines terminated by the LF (‘’n’ ’) character. Different terminal programs may require dif-
ferent line termination, such as CR or CRLF. Applications can configure this separately for input and output ei-
ther via menuconfig, or by calls to the functions esp_vfs_dev_uart_port_set_rx_line_endings and
esp_vfs_dev_uart_port_set_tx_line_endings.
Standard streams and FreeRTOS tasks FILE objects for stdin, stdout, and stderr are shared between
all FreeRTOS tasks, but the pointers to these objects are stored in per-task struct _reent.
The following code is transferred to fprintf(__getreent()->_stderr, "42\n"); by the preprocessor:
fprintf(stderr, "42\n");
The __getreent() function returns a per-task pointer to struct _reent in newlib libc. This structure is
allocated on the TCB of each task. When a task is initialized, _stdin, _stdout, and _stderr members of
struct _reent are set to the values of _stdin, _stdout, and _stderr of _GLOBAL_REENT (i.e., the
structure which is used before FreeRTOS is started).
Such a design has the following consequences:
• It is possible to set stdin, stdout, and stderr for any given task without affecting other tasks, e.g., by
doing stdin = fopen("/dev/uart/1", "r").
• Closing default stdin, stdout, or stderr using fclose will close the FILE stream object, which will
affect all other tasks.
• To change the default stdin, stdout, stderr streams for new tasks, modify
_GLOBAL_REENT->_stdin (_stdout, _stderr) before creating the task.
Event fds
eventfd() call is a powerful tool to notify a select() based loop of custom events. The eventfd() imple-
mentation in ESP-IDF is generally the same as described in man(2) eventfd except for:
• esp_vfs_eventfd_register() has to be called before calling eventfd()
• Options EFD_CLOEXEC, EFD_NONBLOCK and EFD_SEMAPHORE are not supported in flags.
• Option EFD_SUPPORT_ISR has been added in flags. This flag is required to read and write the eventfd in
an interrupt handler.
Note that creating an eventfd with EFD_SUPPORT_ISR will cause interrupts to be temporarily disabled when
reading, writing the file and during the beginning and the ending of the select() when this file is set.
API Reference
Header File
• components/vfs/include/esp_vfs.h
Functions
ssize_t esp_vfs_write(struct _reent *r, int fd, const void *data, size_t size)
These functions are to be used in newlib syscall table. They will be called by newlib when it needs to use any
of the syscalls.
off_t esp_vfs_lseek(struct _reent *r, int fd, off_t size, int mode)
ssize_t esp_vfs_read(struct _reent *r, int fd, void *dst, size_t size)
int esp_vfs_open(struct _reent *r, const char *path, int flags, int mode)
int esp_vfs_stat(struct _reent *r, const char *path, struct stat *st)
int esp_vfs_link(struct _reent *r, const char *n1, const char *n2)
int esp_vfs_rename(struct _reent *r, const char *src, const char *dst)
Structures
struct esp_vfs_select_sem_t
VFS semaphore type for select()
Public Members
bool is_sem_local
type of “sem”is SemaphoreHandle_t when true, defined by socket driver otherwise
void *sem
semaphore instance
struct esp_vfs_t
VFS definition structure.
This structure should be filled with pointers to corresponding FS driver functions.
VFS component will translate all FDs so that the filesystem implementation sees them starting at zero. The
caller sees a global FD which is prefixed with an pre-filesystem-implementation.
Some FS implementations expect some state (e.g. pointer to some structure) to be passed in as a first argument.
For these implementations, populate the members of this structure which have _p suffix, set flags member
to ESP_VFS_FLAG_CONTEXT_PTR and provide the context pointer to esp_vfs_register function. If the
implementation doesn’t use this extra argument, populate the members without _p suffix and set flags member
to ESP_VFS_FLAG_DEFAULT.
If the FS driver doesn’t provide some of the functions, set corresponding members to NULL.
Public Members
int flags
ESP_VFS_FLAG_CONTEXT_PTR or ESP_VFS_FLAG_DEFAULT
ssize_t (*write_p)(void *p, int fd, const void *data, size_t size)
Write with context pointer
ssize_t (*pread_p)(void *ctx, int fd, void *dst, size_t size, off_t offset)
pread with context pointer
ssize_t (*pwrite_p)(void *ctx, int fd, const void *src, size_t size, off_t offset)
pwrite with context pointer
ssize_t (*pwrite)(int fd, const void *src, size_t size, off_t offset)
pwrite without context pointer
int (*open_p)(void *ctx, const char *path, int flags, int mode)
open with context pointer
int (*readdir_r_p)(void *ctx, DIR *pdir, struct dirent *entry, struct dirent **out_dirent)
readdir_r with context pointer
int (*utime_p)(void *ctx, const char *path, const struct utimbuf *times)
utime with context pointer
int (*tcsetattr_p)(void *ctx, int fd, int optional_actions, const struct termios *p)
tcsetattr with context pointer
int (*socket_select)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval
*timeout)
socket select function for socket FDs with the functionality of POSIX select(); this should be set only for
the socket VFS
void *(*get_socket_select_semaphore)(void)
end_select is called to stop the I/O multiplexing and deinitialize the environment created by start_select
for the given VFS
Macros
MAX_FDS
Maximum number of (global) file descriptors.
ESP_VFS_PATH_MAX
Maximum length of path prefix (not including zero terminator)
ESP_VFS_FLAG_DEFAULT
Default value of flags member in esp_vfs_t structure.
ESP_VFS_FLAG_CONTEXT_PTR
Flag which indicates that FS needs extra context pointer in syscalls.
Type Definitions
Header File
• components/vfs/include/esp_vfs_dev.h
Functions
void esp_vfs_dev_uart_register(void)
add /dev/uart virtual filesystem driver
This function is called from startup code to enable serial output
void esp_vfs_dev_uart_set_rx_line_endings(esp_line_endings_t mode)
Set the line endings expected to be received on UART.
This specifies the conversion between line endings received on UART and newlines (‘
’, LF) passed into stdin:
Note: this function is not thread safe w.r.t. reading from UART
This specifies the conversion between line endings received on UART and newlines (‘
’, LF) passed into stdin:
Note: this function is not thread safe w.r.t. reading from UART
Parameters
• uart_num –the UART number
• mode –line endings to send to UART
Returns 0 if successed, or -1 when an error (specified by errno) have occurred.
Parameters
• uart_num –the UART number
• mode –line endings to send to UART
Returns 0 if successed, or -1 when an error (specified by errno) have occurred.
Note: application must configure UART driver before calling these functions With these functions, read and
write are blocking and interrupt-driven.
void esp_vfs_usb_serial_jtag_use_driver(void)
set VFS to use USB-SERIAL-JTAG driver for reading and writing
Note: application must configure USB-SERIAL-JTAG driver before calling these functions With these func-
tions, read and write are blocking and interrupt-driven.
void esp_vfs_usb_serial_jtag_use_nonblocking(void)
set VFS to use simple functions for reading and writing UART Read is non-blocking, write is busy waiting
until TX FIFO has enough space. These functions are used by default.
Header File
• components/vfs/include/esp_vfs_eventfd.h
Functions
esp_err_t esp_vfs_eventfd_register(const esp_vfs_eventfd_config_t *config)
Registers the event vfs.
Returns ESP_OK if successful, ESP_ERR_NO_MEM if too many VFSes are registered.
esp_err_t esp_vfs_eventfd_unregister(void)
Unregisters the event vfs.
Returns ESP_OK if successful, ESP_ERR_INVALID_STATE if VFS for given prefix hasn’t
been registered
int eventfd(unsigned int initval, int flags)
Structures
struct esp_vfs_eventfd_config_t
Eventfd vfs initialization settings.
Public Members
size_t max_fds
The maxinum number of eventfds supported
Macros
EFD_SUPPORT_ISR
ESP_VFS_EVENTD_CONFIG_DEFAULT()
Overview
Most of flash memory and especially SPI flash that is used in ESP32 has a sector-based organization and also has a
limited number of erase/modification cycles per memory sector. The wear levelling component helps to distribute
wear and tear among sectors more evenly without requiring any attention from the user.
The wear levelling component provides API functions related to reading, writing, erasing, and memory mapping of
data in external SPI flash through the partition component. The component also has higher-level API functions which
work with the FAT filesystem defined in FAT filesystem.
The wear levelling component, together with the FAT FS component, uses FAT FS sectors of 4096 bytes, which is
a standard size for flash memory. With this size, the component shows the best performance but needs additional
memory in RAM.
To save internal memory, the component has two additional modes which both use sectors of 512 bytes:
• Performance mode. Erase sector operation data is stored in RAM, the sector is erased, and then data is copied
back to flash memory. However, if a device is powered off for any reason, all 4096 bytes of data is lost.
• Safety mode. The data is first saved to flash memory, and after the sector is erased, the data is saved back. If
a device is powered off, the data can be recovered as soon as the device boots up.
The default settings are as follows:
• Sector size is 512 bytes
• Performance mode
You can change the settings through the configuration menu.
The wear levelling component does not cache data in RAM. The write and erase functions modify flash directly, and
flash contents are consistent when the function returns.
This is the set of API functions for working with data in flash:
• wl_mount - initializes the wear levelling module and mounts the specified partition
• wl_unmount - unmounts the partition and deinitializes the wear levelling module
• wl_erase_range - erases a range of addresses in flash
• wl_write - writes data to a partition
• wl_read - reads data from a partition
• wl_size - returns the size of available memory in bytes
• wl_sector_size - returns the size of one sector
As a rule, try to avoid using raw wear levelling functions and use filesystem-specific functions instead.
Memory Size
The memory size is calculated in the wear levelling module based on partition parameters. The module uses some
sectors of flash for internal data.
See also
• FAT Filesystem
• Partition Table documentation
Application Example
An example which combines the wear levelling driver with the FATFS library is provided in the storage/wear_levelling
directory. This example initializes the wear levelling driver, mounts FATFS partition, as well as writes and reads data
from it using POSIX and C library APIs. See the storage/wear_levelling/README.md file for more information.
Header Files
• fatfs/vfs/esp_vfs_fat.h
Functions
esp_err_t esp_vfs_fat_spiflash_mount_rw_wl(const char *base_path, const char *partition_label,
const esp_vfs_fat_mount_config_t *mount_config,
wl_handle_t *wl_handle)
Convenience function to initialize FAT filesystem in SPI flash and register it in VFS.
This is an all-in-one function which does the following:
• finds the partition with defined partition_label. Partition label should be configured in the partition table.
• initializes flash wear levelling library on top of the given partition
• mounts FAT partition using FATFS library on top of flash wear levelling library
• registers FATFS library with VFS, with prefix given by base_prefix variable
This function is intended to make example code more compact.
Parameters
• base_path –path where FATFS partition should be mounted (e.g. “/spiflash”)
• partition_label –label of the partition which should be used
• mount_config –pointer to structure with extra parameters for mounting FATFS
• wl_handle –[out] wear levelling driver handle
Returns
• ESP_OK on success
• ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with
given label
• ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_rw_wl was already called
• ESP_ERR_NO_MEM if memory can not be allocated
• ESP_FAIL if partition can not be mounted
• other error codes from wear levelling library, SPI flash driver, or FATFS drivers
struct esp_vfs_fat_mount_config_t
Configuration arguments for esp_vfs_fat_sdmmc_mount and esp_vfs_fat_spiflash_mount_rw_wl functions.
Public Members
bool format_if_mount_failed
If FAT partition can not be mounted, and this parameter is true, create partition table and format the
filesystem.
int max_files
Max number of open files.
size_t allocation_unit_size
If format_if_mount_failed is set, and mount fails, format the card with given allocation unit size. Must
be a power of 2, between sector size and 128 * sector size. For SD cards, sector size is always 512 bytes.
For wear_levelling, sector size is determined by CONFIG_WL_SECTOR_SIZE option.
Using larger allocation unit size will result in higher read/write performance and higher overhead when
storing small files.
Setting this field to 0 will result in allocation unit set to the sector size.
bool disk_status_check_enable
Enables real ff_disk_status function implementation for SD cards (ff_sdmmc_status). Possibly slows
down IO performance.
Try to enable if you need to handle situations when SD cards are not unmounted properly before physical
removal or you are experiencing issues with SD cards.
Doesn’t do anything for other memory storage media.
esp_err_t esp_vfs_fat_spiflash_unmount_rw_wl(const char *base_path, wl_handle_t wl_handle)
Unmount FAT filesystem and release resources acquired using esp_vfs_fat_spiflash_mount_rw_wl.
Parameters
• base_path –path where partition should be registered (e.g. “/spiflash”)
• wl_handle –wear levelling driver handle returned by
esp_vfs_fat_spiflash_mount_rw_wl
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_rw_wl hasn’t been called
Header File
• components/wear_levelling/include/wear_levelling.h
Functions
esp_err_t wl_mount(const esp_partition_t *partition, wl_handle_t *out_handle)
Mount WL for defined partition.
Parameters
• partition –that will be used for access
• out_handle –handle of the WL instance
Returns
• ESP_OK, if the allocation was successfully;
• ESP_ERR_INVALID_ARG, if WL allocation was unsuccessful;
• ESP_ERR_NO_MEM, if there was no memory to allocate WL components;
esp_err_t wl_unmount(wl_handle_t handle)
Unmount WL for defined partition.
Parameters handle –WL partition handle
Returns
• ESP_OK, if the operation completed successfully;
• or one of error codes from lower-level flash driver.
esp_err_t wl_erase_range(wl_handle_t handle, size_t start_addr, size_t size)
Erase part of the WL storage.
Parameters
• handle –WL handle that are related to the partition
• start_addr –Address where erase operation should start. Must be aligned to the result
of function wl_sector_size(…).
• size –Size of the range which should be erased, in bytes. Must be divisible by result of
function wl_sector_size(…)..
Returns
• ESP_OK, if the range was erased successfully;
• ESP_ERR_INVALID_ARG, if iterator or dst are NULL;
• ESP_ERR_INVALID_SIZE, if erase would go out of bounds of the partition;
• or one of error codes from lower-level flash driver.
esp_err_t wl_write(wl_handle_t handle, size_t dest_addr, const void *src, size_t size)
Write data to the WL storage.
Before writing data to flash, corresponding region of flash needs to be erased. This can be done using
wl_erase_range function.
Note: Prior to writing to WL storage, make sure it has been erased with wl_erase_range call.
Parameters
• handle –WL handle that are related to the partition
• dest_addr –Address where the data should be written, relative to the beginning of the
partition.
• src –Pointer to the source buffer. Pointer must be non-NULL and buffer must be at least
‘size’bytes long.
• size –Size of data to be written, in bytes.
Returns
• ESP_OK, if data was written successfully;
• ESP_ERR_INVALID_ARG, if dst_offset exceeds partition size;
• ESP_ERR_INVALID_SIZE, if write would go out of bounds of the partition;
• or one of error codes from lower-level flash driver.
Macros
WL_INVALID_HANDLE
Type Definitions
esptool.py v2.3.1
Image version: 1
Entry point: 40080ea4
13 segments
Segment 1: len 0x13ce0 load 0x3f400020 file_offs 0x00000018 SOC_DROM
Segment 2: len 0x00000 load 0x3ff80000 file_offs 0x00013d00 SOC_RTC_DRAM
Segment 3: len 0x00000 load 0x3ff80000 file_offs 0x00013d08 SOC_RTC_DRAM
Segment 4: len 0x028e0 load 0x3ffb0000 file_offs 0x00013d10 DRAM
Segment 5: len 0x00000 load 0x3ffb28e0 file_offs 0x000165f8 DRAM
Segment 6: len 0x00400 load 0x40080000 file_offs 0x00016600 SOC_IRAM
Segment 7: len 0x09600 load 0x40080400 file_offs 0x00016a08 SOC_IRAM
Segment 8: len 0x62e4c load 0x400d0018 file_offs 0x00020010 SOC_IROM
Segment 9: len 0x06cec load 0x40089a00 file_offs 0x00082e64 SOC_IROM
Segment 10: len 0x00000 load 0x400c0000 file_offs 0x00089b58 SOC_RTC_IRAM
Segment 11: len 0x00004 load 0x50000000 file_offs 0x00089b60 SOC_RTC_DATA
Segment 12: len 0x00000 load 0x50000004 file_offs 0x00089b6c SOC_RTC_DATA
Segment 13: len 0x00000 load 0x50000004 file_offs 0x00089b74 SOC_RTC_DATA
Checksum: e8 (valid)Validation Hash:␣
,→407089ca0eae2bbf83b4120979d3354b1c938a49cb7a0c997f240474ef2ec76b (valid)
You can also see the information on segments in the ESP-IDF logs while your application is booting:
I (443) esp_image: segment 0: paddr=0x00020020 vaddr=0x3f400020 size=0x13ce0 (␣
,→81120) map
For more details on the type of memory segments and their address ranges, see ESP32 Technical Reference Manual
> System and Memory > Embedded Memory [PDF].
3. The image has a single checksum byte after the last segment. This byte is written on a sixteen byte padded
boundary, so the application image might need padding.
4. If the hash_appended field from esp_image_header_t is set then a SHA256 checksum will be ap-
pended. The value of SHA256 is calculated on the range from the first byte and up to this field. The length of
this field is 32 bytes.
5. If the options CONFIG_SECURE_SIGNED_APPS_SCHEME is set to ECDSA then the application image will
have additional 68 bytes for an ECDSA signature, which includes:
• version word (4 bytes),
• signature data (64 bytes).
Application Description
The DROM segment starts with the esp_app_desc_t structure which carries specific fields describing the appli-
cation:
• magic_word - the magic word for the esp_app_desc structure.
• secure_version - see Anti-rollback.
• version - see App version. *
• project_name is filled from PROJECT_NAME. *
• time and date - compile time and date.
• idf_ver - version of ESP-IDF. *
• app_elf_sha256 - contains sha256 for the elf application file.
* - The maximum length is 32 characters, including null-termination character. For example, if the length of
PROJECT_NAME exceeds 32 characters, the excess characters will be disregarded.
This structure is useful for identification of images uploaded OTA because it has a fixed offset =
sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t). As soon as a device receives
the first fragment containing this structure, it has all the information to determine whether the update should be
continued or not.
Users also have the opportunity to have similar structure with a fixed offset relative to the beginning of the image.
The following pattern can be used to add a custom structure to your image:
API Reference
Header File
• components/bootloader_support/include/esp_app_format.h
Structures
struct esp_image_header_t
Main header of binary image.
Public Members
uint8_t magic
Magic word ESP_IMAGE_HEADER_MAGIC
uint8_t segment_count
Count of memory segments
uint8_t spi_mode
flash read mode (esp_image_spi_mode_t as uint8_t)
uint8_t spi_speed
flash frequency (esp_image_spi_freq_t as uint8_t)
uint8_t spi_size
flash chip size (esp_image_flash_size_t as uint8_t)
uint32_t entry_addr
Entry address
uint8_t wp_pin
WP pin when SPI pins set via efuse (read by ROM bootloader, the IDF bootloader uses software to
configure the WP pin and sets this field to 0xEE=disabled)
uint8_t spi_pin_drv[3]
Drive settings for the SPI flash pins (read by ROM bootloader)
esp_chip_id_t chip_id
Chip identification number
uint8_t min_chip_rev
Minimum chip revision supported by image
uint8_t reserved[8]
Reserved bytes in additional header space, currently unused
uint8_t hash_appended
If 1, a SHA256 digest “simple hash”(of the entire image) is appended after the checksum. Included
in image length. This digest is separate to secure boot and only used for detecting corruption. For secure
boot signed images, the signature is appended after this (and the simple hash is included in the signed
data).
struct esp_image_segment_header_t
Header of binary image segment.
Public Members
uint32_t load_addr
Address of segment
uint32_t data_len
Length of data
struct esp_app_desc_t
Description about application.
Public Members
uint32_t magic_word
Magic word ESP_APP_DESC_MAGIC_WORD
uint32_t secure_version
Secure version
uint32_t reserv1[2]
reserv1
char version[32]
Application version
char project_name[32]
Project name
char time[16]
Compile time
char date[16]
Compile date
char idf_ver[32]
Version IDF
uint8_t app_elf_sha256[32]
sha256 of elf file
uint32_t reserv2[20]
reserv2
Macros
ESP_IMAGE_HEADER_MAGIC
The magic word for the esp_image_header_t structure.
ESP_IMAGE_MAX_SEGMENTS
Max count of segments in the image.
ESP_APP_DESC_MAGIC_WORD
The magic word for the esp_app_desc structure that is in DROM.
Enumerations
enum esp_chip_id_t
ESP chip ID.
Values:
enumerator ESP_CHIP_ID_ESP32
chip ID: ESP32
enumerator ESP_CHIP_ID_ESP32S2
chip ID: ESP32-S2
enumerator ESP_CHIP_ID_ESP32C3
chip ID: ESP32-C3
enumerator ESP_CHIP_ID_ESP32S3
chip ID: ESP32-S3
enumerator ESP_CHIP_ID_ESP32C2
chip ID: ESP32-C2
enumerator ESP_CHIP_ID_INVALID
Invalid chip ID (we defined it to make sure the esp_chip_id_t is 2 bytes size)
enum esp_image_spi_mode_t
SPI flash mode, used in esp_image_header_t.
Values:
enumerator ESP_IMAGE_SPI_MODE_QIO
SPI mode QIO
enumerator ESP_IMAGE_SPI_MODE_QOUT
SPI mode QOUT
enumerator ESP_IMAGE_SPI_MODE_DIO
SPI mode DIO
enumerator ESP_IMAGE_SPI_MODE_DOUT
SPI mode DOUT
enumerator ESP_IMAGE_SPI_MODE_FAST_READ
SPI mode FAST_READ
enumerator ESP_IMAGE_SPI_MODE_SLOW_READ
SPI mode SLOW_READ
enum esp_image_spi_freq_t
SPI flash clock division factor.
Values:
enumerator ESP_IMAGE_SPI_SPEED_DIV_2
The SPI flash clock frequency is divided by 2 of the clock source
enumerator ESP_IMAGE_SPI_SPEED_DIV_3
The SPI flash clock frequency is divided by 3 of the clock source
enumerator ESP_IMAGE_SPI_SPEED_DIV_4
The SPI flash clock frequency is divided by 4 of the clock source
enumerator ESP_IMAGE_SPI_SPEED_DIV_1
The SPI flash clock frequency equals to the clock source
enum esp_image_flash_size_t
Supported SPI flash sizes.
Values:
enumerator ESP_IMAGE_FLASH_SIZE_1MB
SPI flash size 1 MB
enumerator ESP_IMAGE_FLASH_SIZE_2MB
SPI flash size 2 MB
enumerator ESP_IMAGE_FLASH_SIZE_4MB
SPI flash size 4 MB
enumerator ESP_IMAGE_FLASH_SIZE_8MB
SPI flash size 8 MB
enumerator ESP_IMAGE_FLASH_SIZE_16MB
SPI flash size 16 MB
enumerator ESP_IMAGE_FLASH_SIZE_32MB
SPI flash size 32 MB
enumerator ESP_IMAGE_FLASH_SIZE_64MB
SPI flash size 64 MB
enumerator ESP_IMAGE_FLASH_SIZE_128MB
SPI flash size 128 MB
enumerator ESP_IMAGE_FLASH_SIZE_MAX
SPI flash size MAX
Overview
IDF provides a useful feature for program behavior analysis called Application Level Tracing. The feature can
be enabled in menuconfig and allows transfer of arbitrary data between the host and ESP32 via JTAG interface with
minimal overhead on program execution. Developers can use this library to send application specific state of execution
to the host and receive commands or other type of info in the opposite direction at runtime. The main use cases of
this library are:
1. Collecting application specific data, see Application Specific Tracing
2. Lightweight logging to the host, see Logging to Host
3. System behaviour analysis, see System Behavior Analysis with SEGGER SystemView
API Reference
Header File
• components/app_trace/include/esp_app_trace.h
Functions
esp_err_t esp_apptrace_init(void)
Initializes application tracing module.
Note: Needs to be called before attempting to receive any data using esp_apptrace_down_buffer_get and
esp_apptrace_read. This function does not protect internal data by lock.
Parameters
• buf –Address of buffer to use for down channel (host to target) data.
void esp_gcov_dump(void)
Triggers gcov info dump. This function waits for the host to connect to target before dumping data.
Enumerations
enum esp_apptrace_dest_t
Application trace data destinations bits.
Values:
enumerator ESP_APPTRACE_DEST_JTAG
JTAG destination.
enumerator ESP_APPTRACE_DEST_TRAX
xxx_TRAX name is obsolete, use more common xxx_JTAG
enumerator ESP_APPTRACE_DEST_UART
UART destination.
enumerator ESP_APPTRACE_DEST_MAX
enumerator ESP_APPTRACE_DEST_NUM
Header File
• components/app_trace/include/esp_sysview_trace.h
Functions
static inline esp_err_t esp_sysview_flush(uint32_t tmo)
Flushes remaining data in SystemView trace buffer to host.
Parameters tmo –Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to
wait indefinetly.
Returns ESP_OK.
int esp_sysview_vprintf(const char *format, va_list args)
vprintf-like function to sent log messages to the host.
Parameters
• format –Address of format string.
• args –List of arguments.
Returns Number of bytes written.
esp_err_t esp_sysview_heap_trace_start(uint32_t tmo)
Starts SystemView heap tracing.
Parameters tmo –Timeout (in us) to wait for the host to be connected. Use -1 to wait forever.
Returns ESP_OK on success, ESP_ERR_TIMEOUT if operation has been timed out.
esp_err_t esp_sysview_heap_trace_stop(void)
Stops SystemView heap tracing.
Returns ESP_OK.
Overview
A given function can be executed with a user allocated stack space which is independent of current task stack, this
mechanism can be used to save stack space wasted by tasks which call a common function with intensive stack usage
such as printf. The given function can be called inside the shared stack space which is a callback function deferred
by calling esp_execute_shared_stack_function(), passing that function as parameter
Usage
void external_stack_function(void)
{
printf("Executing this printf from external stack! \n");
}
vSemaphoreDelete(printf_lock);
free(shared_stack);
}
API Reference
Header File
• components/esp_system/include/esp_expression_with_stack.h
Functions
void esp_execute_shared_stack_function(SemaphoreHandle_t lock, void *stack, size_t stack_size,
shared_stack_function function)
Calls user defined shared stack space function.
Note: if either lock, stack or stack size is invalid, the expression will be called using the current stack.
Parameters
• lock –Mutex object to protect in case of shared stack
• stack –Pointer to user alocated stack
• stack_size –Size of current stack in bytes
• function –pointer to the shared stack function to be executed
Macros
ESP_EXECUTE_EXPRESSION_WITH_STACK(lock, stack, stack_size, expression)
Type Definitions
2.10.4 Console
ESP-IDF provides console component, which includes building blocks needed to develop an interactive console
over serial port. This component includes following facilities:
• Line editing, provided by linenoise library. This includes handling of backspace and arrow keys, scrolling
through command history, command auto-completion, and argument hints.
• Splitting of command line into arguments.
• Argument parsing, provided by argtable3 library. This library includes APIs used for parsing GNU style
command line arguments.
• Functions for registration and dispatching of commands.
• Functions to establish a basic REPL (Read-Evaluate-Print-Loop) environment.
Note: These facilities can be used together or independently. For example, it is possible to use line editing and
command registration features, but use getopt or custom code for argument parsing, instead of argtable3. Likewise,
it is possible to use simpler means of command input (such as fgets) together with the rest of the means for
command splitting and argument parsing.
Line editing
Line editing feature lets users compose commands by typing them, erasing symbols using ‘backspace’key, navi-
gating within the command using left/right keys, navigating to previously typed commands using up/down keys, and
performing autocompletion using ‘tab’key.
Note: This feature relies on ANSI escape sequence support in the terminal application. As such, serial monitors
which display raw UART data can not be used together with the line editing library. If you see [6n or similar escape
sequence when running system/console example instead of a command prompt (e.g. esp> ), it means that the serial
monitor does not support escape sequences. Programs which are known to work are GNU screen, minicom, and
idf_monitor.py (which can be invoked using idf.py monitor from project directory).
Configuration Linenoise library does not need explicit initialization. However, some configuration defaults may
need to be changed before invoking the main line editing function.
linenoiseClearScreen()
Clear terminal screen using an escape sequence and position the cursor at the top left corner.
linenoiseSetMultiLine()
Switch between single line and multi line editing modes. In single line mode, if the length of the com-
mand exceeds the width of the terminal, the command text is scrolled within the line to show the end of
the text. In this case the beginning of the text is hidden. Single line needs less data to be sent to refresh
screen on each key press, so exhibits less glitching compared to the multi line mode. On the flip side,
editing commands and copying command text from terminal in single line mode is harder. Default is
single line mode.
linenoiseAllowEmpty()
Set whether linenoise library will return a zero-length string (if true) or NULL (if false) for empty
lines. By default, zero-length strings are returned.
linenoiseSetMaxLineLen()
Set maximum length of the line for linenoise library. Default length is 4096. If you need optimize RAM
memory usage, you can do it by this function by setting a value less than default 4 KB.
console component provides a ready made function to provide completions for registered commands,
esp_console_get_completion() (see below).
linenoiseAddCompletion()
Function to be called by completion callback to inform the library about possible completions of the
currently typed command.
linenoiseSetHintsCallback()
Whenever user input changes, linenoise invokes hints callback. This callback can inspect the command
line typed so far, and provide a string with hints (which can include list of command arguments, for
example). The library then displays the hint text on the same line where editing happens, possibly with
a different color.
linenoiseSetFreeHintsCallback()
If hint string returned by hints callback is dynamically allocated or needs to be otherwise recycled, the
function which performs such cleanup should be registered via linenoiseSetFreeHintsCall-
back().
History linenoiseHistorySetMaxLen()
This function sets the number of most recently typed commands to be kept in memory. Users can
navigate the history using up/down arrows.
linenoiseHistoryAdd()
Linenoise does not automatically add commands to history. Instead, applications need to call this func-
tion to add command strings to the history.
linenoiseHistorySave()
Function saves command history from RAM to a text file, for example on an SD card or on a filesystem
in flash memory.
linenoiseHistoryLoad()
Counterpart to linenoiseHistorySave(), loads history from a file.
linenoiseHistoryFree()
Releases memory used to store command history. Call this function when done working with linenoise
library.
console component provides esp_console_split_argv() function to split command line string into ar-
guments. The function returns the number of arguments found (argc) and fills an array of pointers which can be
passed as argv argument to any function which accepts arguments in argc, argv format.
The command line is split into arguments according to the following rules:
• Arguments are separated by spaces
• If spaces within arguments are required, they can be escaped using \ (backslash) character.
• Other escape sequences which are recognized are \\ (which produces literal backslash) and \", which pro-
duces a double quote.
• Arguments can be quoted using double quotes. Quotes may appear only in the beginning and at the end of the
argument. Quotes within the argument must be escaped as mentioned above. Quotes surrounding the argument
are stripped by esp_console_split_argv function.
Examples:
• abc def 1 20 .3 ⟶ [ abc, def, 1, 20, .3 ]
• abc "123 456" def ⟶ [ abc, 123 456, def ]
• `a\ b\\c\" ⟶ [ a b\c" ]
Argument parsing
For argument parsing, console component includes argtable3 library. Please see tutorial for an introduction to
argtable3. Github repository also includes examples.
console component includes utility functions which handle registration of commands, matching commands typed
by the user to registered ones, and calling these commands with the arguments given on the command line.
Application first initializes command registration module using a call to esp_console_init(), and calls
esp_console_cmd_register() function to register command handlers.
For each command, application provides the following information (in the form of esp_console_cmd_t struc-
ture):
• Command name (string without spaces)
• Help text explaining what the command does
• Optional hint text listing the arguments of the command. If application uses Argtable3 for argument pars-
ing, hint text can be generated automatically by providing a pointer to argtable argument definitions structure
instead.
• The command handler function.
A few other functions are provided by the command registration module:
esp_console_run()
This function takes the command line string, splits it into argc/argv argument list using
esp_console_split_argv(), looks up the command in the list of registered components, and
if it is found, executes its handler.
esp_console_register_help_command()
Adds help command to the list of registered commands. This command prints the list of all the regis-
tered commands, along with their arguments and help texts.
esp_console_get_completion()
Callback function to be used with linenoiseSetCompletionCallback() from linenoise li-
brary. Provides completions to linenoise based on the list of registered commands.
esp_console_get_hint()
Callback function to be used with linenoiseSetHintsCallback() from linenoise library. Pro-
vides argument hints for registered commands to linenoise.
To establish a basic REPL environment, console component provides several useful APIs, combining those func-
tions described above.
In a typical application, you only need to call esp_console_new_repl_uart() to initialize the REPL envi-
ronment based on UART device, including driver install, basic console configuration, spawning a thread to do REPL
task and register several useful commands (e.g. help).
After that, you can register your own commands with esp_console_cmd_register(). The REPL environ-
ment keeps in init state until you call esp_console_start_repl().
Application Example
Example application illustrating usage of the console component is available in system/console directory. This
example shows how to initialize UART and VFS functions, set up linenoise library, read and handle commands from
UART, and store command history in Flash. See README.md in the example directory for more details.
Besides that, ESP-IDF contains several useful examples which based on console component and can be treated as
“tools”when developing applications. For example, peripherals/i2c/i2c_tools, wifi/iperf.
API Reference
Header File
• components/console/esp_console.h
Functions
esp_err_t esp_console_init(const esp_console_config_t *config)
initialize console module
Note: Call this once before using other console module features
Note: Call this once when done using console module functions
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if not initialized yet
Note: Pointers to at most argv_size - 1 arguments are returned in argv array. The pointer after the last one
(i.e. argv[argc]) is set to NULL.
Parameters
• line –pointer to buffer to parse; it is modified in place
• argv –array where the pointers to arguments are written
• argv_size –number of elements in argv_array (max. number of arguments)
Returns number of arguments found (argc)
Attention This function is meant to be used in the examples to make the code more compact. Applications
which use console functionality should be based on the underlying linenoise and esp_console functions.
Note: This is an all-in-one function to establish the environment needed for REPL, includes:
• Install the UART driver on the console UART (8n1, 115200, REF_TICK clock source)
• Configures the stdin/stdout to go through the UART driver
• Initializes linenoise
• Spawn new thread to run REPL in the background
Parameters
• dev_config –[in] UART device configuration
• repl_config –[in] REPL configuration
• ret_repl –[out] return REPL handle after initialization succeed, return NULL other-
wise
Returns
• ESP_OK on success
• ESP_FAIL Parameter error
Attention This function is meant to be used in the examples to make the code more compact. Applications
which use console functionality should be based on the underlying linenoise and esp_console functions.
Note: This is a all-in-one function to establish the environment needed for REPL, includes:
• Initializes linenoise
• Spawn new thread to run REPL in the background
Parameters
• dev_config –[in] USB CDC configuration
• repl_config –[in] REPL configuration
• ret_repl –[out] return REPL handle after initialization succeed, return NULL other-
wise
Returns
• ESP_OK on success
• ESP_FAIL Parameter error
Note: Once the REPL gets started, it won’t be stopped until the user calls repl->del(repl) to destroy the
REPL environment.
• ESP_OK on success
• ESP_ERR_INVALID_STATE, if repl has started already
Structures
struct esp_console_config_t
Parameters for console initialization.
Public Members
size_t max_cmdline_length
length of command line buffer, in bytes
size_t max_cmdline_args
maximum number of command line arguments to parse
int hint_color
ASCII color code of hint text.
int hint_bold
Set to 1 to print hint text in bold.
struct esp_console_repl_config_t
Parameters for console REPL (Read Eval Print Loop)
Public Members
uint32_t max_history_len
maximum length for the history
uint32_t task_stack_size
repl task stack size
uint32_t task_priority
repl task priority
size_t max_cmdline_length
maximum length of a command line. If 0, default value will be used
struct esp_console_dev_uart_config_t
Parameters for console device: UART.
Public Members
int channel
UART channel number (count from zero)
int baud_rate
Comunication baud rate.
int tx_gpio_num
GPIO number for TX path, -1 means using default one.
int rx_gpio_num
GPIO number for RX path, -1 means using default one.
struct esp_console_dev_usb_cdc_config_t
Parameters for console device: USB CDC.
struct esp_console_cmd_t
Console command description.
Public Members
esp_console_cmd_func_t func
Pointer to a function which implements the command.
void *argtable
Array or structure of pointers to arg_xxx structures, may be NULL. Used to generate hint text if ‘hint’
is set to NULL. Array/structure which this field points to must end with an arg_end. Only used for the
duration of esp_console_cmd_register call.
struct esp_console_repl_s
Console REPL base structure.
Public Members
Macros
ESP_CONSOLE_CONFIG_DEFAULT()
Default console configuration value.
ESP_CONSOLE_REPL_CONFIG_DEFAULT()
Default console repl configuration value.
ESP_CONSOLE_DEV_UART_CONFIG_DEFAULT()
ESP_CONSOLE_DEV_CDC_CONFIG_DEFAULT()
Type Definitions
Introduction
The eFuse Manager library is designed to structure access to eFuse bits and make using these easy. This library
operates eFuse bits by a structure name which is assigned in eFuse table. This sections introduces some concepts
used by eFuse Manager.
Hardware description
The ESP32 has a number of eFuses which can store system and user parameters. Each eFuse is a one-bit field which
can be programmed to 1 after which it cannot be reverted back to 0. Some of system parameters are using these
eFuse bits directly by hardware modules and have special place (for example EFUSE_BLK0).
For more details, see ESP32 Technical Reference Manual > eFuse Controller (eFuse) [PDF]. Some eFuse bits are
available for user applications.
ESP32 has 4 eFuse blocks each of the size of 256 bits (not all bits are available):
• EFUSE_BLK0 is used entirely for system purposes;
• EFUSE_BLK1 is used for flash encrypt key. If not using that Flash Encryption feature, they can be used for
another purpose;
• EFUSE_BLK2 is used for security boot key. If not using that Secure Boot feature, they can be used for another
purpose;
• EFUSE_BLK3 can be partially reserved for the custom MAC address, or used entirely for user application.
Note that some bits are already used in IDF.
Each block is divided into 8 32-bits registers.
The component has API functions for reading and writing fields. Access to the fields is carried out through the
structures that describe the location of the eFuse bits in the blocks. The component provides the ability to form fields
of any length and from any number of individual bits. The description of the fields is made in a CSV file in a table
form. To generate from a tabular form (CSV file) in the C-source uses the tool efuse_table_gen.py. The tool checks
the CSV file for uniqueness of field names and bit intersection, in case of using a custom file from the user’s project
directory, the utility will check with the common CSV file.
CSV files:
• common (esp_efuse_table.csv) - contains eFuse fields which are used inside the IDF. C-source generation should
be done manually when changing this file (run command idf.py efuse-common-table). Note that
changes in this file can lead to incorrect operation.
• custom - (optional and can be enabled by CONFIG_EFUSE_CUSTOM_TABLE) contains eFuse fields that are
used by the user in their application. C-source generation should be done manually when changing this file and
running idf.py efuse-custom-table.
The CSV file contains a description of the eFuse fields. In the simple case, one field has one line of description. Table
header:
The structured eFuse field looks like WR_DIS.RD_DIS where the dot points that this field belongs to the parent
field - WR_DIS and can not be out of the parent’s range.
It is possible to use some levels of structured fields as WR_DIS.FIELD_2.B1 and B2. These fields should not be
crossed each other and should be in the range of two fields: WR_DIS and WR_DIS.FIELD_2.
It is possible to create aliases for fields with the same range, see WR_DIS.FIELD_3 and WR_DIS.FIELD_3.
ALIAS.
The IDF names for structured efuse fields should be unique. The efuse_table_gen tool will generate the
final names where the dot will be replaced by _. The names for using in IDF are ESP_EFUSE_WR_DIS,
ESP_EFUSE_WR_DIS_RD_DIS, ESP_EFUSE_WR_DIS_FIELD_2_B1, etc.
The efuse_table_gen tool checks that the fields do not overlap each other and must be within the range of a
field if there is a violation, then throws the following error:
efuse_table_gen.py tool
The tool is designed to generate C-source files from CSV file and validate fields. First of all, the check is carried out
on the uniqueness of the names and overlaps of the field bits. If an additional custom file is used, it will be checked
with the existing common file (esp_efuse_table.csv). In case of errors, a message will be displayed and the string that
caused the error. C-source files contain structures of type esp_efuse_desc_t.
To generate a common files, use the following command idf.py efuse-common-table or:
cd $IDF_PATH/components/efuse/
./efuse_table_gen.py --idf_target esp32 esp32/esp_efuse_table.csv
cd $IDF_PATH/components/efuse/
./efuse_table_gen.py --idf_target esp32 esp32/esp_efuse_table.csv PROJECT_PATH/
,→main/esp_efuse_custom_table.csv
#include "esp_efuse.h"
#include "esp_efuse_table.h" // or "esp_efuse_custom_table.h"
Also, 3/4 coding scheme imposes restrictions on writing bits belonging to one coding unit. The whole block with a
length of 256 bits is divided into 4 coding units, and in each coding unit there are 6 bytes of useful data and 2 service
bytes. These 2 service bytes contain the checksum of the previous 6 data bytes.
It turns out that only one field can be written into one coding unit. Repeated rewriting in one coding unit is prohibited.
But if the record was made in advance or through a esp_efuse_write_block() function, then reading the
fields belonging to one coding unit is possible.
In case 3/4 coding scheme, the writing process is divided into the coding units and we can not use the usual mode
of writing some fields. We can prepare all the data for writing and burn it in one time. You can also use this mode
for None coding scheme but it is not necessary. It is important for 3/4 coding scheme. The batch writing
mode blocks esp_efuse_read_... operations.
After changing the coding scheme, run efuse_common_table and efuse_custom_table commands to
check the tables of the new coding scheme.
To write some fields into one block, or different blocks in one time, you need to use the batch writ-
ing mode. Firstly set this mode through esp_efuse_batch_write_begin() function then write
some fields as usual using the esp_efuse_write_... functions. At the end to burn them, call the
esp_efuse_batch_write_commit() function. It burns prepared data to the eFuse blocks and disables the
batch recording mode.
Note: If there is already pre-written data in the eFuse block using the 3/4 or Repeat encoding scheme, then it is
not possible to write anything extra (even if the required bits are empty) without breaking the previous encoding data.
This encoding data will be overwritten with new encoding data and completely destroyed (however, the payload eFuses
are not damaged). It can be related to: CUSTOM_MAC, SPI_PAD_CONFIG_HD, SPI_PAD_CONFIG_CS, etc.
Please contact Espressif to order the required pre-burnt eFuses.
FOR TESTING ONLY (NOT RECOMMENDED): You can ignore or suppress errors that violate encoding scheme
data in order to burn the necessary bits in the eFuse block.
eFuse API
Access to the fields is via a pointer to the description structure. API functions have some basic operation:
• esp_efuse_read_field_blob() - returns an array of read eFuse bits.
• esp_efuse_read_field_cnt() - returns the number of bits programmed as “1”.
• esp_efuse_write_field_blob() - writes an array.
• esp_efuse_write_field_cnt() - writes a required count of bits as “1”.
• esp_efuse_get_field_size() - returns the number of bits by the field name.
• esp_efuse_read_reg() - returns value of eFuse register.
• esp_efuse_write_reg() - writes value to eFuse register.
• esp_efuse_get_coding_scheme() - returns eFuse coding scheme for blocks.
• esp_efuse_read_block() - reads key to eFuse block starting at the offset and the required size.
• esp_efuse_write_block() - writes key to eFuse block starting at the offset and the required size.
• esp_efuse_batch_write_begin() - set the batch mode of writing fields.
• esp_efuse_batch_write_commit() - writes all prepared data for batch writing mode and reset the
batch writing mode.
• esp_efuse_batch_write_cancel() - reset the batch writing mode and prepared data.
• esp_efuse_get_key_dis_read() - Returns a read protection for the key block.
• esp_efuse_set_key_dis_read() - Sets a read protection for the key block.
• esp_efuse_get_key_dis_write() - Returns a write protection for the key block.
• esp_efuse_set_key_dis_write() - Sets a write protection for the key block.
• esp_efuse_get_key_purpose() - Returns the current purpose set for an eFuse key block.
• esp_efuse_write_key() - Programs a block of key data to an eFuse block
• esp_efuse_write_keys() - Programs keys to unused eFuse blocks
• esp_efuse_find_purpose() - Finds a key block with the particular purpose set.
• esp_efuse_get_keypurpose_dis_write() - Returns a write protection of the key purpose field
for an eFuse key block (for esp32 always true).
1. Find a free bits for field. Show esp_efuse_table.csv file or run idf.py show-efuse-table or the next
command:
$ ./efuse_table_gen.py esp32/esp_efuse_table.csv --info
EFUSE_BLK1
[0 191]
EFUSE_BLK2
[0 191]
EFUSE_BLK3
[0 55] [96 159] [184 191]
Note: Not printed ranges are free for using. (bits in EFUSE_BLK0 are reserved for␣
,→Espressif)
The number of bits not included in square brackets is free (some bits are reserved for Espressif). All fields are checked
for overlapping.
To add fields to an existing field, use the Structured efuse fields technique. For example, adding the fields: SE-
RIAL_NUMBER, MODEL_NUMBER and HARDWARE REV to an existing USER_DATA field. Use . (dot) to
show an attachment in a field.
Bit Order
The eFuses bit order is little endian (see the example below), it means that eFuse bits are read and written from LSB
to MSB:
$ espefuse.py dump
EFUSE_RD_USR_DATA0_REG = 0x03020100
EFUSE_RD_USR_DATA1_REG = 0x07060504
EFUSE_RD_USR_DATA2_REG = 0x0B0A0908
EFUSE_RD_USR_DATA3_REG = 0x0F0E0D0C
EFUSE_RD_USR_DATA4_REG = 0x13121111
EFUSE_RD_USR_DATA5_REG = 0x17161514
EFUSE_RD_USR_DATA6_REG = 0x1B1A1918
EFUSE_RD_USR_DATA7_REG = 0x1F1E1D1C
(continues on next page)
byte[0] = 0x00, byte[1] = 0x01, ... byte[3] = 0x03, byte[4] = 0x04, ..., byte[31]␣
,→= 0x1F
For example, csv file describes the USER_DATA field, which occupies all 256 bits (a whole block).
Thus, reading the eFuse USER_DATA block written as above gives the following results:
uint8_t buf[32] = { 0 };
esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA, &buf, sizeof(buf) * 8);
// buf[0] = 0x00, buf[1] = 0x01, ... buf[31] = 0x1F
uint32_t field1 = 0;
size_t field1_size = ESP_EFUSE_USER_DATA[0]->bit_count; // can be used for this␣
,→case because it only consists of one entry
uint32_t field1_1 = 0;
esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA, &field1_1, 2); // reads only first␣
,→2 bits
// field1 = 0x0002
uint8_t id = 0;
size_t id_size = esp_efuse_get_field_size(ESP_EFUSE_ID); // returns 6
// size_t id_size = ESP_EFUSE_USER_DATA[0]->bit_count; // can NOT be used because␣
,→it consists of 3 entries. It returns 3 not 6.
uint8_t id_1 = 0;
esp_efuse_read_field_blob(ESP_EFUSE_ID, &id_1, 3);
// id = 0x01
// b'001
Virtual eFuses The Kconfig option CONFIG_EFUSE_VIRTUAL will virtualize eFuse values inside the eFuse Man-
ager, so writes are emulated and no eFuse values are permanently changed. This can be useful for debugging app and
unit tests. During startup, the eFuses are copied to RAM. All eFuse operations (read and write) are performed with
RAM instead of the real eFuse registers.
In addition to the CONFIG_EFUSE_VIRTUAL option there is CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH option
that adds a feature to keep eFuses in flash memory. To use this mode the partition_table should have the efuse
partition. partition.csv: "efuse_em, data, efuse, , 0x2000,". During startup, the eFuses are copied
from flash or, in case if flash is empty, from real eFuse to RAM and then update flash. This option allows keeping
eFuses after reboots (possible to test secure_boot and flash_encryption features with this option).
espefuse.py esptool includes a useful tool for reading/writing ESP32 eFuse bits - espefuse.py.
espefuse.py -p PORT summary
Connecting........__
Detecting chip type... ESP32
espefuse.py v3.1-dev
EFUSE_NAME (Block) Description = [Meaningful Value]␣
,→[Readable/Writeable] (Hex Value)
-----------------------------------------------------------------------------------
,→-----
Calibration fuses:
BLK3_PART_RESERVE (BLOCK0): BLOCK3 partially served for ADC␣
,→calibration data = True R/W (0b1)
ADC_VREF (BLOCK0): Voltage reference calibration ␣
,→ = 1114 R/W (0b00010)
ADC1_TP_LOW (BLOCK3): ADC1 150mV reading ␣
,→ = 346 R/W (0b0010001)
ADC1_TP_HIGH (BLOCK3): ADC1 850mV reading ␣
,→ = 3285 R/W (0b000000101)
ADC2_TP_LOW (BLOCK3): ADC2 150mV reading ␣
,→ = 449 R/W (0b0000111)
ADC2_TP_HIGH (BLOCK3): ADC2 850mV reading ␣
,→ = 3362 R/W (0b111110101)
Config fuses:
XPD_SDIO_FORCE (BLOCK0): Ignore MTDI pin (GPIO12) for VDD_SDIO on␣
,→reset = False R/W (0b0)
XPD_SDIO_REG (BLOCK0): If XPD_SDIO_FORCE, enable VDD_SDIO reg on␣
,→reset = False R/W (0b0)
XPD_SDIO_TIEH (BLOCK0): If XPD_SDIO_FORCE & XPD_SDIO_REG ␣
,→ = 1.8V R/W (0b0)
CLK8M_FREQ (BLOCK0): 8MHz clock freq override ␣
,→ = 53 R/W (0x35)
SPI_PAD_CONFIG_CLK (BLOCK0): Override SD_CLK pad (GPIO6/SPICLK) ␣
,→ = 0 R/W (0b00000)
SPI_PAD_CONFIG_Q (BLOCK0): Override SD_DATA_0 pad (GPIO7/SPIQ) ␣
,→ = 0 R/W (0b00000)
SPI_PAD_CONFIG_D (BLOCK0): Override SD_DATA_1 pad (GPIO8/SPID) ␣
,→ = 0 R/W (0b00000)
SPI_PAD_CONFIG_HD (BLOCK0): Override SD_DATA_2 pad (GPIO9/SPIHD) ␣
,→ = 0 R/W (0b00000)
SPI_PAD_CONFIG_CS0 (BLOCK0): Override SD_CMD pad (GPIO11/SPICS0) ␣
,→ = 0 R/W (0b00000)
DISABLE_SDIO_HOST (BLOCK0): Disable SDIO host ␣
,→ = False R/W (0b0)
Efuse fuses:
WR_DIS (BLOCK0): Efuse write disable mask ␣
,→ = 0 R/W (0x0000)
RD_DIS (BLOCK0): Efuse read disable mask ␣
,→ = 0 R/W (0x0)
CODING_SCHEME (BLOCK0): Efuse variable block length scheme
= 3/4 (BLK1-3 len=192 bits) R/W (0b01)
KEY_STATUS (BLOCK0): Usage of efuse block 3 (reserved) ␣
,→ = False R/W (0b0)
Identity fuses:
MAC (BLOCK0): Factory MAC Address
= 84:0d:8e:18:8e:44 (CRC 0xad OK) R/W
MAC_CRC (BLOCK0): CRC8 for factory MAC address ␣
,→ = 173 R/W (0xad)
CHIP_VER_REV1 (BLOCK0): Silicon Revision 1 ␣
,→ = True R/W (0b1) (continues on next page)
Security fuses:
FLASH_CRYPT_CNT (BLOCK0): Flash encryption mode counter ␣
,→ = 0 R/W (0b0000000)
UART_DOWNLOAD_DIS (BLOCK0): Disable UART download mode (ESP32 rev3␣
,→only) = False R/W (0b0)
FLASH_CRYPT_CONFIG (BLOCK0): Flash encryption config (key tweak bits) ␣
,→ = 0 R/W (0x0)
CONSOLE_DEBUG_DISABLE (BLOCK0): Disable ROM BASIC interpreter fallback ␣
,→ = True R/W (0b1)
ABS_DONE_0 (BLOCK0): Secure boot V1 is enabled for bootloader␣
,→image = False R/W (0b0)
ABS_DONE_1 (BLOCK0): Secure boot V2 is enabled for bootloader␣
,→image = False R/W (0b0)
JTAG_DISABLE (BLOCK0): Disable JTAG ␣
,→ = False R/W (0b0)
DISABLE_DL_ENCRYPT (BLOCK0): Disable flash encryption in UART␣
,→bootloader = False R/W (0b0)
DISABLE_DL_DECRYPT (BLOCK0): Disable flash decryption in UART␣
,→bootloader = False R/W (0b0)
DISABLE_DL_CACHE (BLOCK0): Disable flash cache in UART bootloader ␣
,→ = False R/W (0b0)
BLOCK1 (BLOCK1): Flash encryption key
= 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 R/W
BLOCK2 (BLOCK2): Secure boot key
= 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 R/W
BLOCK3 (BLOCK3): Variable Block 3
= 00 00 00 00 00 00 00 00 00 00 00 00 91 02 87 fa 00 00 00 00 00 00 00 00 R/W
Flash voltage (VDD_SDIO) determined by GPIO12 on reset (High for 1.8V, Low/NC for␣
,→3.3V).
Connecting........_
Detecting chip type... ESP32
BLOCK0 ( ) [0 ] read_regs: 00000000 8e188e44 00ad840d␣
,→0000e000 00000235 00000000 00000005
espefuse.py v3.1-dev
Header File
• components/efuse/esp32/include/esp_efuse.h
Enumerations
enum esp_efuse_block_t
Type of eFuse blocks for ESP32.
Values:
enumerator EFUSE_BLK0
Number of eFuse block. Reserved.
enumerator EFUSE_BLK1
Number of eFuse block. Used for Flash Encryption. If not using that Flash Encryption feature, they can
be used for another purpose.
enumerator EFUSE_BLK_KEY0
Number of eFuse block. Used for Flash Encryption. If not using that Flash Encryption feature, they can
be used for another purpose.
enumerator EFUSE_BLK_ENCRYPT_FLASH
Number of eFuse block. Used for Flash Encryption. If not using that Flash Encryption feature, they can
be used for another purpose.
enumerator EFUSE_BLK2
Number of eFuse block. Used for Secure Boot. If not using that Secure Boot feature, they can be used
for another purpose.
enumerator EFUSE_BLK_KEY1
Number of eFuse block. Used for Secure Boot. If not using that Secure Boot feature, they can be used
for another purpose.
enumerator EFUSE_BLK_SECURE_BOOT
Number of eFuse block. Used for Secure Boot. If not using that Secure Boot feature, they can be used
for another purpose.
enumerator EFUSE_BLK3
Number of eFuse block. Uses for the purpose of the user.
enumerator EFUSE_BLK_KEY2
Number of eFuse block. Uses for the purpose of the user.
enumerator EFUSE_BLK_KEY_MAX
enumerator EFUSE_BLK_MAX
enum esp_efuse_coding_scheme_t
Type of coding scheme.
Values:
enumerator EFUSE_CODING_SCHEME_NONE
None
enumerator EFUSE_CODING_SCHEME_3_4
3/4 coding
enumerator EFUSE_CODING_SCHEME_REPEAT
Repeat coding
enum esp_efuse_purpose_t
Type of key purpose (virtual because ESP32 has only fixed purposes for blocks)
Values:
enumerator ESP_EFUSE_KEY_PURPOSE_USER
BLOCK3
enumerator ESP_EFUSE_KEY_PURPOSE_SYSTEM
BLOCK0
enumerator ESP_EFUSE_KEY_PURPOSE_FLASH_ENCRYPTION
BLOCK1
enumerator ESP_EFUSE_KEY_PURPOSE_SECURE_BOOT_V2
BLOCK2
enumerator ESP_EFUSE_KEY_PURPOSE_MAX
MAX PURPOSE
Header File
• components/efuse/include/esp_efuse.h
Functions
esp_err_t esp_efuse_read_field_blob(const esp_efuse_desc_t *field[], void *dst, size_t dst_size_bits)
Reads bits from EFUSE field and writes it into an array.
The number of read bits will be limited to the minimum value from the description of the bits in “field”
structure or“dst_size_bits”required size. Use“esp_efuse_get_field_size()”function to determine the length
of the field.
Note: Please note that reading in the batch mode does not show uncommitted changes.
Parameters
• field –[in] A pointer to the structure describing the fields of efuse.
• dst –[out] A pointer to array that will contain the result of reading.
• dst_size_bits –[in] The number of bits required to read. If the requested number
of bits is greater than the field, the number will be limited to the field size.
Returns
• ESP_OK: The operation was successfully completed.
• ESP_ERR_INVALID_ARG: Error in the passed arguments.
Note: The value must exist and must be a single bit wide. If there is any possibility of an error in the provided
arguments, call esp_efuse_read_field_blob() and check the returned value instead.
Note: If assertions are enabled and the parameter is invalid, execution will abort
Note: Please note that reading in the batch mode does not show uncommitted changes.
Parameters field –[in] A pointer to the structure describing the fields of efuse.
Returns
• true: The field parameter is valid and the bit is set.
• false: The bit is not set, or the parameter is invalid and assertions are disabled.
Note: Please note that reading in the batch mode does not show uncommitted changes.
Parameters
• field –[in] A pointer to the structure describing the fields of efuse.
• out_cnt –[out] A pointer that will contain the number of programmed as “1”bits.
Returns
• ESP_OK: The operation was successfully completed.
• ESP_ERR_INVALID_ARG: Error in the passed arguments.
Parameters
• field –[in] A pointer to the structure describing the fields of efuse.
• cnt –[in] Required number of programmed as “1”bits.
Returns
• ESP_OK: The operation was successfully completed.
• ESP_ERR_INVALID_ARG: Error in the passed arguments.
• ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set.
esp_err_t esp_efuse_write_field_bit(const esp_efuse_desc_t *field[])
Write a single bit eFuse field to 1.
For use with eFuse fields that are a single bit. This function will write the bit to value 1 if it is not already set,
or does nothing if the bit is already set.
This is equivalent to calling esp_efuse_write_field_cnt() with the cnt parameter equal to 1, except that it will
return ESP_OK if the field is already set to 1.
Parameters field –[in] Pointer to the structure describing the efuse field.
Returns
• ESP_OK: The operation was successfully completed, or the bit was already set to value 1.
• ESP_ERR_INVALID_ARG: Error in the passed arugments, including if the efuse field is
not 1 bit wide.
esp_err_t esp_efuse_set_write_protect(esp_efuse_block_t blk)
Sets a write protection for the whole block.
After that, it is impossible to write to this block. The write protection does not apply to block 0.
Parameters blk –[in] Block number of eFuse. (EFUSE_BLK1, EFUSE_BLK2 and
EFUSE_BLK3)
Returns
• ESP_OK: The operation was successfully completed.
• ESP_ERR_INVALID_ARG: Error in the passed arguments.
• ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set.
• ESP_ERR_NOT_SUPPORTED: The block does not support this command.
esp_err_t esp_efuse_set_read_protect(esp_efuse_block_t blk)
Sets a read protection for the whole block.
After that, it is impossible to read from this block. The read protection does not apply to block 0.
Parameters blk –[in] Block number of eFuse. (EFUSE_BLK1, EFUSE_BLK2 and
EFUSE_BLK3)
Returns
• ESP_OK: The operation was successfully completed.
• ESP_ERR_INVALID_ARG: Error in the passed arguments.
• ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set.
• ESP_ERR_NOT_SUPPORTED: The block does not support this command.
int esp_efuse_get_field_size(const esp_efuse_desc_t *field[])
Returns the number of bits used by field.
Parameters field –[in] A pointer to the structure describing the fields of efuse.
Returns Returns the number of bits used by field.
uint32_t esp_efuse_read_reg(esp_efuse_block_t blk, unsigned int num_reg)
Returns value of efuse register.
This is a thread-safe implementation. Example: EFUSE_BLK2_RDATA3_REG where (blk=2, num_reg=3)
Note: Please note that reading in the batch mode does not show uncommitted changes.
Parameters
Note: Please note that reading in the batch mode does not show uncommitted changes.
Parameters
• blk –[in] Block number of eFuse.
• dst_key –[in] A pointer to array that will contain the result of reading.
• offset_in_bits –[in] Start bit in block.
• size_bits –[in] The number of bits required to read.
Returns
• ESP_OK: The operation was successfully completed.
• ESP_ERR_INVALID_ARG: Error in the passed arguments.
• ESP_ERR_CODING: Error range of data does not match the coding scheme.
uint32_t esp_efuse_get_pkg_ver(void)
Returns chip package from efuse.
Returns chip package
void esp_efuse_reset(void)
Reset efuse write registers.
Efuse write registers are written to zero, to negate any changes that have been staged here.
Note: This function is not threadsafe, if calling code updates efuse values from multiple tasks then this is
caller’s responsibility to serialise.
void esp_efuse_disable_basic_rom_console(void)
Disable BASIC ROM Console via efuse.
By default, if booting from flash fails the ESP32 will boot a BASIC console in ROM.
Call this function (from bootloader or app) to permanently disable the console on this chip.
esp_err_t esp_efuse_disable_rom_download_mode(void)
Disable ROM Download Mode via eFuse.
Permanently disables the ROM Download Mode feature. Once disabled, if the SoC is booted with strapping
pins set for ROM Download Mode then an error is printed instead.
Note: Not all SoCs support this option. An error will be returned if called on an ESP32 with a silicon revision
lower than 3, as these revisions do not support this option.
Note: If ROM Download Mode is already disabled, this function does nothing and returns success.
Returns
• ESP_OK If the eFuse was successfully burned, or had already been burned.
• ESP_ERR_NOT_SUPPORTED (ESP32 only) This SoC is not capable of disabling
UART download mode
• ESP_ERR_INVALID_STATE (ESP32 only) This eFuse is write protected and cannot be
written
Note: By default, the boot ROM will always print to console. This API can be called to set the log scheme
only once per chip, once the value is changed from the default it can’t be changed again.
uint32_t esp_efuse_read_secure_version(void)
Return secure_version from efuse field.
Returns Secure version from efuse field
Note: If batch mode is enabled by the first task, at this time the second task cannot write/read efuses. The
second task will wait for the first task to complete the batch operation.
,→after commit.
...
...
Note: Please note that reading in the batch mode does not show uncommitted changes.
Returns
• ESP_OK: Successful.
esp_err_t esp_efuse_batch_write_cancel(void)
Reset the batch mode of writing fields.
It will reset the batch writing mode and any written changes.
Returns
• ESP_OK: Successful.
• ESP_ERR_INVALID_STATE: Tha batch mode was not set.
esp_err_t esp_efuse_batch_write_commit(void)
Writes all prepared data for the batch mode.
Must be called to ensure changes are written to the efuse registers. After this the batch writing mode will be
reset.
Returns
• ESP_OK: Successful.
• ESP_ERR_INVALID_STATE: The deferred writing mode was not set.
bool esp_efuse_block_is_empty(esp_efuse_block_t block)
Checks that the given block is empty.
Returns
• True: The block is empty.
• False: The block is not empty or was an error.
bool esp_efuse_get_key_dis_read(esp_efuse_block_t block)
Returns a read protection for the key block.
Parameters block –[in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX
Returns True: The key block is read protected False: The key block is readable.
esp_err_t esp_efuse_set_key_dis_read(esp_efuse_block_t block)
Sets a read protection for the key block.
Parameters block –[in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX
Returns
• ESP_OK: Successful.
• ESP_ERR_INVALID_ARG: Error in the passed arguments.
• ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed
bits is strictly forbidden.
• ESP_ERR_CODING: Error range of data does not match the coding scheme.
bool esp_efuse_get_key_dis_write(esp_efuse_block_t block)
Returns a write protection for the key block.
Parameters block –[in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX
Returns True: The key block is write protected False: The key block is writeable.
esp_err_t esp_efuse_set_key_dis_write(esp_efuse_block_t block)
Sets a write protection for the key block.
Parameters block –[in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX
Returns
• ESP_OK: Successful.
• ESP_ERR_INVALID_ARG: Error in the passed arguments.
• ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed
bits is strictly forbidden.
• ESP_ERR_CODING: Error range of data does not match the coding scheme.
bool esp_efuse_key_block_unused(esp_efuse_block_t block)
Returns true if the key block is unused, false otherwise.
An unused key block is all zero content, not read or write protected, and has purpose 0
(ESP_EFUSE_KEY_PURPOSE_USER)
Parameters block –key block to check.
Returns
• True if key block is unused,
• False if key block is used or the specified block index is not a key block.
bool esp_efuse_find_purpose(esp_efuse_purpose_t purpose, esp_efuse_block_t *block)
Find a key block with the particular purpose set.
Parameters
• purpose –[in] Purpose to search for.
• block –[out] Pointer in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX
which will be set to the key block if found. Can be NULL, if only need to test the key
block exists.
Returns
• True: If found,
• False: If not found (value at block pointer is unchanged).
bool esp_efuse_get_keypurpose_dis_write(esp_efuse_block_t block)
Returns a write protection of the key purpose field for an efuse key block.
It does a BLOCK0 check if eFuse EFUSE_ERR_RST_ENABLE is set. If BLOCK0 has an error, it prints the
error and returns ESP_FAIL, which should be treated as esp_restart.
Returns
• ESP_OK: No errors in BLOCK0.
• ESP_FAIL: Error in BLOCK0 requiring reboot.
Structures
struct esp_efuse_desc_t
Type definition for an eFuse field.
Public Members
esp_efuse_block_t efuse_block
Block of eFuse
uint8_t bit_start
Start bit [0..255]
uint16_t bit_count
Length of bit field [1..-]
Macros
ESP_ERR_EFUSE
Base error code for efuse api.
ESP_OK_EFUSE_CNT
OK the required number of bits is set.
ESP_ERR_EFUSE_CNT_IS_FULL
Error field is full.
ESP_ERR_EFUSE_REPEATED_PROG
Error repeated programming of programmed bits is strictly forbidden.
ESP_ERR_CODING
Error while a encoding operation.
ESP_ERR_NOT_ENOUGH_UNUSED_KEY_BLOCKS
Error not enough unused key blocks available
ESP_ERR_DAMAGED_READING
Error. Burn or reset was done during a reading operation leads to damage read data. This error is internal to
the efuse component and not returned by any public API.
Enumerations
enum esp_efuse_rom_log_scheme_t
Type definition for ROM log scheme.
Values:
enumerator ESP_EFUSE_ROM_LOG_ALWAYS_ON
Always enable ROM logging
enumerator ESP_EFUSE_ROM_LOG_ON_GPIO_LOW
ROM logging is enabled when specific GPIO level is low during start up
enumerator ESP_EFUSE_ROM_LOG_ON_GPIO_HIGH
ROM logging is enabled when specific GPIO level is high during start up
enumerator ESP_EFUSE_ROM_LOG_ALWAYS_OFF
Disable ROM logging permanently
This section lists definitions of common ESP-IDF error codes and several helper functions related to error handling.
For general information about error codes in ESP-IDF, see Error Handling.
For the full list of error codes defined in ESP-IDF, see Error Code Reference.
API Reference
Header File
• components/esp_common/include/esp_check.h
Macros
ESP_RETURN_ON_ERROR(x, log_tag, format, ...)
Macro which can be used to check the error code. If the code is not ESP_OK, it prints the message and
returns. In the future, we want to switch to C++20. We also want to become compatible with clang. Hence,
we provide two versions of the following macros. The first one is using the GNU extension ##__VA_ARGS__.
The second one is using the C++20 feature VA_OPT(,). This allows users to compile their code with standard
C++20 enabled instead of the GNU extension. Below C++20, we haven’t found any good alternative to using
##__VA_ARGS__. Macro which can be used to check the error code. If the code is not ESP_OK, it prints
the message and returns.
ESP_RETURN_ON_ERROR_ISR(x, log_tag, format, ...)
A version of ESP_RETURN_ON_ERROR() macro that can be called from ISR.
ESP_GOTO_ON_ERROR(x, goto_tag, log_tag, format, ...)
Macro which can be used to check the error code. If the code is not ESP_OK, it prints the message, sets the
local variable ‘ret’to the code, and then exits by jumping to ‘goto_tag’.
ESP_GOTO_ON_ERROR_ISR(x, goto_tag, log_tag, format, ...)
A version of ESP_GOTO_ON_ERROR() macro that can be called from ISR.
ESP_RETURN_ON_FALSE(a, err_code, log_tag, format, ...)
Macro which can be used to check the condition. If the condition is not ‘true’, it prints the message and
returns with the supplied ‘err_code’.
ESP_RETURN_ON_FALSE_ISR(a, err_code, log_tag, format, ...)
A version of ESP_RETURN_ON_FALSE() macro that can be called from ISR.
ESP_GOTO_ON_FALSE(a, err_code, goto_tag, log_tag, format, ...)
Macro which can be used to check the condition. If the condition is not ‘true’, it prints the message, sets
the local variable ‘ret’to the supplied ‘err_code’, and then exits by jumping to ‘goto_tag’.
ESP_GOTO_ON_FALSE_ISR(a, err_code, goto_tag, log_tag, format, ...)
A version of ESP_GOTO_ON_FALSE() macro that can be called from ISR.
Header File
• components/esp_common/include/esp_err.h
Functions
const char *esp_err_to_name(esp_err_t code)
Returns string for esp_err_t error codes.
This function finds the error code in a pre-generated lookup-table and returns its string representation.
The function is generated by the Python script tools/gen_esp_err_to_name.py which should be run each time
an esp_err_t error is modified, created or removed from the IDF project.
Parameters code –esp_err_t error code
Returns string error message
const char *esp_err_to_name_r(esp_err_t code, char *buf, size_t buflen)
Returns string for esp_err_t and system error codes.
This function finds the error code in a pre-generated lookup-table of esp_err_t errors and returns its string
representation. If the error code is not found then it is attempted to be found among system errors.
The function is generated by the Python script tools/gen_esp_err_to_name.py which should be run each time
an esp_err_t error is modified, created or removed from the IDF project.
Parameters
• code –esp_err_t error code
• buf –[out] buffer where the error message should be written
• buflen –Size of buffer buf. At most buflen bytes are written into the buf buffer (includ-
ing the terminating null byte).
Returns buf containing the string error message
Macros
ESP_OK
esp_err_t value indicating success (no error)
ESP_FAIL
Generic esp_err_t code indicating failure
ESP_ERR_NO_MEM
Out of memory
ESP_ERR_INVALID_ARG
Invalid argument
ESP_ERR_INVALID_STATE
Invalid state
ESP_ERR_INVALID_SIZE
Invalid size
ESP_ERR_NOT_FOUND
Requested resource not found
ESP_ERR_NOT_SUPPORTED
Operation or feature not supported
ESP_ERR_TIMEOUT
Operation timed out
ESP_ERR_INVALID_RESPONSE
Received response was invalid
ESP_ERR_INVALID_CRC
CRC or checksum was invalid
ESP_ERR_INVALID_VERSION
Version was invalid
ESP_ERR_INVALID_MAC
MAC address was invalid
ESP_ERR_NOT_FINISHED
There are items remained to retrieve
ESP_ERR_WIFI_BASE
Starting number of WiFi error codes
ESP_ERR_MESH_BASE
Starting number of MESH error codes
ESP_ERR_FLASH_BASE
Starting number of flash error codes
ESP_ERR_HW_CRYPTO_BASE
Starting number of HW cryptography module error codes
ESP_ERR_MEMPROT_BASE
Starting number of Memory Protection API error codes
ESP_ERROR_CHECK(x)
Macro which can be used to check the error code, and terminate the program in case the code is not ESP_OK.
Prints the error code, error location, and the failed statement to serial output.
Disabled if assertions are disabled.
ESP_ERROR_CHECK_WITHOUT_ABORT(x)
Macro which can be used to check the error code. Prints the error code, error location, and the failed statement
to serial output. In comparison with ESP_ERROR_CHECK(), this prints the same error message but isn’t
terminating the program.
Type Definitions
Overview
esp_https_ota provides simplified APIs to perform firmware upgrades over HTTPS. It’s an abstraction layer
over existing OTA APIs.
Application Example
esp_err_t do_firmware_upgrade()
{
esp_http_client_config_t config = {
.url = CONFIG_FIRMWARE_UPGRADE_URL,
.cert_pem = (char *)server_cert_pem_start,
};
esp_https_ota_config_t ota_config = {
.http_config = &config,
};
esp_err_t ret = esp_https_ota(&ota_config);
if (ret == ESP_OK) {
(continues on next page)
Server Verification
Please refer to ESP-TLS: TLS Server Verification for more information on server verification. The root certificate (in
PEM format) needs to be provided to the esp_http_client_config_t::cert_pem member.
Note: The server-endpoint root certificate should be used for verification instead of any intermedi-
ate ones from the certificate chain. The reason being that the root certificate has the maximum validity
and usually remains the same for a long period of time. Users can also use the ESP x509 Cer-
tificate Bundle feature for verification, which covers most of the trusted root certificates (using the
esp_http_client_config_t::crt_bundle_attach member).
Signature Verification
For additional security, signature of OTA firmware images can be verified. For that, refer Secure OTA Updates Without
Secure boot
Advanced APIs
esp_https_ota also provides advanced APIs which can be used if more information and control is needed during
the OTA process.
Example that uses advanced ESP_HTTPS_OTA APIs: system/ota/advanced_https_ota.
API Reference
Header File
• components/esp_https_ota/include/esp_https_ota.h
Functions
esp_err_t esp_https_ota(const esp_https_ota_config_t *ota_config)
HTTPS OTA Firmware upgrade.
This function allocates HTTPS OTA Firmware upgrade context, establishes HTTPS connection, reads image
data from HTTP stream and writes it to OTA partition and finishes HTTPS OTA Firmware upgrade operation.
This API supports URL redirection, but if CA cert of URLs differ then it should be appended to cert_pem
member of ota_config->http_config.
Note: This API handles the entire OTA operation, so if this API is being used then no other APIs from
esp_https_ota component should be called. If more information and control is needed during the HTTPS
OTA process, then one can use esp_https_ota_begin and subsequent APIs. If this API returns suc-
cessfully, esp_restart() must be called to boot from the new firmware image.
Note: This API is blocking, so setting is_async member of http_config structure will result in an
error.
Parameters
• ota_config –[in] pointer to esp_https_ota_config_t structure
• handle –[out] pointer to an allocated data of type esp_https_ota_handle_t
which will be initialised in this function
Returns
• ESP_OK: HTTPS OTA Firmware upgrade context initialised and HTTPS connection es-
tablished
• ESP_FAIL: For generic failure.
• ESP_ERR_INVALID_ARG: Invalid argument (missing/incorrect config, certificate, etc.)
• For other return codes, refer documentation in app_update component and esp_http_client
component in esp-idf.
Note: This API can be called just before esp_https_ota_finish() to validate if the complete image was indeed
received.
Note: If this API returns successfully, esp_restart() must be called to boot from the new firmware image
esp_https_ota_finish should not be called after calling esp_https_ota_abort
Note: This API can be called only after esp_https_ota_begin() and before esp_https_ota_perform(). Calling
this API is not mandatory.
Parameters
• https_ota_handle –[in] pointer to esp_https_ota_handle_t structure
• new_app_info –[out] pointer to an allocated esp_app_desc_t structure
Returns
• ESP_ERR_INVALID_ARG: Invalid arguments
• ESP_ERR_INVALID_STATE: Invalid state to call this API. esp_https_ota_begin() not
called yet.
• ESP_FAIL: Failed to read image descriptor
• ESP_OK: Successfully read image descriptor
Note: This API should be called only if esp_https_ota_perform() has been called atleast once or if
esp_https_ota_get_img_desc has been called before.
Note: This API should be called after esp_https_ota_begin() has been already called. This can be used to
create some sort of progress indication (in combination with esp_https_ota_get_image_len_read())
Structures
struct esp_https_ota_config_t
ESP HTTPS OTA configuration.
Public Members
http_client_init_cb_t http_client_init_cb
Callback after ESP HTTP client is initialised
bool bulk_flash_erase
Erase entire flash partition during initialization. By default flash partition is erased during write operation
and in chunk of 4K sector size
bool partial_http_download
Enable Firmware image to be downloaded over multiple HTTP requests
int max_http_request_size
Maximum request size for partial HTTP download
Macros
ESP_ERR_HTTPS_OTA_BASE
ESP_ERR_HTTPS_OTA_IN_PROGRESS
Type Definitions
Overview
The event loop library allows components to declare events to which other components can register handlers –code
which will execute when those events occur. This allows loosely coupled components to attach desired behavior to
changes in state of other components without application involvement. For instance, a high level connection handling
library may subscribe to events produced by the Wi-Fi subsystem directly and act on those events. This also simplifies
event processing by serializing and deferring code execution to another context.
There are two objects of concern for users of this library: events and event loops.
Events are occurrences of note. For example, for Wi-Fi, a successful connection to the access point may be an event.
Events are referenced using a two part identifier which are discussed more here. Event loops are the vehicle by which
events get posted by event sources and handled by event handler functions. These two appear prominently in the event
loop library APIs.
Using this library roughly entails the following flow:
1. A user defines a function that should run when an event is posted to a loop. This function is referred to as the
event handler. It should have the same signature as esp_event_handler_t.
2. An event loop is created using esp_event_loop_create(), which outputs a handle to the loop of type
esp_event_loop_handle_t. Event loops created using this API are referred to as user event loops.
There is, however, a special type of event loop called the default event loop which are discussed here.
3. Components register event handlers to the loop using esp_event_handler_register_with(). Han-
dlers can be registered with multiple loops, more on that here.
4. Event sources post an event to the loop using esp_event_post_to().
5. Components wanting to remove their handlers from being called can do so by unregistering from the loop using
esp_event_handler_unregister_with().
6. Event loops which are no longer needed can be deleted using esp_event_loop_delete().
In code, the flow above may look like as follows:
{
// Event handler logic
}
void app_main()
{
// 2. A configuration structure of type esp_event_loop_args_t is needed to␣
,→specify the properties of the loop to be
esp_event_loop_handle_t loop_handle;
esp_event_loop_create(&loop_args, &loop_handle);
...
// 4. Post events to the loop. This queues the event on the event loop. At␣
,→some point in time
// the event loop executes the event handler registered to the posted event,␣
,→in this case run_on_event.
// For simplicity sake this example calls esp_event_post_to from app_main, but␣
,→posting can be done from
...
As mentioned previously, events consists of two-part identifiers: the event base and the event ID. The event base
identifies an independent group of events; the event ID identifies the event within that group. Think of the event base
and event ID as a person’s last name and first name, respectively. A last name identifies a family, and the first name
identifies a person within that family.
The event loop library provides macros to declare and define the event base easily.
Event base declaration:
ESP_EVENT_DECLARE_BASE(EVENT_BASE)
Note: In IDF, the base identifiers for system events are uppercase and are postfixed with _EVENT. For example,
the base for Wi-Fi events is declared and defined as WIFI_EVENT, the ethernet event base ETHERNET_EVENT,
and so on. The purpose is to have event bases look like constants (although they are global variables considering the
defintions of macros ESP_EVENT_DECLARE_BASE and ESP_EVENT_DEFINE_BASE).
For event ID’s, declaring them as enumerations is recommended. Once again, for visibility, these are typically
placed in public header files.
Event ID:
enum {
EVENT_ID_1,
EVENT_ID_2,
EVENT_ID_3,
...
}
The default event loop is a special type of loop used for system events (Wi-Fi events, for example). The handle for
this loop is hidden from the user. The creation, deletion, handler registration/unregistration and posting of events is
done through a variant of the APIs for user event loops. The table below enumerates those variants, and the user
event loops equivalent.
If you compare the signatures for both, they are mostly similar except the for the lack of loop handle specification for
the default event loop APIs.
Other than the API difference and the special designation to which system events are posted to, there is no difference
to how default event loops and user event loops behave. It is even possible for users to post their own events to the
default event loop, should the user opt to not create their own loops to save memory.
It is possible to register a single handler to multiple events individually, i.e. using multiple calls to
esp_event_handler_register_with(). For those multiple calls, the specific event base and event ID
can be specified with which the handler should execute.
However, in some cases it is desirable for a handler to execute on (1) all events that get posted to a loop or (2) all events
of a particular base identifier. This is possible using the special event base identifier ESP_EVENT_ANY_BASE and
special event ID ESP_EVENT_ANY_ID. These special identifiers may be passed as the event base and event ID
arguments for esp_event_handler_register_with().
Therefore, the valid arguments to esp_event_handler_register_with() are:
1. <event base>, <event ID> - handler executes when the event with base <event base> and event ID <event ID>
gets posted to the loop
2. <event base>, ESP_EVENT_ANY_ID - handler executes when any event with base <event base> gets posted
to the loop
3. ESP_EVENT_ANY_BASE, ESP_EVENT_ANY_ID - handler executes when any event gets posted to the
loop
As an example, suppose the following handler registrations were performed:
If the hypothetical event MY_EVENT_BASE, MY_EVENT_ID is posted, all three handlers run_on_event_1,
run_on_event_2, and run_on_event_3 would execute.
If the hypothetical event MY_EVENT_BASE, MY_OTHER_EVENT_ID is posted, only run_on_event_2 and
run_on_event_3 would execute.
If the hypothetical event MY_OTHER_EVENT_BASE, MY_OTHER_EVENT_ID is posted, only
run_on_event_3 would execute.
Handler Registration and Handler Dispatch Order The general rule is that for handlers that match a certain
posted event during dispatch, those which are registered first also gets executed first. The user can then control which
handlers get executed first by registering them before other handlers, provided that all registrations are performed
using a single task. If the user plans to take advantage of this behavior, caution must be exercised if there are multiple
tasks registering handlers. While the ‘first registered, first executed’behavior still holds true, the task which gets
executed first will also get their handlers registered first. Handlers registered one after the other by a single task
will still be dispatched in the order relative to each other, but if that task gets pre-empted in between registration by
another task which also registers handlers; then during dispatch those handlers will also get executed in between.
Application Example
Examples on using the esp_event library can be found in system/esp_event. The examples cover event declaration,
loop creation, handler registration and unregistration and event posting.
Other examples which also adopt esp_event library:
• NMEA Parser , which will decode the statements received from GPS.
API Reference
Header File
• components/esp_event/include/esp_event.h
Functions
esp_err_t esp_event_loop_create(const esp_event_loop_args_t *event_loop_args,
esp_event_loop_handle_t *event_loop)
Create a new event loop.
Parameters
• event_loop_args –[in] configuration structure for the event loop to create
• event_loop –[out] handle to the created event loop
Returns
• ESP_OK: Success
• ESP_ERR_INVALID_ARG: event_loop_args or event_loop was NULL
• ESP_ERR_NO_MEM: Cannot allocate memory for event loops list
• ESP_FAIL: Failed to create task loop
• Others: Fail
esp_err_t esp_event_loop_delete(esp_event_loop_handle_t event_loop)
Delete an existing event loop.
Parameters event_loop –[in] event loop to delete, must not be NULL
Returns
• ESP_OK: Success
• Others: Fail
esp_err_t esp_event_loop_create_default(void)
Create default event loop.
Returns
• ESP_OK: Success
• ESP_ERR_NO_MEM: Cannot allocate memory for event loops list
• ESP_FAIL: Failed to create task loop
• Others: Fail
esp_err_t esp_event_loop_delete_default(void)
Delete the default event loop.
Returns
• ESP_OK: Success
• Others: Fail
esp_err_t esp_event_loop_run(esp_event_loop_handle_t event_loop, TickType_t ticks_to_run)
Dispatch events posted to an event loop.
This function is used to dispatch events posted to a loop with no dedicated task, i.e. task name was set to
NULL in event_loop_args argument during loop creation. This function includes an argument to limit the
amount of time it runs, returning control to the caller when that time expires (or some time afterwards). There
is no guarantee that a call to this function will exit at exactly the time of expiry. There is also no guarantee that
events have been dispatched during the call, as the function might have spent all the allotted time waiting on
the event queue. Once an event has been dequeued, however, it is guaranteed to be dispatched. This guarantee
contributes to not being able to exit exactly at time of expiry as (1) blocking on internal mutexes is necessary
for dispatching the dequeued event, and (2) during dispatch of the dequeued event there is no way to control the
time occupied by handler code execution. The guaranteed time of exit is therefore the allotted time + amount
of time required to dispatch the last dequeued event.
In cases where waiting on the queue times out, ESP_OK is returned and not ESP_ERR_TIMEOUT, since it
is normal behavior.
Note: encountering an unknown event that has been posted to the loop will only generate a warning, not an
error.
Parameters
• event_loop –[in] event loop to dispatch posted events from, must not be NULL
• ticks_to_run –[in] number of ticks to run the loop
Returns
• ESP_OK: Success
• Others: Fail
This function can be used to register a handler for either: (1) specific events, (2) all events of a certain event
base, or (3) all events known by the system event loop.
Note: This function is obsolete and will be deprecated soon, please use esp_event_handler_instance_register()
instead.
Note: the event loop library does not maintain a copy of event_handler_arg, therefore the user should ensure
that event_handler_arg still points to a valid location by the time the handler gets called
Parameters
• event_base –[in] the base ID of the event to register the handler for
• event_id –[in] the ID of the event to register the handler for
• event_handler –[in] the handler function which gets called when the event is dis-
patched
• event_handler_arg –[in] data, aside from event data, that is passed to the handler
when it is called
Returns
• ESP_OK: Success
• ESP_ERR_NO_MEM: Cannot allocate memory for the handler
• ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID
• Others: Fail
This function behaves in the same manner as esp_event_handler_register, except the additional specification
of the event loop to register the handler to.
Note: This function is obsolete and will be deprecated soon, please use
esp_event_handler_instance_register_with() instead.
Note: the event loop library does not maintain a copy of event_handler_arg, therefore the user should ensure
that event_handler_arg still points to a valid location by the time the handler gets called
Parameters
• event_loop –[in] the event loop to register this handler function to, must not be NULL
• event_base –[in] the base ID of the event to register the handler for
• event_id –[in] the ID of the event to register the handler for
• event_handler –[in] the handler function which gets called when the event is dis-
patched
• event_handler_arg –[in] data, aside from event data, that is passed to the handler
when it is called
Returns
• ESP_OK: Success
• ESP_ERR_NO_MEM: Cannot allocate memory for the handler
• ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID
• Others: Fail
Note: the event loop library does not maintain a copy of event_handler_arg, therefore the user should ensure
that event_handler_arg still points to a valid location by the time the handler gets called
Parameters
• event_loop –[in] the event loop to register this handler function to, must not be NULL
• event_base –[in] the base ID of the event to register the handler for
• event_id –[in] the ID of the event to register the handler for
• event_handler –[in] the handler function which gets called when the event is dis-
patched
• event_handler_arg –[in] data, aside from event data, that is passed to the handler
when it is called
• instance –[out] An event handler instance object related to the registered event handler
and data, can be NULL. This needs to be kept if the specific callback instance should be
unregistered before deleting the whole event loop. Registering the same event handler
multiple times is possible and yields distinct instance objects. The data can be the same
for all registrations. If no unregistration is needed, but the handler should be deleted when
the event loop is deleted, instance can be NULL.
Returns
• ESP_OK: Success
• ESP_ERR_NO_MEM: Cannot allocate memory for the handler
• ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID or instance
is NULL
• Others: Fail
Note: the event loop library does not maintain a copy of event_handler_arg, therefore the user should ensure
that event_handler_arg still points to a valid location by the time the handler gets called
Parameters
• event_base –[in] the base ID of the event to register the handler for
• event_id –[in] the ID of the event to register the handler for
• event_handler –[in] the handler function which gets called when the event is dis-
patched
• event_handler_arg –[in] data, aside from event data, that is passed to the handler
when it is called
• instance –[out] An event handler instance object related to the registered event handler
and data, can be NULL. This needs to be kept if the specific callback instance should be
unregistered before deleting the whole event loop. Registering the same event handler
multiple times is possible and yields distinct instance objects. The data can be the same
for all registrations. If no unregistration is needed, but the handler should be deleted when
the event loop is deleted, instance can be NULL.
Returns
• ESP_OK: Success
• ESP_ERR_NO_MEM: Cannot allocate memory for the handler
• ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID or instance
is NULL
• Others: Fail
Unregisters a handler, so it will no longer be called during dispatch. Handlers can be unregistered for any com-
bination of event_base and event_id which were previously registered. To unregister a handler, the event_base
and event_id arguments must match exactly the arguments passed to esp_event_handler_register() when that
handler was registered. Passing ESP_EVENT_ANY_BASE and/or ESP_EVENT_ANY_ID will only unreg-
ister handlers that were registered with the same wildcard arguments.
Note: This function is obsolete and will be deprecated soon, please use
esp_event_handler_instance_unregister() instead.
Note: When using ESP_EVENT_ANY_ID, handlers registered to specific event IDs using the same base
will not be unregistered. When using ESP_EVENT_ANY_BASE, events registered to specific bases will also
not be unregistered. This avoids accidental unregistration of handlers registered by other users or components.
Parameters
• event_base –[in] the base of the event with which to unregister the handler
• event_id –[in] the ID of the event with which to unregister the handler
• event_handler –[in] the handler to unregister
Returns ESP_OK success
Returns ESP_ERR_INVALID_ARG invalid combination of event base and event ID
Returns others fail
This function behaves in the same manner as esp_event_handler_unregister, except the additional specification
of the event loop to unregister the handler with.
Note: This function is obsolete and will be deprecated soon, please use
esp_event_handler_instance_unregister_with() instead.
Parameters
• event_loop –[in] the event loop with which to unregister this handler function, must
not be NULL
• event_base –[in] the base of the event with which to unregister the handler
• event_id –[in] the ID of the event with which to unregister the handler
• event_handler –[in] the handler to unregister
Returns
• ESP_OK: Success
• ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID
• Others: Fail
Note: When using ESP_EVENT_ANY_ID, handlers registered to specific event IDs using the same base
will not be unregistered. When using ESP_EVENT_ANY_BASE, events registered to specific bases will also
not be unregistered. This avoids accidental unregistration of handlers registered by other users or components.
Parameters
• event_loop –[in] the event loop with which to unregister this handler function, must
not be NULL
• event_base –[in] the base of the event with which to unregister the handler
• event_id –[in] the ID of the event with which to unregister the handler
• instance –[in] the instance object of the registration to be unregistered
Returns
• ESP_OK: Success
• ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID
• Others: Fail
Note: when this function is called from an interrupt handler placed in IRAM, this function should be placed
in IRAM as well by enabling CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR
Parameters
• event_base –[in] the event base that identifies the event
• event_id –[in] the event ID that identifies the event
• event_data –[in] the data, specific to the event occurrence, that gets passed to the
handler
• event_data_size –[in] the size of the event data; max is 4 bytes
• task_unblocked –[out] an optional parameter (can be NULL) which indicates that
an event task with higher priority than currently running task has been unblocked by the
posted event; a context switch should be requested before the interrupt is existed.
Returns
• ESP_OK: Success
• ESP_FAIL: Event queue for the default event loop full
• ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID, data size of
more than 4 bytes
• Others: Fail
Note: when this function is called from an interrupt handler placed in IRAM, this function should be placed
in IRAM as well by enabling CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR
Parameters
• event_loop –[in] the event loop to post to, must not be NULL
• event_base –[in] the event base that identifies the event
• event_id –[in] the event ID that identifies the event
• event_data –[in] the data, specific to the event occurrence, that gets passed to the
handler
• event_data_size –[in] the size of the event data
• task_unblocked –[out] an optional parameter (can be NULL) which indicates that
an event task with higher priority than currently running task has been unblocked by the
posted event; a context switch should be requested before the interrupt is existed.
Returns
• ESP_OK: Success
• ESP_FAIL: Event queue for the loop full
• ESP_ERR_INVALID_ARG: Invalid combination of event base and event ID, data size of
more than 4 bytes
• Others: Fail
event loop
handler
handler
...
event loop
handler
handler
...
where:
event loop
format: address,name rx:total_received dr:total_dropped
where:
address - memory address of the event loop
name - name of the event loop, 'none' if no dedicated task
total_received - number of successfully posted events
total_dropped - number of events unsuccessfully posted due to queue␣
,→being full
handler
format: address ev:base,id inv:total_invoked run:total_runtime
where:
address - address of the handler function
base,id - the event specified by event base and ID this handler␣
,→executes
(continues on next page)
Structures
struct esp_event_loop_args_t
Configuration for creating event loops.
Public Members
int32_t queue_size
size of the event loop queue
UBaseType_t task_priority
priority of the event loop task, ignored if task name is NULL
uint32_t task_stack_size
stack size of the event loop task, ignored if task name is NULL
BaseType_t task_core_id
core to which the event loop task is pinned to, ignored if task name is NULL
Header File
• components/esp_event/include/esp_event_base.h
Macros
ESP_EVENT_DECLARE_BASE(id)
ESP_EVENT_DEFINE_BASE(id)
ESP_EVENT_ANY_BASE
register handler for any event base
ESP_EVENT_ANY_ID
register handler for any event id
Type Definitions
Related Documents
2.10.9 FreeRTOS
Overview
This section contains documentation of FreeRTOS types, functions, and macros. It is automatically generated from
FreeRTOS header files.
• For more information about the SMP changes of ESP-IDF FreeRTOS, see ESP-IDF FreeRTOS (SMP)
• For more information about the features added to ESP-IDF FreeRTOS, see FreeRTOS Supplemental Features.
Configuration
Vanilla FreeRTOS allows ports and applications to configure the kernel by adding various #define config...
macros to FreeRTOSConfig.h. Through these macros, the kernel’s scheduling behavior and various kernel
features can be enabled or disabled. However, in ESP-IDF FreeRTOS, the ``FreeRTOSConfig.h`` file is con-
sidered a private and must not be modified by users. Any FreeRTOS configuration that is exposed to the user
will be done so via menuconfig.
ESP-IDF FreeRTOS can be configured in the project configuration menu (idf.py menuconfig) under Com-
ponent Config/FreeRTOS. The following section highlights some of the ESP-IDF FreeRTOS configuration
options. For a full list of ESP-IDF FreeRTOS configurations, see Project Configuration
• CONFIG_FREERTOS_UNICORE will run ESP-IDF FreeRTOS only on CPU0. Note that this is not equiv-
alent to running Vanilla FreeRTOS. Futhermore, this option may affect behavior of components other
than freertos. For more details regarding the effects of running ESP-IDF FreeRTOS on a single core,
refer to ESP-IDF FreeRTOS Single Core. Alternatively, users can also search for occurrences of CON-
FIG_FREERTOS_UNICORE in the ESP-IDF components.
• CONFIG_FREERTOS_ASSERT_ON_UNTESTED_FUNCTION will trigger a halt in functions in ESP-IDF
FreeRTOS that have not been fully tested in an SMP context.
• CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER will enclose all task functions within a wrapper function.
In the case that a task function mistakenly returns (i.e. does not call vTaskDelete()), the call flow will
return to the wrapper function. The wrapper function will then log an error and abort the application, as
illustrated below:
Unlike Vanilla FreeRTOS, users must not call vTaskStartScheduler(). Instead, ESP-IDF FreeRTOS is
started automatically. The entry point is a user defined void app_main(void) function.
• Typically, users would spawn the rest of their applications task from app_main.
• The app_main function is allowed to return at any point (i.e., before the application terminates).
• The app_main function is called from the main task.
The main task is one of multiple tasks that are automatically spawned by ESP-IDF during startup. These tasks are:
Task API
Header File
• components/freertos/FreeRTOS-Kernel/include/freertos/task.h
Functions
BaseType_t xTaskCreatePinnedToCore(TaskFunction_t pvTaskCode, const char *const pcName, const
uint32_t usStackDepth, void *const pvParameters, UBaseType_t
uxPriority, TaskHandle_t *const pvCreatedTask, const
BaseType_t xCoreID)
Create a new task with a specified affinity.
This function is similar to xTaskCreate, but allows setting task affinity in SMP system.
Parameters
• pvTaskCode –Pointer to the task entry function. Tasks must be implemented to never
return (i.e. continuous loop), or should be terminated using vTaskDelete function.
• pcName –A descriptive name for the task. This is mainly used to facilitate debugging.
Max length defined by configMAX_TASK_NAME_LEN - default is 16.
• usStackDepth –The size of the task stack specified as the number of bytes. Note that
this differs from vanilla FreeRTOS.
• pvParameters –Pointer that will be used as the parameter for the task being created.
• uxPriority –The priority at which the task should run. Systems that include MPU
support can optionally create tasks in a privileged (system) mode by setting bit portPRIV-
ILEGE_BIT of the priority parameter. For example, to create a privileged task at priority
2 the uxPriority parameter should be set to ( 2 | portPRIVILEGE_BIT ).
• pvCreatedTask –Used to pass back a handle by which the created task can be refer-
enced.
• xCoreID –If the value is tskNO_AFFINITY, the created task is not pinned to any CPU,
and the scheduler can run it on any core available. Values 0 or 1 indicate the index num-
ber of the CPU which the task should be pinned to. Specifying values larger than (port-
NUM_PROCESSORS - 1) will cause the function to fail.
Returns pdPASS if the task was successfully created and added to a ready list, otherwise an error
code defined in the file projdefs.h
static inline BaseType_t xTaskCreate(TaskFunction_t pvTaskCode, const char *const pcName, const uint32_t
usStackDepth, void *const pvParameters, UBaseType_t uxPriority,
TaskHandle_t *const pxCreatedTask)
Create a new task and add it to the list of tasks that are ready to run.
Internally, within the FreeRTOS implementation, tasks use two blocks of memory. The first block is used to
hold the task’s data structures. The second block is used by the task as its stack. If a task is created using
xTaskCreate() then both blocks of memory are automatically dynamically allocated inside the xTaskCreate()
function. (see https://www.FreeRTOS.org/a00111.html). If a task is created using xTaskCreateStatic() then
the application writer must provide the required memory. xTaskCreateStatic() therefore allows a task to be
created without using any dynamic memory allocation.
See xTaskCreateStatic() for a version that does not use any dynamic memory allocation.
xTaskCreate() can only be used to create a task that has unrestricted access to the entire microcontroller
memory map. Systems that include MPU support can alternatively create an MPU constrained task using
xTaskCreateRestricted().
Example usage:
// Task to be created.
void vTaskCode( void * pvParameters )
{
for( ;; )
{
// Task code goes here.
}
}
// Create the task, storing the handle. Note that the passed parameter␣
,→ucParameterToPass
// must exist for the lifetime of the task, so in this case is declared␣
,→static. If it was just an
// an automatic stack variable it might no longer exist, or at least have␣
,→been corrupted, by the time
configASSERT( xHandle );
Note: If program uses thread local variables (ones specified with“__thread”keyword) then storage for them
will be allocated on the task’s stack.
Parameters
• pvTaskCode –Pointer to the task entry function. Tasks must be implemented to never
return (i.e. continuous loop), or should be terminated using vTaskDelete function.
• pcName –A descriptive name for the task. This is mainly used to facilitate debugging.
Max length defined by configMAX_TASK_NAME_LEN - default is 16.
• usStackDepth –The size of the task stack specified as the number of bytes. Note that
this differs from vanilla FreeRTOS.
• pvParameters –Pointer that will be used as the parameter for the task being created.
• uxPriority –The priority at which the task should run. Systems that include MPU
support can optionally create tasks in a privileged (system) mode by setting bit portPRIV-
ILEGE_BIT of the priority parameter. For example, to create a privileged task at priority
2 the uxPriority parameter should be set to ( 2 | portPRIVILEGE_BIT ).
• pxCreatedTask –Used to pass back a handle by which the created task can be refer-
enced.
Returns pdPASS if the task was successfully created and added to a ready list, otherwise an error
code defined in the file projdefs.h
Example usage:
// Dimensions the buffer that the task being created will use as its stack.
// NOTE: This is the number of bytes the stack will hold, not the number of
// words as found in vanilla FreeRTOS.
#define STACK_SIZE 200
// Structure that will hold the TCB of the task being created.
StaticTask_t xTaskBuffer;
// Buffer that the task being created will use as its stack. Note this is
// an array of StackType_t variables. The size of StackType_t is dependent on
// the RTOS port.
StackType_t xStack[ STACK_SIZE ];
for( ;; )
{
// Task code goes here.
}
}
// puxStackBuffer and pxTaskBuffer were not NULL, so the task will have
// been created, and xHandle will be the task's handle. Use the handle
// to suspend the task.
vTaskSuspend( xHandle );
}
Note: If program uses thread local variables (ones specified with“__thread”keyword) then storage for them
will be allocated on the task’s stack.
Parameters
• pvTaskCode –Pointer to the task entry function. Tasks must be implemented to never
return (i.e. continuous loop), or should be terminated using vTaskDelete function.
• pcName –A descriptive name for the task. This is mainly used to facilitate debugging.
The maximum length of the string is defined by configMAX_TASK_NAME_LEN in
FreeRTOSConfig.h.
• ulStackDepth –The size of the task stack specified as the number of bytes. Note that
this differs from vanilla FreeRTOS.
• pvParameters –Pointer that will be used as the parameter for the task being created.
• uxPriority –The priority at which the task will run.
• puxStackBuffer –Must point to a StackType_t array that has at least ulStackDepth
indexes - the array will then be used as the task’s stack, removing the need for the stack
to be allocated dynamically.
• pxTaskBuffer –Must point to a variable of type StaticTask_t, which will then be used
to hold the task’s data structures, removing the need for the memory to be allocated
dynamically.
Returns If neither pxStackBuffer or pxTaskBuffer are NULL, then the task will be created and
pdPASS is returned. If either pxStackBuffer or pxTaskBuffer are NULL then the task will not
be created and errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY is returned.
return pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined
in the file projdefs.h
Example usage:
// Create an TaskParameters_t structure that defines the task to be created.
static const TaskParameters_t xCheckTaskParameters =
{
vATask, // pvTaskCode - the function that implements the task.
"ATask", // pcName - just a text name for the task to assist debugging.
100, // usStackDepth - the stack size DEFINED IN WORDS.
NULL, // pvParameters - passed into the task function as the function␣
,→parameters.
}
};
// Create a task from the const structure defined above. The task handle
(continues on next page)
// Will only get here if there was insufficient memory to create the idle
// and/or timer task.
for( ;; );
}
Parameters
• pxTaskDefinition –Pointer to a structure that contains a member for each of the
normal xTaskCreate() parameters (see the xTaskCreate() API documentation) plus an
optional stack buffer and the memory region definitions.
• pxCreatedTask –Used to pass back a handle by which the created task can be refer-
enced.
return pdPASS if the task was successfully created and added to a ready list, otherwise an error code defined
in the file projdefs.h
Example usage:
// Create an TaskParameters_t structure that defines the task to be created.
// The StaticTask_t variable is only included in the structure when
// configSUPPORT_STATIC_ALLOCATION is set to 1. The PRIVILEGED_DATA macro can
// be used to force the variable into the RTOS kernel's privileged data area.
static PRIVILEGED_DATA StaticTask_t xTaskBuffer;
static const TaskParameters_t xCheckTaskParameters =
{
vATask, // pvTaskCode - the function that implements the task.
"ATask", // pcName - just a text name for the task to assist debugging.
100, // usStackDepth - the stack size DEFINED IN BYTES.
NULL, // pvParameters - passed into the task function as the function␣
,→parameters.
// Create a task from the const structure defined above. The task handle
// is requested (the second parameter is not NULL) but in this case just for
// demonstration purposes as its not actually used.
xTaskCreateRestricted( &xRegTest1Parameters, &xHandle );
// Will only get here if there was insufficient memory to create the idle
// and/or timer task.
for( ;; );
}
Memory regions are assigned to a restricted task when the task is created by a call to xTaskCreateRestricted().
These regions can be redefined using vTaskAllocateMPURegions().
Example usage:
// Now the task can continue its function, but from this point on can only
// access its stack and the ucOneKByte array (unless any other statically
// defined or shared regions have been declared elsewhere).
}
Parameters
Example usage:
Parameters xTaskToDelete –The handle of the task to be deleted. Passing NULL will cause
the calling task to be deleted.
Example usage:
for( ;; )
{
// Simply toggle the LED every 500ms, blocking between each toggle.
vToggleLED();
vTaskDelay( xDelay );
}
}
Parameters xTicksToDelay –The amount of time, in tick periods, that the calling task should
block.
Example usage:
Parameters
• pxPreviousWakeTime –Pointer to a variable that holds the time at which the task
was last unblocked. The variable must be initialised with the current time prior to its first
use (see the example below). Following this the variable is automatically updated within
xTaskDelayUntil ().
• xTimeIncrement –The cycle time period. The task will be unblocked at time *pxPre-
viousWakeTime + xTimeIncrement. Calling xTaskDelayUntil with the same xTimeIn-
crement parameter value will cause the task to execute with a fixed interface period.
Returns Value which can be used to check whether the task was actually delayed. Will be pdTRUE
if the task way delayed and pdFALSE otherwise. A task will not be delayed if the next expected
wake time is in the past.
Example usage:
// ...
// ...
Parameters xTask –Handle of the task to be queried. Passing a NULL handle results in the
priority of the calling task being returned.
Returns The priority of xTask.
Example usage:
void vAFunction( void )
{
TaskHandle_t xHandle;
TaskStatus_t xTaskDetails;
Parameters
• xTask –Handle of the task being queried. If xTask is NULL then information will be
returned about the calling task.
• pxTaskStatus –A pointer to the TaskStatus_t structure that will be filled with infor-
mation about the task referenced by the handle passed using the xTask parameter.
• xGetFreeStackSpace –The TaskStatus_t structure contains a member to report the
stack high water mark of the task being queried. Calculating the stack high water mark
takes a relatively long time, and can make the system temporarily unresponsive - so the
xGetFreeStackSpace parameter is provided to allow the high water mark checking to be
skipped. The high watermark value will only be written to the TaskStatus_t structure if
xGetFreeStackSpace is not set to pdFALSE;
• eState –The TaskStatus_t structure contains a member to report the state of the task
being queried. Obtaining the task state is not as fast as a simple assignment - so the eState
parameter is provided to allow the state information to be omitted from the TaskStatus_t
structure. To obtain state information then set eState to eInvalid - otherwise the value
passed in eState will be reported as the task state in the TaskStatus_t structure.
Example usage:
void vAFunction( void )
{
TaskHandle_t xHandle;
// ...
// ...
Parameters
• xTask –Handle to the task for which the priority is being set. Passing a NULL handle
results in the priority of the calling task being set.
• uxNewPriority –The priority to which the task will be set.
Example usage:
void vAFunction( void )
{
TaskHandle_t xHandle;
// ...
// ...
// The created task will not run during this period, unless
// another task calls vTaskResume( xHandle ).
//...
// Suspend ourselves.
vTaskSuspend( NULL );
Parameters xTaskToSuspend –Handle to the task being suspended. Passing a NULL handle
will cause the calling task to be suspended.
Example usage:
// ...
// ...
// The created task will not run during this period, unless
// another task calls vTaskResume( xHandle ).
//...
void vTaskEndScheduler(void)
NOTE: At the time of writing only the x86 real mode port, which runs on a PC in place of DOS, implements
this function.
Stops the real time kernel tick. All created tasks will be automatically deleted and multitasking (either pre-
emptive or cooperative) will stop. Execution then resumes from the point where vTaskStartScheduler () was
called, as if vTaskStartScheduler () had just returned.
See the demo application file main. c in the demo/PC directory for an example that uses vTaskEndScheduler
().
vTaskEndScheduler () requires an exit function to be defined within the portable layer (see vPortEndScheduler
() in port. c for the PC port). This performs hardware specific operations such as stopping the kernel tick.
vTaskEndScheduler () will cause all of the resources allocated by the kernel to be freed - but will not free
resources allocated by application tasks.
Example usage:
// Will only get here when the vTaskCode () task has called
// vTaskEndScheduler (). When we get here we are back to single task
// execution.
}
void vTaskSuspendAll(void)
Suspends the scheduler without disabling interrupts. Context switches will not occur while the scheduler is
suspended.
After calling vTaskSuspendAll () the calling task will continue to execute without risk of being swapped out
until a call to xTaskResumeAll () has been made.
API functions that have the potential to cause a context switch (for example, vTaskDelayUntil(), xQueueSend(),
etc.) must not be called while the scheduler is suspended.
Example usage:
// ...
// ...
BaseType_t xTaskResumeAll(void)
Resumes scheduler activity after it was suspended by a call to vTaskSuspendAll().
xTaskResumeAll() only resumes the scheduler. It does not unsuspend tasks that were previously suspended by
a call to vTaskSuspend().
Example usage:
// ...
// ...
Returns If resuming the scheduler caused a context switch then pdTRUE is returned, otherwise
pdFALSE is returned.
TickType_t xTaskGetTickCount(void)
This is a version of xTaskGetTickCount() that is safe to be called from an ISR - provided that TickType_t is
the natural word size of the microcontroller being used or interrupt nesting is either not supported or not being
used.
Returns The count of ticks since vTaskStartScheduler was called.
UBaseType_t uxTaskGetNumberOfTasks(void)
Returns The number of tasks that the real time kernel is currently managing. This includes all
ready, blocked and suspended tasks. A task that has been deleted but not yet freed by the idle
task will also be included in the count.
char *pcTaskGetName(TaskHandle_t xTaskToQuery)
Returns The text (human readable) name of the task referenced by the handle xTaskToQuery. A
task can query its own name by either passing in its own handle, or by setting xTaskToQuery
to NULL.
TaskHandle_t xTaskGetHandle(const char *pcNameToQuery)
NOTE: This function takes a relatively long time to complete and should be used sparingly.
Returns The handle of the task that has the human readable name pcNameToQuery. NULL
is returned if no matching name is found. INCLUDE_xTaskGetHandle must be set to 1 in
FreeRTOSConfig.h for pcTaskGetHandle() to be available.
UBaseType_t uxTaskGetStackHighWaterMark(TaskHandle_t xTask)
Returns the high water mark of the stack associated with xTask.
INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for this function to be
available.
Returns the high water mark of the stack associated with xTask. That is, the minimum free stack space there
has been (in bytes not words, unlike vanilla FreeRTOS) since the task started. The smaller the returned number
the closer the task has come to overflowing its stack.
uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the same except for their re-
turn type. Using configSTACK_DEPTH_TYPE allows the user to determine the return type. It gets around
the problem of the value overflowing on 8-bit types without breaking backward compatibility for applications
that expect an 8-bit return type.
Parameters xTask –Handle of the task associated with the stack to be checked. Set xTask to
NULL to check the stack of the calling task.
Returns The smallest amount of free stack space there has been (in bytes not words, unlike vanilla
FreeRTOS) since the task referenced by xTask was created.
configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2(TaskHandle_t xTask)
Returns the start of the stack associated with xTask.
INCLUDE_uxTaskGetStackHighWaterMark2 must be set to 1 in FreeRTOSConfig.h for this function to be
available.
Returns the high water mark of the stack associated with xTask. That is, the minimum free stack space there
has been (in words, so on a 32 bit machine a value of 1 means 4 bytes) since the task started. The smaller the
returned number the closer the task has come to overflowing its stack.
uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the same except for their re-
turn type. Using configSTACK_DEPTH_TYPE allows the user to determine the return type. It gets around
the problem of the value overflowing on 8-bit types without breaking backward compatibility for applications
that expect an 8-bit return type.
Parameters xTask –Handle of the task associated with the stack to be checked. Set xTask to
NULL to check the stack of the calling task.
Returns The smallest amount of free stack space there has been (in words, so actual spaces on the
stack rather than bytes) since the task referenced by xTask was created.
uint8_t *pxTaskGetStackStart(TaskHandle_t xTask)
Returns the start of the stack associated with xTask.
INCLUDE_pxTaskGetStackStart must be set to 1 in FreeRTOSConfig.h for this function to be available.
Returns the lowest stack memory address, regardless of whether the stack grows up or down.
Parameters xTask –Handle of the task associated with the stack returned. Set xTask to NULL
to return the stack of the calling task.
Returns A pointer to the start of the stack.
void vTaskSetApplicationTaskTag(TaskHandle_t xTask, TaskHookFunction_t pxHookFunction)
Sets pxHookFunction to be the task hook function used by the task xTask.
Parameters
• xTask –Handle of the task to set the hook function for Passing xTask as NULL has the
effect of setting the calling tasks hook function.
• pxHookFunction –Pointer to the hook function.
TaskHookFunction_t xTaskGetApplicationTaskTag(TaskHandle_t xTask)
Returns the pxHookFunction value assigned to the task xTask. Do not call from an interrupt service routine -
call xTaskGetApplicationTaskTagFromISR() instead.
TaskHookFunction_t xTaskGetApplicationTaskTagFromISR(TaskHandle_t xTask)
Returns the pxHookFunction value assigned to the task xTask. Can be called from an interrupt service routine.
void vTaskSetThreadLocalStoragePointer(TaskHandle_t xTaskToSet, BaseType_t xIndex, void
*pvValue)
Set local storage pointer specific to the given task.
Each task contains an array of pointers that is dimensioned by the con-
figNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The kernel does
not use the pointers itself, so the application writer can use the pointers for any purpose they wish.
Parameters
• xTaskToSet –Task to set thread local storage pointer for
• xIndex –The index of the pointer to set, from 0 to con-
figNUM_THREAD_LOCAL_STORAGE_POINTERS - 1.
• pvValue –Pointer value to set.
void *pvTaskGetThreadLocalStoragePointer(TaskHandle_t xTaskToQuery, BaseType_t xIndex)
Get local storage pointer specific to the given task.
Each task contains an array of pointers that is dimensioned by the con-
figNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The kernel does
not use the pointers itself, so the application writer can use the pointers for any purpose they wish.
Parameters
• xTaskToQuery –Task to get thread local storage pointer for
• xIndex –The index of the pointer to get, from 0 to con-
figNUM_THREAD_LOCAL_STORAGE_POINTERS - 1.
Returns Pointer value
void vTaskSetThreadLocalStoragePointerAndDelCallback(TaskHandle_t xTaskToSet,
BaseType_t xIndex, void *pvValue,
TlsDeleteCallbackFunction_t
pvDelCallback)
Set local storage pointer and deletion callback.
Each task contains an array of pointers that is dimensioned by the con-
figNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The kernel does
not use the pointers itself, so the application writer can use the pointers for any purpose they wish.
Local storage pointers set for a task can reference dynamically allocated resources. This function is similar to
vTaskSetThreadLocalStoragePointer, but provides a way to release these resources when the task gets deleted.
For each pointer, a callback function can be set. This function will be called when task is deleted, with the
local storage pointer index and value as arguments.
Parameters
• xTaskToSet –Task to set thread local storage pointer for
Example usage:
// This example demonstrates how a human readable table of run time stats
// information is generated from raw data provided by uxTaskGetSystemState().
// The human readable table is written to pcWriteBuffer
void vTaskGetRunTimeStats( char *pcWriteBuffer )
{
TaskStatus_t *pxTaskStatusArray;
volatile UBaseType_t uxArraySize, x;
uint32_t ulTotalRunTime, ulStatsAsPercentage;
,→ulStatsAsPercentage );
}
else
{
// If the percentage is zero here then the task has
// consumed less than 1% of the total run time.
sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n",␣
,→pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter );
Parameters
• pxTaskStatusArray –A pointer to an array of TaskStatus_t structures. The array
must contain at least one TaskStatus_t structure for each task that is under the control of
the RTOS. The number of tasks under the control of the RTOS can be determined using
the uxTaskGetNumberOfTasks() API function.
• uxArraySize –The size of the array pointed to by the pxTaskStatusArray parameter.
The size is specified as the number of indexes in the array, or the number of TaskStatus_t
structures contained in the array, not by the number of bytes in the array.
• pulTotalRunTime –If configGENERATE_RUN_TIME_STATS is set to 1 in FreeR-
TOSConfig.h then *pulTotalRunTime is set by uxTaskGetSystemState() to the total
run time (as defined by the run time stats clock, see https://www.FreeRTOS.org/
rtos-run-time-stats.html) since the target booted. pulTotalRunTime can be set to NULL
to omit the total run time information.
Returns The number of TaskStatus_t structures that were populated by uxTaskGetSystemState().
This should equal the number returned by the uxTaskGetNumberOfTasks() API function, but
will be zero if the value passed in the uxArraySize parameter was too small.
This function is provided for convenience only, and is used by many of the demo applications. Do not consider
it to be part of the scheduler.
vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the uxTaskGetSystemState()
output into a human readable table that displays the amount of time each task has spent in the Running state
in both absolute and percentage terms.
vTaskGetRunTimeStats() has a dependency on the sprintf() C library function that might bloat the code size,
use a lot of stack, and provide different results on different platforms. An alternative, tiny, third party, and
limited functionality implementation of sprintf() is provided in many of the FreeRTOS/Demo sub-directories
in a file called printf-stdarg.c (note printf-stdarg.c does not provide a full snprintf() implementation!).
It is recommended that production systems call uxTaskGetSystemState() directly to get access to raw stats data,
rather than indirectly through a call to vTaskGetRunTimeStats().
Parameters pcWriteBuffer –A buffer into which the execution times will be written, in
ASCII form. This buffer is assumed to be large enough to contain the generated report. Ap-
proximately 40 bytes per task should be sufficient.
uint32_t ulTaskGetIdleRunTimeCounter(void)
configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS must
both be defined as 1 for this function to be available. The application must also then provide definitions for port-
CONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE()
to configure a peripheral timer/counter and return the timers current count value respectively. The counter
should be at least 10 times the frequency of the tick count.
Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total accumulated execution time being
stored for each task. The resolution of the accumulated time value depends on the frequency of the timer con-
figured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. While uxTaskGetSystem-
State() and vTaskGetRunTimeStats() writes the total execution time of each task into a buffer, ulTaskGetI-
dleRunTimeCounter() returns the total execution time of just the idle task.
Returns The total run time of the idle task. This is the amount of time the idle
task has actually been executing. The unit of time is dependent on the frequency
configured using the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and port-
GET_RUN_TIME_COUNTER_VALUE() macros.
BaseType_t xTaskGenericNotify(TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t
ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue)
See https://www.FreeRTOS.org/RTOS-task-notifications.html for details.
configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these functions to be available.
Sends a direct to task notification to a task, with an optional value and action.
Each task has a private array of “notification values”(or ‘notifications’), each of which is a 32-bit un-
signed integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number
of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS
V10.4.0 there was only one notification value per task.
Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores,
mutexes and event groups. Task notifications are a method of sending an event directly to a task without the
need for such an intermediary object.
A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of
the task’s notification values. In that way task notifications can be used to send data to a task, or be used as
light weight and fast binary or counting semaphores.
A task can use xTaskNotifyWaitIndexed() to [optionally] block to wait for a notification to be pending, or
ulTaskNotifyTakeIndexed() to [optionally] block to wait for a notification value to have a non-zero value. The
task does not consume any CPU time while it is in the Blocked state.
A notification sent to a task will remain pending until it is cleared by the task calling xTaskNotifyWaitIndexed()
or ulTaskNotifyTakeIndexed() (or their un-indexed equivalents). If the task was already in the Blocked state
to wait for a notification when the notification arrives then the task will automatically be removed from the
Blocked state (unblocked) and the notification cleared.
NOTE Each notification within the array operates independently - a task can only block on one notification
within the array at a time and will not be unblocked by a notification sent to any other array index.
Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single “notification value”
, and all task notification API functions operated on that value. Replacing the single notification value with
an array of notification values necessitated a new set of API functions that could address specific notifications
within the array. xTaskNotify() is the original API function, and remains backward compatible by always
operating on the notification value at index 0 in the array. Calling xTaskNotify() is equivalent to calling xTas-
kNotifyIndexed() with the uxIndexToNotify parameter set to 0.
eSetBits - The target notification value is bitwise ORed with ulValue. xTaskNotifyIndexed() always returns
pdPASS in this case.
eIncrement - The target notification value is incremented. ulValue is not used and xTaskNotifyIndexed() always
returns pdPASS in this case.
eSetValueWithOverwrite - The target notification value is set to the value of ulValue, even if the task being no-
tified had not yet processed the previous notification at the same array index (the task already had a notification
pending at that index). xTaskNotifyIndexed() always returns pdPASS in this case.
eSetValueWithoutOverwrite - If the task being notified did not already have a notification pending at the same
array index then the target notification value is set to ulValue and xTaskNotifyIndexed() will return pdPASS.
If the task being notified already had a notification pending at the same array index then no action is performed
and pdFAIL is returned.
eNoAction - The task receives a notification at the specified array index without the notification value at that
index being updated. ulValue is not used and xTaskNotifyIndexed() always returns pdPASS in this case.
Parameters
• xTaskToNotify –The handle of the task being notified. The handle to a task can be
returned from the xTaskCreate() API function used to create the task, and the handle of
the currently running task can be obtained by calling xTaskGetCurrentTaskHandle().
• uxIndexToNotify –The index within the target task’s array of notification val-
ues to which the notification is to be sent. uxIndexToNotify must be less than config-
TASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotify() does not have this param-
eter and always sends notifications to index 0.
• ulValue –Data that can be sent with the notification. How the data is used depends on
the value of the eAction parameter.
• eAction –Specifies how the notification updates the task’s notification value, if at all.
Valid values for eAction are as follows:
• pulPreviousNotificationValue –- Can be used to pass out the subject task’s
notification value before any bits are modified by the notify function.
Returns Dependent on the value of eAction. See the description of the eAction parameter.
BaseType_t xTaskGenericNotifyFromISR(TaskHandle_t xTaskToNotify, UBaseType_t
uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction,
uint32_t *pulPreviousNotificationValue, BaseType_t
*pxHigherPriorityTaskWoken)
See https://www.FreeRTOS.org/RTOS-task-notifications.html for details.
configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these functions to be available.
A version of xTaskNotifyIndexed() that can be used from an interrupt service routine (ISR).
Each task has a private array of “notification values”(or ‘notifications’), each of which is a 32-bit un-
signed integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number
of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS
V10.4.0 there was only one notification value per task.
Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores,
mutexes and event groups. Task notifications are a method of sending an event directly to a task without the
need for such an intermediary object.
A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of
the task’s notification values. In that way task notifications can be used to send data to a task, or be used as
light weight and fast binary or counting semaphores.
A task can use xTaskNotifyWaitIndexed() to [optionally] block to wait for a notification to be pending, or
ulTaskNotifyTakeIndexed() to [optionally] block to wait for a notification value to have a non-zero value. The
task does not consume any CPU time while it is in the Blocked state.
A notification sent to a task will remain pending until it is cleared by the task calling xTaskNotifyWaitIndexed()
or ulTaskNotifyTakeIndexed() (or their un-indexed equivalents). If the task was already in the Blocked state
to wait for a notification when the notification arrives then the task will automatically be removed from the
Blocked state (unblocked) and the notification cleared.
NOTE Each notification within the array operates independently - a task can only block on one notification
within the array at a time and will not be unblocked by a notification sent to any other array index.
Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single “notification value”
, and all task notification API functions operated on that value. Replacing the single notification value with
an array of notification values necessitated a new set of API functions that could address specific notifica-
tions within the array. xTaskNotifyFromISR() is the original API function, and remains backward compatible
by always operating on the notification value at index 0 within the array. Calling xTaskNotifyFromISR() is
equivalent to calling xTaskNotifyIndexedFromISR() with the uxIndexToNotify parameter set to 0.
eSetBits - The task’s notification value is bitwise ORed with ulValue. xTaskNotify() always returns pdPASS
in this case.
eIncrement - The task’s notification value is incremented. ulValue is not used and xTaskNotify() always
returns pdPASS in this case.
eSetValueWithOverwrite - The task’s notification value is set to the value of ulValue, even if the task being
notified had not yet processed the previous notification (the task already had a notification pending). xTaskNo-
tify() always returns pdPASS in this case.
eSetValueWithoutOverwrite - If the task being notified did not already have a notification pending then the
task’s notification value is set to ulValue and xTaskNotify() will return pdPASS. If the task being notified
already had a notification pending then no action is performed and pdFAIL is returned.
eNoAction - The task receives a notification without its notification value being updated. ulValue is not used
and xTaskNotify() always returns pdPASS in this case.
Parameters
• uxIndexToNotify –The index within the target task’s array of notification val-
ues to which the notification is to be sent. uxIndexToNotify must be less than con-
figTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyFromISR() does not have
this parameter and always sends notifications to index 0.
• xTaskToNotify –The handle of the task being notified. The handle to a task can be
returned from the xTaskCreate() API function used to create the task, and the handle of
the currently running task can be obtained by calling xTaskGetCurrentTaskHandle().
• ulValue –Data that can be sent with the notification. How the data is used depends on
the value of the eAction parameter.
• eAction –Specifies how the notification updates the task’s notification value, if at all.
Valid values for eAction are as follows:
• pulPreviousNotificationValue –- Can be used to pass out the subject task’s
notification value before any bits are modified by the notify function.
• pxHigherPriorityTaskWoken –xTaskNotifyFromISR() will set *pxHigherPrior-
ityTaskWoken to pdTRUE if sending the notification caused the task to which the noti-
fication was sent to leave the Blocked state, and the unblocked task has a priority higher
than the currently running task. If xTaskNotifyFromISR() sets this value to pdTRUE then
a context switch should be requested before the interrupt is exited. How a context switch
is requested from an ISR is dependent on the port - see the documentation page for the
port in use.
Returns Dependent on the value of eAction. See the description of the eAction parameter.
BaseType_t xTaskGenericNotifyWait(UBaseType_t uxIndexToWaitOn, uint32_t ulBitsToClearOnEntry,
uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue,
TickType_t xTicksToWait)
Waits for a direct to task notification to be pending at a given index within an array of direct to task notifications.
See https://www.FreeRTOS.org/RTOS-task-notifications.html for details.
configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this function to be available.
Each task has a private array of “notification values”(or ‘notifications’), each of which is a 32-bit un-
signed integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number
of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS
V10.4.0 there was only one notification value per task.
Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores,
mutexes and event groups. Task notifications are a method of sending an event directly to a task without the
need for such an intermediary object.
A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of
the task’s notification values. In that way task notifications can be used to send data to a task, or be used as
light weight and fast binary or counting semaphores.
A notification sent to a task will remain pending until it is cleared by the task calling xTaskNotifyWaitIndexed()
or ulTaskNotifyTakeIndexed() (or their un-indexed equivalents). If the task was already in the Blocked state
to wait for a notification when the notification arrives then the task will automatically be removed from the
Blocked state (unblocked) and the notification cleared.
A task can use xTaskNotifyWaitIndexed() to [optionally] block to wait for a notification to be pending, or
ulTaskNotifyTakeIndexed() to [optionally] block to wait for a notification value to have a non-zero value. The
task does not consume any CPU time while it is in the Blocked state.
NOTE Each notification within the array operates independently - a task can only block on one notification
within the array at a time and will not be unblocked by a notification sent to any other array index.
Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single “notification value”
, and all task notification API functions operated on that value. Replacing the single notification value with
an array of notification values necessitated a new set of API functions that could address specific notifications
within the array. xTaskNotifyWait() is the original API function, and remains backward compatible by always
operating on the notification value at index 0 in the array. Calling xTaskNotifyWait() is equivalent to calling
xTaskNotifyWaitIndexed() with the uxIndexToWaitOn parameter set to 0.
Parameters
• uxIndexToWaitOn –The index within the calling task’s array of notification values on
which the calling task will wait for a notification to be received. uxIndexToWaitOn must be
less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyWait() does
not have this parameter and always waits for notifications on index 0.
• ulBitsToClearOnEntry –Bits that are set in ulBitsToClearOnEntry value will be
cleared in the calling task’s notification value before the task checks to see if any noti-
fications are pending, and optionally blocks if no notifications are pending. Setting ulBit-
sToClearOnEntry to ULONG_MAX (if limits.h is included) or 0xffffffffUL (if limits.h
is not included) will have the effect of resetting the task’s notification value to 0. Setting
ulBitsToClearOnEntry to 0 will leave the task’s notification value unchanged.
• ulBitsToClearOnExit –If a notification is pending or received before the calling
task exits the xTaskNotifyWait() function then the task’s notification value (see the xTas-
kNotify() API function) is passed out using the pulNotificationValue parameter. Then any
bits that are set in ulBitsToClearOnExit will be cleared in the task’s notification value (note
*pulNotificationValue is set before any bits are cleared). Setting ulBitsToClearOnExit to
ULONG_MAX (if limits.h is included) or 0xffffffffUL (if limits.h is not included) will
have the effect of resetting the task’s notification value to 0 before the function exits.
Setting ulBitsToClearOnExit to 0 will leave the task’s notification value unchanged when
the function exits (in which case the value passed out in pulNotificationValue will match
the task’s notification value).
• pulNotificationValue –Used to pass the task’s notification value out of the func-
tion. Note the value passed out will not be effected by the clearing of any bits caused by
ulBitsToClearOnExit being non-zero.
• xTicksToWait –The maximum amount of time that the task should wait in the Blocked
state for a notification to be received, should a notification not already be pending when
xTaskNotifyWait() was called. The task will not consume any processing time while it
is in the Blocked state. This is specified in kernel ticks, the macro pdMS_TO_TICKS(
value_in_ms ) can be used to convert a time specified in milliseconds to a time specified
in ticks.
Returns If a notification was received (including notifications that were already pending when
xTaskNotifyWait was called) then pdPASS is returned. Otherwise pdFAIL is returned.
void vTaskGenericNotifyGiveFromISR(TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify,
BaseType_t *pxHigherPriorityTaskWoken)
A version of xTaskNotifyGiveIndexed() that can be called from an interrupt service routine (ISR).
See https://www.FreeRTOS.org/RTOS-task-notifications.html for more details.
configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro to be available.
Each task has a private array of “notification values”(or ‘notifications’), each of which is a 32-bit un-
signed integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number
of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS
V10.4.0 there was only one notification value per task.
Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores,
mutexes and event groups. Task notifications are a method of sending an event directly to a task without the
need for such an intermediary object.
A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of
the task’s notification values. In that way task notifications can be used to send data to a task, or be used as
light weight and fast binary or counting semaphores.
vTaskNotifyGiveIndexedFromISR() is intended for use when task notifications are used as light weight and
faster binary or counting semaphore equivalents. Actual FreeRTOS semaphores are given from an ISR using
the xSemaphoreGiveFromISR() API function, the equivalent action that instead uses a task notification is
vTaskNotifyGiveIndexedFromISR().
When task notifications are being used as a binary or counting semaphore equivalent then the task being no-
tified should wait for the notification using the ulTaskNotificationTakeIndexed() API function rather than the
xTaskNotifyWaitIndexed() API function.
NOTE Each notification within the array operates independently - a task can only block on one notification
within the array at a time and will not be unblocked by a notification sent to any other array index.
Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single “notification value”
, and all task notification API functions operated on that value. Replacing the single notification value with
an array of notification values necessitated a new set of API functions that could address specific notifications
within the array. xTaskNotifyFromISR() is the original API function, and remains backward compatible by
always operating on the notification value at index 0 within the array. Calling xTaskNotifyGiveFromISR() is
equivalent to calling xTaskNotifyGiveIndexedFromISR() with the uxIndexToNotify parameter set to 0.
Parameters
• xTaskToNotify –The handle of the task being notified. The handle to a task can be
returned from the xTaskCreate() API function used to create the task, and the handle of
the currently running task can be obtained by calling xTaskGetCurrentTaskHandle().
• uxIndexToNotify –The index within the target task’s array of notification val-
ues to which the notification is to be sent. uxIndexToNotify must be less than con-
figTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyGiveFromISR() does not
Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single “notification value”
, and all task notification API functions operated on that value. Replacing the single notification value with
an array of notification values necessitated a new set of API functions that could address specific notifications
within the array. ulTaskNotifyValueClear() is the original API function, and remains backward compatible
by always operating on the notification value at index 0 within the array. Calling ulTaskNotifyValueClear() is
equivalent to calling ulTaskNotifyValueClearIndexed() with the uxIndexToClear parameter set to 0.
Parameters
• xTask –The handle of the RTOS task that will have bits in one of its notification values
cleared. Set xTask to NULL to clear bits in a notification value of the calling task. To
obtain a task’s handle create the task using xTaskCreate() and make use of the pxCre-
atedTask parameter, or create the task using xTaskCreateStatic() and store the returned
value, or use the task’s name in a call to xTaskGetHandle().
• uxIndexToClear –The index within the target task’s array of notification
values in which to clear the bits. uxIndexToClear must be less than config-
TASK_NOTIFICATION_ARRAY_ENTRIES. ulTaskNotifyValueClear() does not have
this parameter and always clears bits in the notification value at index 0.
• ulBitsToClear –Bit mask of the bits to clear in the notification value of xTask. Set a
bit to 1 to clear the corresponding bits in the task’s notification value. Set ulBitsToClear
to 0xffffffff (UINT_MAX on 32-bit architectures) to clear the notification value to 0. Set
ulBitsToClear to 0 to query the task’s notification value without clearing any bits.
Returns The value of the target task’s notification value before the bits specified by ulBitsToClear
were cleared.
void vTaskSetTimeOutState(TimeOut_t *const pxTimeOut)
Example Usage:
// Driver library function used to receive uxWantedBytes from an Rx buffer
// that is filled by a UART interrupt. If there are not enough bytes in the
// Rx buffer then the task enters the Blocked state until it is notified that
// more data has been placed into the buffer. If there is still not enough
// data then the task re-enters the Blocked state, and xTaskCheckForTimeOut()
// is used to re-calculate the Block time to ensure the total amount of time
// spent in the Blocked state does not exceed MAX_TIME_TO_WAIT. This
// continues until either the buffer contains at least uxWantedBytes bytes,
// or the total amount of time spent in the Blocked state reaches
// MAX_TIME_TO_WAIT – at which point the task reads however many bytes are
// available up to a maximum of uxWantedBytes.
return uxReceived;
}
See also:
https://www.FreeRTOS.org/xTaskCheckForTimeOut.html
Parameters
• pxTimeOut –The time status as captured previously using vTaskSetTimeOutState. If
the timeout has not yet occurred, it is updated to reflect the current time status.
• pxTicksToWait –The number of ticks to check for timeout i.e. if pxTicksToWait
ticks have passed since pxTimeOut was last updated (either by vTaskSetTimeOutState()
or xTaskCheckForTimeOut()), the timeout has occurred. If the timeout has not occurred,
pxTicksToWait is updated to reflect the number of remaining ticks.
Returns If timeout has occurred, pdTRUE is returned. Otherwise pdFALSE is returned and
pxTicksToWait is updated to reflect the number of remaining ticks.
Macros
tskKERNEL_VERSION_NUMBER
tskKERNEL_VERSION_MAJOR
tskKERNEL_VERSION_MINOR
tskKERNEL_VERSION_BUILD
tskMPU_REGION_READ_ONLY
tskMPU_REGION_READ_WRITE
tskMPU_REGION_EXECUTE_NEVER
tskMPU_REGION_NORMAL_MEMORY
tskMPU_REGION_DEVICE_MEMORY
tskDEFAULT_INDEX_TO_NOTIFY
tskNO_AFFINITY
tskIDLE_PRIORITY
Defines the priority used by the idle task. This must not be modified.
taskYIELD()
Macro for forcing a context switch.
taskENTER_CRITICAL()
Macro to mark the start of a critical code region. Preemptive context switches cannot occur when in a critical
region.
Note: This may alter the stack (depending on the portable implementation) so must be used with care!
taskENTER_CRITICAL_FROM_ISR()
taskENTER_CRITICAL_ISR()
taskEXIT_CRITICAL()
Macro to mark the end of a critical code region. Preemptive context switches cannot occur when in a critical
region.
Note: This may alter the stack (depending on the portable implementation) so must be used with care!
taskEXIT_CRITICAL_FROM_ISR(x)
taskEXIT_CRITICAL_ISR()
taskDISABLE_INTERRUPTS()
Macro to disable all maskable interrupts.
taskENABLE_INTERRUPTS()
Macro to enable microcontroller interrupts.
taskSCHEDULER_SUSPENDED
taskSCHEDULER_NOT_STARTED
taskSCHEDULER_RUNNING
vTaskDelayUntil(pxPreviousWakeTime, xTimeIncrement)
xTaskNotifyGiveIndexed(xTaskToNotify, uxIndexToNotify)
Sends a direct to task notification to a particular index in the target task’s notification array in a manner similar
to giving a counting semaphore.
See https://www.FreeRTOS.org/RTOS-task-notifications.html for more details.
configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these macros to be available.
Each task has a private array of “notification values”(or ‘notifications’), each of which is a 32-bit un-
signed integer (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number
of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS
V10.4.0 there was only one notification value per task.
Events can be sent to a task using an intermediary object. Examples of such objects are queues, semaphores,
mutexes and event groups. Task notifications are a method of sending an event directly to a task without the
need for such an intermediary object.
A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of
the task’s notification values. In that way task notifications can be used to send data to a task, or be used as
light weight and fast binary or counting semaphores.
xTaskNotifyGiveIndexed() is a helper macro intended for use when task notifications are used as light weight
and faster binary or counting semaphore equivalents. Actual FreeRTOS semaphores are given using the
xSemaphoreGive() API function, the equivalent action that instead uses a task notification is xTaskNotify-
GiveIndexed().
When task notifications are being used as a binary or counting semaphore equivalent then the task being no-
tified should wait for the notification using the ulTaskNotificationTakeIndexed() API function rather than the
xTaskNotifyWaitIndexed() API function.
NOTE Each notification within the array operates independently - a task can only block on one notification
within the array at a time and will not be unblocked by a notification sent to any other array index.
Backward compatibility information: Prior to FreeRTOS V10.4.0 each task had a single “notification value”
, and all task notification API functions operated on that value. Replacing the single notification value with
an array of notification values necessitated a new set of API functions that could address specific notifications
within the array. xTaskNotifyGive() is the original API function, and remains backward compatible by always
operating on the notification value at index 0 in the array. Calling xTaskNotifyGive() is equivalent to calling
xTaskNotifyGiveIndexed() with the uxIndexToNotify parameter set to 0.
Parameters
• xTaskToNotify –The handle of the task being notified. The handle to a task can be
returned from the xTaskCreate() API function used to create the task, and the handle of
the currently running task can be obtained by calling xTaskGetCurrentTaskHandle().
• uxIndexToNotify –The index within the target task’s array of notification val-
ues to which the notification is to be sent. uxIndexToNotify must be less than config-
TASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyGive() does not have this pa-
rameter and always sends notifications to index 0.
Returns xTaskNotifyGive() is a macro that calls xTaskNotify() with the eAction parameter set to
eIncrement - so pdPASS is always returned.
xTaskNotifyGive(xTaskToNotify)
vTaskNotifyGiveFromISR(xTaskToNotify, pxHigherPriorityTaskWoken)
ulTaskNotifyTake(xClearCountOnExit, xTicksToWait)
xTaskNotifyStateClear(xTask)
xTaskNotifyStateClearIndexed(xTask, uxIndexToClear)
ulTaskNotifyValueClear(xTask, ulBitsToClear)
Type Definitions
Enumerations
enum eTaskState
Task states returned by eTaskGetState.
Values:
enumerator eRunning
enumerator eReady
enumerator eBlocked
enumerator eSuspended
enumerator eDeleted
enumerator eInvalid
enum eNotifyAction
Values:
enumerator eNoAction
enumerator eSetBits
enumerator eIncrement
enumerator eSetValueWithOverwrite
enumerator eSetValueWithoutOverwrite
enum eSleepModeStatus
Possible return values for eTaskConfirmSleepModeStatus().
Values:
enumerator eAbortSleep
enumerator eStandardSleep
enumerator eNoTasksWaitingTimeout
Queue API
Header File
• components/freertos/FreeRTOS-Kernel/include/freertos/queue.h
Functions
BaseType_t xQueueGenericSend(QueueHandle_t xQueue, const void *const pvItemToQueue, TickType_t
xTicksToWait, const BaseType_t xCopyPosition)
It is preferred that the macros xQueueSend(), xQueueSendToFront() and xQueueSendToBack() are used in
place of calling this function directly.
Post an item on a queue. The item is queued by copy, not by reference. This function must not be called from
an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR.
Example usage:
struct AMessage
{
char ucMessageID;
char ucData[ 20 ];
} xMessage;
// ...
if( xQueue1 != 0 )
{
// Send an uint32_t. Wait for 10 ticks for space to become
// available if necessary.
if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10,␣
,→queueSEND_TO_BACK ) != pdPASS )
{
// Failed to post the message, even after 10 ticks.
}
}
if( xQueue2 != 0 )
{
// Send a pointer to a struct AMessage object. Don't block if the
// queue is already full.
pxMessage = & xMessage;
xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0,␣
,→queueSEND_TO_BACK );
Parameters
• xQueue –The handle to the queue on which the item is to be posted.
• pvItemToQueue –A pointer to the item that is to be placed on the queue. The size of
the items the queue will hold was defined when the queue was created, so this many bytes
will be copied from pvItemToQueue into the queue storage area.
• xTicksToWait –The maximum amount of time the task should block waiting for space
to become available on the queue, should it already be full. The call will return immediately
if this is set to 0 and the queue is full. The time is defined in tick periods so the constant
portTICK_PERIOD_MS should be used to convert to real time if this is required.
• xCopyPosition –Can take the value queueSEND_TO_BACK to place the item at the
back of the queue, or queueSEND_TO_FRONT to place the item at the front of the queue
(for high priority messages).
Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.
Example usage:
struct AMessage
{
char ucMessageID;
char ucData[ 20 ];
} xMessage;
QueueHandle_t xQueue;
// ...
if( xQueue != 0 )
{
// Peek a message on the created queue. Block for 10 ticks if a
// message is not immediately available.
if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
{
// pcRxedMessage now points to the struct AMessage variable posted
// by vATask, but the item still remains on the queue.
}
}
Parameters
• xQueue –The handle to the queue from which the item is to be received.
• pvBuffer –Pointer to the buffer into which the received item will be copied.
• xTicksToWait –The maximum amount of time the task should block waiting for an
item to receive should the queue be empty at the time of the call. The time is defined
in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real
time if this is required. xQueuePeek() will return immediately if xTicksToWait is 0 and
the queue is empty.
Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE.
Example usage:
struct AMessage
{
char ucMessageID;
char ucData[ 20 ];
} xMessage;
QueueHandle_t xQueue;
// ...
if( xQueue != 0 )
{
// Receive a message on the created queue. Block for 10 ticks if a
// message is not immediately available.
if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
{
// pcRxedMessage now points to the struct AMessage variable posted
// by vATask.
}
}
Parameters
• xQueue –The handle to the queue from which the item is to be received.
• pvBuffer –Pointer to the buffer into which the received item will be copied.
• xTicksToWait –The maximum amount of time the task should block waiting for an
item to receive should the queue be empty at the time of the call. xQueueReceive() will
return immediately if xTicksToWait is zero and the queue is empty. The time is defined
in tick periods so the constant portTICK_PERIOD_MS should be used to convert to real
time if this is required.
Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE.
Items are queued by copy not reference so it is preferable to only queue small items, especially when called
from an ISR. In most cases it would be preferable to store a pointer to the item being queued.
Example usage for buffered IO (where the ISR can obtain more than one value per call):
void vBufferISR( void )
{
char cIn;
BaseType_t xHigherPriorityTaskWokenByPost;
// Now the buffer is empty we can switch context if necessary. Note that the
// name of the yield function required is port specific.
if( xHigherPriorityTaskWokenByPost )
{
taskYIELD_YIELD_FROM_ISR();
}
}
Parameters
• xQueue –The handle to the queue on which the item is to be posted.
• pvItemToQueue –A pointer to the item that is to be placed on the queue. The size of
the items the queue will hold was defined when the queue was created, so this many bytes
will be copied from pvItemToQueue into the queue storage area.
• pxHigherPriorityTaskWoken –[out] xQueueGenericSendFromISR() will set
*pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to un-
block, and the unblocked task has a priority higher than the currently running task. If
xQueueGenericSendFromISR() sets this value to pdTRUE then a context switch should
be requested before the interrupt is exited.
• xCopyPosition –Can take the value queueSEND_TO_BACK to place the item at the
back of the queue, or queueSEND_TO_FRONT to place the item at the front of the queue
(for high priority messages).
Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL.
Example usage:
QueueHandle_t xQueue;
// ...
// Post some characters that will be used within an ISR. If the queue
// is full then this task will block for xTicksToWait ticks.
cValueToPost = 'a';
xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );
cValueToPost = 'b';
xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );
// ... keep posting characters ... this task may block when the queue
// becomes full.
cValueToPost = 'c';
xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );
}
// If removing the character from the queue woke the task that was
// posting onto the queue cTaskWokenByReceive will have been set to
// pdTRUE. No matter how many times this loop iterates only one
// task will be woken.
}
Parameters
• xQueue –The handle to the queue from which the item is to be received.
• pvBuffer –Pointer to the buffer into which the received item will be copied.
• pxHigherPriorityTaskWoken –[out] A task may be blocked waiting for space to
become available on the queue. If xQueueReceiveFromISR causes such a task to unblock
*pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will remain unchanged.
Returns pdTRUE if an item was successfully received from the queue, otherwise pdFALSE.
Macros
xQueueCreate(uxQueueLength, uxItemSize)
Creates a new queue instance, and returns a handle by which the new queue can be referenced.
Internally, within the FreeRTOS implementation, queues use two blocks of memory. The first block is used
to hold the queue’s data structures. The second block is used to hold items placed into the queue. If a queue
is created using xQueueCreate() then both blocks of memory are automatically dynamically allocated inside
the xQueueCreate() function. (see https://www.FreeRTOS.org/a00111.html). If a queue is created using
xQueueCreateStatic() then the application writer must provide the memory that will get used by the queue.
xQueueCreateStatic() therefore allows a queue to be created without using any dynamic memory allocation.
https://www.FreeRTOS.org/Embedded-RTOS-Queues.html
Example usage:
struct AMessage
{
char ucMessageID;
char ucData[ 20 ];
};
Parameters
• uxQueueLength –The maximum number of items that the queue can contain.
• uxItemSize –The number of bytes each item in the queue will require. Items are
queued by copy, not by reference, so this is the number of bytes that will be copied for
each posted item. Each item on the queue must be the same size.
Returns If the queue is successfully create then a handle to the newly created queue is returned.
If the queue cannot be created then 0 is returned.
xQueueCreateStatic(uxQueueLength, uxItemSize, pucQueueStorage, pxQueueBuffer)
Creates a new queue instance, and returns a handle by which the new queue can be referenced.
Internally, within the FreeRTOS implementation, queues use two blocks of memory. The first block is used
to hold the queue’s data structures. The second block is used to hold items placed into the queue. If a queue
is created using xQueueCreate() then both blocks of memory are automatically dynamically allocated inside
the xQueueCreate() function. (see https://www.FreeRTOS.org/a00111.html). If a queue is created using
xQueueCreateStatic() then the application writer must provide the memory that will get used by the queue.
xQueueCreateStatic() therefore allows a queue to be created without using any dynamic memory allocation.
https://www.FreeRTOS.org/Embedded-RTOS-Queues.html
Example usage:
struct AMessage
{
char ucMessageID;
char ucData[ 20 ];
};
#define QUEUE_LENGTH 10
#define ITEM_SIZE sizeof( uint32_t )
// ucQueueStorage will hold the items posted to the queue. Must be at least
// [(queue length) * ( queue item size)] bytes long.
uint8_t ucQueueStorage[ QUEUE_LENGTH * ITEM_SIZE ];
Parameters
• uxQueueLength –The maximum number of items that the queue can contain.
• uxItemSize –The number of bytes each item in the queue will require. Items are
queued by copy, not by reference, so this is the number of bytes that will be copied for
each posted item. Each item on the queue must be the same size.
• pucQueueStorage –If uxItemSize is not zero then pucQueueStorageBuffer must point
to a uint8_t array that is at least large enough to hold the maximum number of items that
can be in the queue at any one time - which is ( uxQueueLength * uxItemsSize ) bytes. If
uxItemSize is zero then pucQueueStorageBuffer can be NULL.
• pxQueueBuffer –Must point to a variable of type StaticQueue_t, which will be used
to hold the queue’s data structure.
Returns If the queue is created then a handle to the created queue is returned. If pxQueueBuffer
is NULL then NULL is returned.
Example usage:
struct AMessage
{
char ucMessageID;
char ucData[ 20 ];
} xMessage;
// ...
if( xQueue1 != 0 )
{
(continues on next page)
{
// Failed to post the message, even after 10 ticks.
}
}
if( xQueue2 != 0 )
{
// Send a pointer to a struct AMessage object. Don't block if the
// queue is already full.
pxMessage = & xMessage;
xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
}
Parameters
• xQueue –The handle to the queue on which the item is to be posted.
• pvItemToQueue –A pointer to the item that is to be placed on the queue. The size of
the items the queue will hold was defined when the queue was created, so this many bytes
will be copied from pvItemToQueue into the queue storage area.
• xTicksToWait –The maximum amount of time the task should block waiting for space
to become available on the queue, should it already be full. The call will return immediately
if this is set to 0 and the queue is full. The time is defined in tick periods so the constant
portTICK_PERIOD_MS should be used to convert to real time if this is required.
Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.
Example usage:
struct AMessage
{
char ucMessageID;
char ucData[ 20 ];
} xMessage;
// ...
if( xQueue1 != 0 )
{
// Send an uint32_t. Wait for 10 ticks for space to become
// available if necessary.
if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) !=␣
,→pdPASS )
{
// Failed to post the message, even after 10 ticks.
}
}
if( xQueue2 != 0 )
{
// Send a pointer to a struct AMessage object. Don't block if the
// queue is already full.
pxMessage = & xMessage;
xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
}
Parameters
• xQueue –The handle to the queue on which the item is to be posted.
• pvItemToQueue –A pointer to the item that is to be placed on the queue. The size of
the items the queue will hold was defined when the queue was created, so this many bytes
will be copied from pvItemToQueue into the queue storage area.
• xTicksToWait –The maximum amount of time the task should block waiting for space
to become available on the queue, should it already be full. The call will return immediately
if this is set to 0 and the queue is full. The time is defined in tick periods so the constant
portTICK_PERIOD_MS should be used to convert to real time if this is required.
Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.
Example usage:
struct AMessage
{
char ucMessageID;
char ucData[ 20 ];
} xMessage;
// ...
if( xQueue1 != 0 )
{
// Send an uint32_t. Wait for 10 ticks for space to become
// available if necessary.
if( xQueueSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS␣
,→)
{
// Failed to post the message, even after 10 ticks.
}
}
if( xQueue2 != 0 )
{
// Send a pointer to a struct AMessage object. Don't block if the
// queue is already full.
pxMessage = & xMessage;
xQueueSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
}
Parameters
• xQueue –The handle to the queue on which the item is to be posted.
• pvItemToQueue –A pointer to the item that is to be placed on the queue. The size of
the items the queue will hold was defined when the queue was created, so this many bytes
will be copied from pvItemToQueue into the queue storage area.
• xTicksToWait –The maximum amount of time the task should block waiting for space
to become available on the queue, should it already be full. The call will return immediately
if this is set to 0 and the queue is full. The time is defined in tick periods so the constant
portTICK_PERIOD_MS should be used to convert to real time if this is required.
Returns pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.
xQueueOverwrite(xQueue, pvItemToQueue)
Only for use with queues that have a length of one - so the queue is either empty or full.
Post an item on a queue. If the queue is already full then overwrite the value held in the queue. The item is
queued by copy, not by reference.
This function must not be called from an interrupt service routine. See xQueueOverwriteFromISR () for an
alternative which may be used in an ISR.
Example usage:
// Peeking the queue should now return 10, but leave the value 10 in
// the queue. A block time of zero is used as it is known that the
// queue holds a value.
ulValReceived = 0;
xQueuePeek( xQueue, &ulValReceived, 0 );
if( ulValReceived != 10 )
{
// Error unless the item was removed by a different task.
}
// This time read from the queue, leaving the queue empty once more.
// A block time of 0 is used again.
xQueueReceive( xQueue, &ulValReceived, 0 );
// The value read should be the last value written, even though the
// queue was already full when the value was written.
if( ulValReceived != 100 )
{
// Error!
}
// ...
}
Parameters
• xQueue –The handle of the queue to which the data is being sent.
• pvItemToQueue –A pointer to the item that is to be placed on the queue. The size of
the items the queue will hold was defined when the queue was created, so this many bytes
will be copied from pvItemToQueue into the queue storage area.
Returns xQueueOverwrite() is a macro that calls xQueueGenericSend(), and therefore has the
same return values as xQueueSendToFront(). However, pdPASS is the only value that can be
returned because xQueueOverwrite() will write to the queue even when the queue is already
full.
Example usage for buffered IO (where the ISR can obtain more than one value per call):
void vBufferISR( void )
{
char cIn;
BaseType_t xHigherPrioritTaskWoken;
Parameters
• xQueue –The handle to the queue on which the item is to be posted.
• pvItemToQueue –A pointer to the item that is to be placed on the queue. The size of
the items the queue will hold was defined when the queue was created, so this many bytes
will be copied from pvItemToQueue into the queue storage area.
• pxHigherPriorityTaskWoken –[out] xQueueSendToFrontFromISR() will set
*pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to un-
block, and the unblocked task has a priority higher than the currently running task. If
xQueueSendToFromFromISR() sets this value to pdTRUE then a context switch should
be requested before the interrupt is exited.
Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL.
Example usage for buffered IO (where the ISR can obtain more than one value per call):
void vBufferISR( void )
{
char cIn;
BaseType_t xHigherPriorityTaskWoken;
Parameters
• xQueue –The handle to the queue on which the item is to be posted.
• pvItemToQueue –A pointer to the item that is to be placed on the queue. The size of
the items the queue will hold was defined when the queue was created, so this many bytes
will be copied from pvItemToQueue into the queue storage area.
• pxHigherPriorityTaskWoken –[out] xQueueSendToBackFromISR() will set
*pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to un-
block, and the unblocked task has a priority higher than the currently running task. If
xQueueSendToBackFromISR() sets this value to pdTRUE then a context switch should
be requested before the interrupt is exited.
Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL.
Example usage:
QueueHandle_t xQueue;
// ...
Parameters
• xQueue –The handle to the queue on which the item is to be posted.
• pvItemToQueue –A pointer to the item that is to be placed on the queue. The size of
the items the queue will hold was defined when the queue was created, so this many bytes
will be copied from pvItemToQueue into the queue storage area.
• pxHigherPriorityTaskWoken –[out] xQueueOverwriteFromISR() will set *px-
HigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to un-
block, and the unblocked task has a priority higher than the currently running task. If
xQueueOverwriteFromISR() sets this value to pdTRUE then a context switch should be
requested before the interrupt is exited.
Returns xQueueOverwriteFromISR() is a macro that calls xQueueGenericSendFromISR(), and
therefore has the same return values as xQueueSendToFrontFromISR(). However, pdPASS
is the only value that can be returned because xQueueOverwriteFromISR() will write to the
queue even when the queue is already full.
Example usage for buffered IO (where the ISR can obtain more than one value per call):
Parameters
• xQueue –The handle to the queue on which the item is to be posted.
• pvItemToQueue –A pointer to the item that is to be placed on the queue. The size of
the items the queue will hold was defined when the queue was created, so this many bytes
will be copied from pvItemToQueue into the queue storage area.
• pxHigherPriorityTaskWoken –[out] xQueueSendFromISR() will set *pxHigh-
erPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and
the unblocked task has a priority higher than the currently running task. If xQueueSend-
FromISR() sets this value to pdTRUE then a context switch should be requested before
the interrupt is exited.
Returns pdTRUE if the data was successfully sent to the queue, otherwise errQUEUE_FULL.
xQueueReset(xQueue)
Reset a queue back to its original empty state. The return value is now obsolete and is always set to pdPASS.
Type Definitions
Semaphore API
Header File
• components/freertos/FreeRTOS-Kernel/include/freertos/semphr.h
Macros
semBINARY_SEMAPHORE_QUEUE_LENGTH
semSEMAPHORE_QUEUE_ITEM_LENGTH
semGIVE_BLOCK_TIME
vSemaphoreCreateBinary(xSemaphore)
xSemaphoreCreateBinary()
Creates a new binary semaphore instance, and returns a handle by which the new semaphore can be referenced.
In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a
binary semaphore! https://www.FreeRTOS.org/RTOS-task-notifications.html
Internally, within the FreeRTOS implementation, binary semaphores use a block of memory, in which the
semaphore structure is stored. If a binary semaphore is created using xSemaphoreCreateBinary() then the
required memory is automatically dynamically allocated inside the xSemaphoreCreateBinary() function. (see
https://www.FreeRTOS.org/a00111.html). If a binary semaphore is created using xSemaphoreCreateBina-
ryStatic() then the application writer must provide the memory. xSemaphoreCreateBinaryStatic() therefore
allows a binary semaphore to be created without using any dynamic memory allocation.
The old vSemaphoreCreateBinary() macro is now deprecated in favour of this xSemaphoreCreateBinary()
function. Note that binary semaphores created using the vSemaphoreCreateBinary() macro are created in a
state such that the first call to ‘take’the semaphore would pass, whereas binary semaphores created using
xSemaphoreCreateBinary() are created in a state such that the the semaphore must first be ‘given’before it
can be ‘taken’.
This type of semaphore can be used for pure synchronisation between tasks or between an interrupt and a
task. The semaphore need not be given back once obtained, so one task/interrupt can continuously‘give’the
semaphore while another continuously‘takes’the semaphore. For this reason this type of semaphore does not
use a priority inheritance mechanism. For an alternative that does use priority inheritance see xSemaphoreCre-
ateMutex().
Example usage:
Returns Handle to the created semaphore, or NULL if the memory required to hold the
semaphore’s data structures could not be allocated.
xSemaphoreCreateBinaryStatic(pxStaticSemaphore)
Creates a new binary semaphore instance, and returns a handle by which the new semaphore can be referenced.
NOTE: In many usage scenarios it is faster and more memory efficient to use a direct to task notification in
place of a binary semaphore! https://www.FreeRTOS.org/RTOS-task-notifications.html
Internally, within the FreeRTOS implementation, binary semaphores use a block of memory, in which the
semaphore structure is stored. If a binary semaphore is created using xSemaphoreCreateBinary() then the
required memory is automatically dynamically allocated inside the xSemaphoreCreateBinary() function. (see
Example usage:
SemaphoreHandle_t xSemaphore = NULL;
StaticSemaphore_t xSemaphoreBuffer;
Parameters
• pxStaticSemaphore –Must point to a variable of type StaticSemaphore_t, which will
then be used to hold the semaphore’s data structure, removing the need for the memory
to be allocated dynamically.
Returns If the semaphore is created then a handle to the created semaphore is returned. If
pxSemaphoreBuffer is NULL then NULL is returned.
xSemaphoreTake(xSemaphore, xBlockTime)
Macro to obtain a semaphore. The semaphore must have previously been created with a call to xSemaphoreCre-
ateBinary(), xSemaphoreCreateMutex() or xSemaphoreCreateCounting().
param xSemaphore A handle to the semaphore being taken - obtained when the semaphore was created.
param xBlockTime The time in ticks to wait for the semaphore to become available. The macro
portTICK_PERIOD_MS can be used to convert this to a real time. A block time of zero can be used to
poll the semaphore. A block time of portMAX_DELAY can be used to block indefinitely (provided IN-
CLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h).
Example usage:
SemaphoreHandle_t xSemaphore = NULL;
// ...
Returns pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime expired without the
semaphore becoming available.
xSemaphoreTakeRecursive(xMutex, xBlockTime)
Macro to recursively obtain, or ‘take’, a mutex type semaphore. The mutex must have previously been
created using a call to xSemaphoreCreateRecursiveMutex();
configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this macro to be available.
This macro must not be used on mutexes created using xSemaphoreCreateMutex().
A mutex used recursively can be ‘taken’repeatedly by the owner. The mutex doesn’t become available
again until the owner has called xSemaphoreGiveRecursive() for each successful‘take’request. For example,
if a task successfully ‘takes’the same mutex 5 times then the mutex will not be available to any other task
until it has also ‘given’the mutex back exactly five times.
Example usage:
// ...
// For some reason due to the nature of the code further calls to
// xSemaphoreTakeRecursive() are made on the same mutex. In real
// code these would not be just sequential calls as this would make
// no sense. Instead the calls are likely to be buried inside
// a more complex call structure.
xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
// The mutex has now been 'taken' three times, so will not be
// available to another task until it has also been given back
// three times. Again it is unlikely that real code would have
// these calls sequentially, but instead buried in a more complex
// call structure. This is just for illustrative purposes.
xSemaphoreGiveRecursive( xMutex );
xSemaphoreGiveRecursive( xMutex );
xSemaphoreGiveRecursive( xMutex );
Parameters
• xMutex –A handle to the mutex being obtained. This is the handle returned by
xSemaphoreCreateRecursiveMutex();
• xBlockTime –The time in ticks to wait for the semaphore to become available. The
macro portTICK_PERIOD_MS can be used to convert this to a real time. A block time
of zero can be used to poll the semaphore. If the task already owns the semaphore then
xSemaphoreTakeRecursive() will return immediately no matter what the value of xBlock-
Time.
Returns pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime expired without the
semaphore becoming available.
xSemaphoreGive(xSemaphore)
Macro to release a semaphore. The semaphore must have previously been created with a call to
xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or xSemaphoreCreateCounting(). and obtained us-
ing sSemaphoreTake().
This macro must not be used from an ISR. See xSemaphoreGiveFromISR () for an alternative which can be
used from an ISR.
This macro must also not be used on semaphores created using xSemaphoreCreateRecursiveMutex().
Example usage:
// ...
Parameters
• xSemaphore –A handle to the semaphore being released. This is the handle returned
when the semaphore was created.
Returns pdTRUE if the semaphore was released. pdFALSE if an error occurred. Semaphores
are implemented using queues. An error can occur if there is no space on the queue to post a
message - indicating that the semaphore was not first obtained correctly.
xSemaphoreGiveRecursive(xMutex)
Macro to recursively release, or ‘give’, a mutex type semaphore. The mutex must have previously been
created using a call to xSemaphoreCreateRecursiveMutex();
configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this macro to be available.
This macro must not be used on mutexes created using xSemaphoreCreateMutex().
A mutex used recursively can be ‘taken’repeatedly by the owner. The mutex doesn’t become available
again until the owner has called xSemaphoreGiveRecursive() for each successful‘take’request. For example,
if a task successfully ‘takes’the same mutex 5 times then the mutex will not be available to any other task
until it has also ‘given’the mutex back exactly five times.
Example usage:
SemaphoreHandle_t xMutex = NULL;
// ...
// For some reason due to the nature of the code further calls to
// xSemaphoreTakeRecursive() are made on the same mutex. In real
// code these would not be just sequential calls as this would make
// no sense. Instead the calls are likely to be buried inside
// a more complex call structure.
xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
// The mutex has now been 'taken' three times, so will not be
// available to another task until it has also been given back
// three times. Again it is unlikely that real code would have
// these calls sequentially, it would be more likely that the calls
// to xSemaphoreGiveRecursive() would be called as a call stack
// unwound. This is just for demonstrative purposes.
xSemaphoreGiveRecursive( xMutex );
xSemaphoreGiveRecursive( xMutex );
xSemaphoreGiveRecursive( xMutex );
Parameters
• xMutex –A handle to the mutex being released, or‘given’. This is the handle returned
by xSemaphoreCreateMutex();
Returns pdTRUE if the semaphore was given.
xSemaphoreGiveFromISR(xSemaphore, pxHigherPriorityTaskWoken)
Macro to release a semaphore. The semaphore must have previously been created with a call to
xSemaphoreCreateBinary() or xSemaphoreCreateCounting().
Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) must not be used with this
macro.
This macro can be used from an ISR.
Example usage:
// Repetitive task.
void vATask( void * pvParameters )
{
for( ;; )
{
// We want this task to run every 10 ticks of a timer. The semaphore
// was created before this task was started.
// ...
// We have finished our task. Return to the top of the loop where
// we will block on the semaphore until it is time to execute
// again. Note when using the semaphore for synchronisation with an
// ISR in this manner there is no need to 'give' the semaphore back.
}
}
}
// Timer ISR
void vTimerISR( void * pvParameters )
{
static uint8_t ucLocalTickCount = 0;
static BaseType_t xHigherPriorityTaskWoken;
Parameters
• xSemaphore –A handle to the semaphore being released. This is the handle returned
xSemaphoreTakeFromISR(xSemaphore, pxHigherPriorityTaskWoken)
Macro to take a semaphore from an ISR. The semaphore must have previously been created with a call to
xSemaphoreCreateBinary() or xSemaphoreCreateCounting().
Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) must not be used with this
macro.
This macro can be used from an ISR, however taking a semaphore from an ISR is not a common operation. It
is likely to only be useful when taking a counting semaphore when an interrupt is obtaining an object from a
resource pool (when the semaphore count indicates the number of resources available).
Parameters
• xSemaphore –A handle to the semaphore being taken. This is the handle returned when
the semaphore was created.
• pxHigherPriorityTaskWoken –[out] xSemaphoreTakeFromISR() will set *px-
HigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task to un-
block, and the unblocked task has a priority higher than the currently running task. If
xSemaphoreTakeFromISR() sets this value to pdTRUE then a context switch should be
requested before the interrupt is exited.
Returns pdTRUE if the semaphore was successfully taken, otherwise pdFALSE
xSemaphoreCreateMutex()
Creates a new mutex type semaphore instance, and returns a handle by which the new mutex can be referenced.
Internally, within the FreeRTOS implementation, mutex semaphores use a block of memory, in which
the mutex structure is stored. If a mutex is created using xSemaphoreCreateMutex() then the required
memory is automatically dynamically allocated inside the xSemaphoreCreateMutex() function. (see https:
//www.FreeRTOS.org/a00111.html). If a mutex is created using xSemaphoreCreateMutexStatic() then the
application writer must provided the memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to
be created without using any dynamic memory allocation.
Mutexes created using this function can be accessed using the xSemaphoreTake() and xSemaphoreGive()
macros. The xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros must not be used.
This type of semaphore uses a priority inheritance mechanism so a task‘taking’a semaphore MUST ALWAYS
‘give’the semaphore back once the semaphore it is no longer required.
Mutex type semaphores cannot be used from within interrupt service routines.
See xSemaphoreCreateBinary() for an alternative implementation that can be used for pure synchronisation
(where one task or interrupt always ‘gives’the semaphore and another always ‘takes’the semaphore) and
from within interrupt service routines.
Example usage:
SemaphoreHandle_t xSemaphore;
Returns If the mutex was successfully created then a handle to the created semaphore is returned.
If there was not enough heap to allocate the mutex data structures then NULL is returned.
xSemaphoreCreateMutexStatic(pxMutexBuffer)
Creates a new mutex type semaphore instance, and returns a handle by which the new mutex can be referenced.
Internally, within the FreeRTOS implementation, mutex semaphores use a block of memory, in which
the mutex structure is stored. If a mutex is created using xSemaphoreCreateMutex() then the required
memory is automatically dynamically allocated inside the xSemaphoreCreateMutex() function. (see https:
//www.FreeRTOS.org/a00111.html). If a mutex is created using xSemaphoreCreateMutexStatic() then the
application writer must provided the memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to
be created without using any dynamic memory allocation.
Mutexes created using this function can be accessed using the xSemaphoreTake() and xSemaphoreGive()
macros. The xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros must not be used.
This type of semaphore uses a priority inheritance mechanism so a task‘taking’a semaphore MUST ALWAYS
‘give’the semaphore back once the semaphore it is no longer required.
Mutex type semaphores cannot be used from within interrupt service routines.
See xSemaphoreCreateBinary() for an alternative implementation that can be used for pure synchronisation
(where one task or interrupt always ‘gives’the semaphore and another always ‘takes’the semaphore) and
from within interrupt service routines.
Example usage:
SemaphoreHandle_t xSemaphore;
StaticSemaphore_t xMutexBuffer;
Parameters
• pxMutexBuffer –Must point to a variable of type StaticSemaphore_t, which will be
used to hold the mutex’s data structure, removing the need for the memory to be allocated
dynamically.
Returns If the mutex was successfully created then a handle to the created mutex is returned. If
pxMutexBuffer was NULL then NULL is returned.
xSemaphoreCreateCounting(uxMaxCount, uxInitialCount)
Creates a new recursive mutex type semaphore instance, and returns a handle by which the new recursive mutex
can be referenced.
Internally, within the FreeRTOS implementation, recursive mutexs use a block of memory, in which the mu-
tex structure is stored. If a recursive mutex is created using xSemaphoreCreateRecursiveMutex() then the
required memory is automatically dynamically allocated inside the xSemaphoreCreateRecursiveMutex() func-
tion. (see http://www.freertos.org/a00111.html). If a recursive mutex is created using xSemaphoreCreateRe-
cursiveMutexStatic() then the application writer must provide the memory that will get used by the mutex.
xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to be created without using any
dynamic memory allocation.
Mutexes created using this macro can be accessed using the xSemaphoreTakeRecursive() and xSemaphore-
GiveRecursive() macros. The xSemaphoreTake() and xSemaphoreGive() macros must not be used.
A mutex used recursively can be ‘taken’repeatedly by the owner. The mutex doesn’t become available
again until the owner has called xSemaphoreGiveRecursive() for each successful‘take’request. For example,
if a task successfully ‘takes’the same mutex 5 times then the mutex will not be available to any other task
until it has also ‘given’the mutex back exactly five times.
This type of semaphore uses a priority inheritance mechanism so a task‘taking’a semaphore MUST ALWAYS
‘give’the semaphore back once the semaphore it is no longer required.
Mutex type semaphores cannot be used from within interrupt service routines.
See vSemaphoreCreateBinary() for an alternative implementation that can be used for pure synchronisation
(where one task or interrupt always ‘gives’the semaphore and another always ‘takes’the semaphore) and
from within interrupt service routines.
Example usage:
SemaphoreHandle_t xSemaphore;
Creates a new recursive mutex type semaphore instance, and returns a handle by which the new recursive mutex
can be referenced.
Internally, within the FreeRTOS implementation, recursive mutexs use a block of memory, in which the mu-
tex structure is stored. If a recursive mutex is created using xSemaphoreCreateRecursiveMutex() then the
required memory is automatically dynamically allocated inside the xSemaphoreCreateRecursiveMutex() func-
tion. (see https://www.FreeRTOS.org/a00111.html). If a recursive mutex is created using xSemaphoreCre-
ateRecursiveMutexStatic() then the application writer must provide the memory that will get used by the mutex.
xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to be created without using any
dynamic memory allocation.
Mutexes created using this macro can be accessed using the xSemaphoreTakeRecursive() and xSemaphore-
GiveRecursive() macros. The xSemaphoreTake() and xSemaphoreGive() macros must not be used.
A mutex used recursively can be ‘taken’repeatedly by the owner. The mutex doesn’t become available
again until the owner has called xSemaphoreGiveRecursive() for each successful‘take’request. For example,
if a task successfully ‘takes’the same mutex 5 times then the mutex will not be available to any other task
until it has also ‘given’the mutex back exactly five times.
This type of semaphore uses a priority inheritance mechanism so a task‘taking’a semaphore MUST ALWAYS
‘give’the semaphore back once the semaphore it is no longer required.
Mutex type semaphores cannot be used from within interrupt service routines.
See xSemaphoreCreateBinary() for an alternative implementation that can be used for pure synchronisation
(where one task or interrupt always ‘gives’the semaphore and another always ‘takes’the semaphore) and
from within interrupt service routines.
Example usage:
SemaphoreHandle_t xSemaphore;
StaticSemaphore_t xMutexBuffer;
Creates a new counting semaphore instance, and returns a handle by which the new counting semaphore can
be referenced.
In many usage scenarios it is faster and more memory efficient to use a direct to task notification in place of a
counting semaphore! https://www.FreeRTOS.org/RTOS-task-notifications.html
Internally, within the FreeRTOS implementation, counting semaphores use a block of memory, in which
the counting semaphore structure is stored. If a counting semaphore is created using xSemaphoreCreate-
Counting() then the required memory is automatically dynamically allocated inside the xSemaphoreCreate-
Counting() function. (see https://www.FreeRTOS.org/a00111.html). If a counting semaphore is created us-
ing xSemaphoreCreateCountingStatic() then the application writer can instead optionally provide the memory
that will get used by the counting semaphore. xSemaphoreCreateCountingStatic() therefore allows a counting
semaphore to be created without using any dynamic memory allocation.
Counting semaphores are typically used for two things:
1) Counting events.
In this usage scenario an event handler will ‘give’a semaphore each time an event occurs (incrementing
the semaphore count value), and a handler task will ‘take’a semaphore each time it processes an event
(decrementing the semaphore count value). The count value is therefore the difference between the number of
events that have occurred and the number that have been processed. In this case it is desirable for the initial
count value to be zero.
2) Resource management.
In this usage scenario the count value indicates the number of resources available. To obtain control of a
resource a task must first obtain a semaphore - decrementing the semaphore count value. When the count value
reaches zero there are no free resources. When a task finishes with the resource it‘gives’the semaphore back
- incrementing the semaphore count value. In this case it is desirable for the initial count value to be equal to
the maximum count value, indicating that all resources are free.
Example usage:
SemaphoreHandle_t xSemaphore;
Returns xSemaphore Handle to the created mutex semaphore. Should be of type SemaphoreHan-
dle_t.
Parameters
• pxStaticSemaphore –Must point to a variable of type StaticSemaphore_t, which
will then be used to hold the recursive mutex’s data structure, removing the need for the
memory to be allocated dynamically.
• uxMaxCount –The maximum count value that can be reached. When the semaphore
reaches this value it can no longer be ‘given’.
• uxInitialCount –The count value assigned to the semaphore when it is created.
Returns If the recursive mutex was successfully created then a handle to the created recursive
mutex is returned. If pxMutexBuffer was NULL then NULL is returned.
Returns Handle to the created semaphore. Null if the semaphore could not be created.
Example usage:
SemaphoreHandle_t xSemaphore;
StaticSemaphore_t xSemaphoreBuffer;
// Counting semaphore cannot be used before they have been created. Create
// a counting semaphore using xSemaphoreCreateCountingStatic(). The max
// value to which the semaphore can count is 10, and the initial value
// assigned to the count will be 0. The address of xSemaphoreBuffer is
// passed in and will be used to hold the semaphore structure, so no dynamic
// memory allocation will be used.
xSemaphore = xSemaphoreCreateCounting( 10, 0, &xSemaphoreBuffer );
Parameters
• uxMaxCount –The maximum count value that can be reached. When the semaphore
reaches this value it can no longer be ‘given’.
• uxInitialCount –The count value assigned to the semaphore when it is created.
• pxSemaphoreBuffer –Must point to a variable of type StaticSemaphore_t, which will
then be used to hold the semaphore’s data structure, removing the need for the memory
to be allocated dynamically.
Returns If the counting semaphore was successfully created then a handle to the created counting
semaphore is returned. If pxSemaphoreBuffer was NULL then NULL is returned.
vSemaphoreDelete(xSemaphore)
Delete a semaphore. This function must be used with care. For example, do not delete a mutex type semaphore
if the mutex is held by a task.
Parameters
• xSemaphore –A handle to the semaphore to be deleted.
xSemaphoreGetMutexHolder(xSemaphore)
If xMutex is indeed a mutex type semaphore, return the current mutex holder. If xMutex is not a mutex type
semaphore, or the mutex is available (not held by a task), return NULL.
Note: This is a good way of determining if the calling task is the mutex holder, but not a good way of deter-
mining the identity of the mutex holder as the holder may change between the function exiting and the returned
value being tested.
xSemaphoreGetMutexHolderFromISR(xSemaphore)
If xMutex is indeed a mutex type semaphore, return the current mutex holder. If xMutex is not a mutex type
semaphore, or the mutex is available (not held by a task), return NULL.
uxSemaphoreGetCount(xSemaphore)
If the semaphore is a counting semaphore then uxSemaphoreGetCount() returns its current count value. If the
semaphore is a binary semaphore then uxSemaphoreGetCount() returns 1 if the semaphore is available, and 0
if the semaphore is not available.
Type Definitions
Timer API
Header File
• components/freertos/FreeRTOS-Kernel/include/freertos/timers.h
Functions
TimerHandle_t xTimerCreate(const char *const pcTimerName, const TickType_t xTimerPeriodInTicks, const
UBaseType_t uxAutoReload, void *const pvTimerID,
TimerCallbackFunction_t pxCallbackFunction)
TimerHandle_t xTimerCreate( const char * const pcTimerName, TickType_t xTimerPeriodInTicks, UBase-
Type_t uxAutoReload, void * pvTimerID, TimerCallbackFunction_t pxCallbackFunction );
Creates a new software timer instance, and returns a handle by which the created software timer can be refer-
enced.
Internally, within the FreeRTOS implementation, software timers use a block of memory, in which the timer
data structure is stored. If a software timer is created using xTimerCreate() then the required memory is auto-
matically dynamically allocated inside the xTimerCreate() function. (see https://www.FreeRTOS.org/a00111.
html). If a software timer is created using xTimerCreateStatic() then the application writer must provide the
memory that will get used by the software timer. xTimerCreateStatic() therefore allows a software timer to be
created without using any dynamic memory allocation.
Timers are created in the dormant state. The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimer-
ResetFromISR(), xTimerChangePeriod() and xTimerChangePeriodFromISR() API functions can all be used
to transition a timer into the active state.
Example usage:
* #define NUM_TIMERS 5
*
* // An array to hold handles to the created timers.
* TimerHandle_t xTimers[ NUM_TIMERS ];
*
* // An array to hold a count of the number of times each timer expires.
* int32_t lExpireCounters[ NUM_TIMERS ] = { 0 };
*
* // Define a callback function that will be used by multiple timer instances.
* // The callback function does nothing but count the number of times the
* // associated timer expires, and stop the timer once the timer has expired
* // 10 times.
* void vTimerCallback( TimerHandle_t pxTimer )
* {
* int32_t lArrayIndex;
* const int32_t xMaxExpiryCountBeforeStopping = 10;
*
* // Optionally do something if the pxTimer parameter is NULL.
* configASSERT( pxTimer );
*
* // Which timer expired?
* lArrayIndex = ( int32_t ) pvTimerGetTimerID( pxTimer );
*
* // Increment the number of times that pxTimer has expired.
* lExpireCounters[ lArrayIndex ] += 1;
*
* // If the timer has expired 10 times then stop it from running.
* if( lExpireCounters[ lArrayIndex ] == xMaxExpiryCountBeforeStopping )
* {
* // Do not use a block time if calling a timer API function from a
* // timer callback function, as doing so could cause a deadlock!
(continues on next page)
* );
*
* if( xTimers[ x ] == NULL )
* {
* // The timer was not created.
* }
* else
* {
* // Start the timer. No block time is specified, and even if one␣
,→was
Parameters
• pcTimerName –A text name that is assigned to the timer. This is done purely to assist
debugging. The kernel itself only ever references a timer by its handle, and never by its
name.
• xTimerPeriodInTicks –The timer period. The time is defined in tick periods so the
constant portTICK_PERIOD_MS can be used to convert a time that has been specified
in milliseconds. For example, if the timer must expire after 100 ticks, then xTimerPeri-
odInTicks should be set to 100. Alternatively, if the timer must expire after 500ms, then
xPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ
is less than or equal to 1000. Time timer period must be greater than 0.
• uxAutoReload –If uxAutoReload is set to pdTRUE then the timer will expire repeat-
edly with a frequency set by the xTimerPeriodInTicks parameter. If uxAutoReload is set
to pdFALSE then the timer will be a one-shot timer and enter the dormant state after it
expires.
• pvTimerID –An identifier that is assigned to the timer being created. Typically this
would be used in the timer callback function to identify which timer expired when the
same callback function is assigned to more than one timer.
• pxCallbackFunction –The function to call when the timer expires. Callback func-
tions must have the prototype defined by TimerCallbackFunction_t, which is“void vCall-
backFunction( TimerHandle_t xTimer );”.
Returns If the timer is successfully created then a handle to the newly created timer is returned.
If the timer cannot be created (because either there is insufficient FreeRTOS heap remaining
to allocate the timer structures, or the timer period was set to 0) then NULL is returned.
TimerHandle_t xTimerCreateStatic(const char *const pcTimerName, const TickType_t
xTimerPeriodInTicks, const UBaseType_t uxAutoReload, void *const
pvTimerID, TimerCallbackFunction_t pxCallbackFunction,
StaticTimer_t *pxTimerBuffer)
TimerHandle_t xTimerCreateStatic(const char * const pcTimerName, TickType_t xTimerPeriodInTicks,
UBaseType_t uxAutoReload, void * pvTimerID, TimerCallbackFunction_t pxCallbackFunction, Static-
Timer_t *pxTimerBuffer );
Creates a new software timer instance, and returns a handle by which the created software timer can be refer-
enced.
Internally, within the FreeRTOS implementation, software timers use a block of memory, in which the timer
data structure is stored. If a software timer is created using xTimerCreate() then the required memory is auto-
matically dynamically allocated inside the xTimerCreate() function. (see https://www.FreeRTOS.org/a00111.
html). If a software timer is created using xTimerCreateStatic() then the application writer must provide the
memory that will get used by the software timer. xTimerCreateStatic() therefore allows a software timer to be
created without using any dynamic memory allocation.
Timers are created in the dormant state. The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimer-
ResetFromISR(), xTimerChangePeriod() and xTimerChangePeriodFromISR() API functions can all be used
to transition a timer into the active state.
Example usage:
*
* // The buffer used to hold the software timer's data structure.
* static StaticTimer_t xTimerBuffer;
*
* // A variable that will be incremented by the software timer's callback
* // function.
* UBaseType_t uxVariableToIncrement = 0;
*
* // A software timer callback function that increments a variable passed to
* // it when the software timer was created. After the 5th increment the
* // callback function stops the software timer.
* static void prvTimerCallback( TimerHandle_t xExpiredTimer )
* {
* UBaseType_t *puxVariableToIncrement;
* BaseType_t xReturned;
(continues on next page)
*
* // Increment the variable to show the timer callback has executed.
* ( *puxVariableToIncrement )++;
*
* // If this callback has executed the required number of times, stop the
* // timer.
* if( *puxVariableToIncrement == 5 )
* {
* // This is called from a timer callback so must not block.
* xTimerStop( xExpiredTimer, staticDONT_BLOCK );
* }
* }
*
*
* void main( void )
* {
* // Create the software time. xTimerCreateStatic() has an extra parameter
* // than the normal xTimerCreate() API function. The parameter is a␣
,→pointer
* ( void * ) &uxVariableToIncrement, // A␣
,→variable incremented by the software timer's callback function
*
* // The scheduler has not started yet so a block time is not used.
* xReturned = xTimerStart( xTimer, 0 );
*
* // ...
* // Create tasks here.
* // ...
*
* // Starting the scheduler will start the timers running as they have␣
,→already
Parameters
• pcTimerName –A text name that is assigned to the timer. This is done purely to assist
debugging. The kernel itself only ever references a timer by its handle, and never by its
name.
• xTimerPeriodInTicks –The timer period. The time is defined in tick periods so the
constant portTICK_PERIOD_MS can be used to convert a time that has been specified
in milliseconds. For example, if the timer must expire after 100 ticks, then xTimerPeri-
odInTicks should be set to 100. Alternatively, if the timer must expire after 500ms, then
xPeriod can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ
is less than or equal to 1000. The timer period must be greater than 0.
• uxAutoReload –If uxAutoReload is set to pdTRUE then the timer will expire repeat-
edly with a frequency set by the xTimerPeriodInTicks parameter. If uxAutoReload is set
to pdFALSE then the timer will be a one-shot timer and enter the dormant state after it
expires.
• pvTimerID –An identifier that is assigned to the timer being created. Typically this
would be used in the timer callback function to identify which timer expired when the
same callback function is assigned to more than one timer.
• pxCallbackFunction –The function to call when the timer expires. Callback func-
tions must have the prototype defined by TimerCallbackFunction_t, which is“void vCall-
backFunction( TimerHandle_t xTimer );”.
• pxTimerBuffer –Must point to a variable of type StaticTimer_t, which will be then
be used to hold the software timer’s data structures, removing the need for the memory
to be allocated dynamically.
Returns If the timer is created then a handle to the created timer is returned. If pxTimerBuffer
was NULL then NULL is returned.
Example usage:
See the xTimerCreate() API function example usage scenario.
Parameters xTimer –The timer being queried.
Returns The ID assigned to the timer being queried.
void vTimerSetTimerID(TimerHandle_t xTimer, void *pvNewID)
void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID );
Sets the ID assigned to the timer.
IDs are assigned to timers using the pvTimerID parameter of the call to xTimerCreated() that was used to
create the timer.
If the same callback function is assigned to multiple timers then the timer ID can be used as time specific (timer
local) storage.
Example usage:
See the xTimerCreate() API function example usage scenario.
Parameters
• xTimer –The timer being updated.
• pvNewID –The ID to assign to the timer.
Example usage:
* {
* // xTimer is active, do something.
* }
* else
* {
* // xTimer is not active, do something else.
* }
* }
*
TaskHandle_t xTimerGetTimerDaemonTaskHandle(void)
TaskHandle_t xTimerGetTimerDaemonTaskHandle( void );
Simply returns the handle of the timer service/daemon task. It it not valid to call xTimerGetTimerDaemon-
TaskHandle() before the scheduler has been started.
BaseType_t xTimerPendFunctionCallFromISR(PendedFunction_t xFunctionToPend, void
*pvParameter1, uint32_t ulParameter2, BaseType_t
*pxHigherPriorityTaskWoken)
BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1,
uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken );
Used from application interrupt service routines to defer the execution of a function to the RTOS daemon task
(the timer service task, hence this function is implemented in timers.c and is prefixed with ‘Timer’).
Ideally an interrupt service routine (ISR) is kept as short as possible, but sometimes an ISR either has a lot of
processing to do, or needs to perform processing that is not deterministic. In these cases xTimerPendFunc-
tionCallFromISR() can be used to defer processing of a function to the RTOS daemon task.
A mechanism is provided that allows the interrupt to return directly to the task that will subsequently execute the
pended callback function. This allows the callback function to execute contiguously in time with the interrupt
- just as if the callback had executed in the interrupt itself.
Example usage:
*
* // The callback function that will execute in the context of the daemon␣
,→ task.
* // Note callback functions must all use this same prototype.
* void vProcessInterface( void *pvParameter1, uint32_t ulParameter2 )
* {
* BaseType_t xInterfaceToService;
*
* // The interface that requires servicing is passed in the second
* // parameter. The first parameter is not used in this case.
* xInterfaceToService = ( BaseType_t ) ulParameter2;
*
* // ...Perform the processing here...
* }
*
* // An ISR that receives data packets from multiple interfaces
* void vAnISR( void )
* {
* BaseType_t xInterfaceToService, xHigherPriorityTaskWoken;
*
* // Query the hardware to determine which interface needs processing.
* xInterfaceToService = prvCheckInterfaces();
*
* // The actual processing is to be deferred to a task. Request the
* // vProcessInterface() callback function is executed, passing in the
* // number of the interface that needs processing. The interface to
* // service is passed in the second parameter. The first parameter is
* // not used in this case.
* xHigherPriorityTaskWoken = pdFALSE;
* xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t )␣
,→xInterfaceToService, &xHigherPriorityTaskWoken );
*
* // If xHigherPriorityTaskWoken is now set to pdTRUE then a context
* // switch should be requested. The macro used is port specific and will
* // be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to
* // the documentation page for the port being used.
* portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
*
* }
*
Parameters
• xFunctionToPend –The function to execute from the timer service/ daemon task. The
function must conform to the PendedFunction_t prototype.
• pvParameter1 –The value of the callback function’s first parameter. The parameter
has a void * type to allow it to be used to pass any type. For example, unsigned longs can
be cast to a void *, or the void * can be used to point to a structure.
• ulParameter2 –The value of the callback function’s second parameter.
• pxHigherPriorityTaskWoken –As mentioned above, calling this function will re-
sult in a message being sent to the timer daemon task. If the priority of the timer dae-
mon task (which is set using configTIMER_TASK_PRIORITY in FreeRTOSConfig.h) is
higher than the priority of the currently running task (the task the interrupt interrupted)
then *pxHigherPriorityTaskWoken will be set to pdTRUE within xTimerPendFunction-
CallFromISR(), indicating that a context switch should be requested before the interrupt
exits. For that reason *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See
the example code below.
Returns pdPASS is returned if the message was successfully sent to the timer daemon task, oth-
erwise pdFALSE is returned.
Returns the time in ticks at which the timer will expire. If this is less than the current tick count then the expiry
time has overflowed from the current time.
Parameters xTimer –The handle of the timer being queried.
Returns If the timer is running then the time in ticks at which the timer will next expire is returned.
If the timer is not running then the return value is undefined.
void vApplicationGetTimerTaskMemory(StaticTask_t **ppxTimerTaskTCBBuffer, StackType_t
**ppxTimerTaskStackBuffer, uint32_t
*pulTimerTaskStackSize)
This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Timer Task
TCB. This function is required when configSUPPORT_STATIC_ALLOCATION is set. For more information
see this URI: https://www.FreeRTOS.org/a00110.html#configSUPPORT_STATIC_ALLOCATION
Parameters
• ppxTimerTaskTCBBuffer –A handle to a statically allocated TCB buffer
• ppxTimerTaskStackBuffer –A handle to a statically allocated Stack buffer for thie
idle task
• pulTimerTaskStackSize –A pointer to the number of elements that will fit in the
allocated stack buffer
Macros
tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR
tmrCOMMAND_EXECUTE_CALLBACK
tmrCOMMAND_START_DONT_TRACE
tmrCOMMAND_START
tmrCOMMAND_RESET
tmrCOMMAND_STOP
tmrCOMMAND_CHANGE_PERIOD
tmrCOMMAND_DELETE
tmrFIRST_FROM_ISR_COMMAND
tmrCOMMAND_START_FROM_ISR
tmrCOMMAND_RESET_FROM_ISR
tmrCOMMAND_STOP_FROM_ISR
tmrCOMMAND_CHANGE_PERIOD_FROM_ISR
xTimerStart(xTimer, xTicksToWait)
BaseType_t xTimerStart( TimerHandle_t xTimer, TickType_t xTicksToWait );
Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API
functions send commands to the timer service task through a queue called the timer command queue. The
timer command queue is private to the kernel itself and is not directly accessible to application code. The
length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant.
xTimerStart() starts a timer that was previously created using the xTimerCreate() API function. If the timer
had already been started and was already in the active state, then xTimerStart() has equivalent functionality to
the xTimerReset() API function.
Starting a timer ensures the timer is in the active state. If the timer is not stopped, deleted, or reset in the mean
time, the callback function associated with the timer will get called ‘n’ticks after xTimerStart() was called,
where ‘n’is the timers defined period.
It is valid to call xTimerStart() before the scheduler has been started, but when this is done the timer will not
actually start until the scheduler is started, and the timers expiry time will be relative to when the scheduler is
started, not relative to when xTimerStart() was called.
The configUSE_TIMERS configuration constant must be set to 1 for xTimerStart() to be available.
Example usage:
See the xTimerCreate() API function example usage scenario.
Parameters
• xTimer –The handle of the timer being started/restarted.
• xTicksToWait –Specifies the time, in ticks, that the calling task should be held in the
Blocked state to wait for the start command to be successfully sent to the timer command
queue, should the queue already be full when xTimerStart() was called. xTicksToWait is
ignored if xTimerStart() is called before the scheduler is started.
Returns pdFAIL will be returned if the start command could not be sent to the timer command
queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command
was successfully sent to the timer command queue. When the command is actually processed
will depend on the priority of the timer service/daemon task relative to other tasks in the sys-
tem, although the timers expiry time is relative to when xTimerStart() is actually called. The
timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configura-
tion constant.
xTimerStop(xTimer, xTicksToWait)
BaseType_t xTimerStop( TimerHandle_t xTimer, TickType_t xTicksToWait );
Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API
functions send commands to the timer service task through a queue called the timer command queue. The
timer command queue is private to the kernel itself and is not directly accessible to application code. The
length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant.
xTimerStop() stops a timer that was previously started using either of the The xTimerStart(), xTimerReset(),
xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() or xTimerChangePeriodFromISR()
API functions.
Stopping a timer ensures the timer is not in the active state.
The configUSE_TIMERS configuration constant must be set to 1 for xTimerStop() to be available.
Example usage:
See the xTimerCreate() API function example usage scenario.
Parameters
• xTimer –The handle of the timer being stopped.
• xTicksToWait –Specifies the time, in ticks, that the calling task should be held in the
Blocked state to wait for the stop command to be successfully sent to the timer command
queue, should the queue already be full when xTimerStop() was called. xTicksToWait is
ignored if xTimerStop() is called before the scheduler is started.
Returns pdFAIL will be returned if the stop command could not be sent to the timer command
queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command
was successfully sent to the timer command queue. When the command is actually processed
will depend on the priority of the timer service/daemon task relative to other tasks in the sys-
tem. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY
configuration constant.
xTimerChangePeriod(xTimer, xNewPeriod, xTicksToWait)
BaseType_t xTimerChangePeriod( TimerHandle_t xTimer, TickType_t xNewPeriod, TickType_t xTick-
sToWait );
Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API
functions send commands to the timer service task through a queue called the timer command queue. The
timer command queue is private to the kernel itself and is not directly accessible to application code. The
length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant.
xTimerChangePeriod() changes the period of a timer that was previously created using the xTimerCreate()
API function.
xTimerChangePeriod() can be called to change the period of an active or dormant state timer.
The configUSE_TIMERS configuration constant must be set to 1 for xTimerChangePeriod() to be available.
Example usage:
* // This function assumes xTimer has already been created. If the timer
* // referenced by xTimer is already active when it is called, then the timer
* // is deleted. If the timer referenced by xTimer is not active when it is
* // called, then the period of the timer is set to 500ms and the timer is
* // started.
* void vAFunction( TimerHandle_t xTimer )
* {
* if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and␣
,→equivalently "if( xTimerIsTimerActive( xTimer ) )"
* {
* // xTimer is already active - delete it.
* xTimerDelete( xTimer );
* }
* else
* {
* // xTimer is not active, change its period to 500ms. This will also
* // cause the timer to start. Block for a maximum of 100 ticks if the
* // change period command cannot immediately be sent to the timer
* // command queue.
* if( xTimerChangePeriod( xTimer, 500 / portTICK_PERIOD_MS, 100 ) ==␣
,→pdPASS )
* {
* // The command was successfully sent.
* }
* else
* {
* // The command could not be sent, even after waiting for 100␣
,→ticks
Parameters
• xTimer –The handle of the timer that is having its period changed.
• xNewPeriod –The new period for xTimer. Timer periods are specified in tick periods,
so the constant portTICK_PERIOD_MS can be used to convert a time that has been spec-
ified in milliseconds. For example, if the timer must expire after 100 ticks, then xNewPe-
riod should be set to 100. Alternatively, if the timer must expire after 500ms, then xNew-
Period can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ
is less than or equal to 1000.
• xTicksToWait –Specifies the time, in ticks, that the calling task should be held in
the Blocked state to wait for the change period command to be successfully sent to the
timer command queue, should the queue already be full when xTimerChangePeriod() was
called. xTicksToWait is ignored if xTimerChangePeriod() is called before the scheduler
is started.
Returns pdFAIL will be returned if the change period command could not be sent to the timer
command queue even after xTicksToWait ticks had passed. pdPASS will be returned if
the command was successfully sent to the timer command queue. When the command
is actually processed will depend on the priority of the timer service/daemon task relative
to other tasks in the system. The timer service/daemon task priority is set by the config-
TIMER_TASK_PRIORITY configuration constant.
xTimerDelete(xTimer, xTicksToWait)
BaseType_t xTimerDelete( TimerHandle_t xTimer, TickType_t xTicksToWait );
Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API
functions send commands to the timer service task through a queue called the timer command queue. The
timer command queue is private to the kernel itself and is not directly accessible to application code. The
length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant.
xTimerDelete() deletes a timer that was previously created using the xTimerCreate() API function.
The configUSE_TIMERS configuration constant must be set to 1 for xTimerDelete() to be available.
Example usage:
See the xTimerChangePeriod() API function example usage scenario.
Parameters
• xTimer –The handle of the timer being deleted.
• xTicksToWait –Specifies the time, in ticks, that the calling task should be held in the
Blocked state to wait for the delete command to be successfully sent to the timer command
queue, should the queue already be full when xTimerDelete() was called. xTicksToWait
is ignored if xTimerDelete() is called before the scheduler is started.
Returns pdFAIL will be returned if the delete command could not be sent to the timer command
queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command
was successfully sent to the timer command queue. When the command is actually processed
will depend on the priority of the timer service/daemon task relative to other tasks in the sys-
tem. The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY
configuration constant.
xTimerReset(xTimer, xTicksToWait)
BaseType_t xTimerReset( TimerHandle_t xTimer, TickType_t xTicksToWait );
Timer functionality is provided by a timer service/daemon task. Many of the public FreeRTOS timer API
functions send commands to the timer service task through a queue called the timer command queue. The
timer command queue is private to the kernel itself and is not directly accessible to application code. The
length of the timer command queue is set by the configTIMER_QUEUE_LENGTH configuration constant.
xTimerReset() re-starts a timer that was previously created using the xTimerCreate() API function. If the
timer had already been started and was already in the active state, then xTimerReset() will cause the timer
to re-evaluate its expiry time so that it is relative to when xTimerReset() was called. If the timer was in the
dormant state then xTimerReset() has equivalent functionality to the xTimerStart() API function.
Resetting a timer ensures the timer is in the active state. If the timer is not stopped, deleted, or reset in the
mean time, the callback function associated with the timer will get called ‘n’ticks after xTimerReset() was
called, where ‘n’is the timers defined period.
It is valid to call xTimerReset() before the scheduler has been started, but when this is done the timer will not
actually start until the scheduler is started, and the timers expiry time will be relative to when the scheduler is
started, not relative to when xTimerReset() was called.
The configUSE_TIMERS configuration constant must be set to 1 for xTimerReset() to be available.
Example usage:
* // When a key is pressed, an LCD back-light is switched on. If 5 seconds␣
,→pass
* // without a key being pressed, then the LCD back-light is switched off. In
* // this case, the timer is a one-shot timer.
*
* TimerHandle_t xBacklightTimer = NULL;
*
* // The callback function assigned to the one-shot timer. In this case the
* // parameter is not used.
* void vBacklightTimerCallback( TimerHandle_t pxTimer )
* {
* // The timer expired, therefore 5 seconds must have passed since a key
* // was pressed. Switch off the LCD back-light.
* vSetBacklightState( BACKLIGHT_OFF );
* }
*
* // The key press event handler.
* void vKeyPressEventHandler( char cKey )
* {
* // Ensure the LCD back-light is on, then reset the timer that is
* // responsible for turning the back-light off after 5 seconds of
* // key inactivity. Wait 10 ticks for the command to be successfully sent
* // if it cannot be sent immediately.
* vSetBacklightState( BACKLIGHT_ON );
* if( xTimerReset( xBacklightTimer, 100 ) != pdPASS )
* {
* // The reset command was not executed successfully. Take appropriate
* // action here.
* }
*
* // Perform the rest of the key processing here.
* }
*
* void main( void )
* {
* int32_t x;
*
* // Create then start the one-shot timer that is responsible for turning
* // the back-light off if no keys are pressed within a 5 second period.
* xBacklightTimer = xTimerCreate( "BacklightTimer", // Just a␣
,→text name, not used by the kernel.
* 0, // The id is␣
,→not used by the callback so can take any value.
* vBacklightTimerCallback // The␣
,→callback function that switches the LCD back-light off.
* );
(continues on next page)
Parameters
• xTimer –The handle of the timer being reset/started/restarted.
• xTicksToWait –Specifies the time, in ticks, that the calling task should be held in the
Blocked state to wait for the reset command to be successfully sent to the timer command
queue, should the queue already be full when xTimerReset() was called. xTicksToWait is
ignored if xTimerReset() is called before the scheduler is started.
Returns pdFAIL will be returned if the reset command could not be sent to the timer command
queue even after xTicksToWait ticks had passed. pdPASS will be returned if the command
was successfully sent to the timer command queue. When the command is actually processed
will depend on the priority of the timer service/daemon task relative to other tasks in the sys-
tem, although the timers expiry time is relative to when xTimerStart() is actually called. The
timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configura-
tion constant.
xTimerStartFromISR(xTimer, pxHigherPriorityTaskWoken)
BaseType_t xTimerStartFromISR( TimerHandle_t xTimer, BaseType_t *pxHigherPriorityTaskWoken );
A version of xTimerStart() that can be called from an interrupt service routine.
Example usage:
* {
* // The start command was not executed successfully. Take appropriate
* // action here.
* }
*
* // Perform the rest of the key processing here.
*
* // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch
* // should be performed. The syntax required to perform a context switch
* // from inside an ISR varies from port to port, and from compiler to
* // compiler. Inspect the demos for the port you are using to find the
* // actual syntax required.
* if( xHigherPriorityTaskWoken != pdFALSE )
* {
* // Call the interrupt safe yield function here (actual function
* // depends on the FreeRTOS port being used).
* }
* }
*
Parameters
• xTimer –The handle of the timer being started/restarted.
• pxHigherPriorityTaskWoken –The timer service/daemon task spends most of its
time in the Blocked state, waiting for messages to arrive on the timer command queue.
Calling xTimerStartFromISR() writes a message to the timer command queue, so has the
potential to transition the timer service/daemon task out of the Blocked state. If calling
xTimerStartFromISR() causes the timer service/daemon task to leave the Blocked state,
and the timer service/ daemon task has a priority equal to or greater than the currently
executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get
set to pdTRUE internally within the xTimerStartFromISR() function. If xTimerStart-
FromISR() sets this value to pdTRUE then a context switch should be performed before
the interrupt exits.
Returns pdFAIL will be returned if the start command could not be sent to the timer command
queue. pdPASS will be returned if the command was successfully sent to the timer command
queue. When the command is actually processed will depend on the priority of the timer ser-
vice/daemon task relative to other tasks in the system, although the timers expiry time is relative
to when xTimerStartFromISR() is actually called. The timer service/daemon task priority is
set by the configTIMER_TASK_PRIORITY configuration constant.
xTimerStopFromISR(xTimer, pxHigherPriorityTaskWoken)
BaseType_t xTimerStopFromISR( TimerHandle_t xTimer, BaseType_t *pxHigherPriorityTaskWoken );
A version of xTimerStop() that can be called from an interrupt service routine.
Example usage:
* // This scenario assumes xTimer has already been created and started. When
* // an interrupt occurs, the timer should be simply stopped.
*
* // The interrupt service routine that stops the timer.
* void vAnExampleInterruptServiceRoutine( void )
* {
* BaseType_t xHigherPriorityTaskWoken = pdFALSE;
*
* // The interrupt has occurred - simply stop the timer.
* // xHigherPriorityTaskWoken was set to pdFALSE where it was defined
* // (within this function). As this is an interrupt service routine, only
* // FreeRTOS API functions that end in "FromISR" can be used.
* if( xTimerStopFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS )
* {
* // The stop command was not executed successfully. Take appropriate
* // action here.
* }
*
* // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch
* // should be performed. The syntax required to perform a context switch
* // from inside an ISR varies from port to port, and from compiler to
* // compiler. Inspect the demos for the port you are using to find the
* // actual syntax required.
* if( xHigherPriorityTaskWoken != pdFALSE )
* {
* // Call the interrupt safe yield function here (actual function
* // depends on the FreeRTOS port being used).
* }
* }
*
Parameters
• xTimer –The handle of the timer being stopped.
• pxHigherPriorityTaskWoken –The timer service/daemon task spends most of its
time in the Blocked state, waiting for messages to arrive on the timer command queue.
Calling xTimerStopFromISR() writes a message to the timer command queue, so has the
potential to transition the timer service/daemon task out of the Blocked state. If call-
ing xTimerStopFromISR() causes the timer service/daemon task to leave the Blocked
state, and the timer service/ daemon task has a priority equal to or greater than the cur-
rently executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken
will get set to pdTRUE internally within the xTimerStopFromISR() function. If xTimer-
StopFromISR() sets this value to pdTRUE then a context switch should be performed
before the interrupt exits.
Returns pdFAIL will be returned if the stop command could not be sent to the timer command
queue. pdPASS will be returned if the command was successfully sent to the timer command
queue. When the command is actually processed will depend on the priority of the timer ser-
vice/daemon task relative to other tasks in the system. The timer service/daemon task priority
is set by the configTIMER_TASK_PRIORITY configuration constant.
Example usage:
* // This scenario assumes xTimer has already been created and started. When
* // an interrupt occurs, the period of xTimer should be changed to 500ms.
*
* // The interrupt service routine that changes the period of xTimer.
* void vAnExampleInterruptServiceRoutine( void )
* {
* BaseType_t xHigherPriorityTaskWoken = pdFALSE;
*
* // The interrupt has occurred - change the period of xTimer to 500ms.
* // xHigherPriorityTaskWoken was set to pdFALSE where it was defined
* // (within this function). As this is an interrupt service routine, only
* // FreeRTOS API functions that end in "FromISR" can be used.
* if( xTimerChangePeriodFromISR( xTimer, &xHigherPriorityTaskWoken ) !=␣
,→pdPASS )
* {
* // The command to change the timers period was not executed
* // successfully. Take appropriate action here.
* }
*
* // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch
* // should be performed. The syntax required to perform a context switch
* // from inside an ISR varies from port to port, and from compiler to
* // compiler. Inspect the demos for the port you are using to find the
* // actual syntax required.
* if( xHigherPriorityTaskWoken != pdFALSE )
* {
* // Call the interrupt safe yield function here (actual function
* // depends on the FreeRTOS port being used).
* }
* }
*
Parameters
• xTimer –The handle of the timer that is having its period changed.
• xNewPeriod –The new period for xTimer. Timer periods are specified in tick periods,
so the constant portTICK_PERIOD_MS can be used to convert a time that has been spec-
ified in milliseconds. For example, if the timer must expire after 100 ticks, then xNewPe-
riod should be set to 100. Alternatively, if the timer must expire after 500ms, then xNew-
Period can be set to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ
is less than or equal to 1000.
• pxHigherPriorityTaskWoken –The timer service/daemon task spends most of its
time in the Blocked state, waiting for messages to arrive on the timer command queue.
Calling xTimerChangePeriodFromISR() writes a message to the timer command queue,
so has the potential to transition the timer service/ daemon task out of the Blocked state.
If calling xTimerChangePeriodFromISR() causes the timer service/daemon task to leave
the Blocked state, and the timer service/daemon task has a priority equal to or greater
than the currently executing task (the task that was interrupted), then *pxHigherPriority-
TaskWoken will get set to pdTRUE internally within the xTimerChangePeriodFromISR()
function. If xTimerChangePeriodFromISR() sets this value to pdTRUE then a context
switch should be performed before the interrupt exits.
Returns pdFAIL will be returned if the command to change the timers period could not be sent
to the timer command queue. pdPASS will be returned if the command was successfully sent
to the timer command queue. When the command is actually processed will depend on the
priority of the timer service/daemon task relative to other tasks in the system. The timer ser-
vice/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration con-
stant.
xTimerResetFromISR(xTimer, pxHigherPriorityTaskWoken)
BaseType_t xTimerResetFromISR( TimerHandle_t xTimer, BaseType_t *pxHigherPriorityTaskWoken );
A version of xTimerReset() that can be called from an interrupt service routine.
Example usage:
* // This scenario assumes xBacklightTimer has already been created. When a
* // key is pressed, an LCD back-light is switched on. If 5 seconds pass
* // without a key being pressed, then the LCD back-light is switched off. In
* // this case, the timer is a one-shot timer, and unlike the example given for
* // the xTimerReset() function, the key press event handler is an interrupt
* // service routine.
*
* // The callback function assigned to the one-shot timer. In this case the
* // parameter is not used.
* void vBacklightTimerCallback( TimerHandle_t pxTimer )
* {
* // The timer expired, therefore 5 seconds must have passed since a key
* // was pressed. Switch off the LCD back-light.
* vSetBacklightState( BACKLIGHT_OFF );
* }
*
* // The key press interrupt service routine.
* void vKeyPressEventInterruptHandler( void )
* {
* BaseType_t xHigherPriorityTaskWoken = pdFALSE;
*
* // Ensure the LCD back-light is on, then reset the timer that is
* // responsible for turning the back-light off after 5 seconds of
* // key inactivity. This is an interrupt service routine so can only
* // call FreeRTOS API functions that end in "FromISR".
* vSetBacklightState( BACKLIGHT_ON );
*
* // xTimerStartFromISR() or xTimerResetFromISR() could be called here
* // as both cause the timer to re-calculate its expiry time.
* // xHigherPriorityTaskWoken was initialised to pdFALSE when it was
* // declared (in this function).
* if( xTimerResetFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) !=␣
,→pdPASS )
* {
* // The reset command was not executed successfully. Take appropriate
* // action here.
* }
*
* // Perform the rest of the key processing here.
*
* // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch
* // should be performed. The syntax required to perform a context switch
* // from inside an ISR varies from port to port, and from compiler to
* // compiler. Inspect the demos for the port you are using to find the
* // actual syntax required.
* if( xHigherPriorityTaskWoken != pdFALSE )
* {
* // Call the interrupt safe yield function here (actual function
* // depends on the FreeRTOS port being used).
(continues on next page)
Parameters
• xTimer –The handle of the timer that is to be started, reset, or restarted.
• pxHigherPriorityTaskWoken –The timer service/daemon task spends most of its
time in the Blocked state, waiting for messages to arrive on the timer command queue.
Calling xTimerResetFromISR() writes a message to the timer command queue, so has the
potential to transition the timer service/daemon task out of the Blocked state. If calling
xTimerResetFromISR() causes the timer service/daemon task to leave the Blocked state,
and the timer service/ daemon task has a priority equal to or greater than the currently
executing task (the task that was interrupted), then *pxHigherPriorityTaskWoken will get
set to pdTRUE internally within the xTimerResetFromISR() function. If xTimerReset-
FromISR() sets this value to pdTRUE then a context switch should be performed before
the interrupt exits.
Returns pdFAIL will be returned if the reset command could not be sent to the timer command
queue. pdPASS will be returned if the command was successfully sent to the timer command
queue. When the command is actually processed will depend on the priority of the timer
service/daemon task relative to other tasks in the system, although the timers expiry time is
relative to when xTimerResetFromISR() is actually called. The timer service/daemon task
priority is set by the configTIMER_TASK_PRIORITY configuration constant.
Type Definitions
Header File
• components/freertos/FreeRTOS-Kernel/include/freertos/event_groups.h
Functions
EventGroupHandle_t xEventGroupCreate(void)
Create a new event group.
Internally, within the FreeRTOS implementation, event groups use a [small] block of memory, in which
the event group’s structure is stored. If an event groups is created using xEventGroupCreate() then the
required memory is automatically dynamically allocated inside the xEventGroupCreate() function. (see
https://www.FreeRTOS.org/a00111.html). If an event group is created using xEventGroupCreateStatic() then
the application writer must instead provide the memory that will get used by the event group. xEventGroupCre-
ateStatic() therefore allows an event group to be created without using any dynamic memory allocation.
Although event groups are not related to ticks, for internal implementation reasons the number of bits avail-
able for use in an event group is dependent on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h.
If configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit 0 to bit 7). If confi-
gUSE_16_BIT_TICKS is set to 0 then each event group has 24 usable bits (bit 0 to bit 23). The EventBits_t
type is used to store event bits within an event group.
Example usage:
Returns If the event group was created then a handle to the event group is returned. If there was
insufficient FreeRTOS heap available to create the event group then NULL is returned. See
https://www.FreeRTOS.org/a00111.html
EventGroupHandle_t xEventGroupCreateStatic(StaticEventGroup_t *pxEventGroupBuffer)
Create a new event group.
Internally, within the FreeRTOS implementation, event groups use a [small] block of memory, in which
the event group’s structure is stored. If an event groups is created using xEventGroupCreate() then the
required memory is automatically dynamically allocated inside the xEventGroupCreate() function. (see
https://www.FreeRTOS.org/a00111.html). If an event group is created using xEventGroupCreateStatic() then
the application writer must instead provide the memory that will get used by the event group. xEventGroupCre-
ateStatic() therefore allows an event group to be created without using any dynamic memory allocation.
Although event groups are not related to ticks, for internal implementation reasons the number of bits avail-
able for use in an event group is dependent on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h.
If configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit 0 to bit 7). If confi-
gUSE_16_BIT_TICKS is set to 0 then each event group has 24 usable bits (bit 0 to bit 23). The EventBits_t
type is used to store event bits within an event group.
Example usage:
Example usage:
Parameters
• xEventGroup –The event group in which the bits are being tested. The event group
must have previously been created using a call to xEventGroupCreate().
• uxBitsToWaitFor –A bitwise value that indicates the bit or bits to test inside the event
group. For example, to wait for bit 0 and/or bit 2 set uxBitsToWaitFor to 0x05. To wait
for bits 0 and/or bit 1 and/or bit 2 set uxBitsToWaitFor to 0x07. Etc.
• xClearOnExit –If xClearOnExit is set to pdTRUE then any bits within uxBitsToWait-
For that are set within the event group will be cleared before xEventGroupWaitBits() re-
turns if the wait condition was met (if the function returns for a reason other than a time-
out). If xClearOnExit is set to pdFALSE then the bits set in the event group are not altered
when the call to xEventGroupWaitBits() returns.
Example usage:
#define BIT_0 ( 1 << 0 )
#define BIT_4 ( 1 << 4 )
Parameters
• xEventGroup –The event group in which the bits are to be cleared.
• uxBitsToClear –A bitwise value that indicates the bit or bits to clear in the event
group. For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 and bit
0 set uxBitsToClear to 0x09.
Returns The value of the event group before the specified bits were cleared.
Example usage:
Parameters
• xEventGroup –The event group in which the bits are to be set.
• uxBitsToSet –A bitwise value that indicates the bit or bits to set. For example, to set
bit 3 only, set uxBitsToSet to 0x08. To set bit 3 and bit 0 set uxBitsToSet to 0x09.
Returns The value of the event group at the time the call to xEventGroupSetBits() returns. There
are two reasons why the returned value might have the bits specified by the uxBitsToSet pa-
rameter cleared. First, if setting a bit results in a task that was waiting for the bit leaving the
blocked state then it is possible the bit will be cleared automatically (see the xClearBitOnExit
parameter of xEventGroupWaitBits()). Second, any unblocked (or otherwise Ready state) task
that has a priority above that of the task that called xEventGroupSetBits() will execute and may
change the event group value before the call to xEventGroupSetBits() returns.
Atomically set bits within an event group, then wait for a combination of bits to be set within the same event
group. This functionality is typically used to synchronise multiple tasks, where each task has to wait for the
other tasks to reach a synchronisation point before proceeding.
This function cannot be used from an interrupt.
The function will return before its block time expires if the bits specified by the uxBitsToWait parameter are
set, or become set within that time. In this case all the bits specified by uxBitsToWait will be automatically
cleared before the function returns.
Example usage:
// Bits used by the three tasks.
#define TASK_0_BIT ( 1 << 0 )
#define TASK_1_BIT ( 1 << 1 )
#define TASK_2_BIT ( 1 << 2 )
for( ;; )
{
// Perform task functionality here.
// Set bit 0 in the event flag to note this task has reached the
// sync point. The other two tasks will set the other two bits defined
// by ALL_SYNC_BITS. All three tasks have reached the synchronisation
// point when all the ALL_SYNC_BITS are set. Wait a maximum of 100ms
// for this to happen.
uxReturn = xEventGroupSync( xEventBits, TASK_0_BIT, ALL_SYNC_BITS,␣
,→xTicksToWait );
// Set bit 1 in the event flag to note this task has reached the
// synchronisation point. The other two tasks will set the other two
// bits defined by ALL_SYNC_BITS. All three tasks have reached the
// synchronisation point when all the ALL_SYNC_BITS are set. Wait
// indefinitely for this to happen.
xEventGroupSync( xEventBits, TASK_1_BIT, ALL_SYNC_BITS, portMAX_DELAY );
// Set bit 2 in the event flag to note this task has reached the
// synchronisation point. The other two tasks will set the other two
// bits defined by ALL_SYNC_BITS. All three tasks have reached the
// synchronisation point when all the ALL_SYNC_BITS are set. Wait
// indefinitely for this to happen.
xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY );
Parameters
• xEventGroup –The event group in which the bits are being tested. The event group
must have previously been created using a call to xEventGroupCreate().
• uxBitsToSet –The bits to set in the event group before determining if, and possibly
waiting for, all the bits specified by the uxBitsToWait parameter are set.
• uxBitsToWaitFor –A bitwise value that indicates the bit or bits to test inside the event
group. For example, to wait for bit 0 and bit 2 set uxBitsToWaitFor to 0x05. To wait for
bits 0 and bit 1 and bit 2 set uxBitsToWaitFor to 0x07. Etc.
• xTicksToWait –The maximum amount of time (specified in ‘ticks’) to wait for all
of the bits specified by uxBitsToWaitFor to become set.
Returns The value of the event group at the time either the bits being waited for became set, or
the block time expired. Test the return value to know which bits were set. If xEventGroup-
Sync() returned because its timeout expired then not all the bits being waited for will be set. If
xEventGroupSync() returned because all the bits it was waiting for were set then the returned
value is the event group value before any bits were automatically cleared.
Macros
xEventGroupClearBitsFromISR(xEventGroup, uxBitsToClear)
A version of xEventGroupClearBits() that can be called from an interrupt.
Setting bits in an event group is not a deterministic operation because there are an unknown number of tasks
that may be waiting for the bit or bits being set. FreeRTOS does not allow nondeterministic operations to be
performed while interrupts are disabled, so protects event groups that are accessed from tasks by suspending
the scheduler rather than disabling interrupts. As a result event groups cannot be accessed directly from an
interrupt service routine. Therefore xEventGroupClearBitsFromISR() sends a message to the timer task to
have the clear operation performed in the context of the timer task.
Example usage:
#define BIT_0 ( 1 << 0 )
#define BIT_4 ( 1 << 4 )
Parameters
• xEventGroup –The event group in which the bits are to be cleared.
• uxBitsToClear –A bitwise value that indicates the bit or bits to clear. For example,
to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 and bit 0 set uxBitsToClear
to 0x09.
Returns If the request to execute the function was posted successfully then pdPASS is returned,
otherwise pdFALSE is returned. pdFALSE will be returned if the timer service queue was
full.
xEventGroupSetBitsFromISR(xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken)
A version of xEventGroupSetBits() that can be called from an interrupt.
Setting bits in an event group is not a deterministic operation because there are an unknown number of tasks
that may be waiting for the bit or bits being set. FreeRTOS does not allow nondeterministic operations to be
performed in interrupts or from critical sections. Therefore xEventGroupSetBitsFromISR() sends a message
to the timer task to have the set operation performed in the context of the timer task - where a scheduler lock
is used in place of a critical section.
Example usage:
#define BIT_0 ( 1 << 0 )
#define BIT_4 ( 1 << 4 )
Parameters
• xEventGroup –The event group in which the bits are to be set.
• uxBitsToSet –A bitwise value that indicates the bit or bits to set. For example, to set
bit 3 only, set uxBitsToSet to 0x08. To set bit 3 and bit 0 set uxBitsToSet to 0x09.
• pxHigherPriorityTaskWoken –As mentioned above, calling this function will re-
sult in a message being sent to the timer daemon task. If the priority of the timer daemon
task is higher than the priority of the currently running task (the task the interrupt inter-
rupted) then *pxHigherPriorityTaskWoken will be set to pdTRUE by xEventGroupSet-
BitsFromISR(), indicating that a context switch should be requested before the interrupt
exits. For that reason *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See
the example code below.
Returns If the request to execute the function was posted successfully then pdPASS is returned,
otherwise pdFALSE is returned. pdFALSE will be returned if the timer service queue was
full.
xEventGroupGetBits(xEventGroup)
Returns the current value of the bits in an event group. This function cannot be used from an interrupt.
Parameters
• xEventGroup –The event group being queried.
Returns The event group bits at the time xEventGroupGetBits() was called.
Type Definitions
Header File
• components/freertos/FreeRTOS-Kernel/include/freertos/stream_buffer.h
Functions
size_t xStreamBufferSend(StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t
xDataLengthBytes, TickType_t xTicksToWait)
Sends bytes to a stream buffer. The bytes are copied into the stream buffer.
: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implemen-
tation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that
will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It
is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not
safe to have multiple different writers or multiple different readers. If there are to be multiple different writers
then the application writer must place each call to a writing API function (such as xStreamBufferSend()) inside
a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then
the application writer must place each call to a reading API function (such as xStreamBufferReceive()) inside
a critical section and set the receive block time to 0.
Use xStreamBufferSend() to write to a stream buffer from a task. Use xStreamBufferSendFromISR() to write
to a stream buffer from an interrupt service routine (ISR).
Example use:
// Send the string to the stream buffer. Return immediately if there is not
// enough space in the buffer.
xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) pcStringToSend,␣
,→strlen( pcStringToSend ), 0 );
Parameters
• xStreamBuffer –The handle of the stream buffer to which a stream is being sent.
• pvTxData –A pointer to the buffer that holds the bytes to be copied into the stream
buffer.
• xDataLengthBytes –The maximum number of bytes to copy from pvTxData into the
stream buffer.
• xTicksToWait –The maximum amount of time the task should remain in the Blocked
state to wait for enough space to become available in the stream buffer, should the
stream buffer contain too little space to hold the another xDataLengthBytes bytes. The
block time is specified in tick periods, so the absolute time it represents is dependent
on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time
specified in milliseconds into a time specified in ticks. Setting xTicksToWait to port-
MAX_DELAY will cause the task to wait indefinitely (without timing out), provided IN-
CLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. If a task times out before it can
write all xDataLengthBytes into the buffer it will still write as many bytes as possible. A
task does not use any CPU time when it is in the blocked state.
Returns The number of bytes written to the stream buffer. If a task times out before it can write
all xDataLengthBytes into the buffer it will still write as many bytes as possible.
size_t xStreamBufferSendFromISR(StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t
xDataLengthBytes, BaseType_t *const pxHigherPriorityTaskWoken)
Interrupt safe version of the API function that sends a stream of bytes to the stream buffer.
: Uniquely among FreeRTOS objects, the stream buffer implementation (so also the message buffer implemen-
tation, as message buffers are built on top of stream buffers) assumes there is only one task or interrupt that
will write to the buffer (the writer), and only one task or interrupt that will read from the buffer (the reader). It
is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not
safe to have multiple different writers or multiple different readers. If there are to be multiple different writers
then the application writer must place each call to a writing API function (such as xStreamBufferSend()) inside
a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers then
the application writer must place each call to a reading API function (such as xStreamBufferReceive()) inside
a critical section and set the receive block time to 0.
Use xStreamBufferSend() to write to a stream buffer from a task. Use xStreamBufferSendFromISR() to write
to a stream buffer from an interrupt service routine (ISR).
Example use:
// A stream buffer that has already been created.
StreamBufferHandle_t xStreamBuffer;
Parameters
• xStreamBuffer –The handle of the stream buffer to which a stream is being sent.
• pvTxData –A pointer to the data that is to be copied into the stream buffer.
• xDataLengthBytes –The maximum number of bytes to copy from pvTxData into the
stream buffer.
• pxHigherPriorityTaskWoken –It is possible that a stream buffer will have a task
blocked on it waiting for data. Calling xStreamBufferSendFromISR() can make data avail-
able, and so cause a task that was waiting for data to leave the Blocked state. If calling
xStreamBufferSendFromISR() causes a task to leave the Blocked state, and the unblocked
task has a priority higher than the currently executing task (the task that was interrupted),
then, internally, xStreamBufferSendFromISR() will set *pxHigherPriorityTaskWoken to
pdTRUE. If xStreamBufferSendFromISR() sets this value to pdTRUE, then normally a
context switch should be performed before the interrupt is exited. This will ensure that
the interrupt returns directly to the highest priority Ready state task. *pxHigherPriori-
tyTaskWoken should be set to pdFALSE before it is passed into the function. See the
example code below for an example.
Returns The number of bytes actually written to the stream buffer, which will be less than xDataL-
engthBytes if the stream buffer didn’t have enough free space for all the bytes to be written.
Example use:
Parameters
• xStreamBuffer –The handle of the stream buffer from which bytes are to be received.
• pvRxData –A pointer to the buffer into which the received bytes will be copied.
• xBufferLengthBytes –The length of the buffer pointed to by the pvRxData parame-
ter. This sets the maximum number of bytes to receive in one call. xStreamBufferReceive
will return as many bytes as possible up to a maximum set by xBufferLengthBytes.
• xTicksToWait –The maximum amount of time the task should remain in the Blocked
state to wait for data to become available if the stream buffer is empty. xStreamBuffer-
Receive() will return immediately if xTicksToWait is zero. The block time is specified in
tick periods, so the absolute time it represents is dependent on the tick frequency. The
macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a
time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to
wait indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in
FreeRTOSConfig.h. A task does not use any CPU time when it is in the Blocked state.
Returns The number of bytes actually read from the stream buffer, which will be less than xBuffer-
LengthBytes if the call to xStreamBufferReceive() timed out before xBufferLengthBytes were
available.
Example use:
Parameters
• xStreamBuffer –The handle of the stream buffer from which a stream is being re-
ceived.
• pvRxData –A pointer to the buffer into which the received bytes are copied.
• xBufferLengthBytes –The length of the buffer pointed to by the pvRxData parame-
ter. This sets the maximum number of bytes to receive in one call. xStreamBufferReceive
will return as many bytes as possible up to a maximum set by xBufferLengthBytes.
• pxHigherPriorityTaskWoken –It is possible that a stream buffer will have a task
blocked on it waiting for space to become available. Calling xStreamBufferReceive-
FromISR() can make space available, and so cause a task that is waiting for space to leave
the Blocked state. If calling xStreamBufferReceiveFromISR() causes a task to leave the
Blocked state, and the unblocked task has a priority higher than the currently executing
task (the task that was interrupted), then, internally, xStreamBufferReceiveFromISR()
will set *pxHigherPriorityTaskWoken to pdTRUE. If xStreamBufferReceiveFromISR()
sets this value to pdTRUE, then normally a context switch should be performed before the
interrupt is exited. That will ensure the interrupt returns directly to the highest priority
Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is
passed into the function. See the code example below for an example.
Returns The number of bytes read from the stream buffer, if any.
• xStreamBuffer –The handle of the stream buffer from which data was read.
• pxHigherPriorityTaskWoken –*pxHigherPriorityTaskWoken should be ini-
tialised to pdFALSE before it is passed into xStreamBufferReceiveCompletedFromISR().
If calling xStreamBufferReceiveCompletedFromISR() removes a task from the Blocked
state, and the task has a priority above the priority of the currently running task, then *px-
HigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should
be performed before exiting the ISR.
Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise
pdFALSE is returned.
Macros
xStreamBufferCreate(xBufferSizeBytes, xTriggerLevelBytes)
Creates a new stream buffer using dynamically allocated memory. See xStreamBufferCreateStatic() for a ver-
sion that uses statically allocated memory (memory that is allocated at compile time).
configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in FreeRTOSConfig.h for
xStreamBufferCreate() to be available.
Example use:
// Create a stream buffer that can hold 100 bytes. The memory used to hold
// both the stream buffer structure and the data in the stream buffer is
// allocated dynamically.
xStreamBuffer = xStreamBufferCreate( xStreamBufferSizeBytes, xTriggerLevel );
Parameters
• xBufferSizeBytes –The total number of bytes the stream buffer will be able to hold
at any one time.
• xTriggerLevelBytes –The number of bytes that must be in the stream buffer before
a task that is blocked on the stream buffer to wait for data is moved out of the blocked state.
For example, if a task is blocked on a read of an empty stream buffer that has a trigger
level of 1 then the task will be unblocked when a single byte is written to the buffer or
the task’s block time expires. As another example, if a task is blocked on a read of an
empty stream buffer that has a trigger level of 10 then the task will not be unblocked until
the stream buffer contains at least 10 bytes or the task’s block time expires. If a reading
task’s block time expires before the trigger level is reached then the task will still receive
however many bytes are actually available. Setting a trigger level of 0 will result in a trigger
level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer
size.
Returns If NULL is returned, then the stream buffer cannot be created because there is insufficient
heap memory available for FreeRTOS to allocate the stream buffer data structures and storage
area. A non-NULL value being returned indicates that the stream buffer has been created
successfully - the returned value should be stored as the handle to the created stream buffer.
xStreamBufferCreateStatic(xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea,
pxStaticStreamBuffer)
Creates a new stream buffer using statically allocated memory. See xStreamBufferCreate() for a version that
uses dynamically allocated memory.
configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h for xStreamBufferCreat-
eStatic() to be available.
Example use:
// Used to dimension the array used to hold the streams. The available space
// will actually be one less than this, so 999.
#define STORAGE_SIZE_BYTES 1000
// Defines the memory that will actually hold the streams within the stream
// buffer.
static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ];
Parameters
• xBufferSizeBytes –The size, in bytes, of the buffer pointed to by the pucStream-
BufferStorageArea parameter.
• xTriggerLevelBytes –The number of bytes that must be in the stream buffer before
a task that is blocked on the stream buffer to wait for data is moved out of the blocked state.
For example, if a task is blocked on a read of an empty stream buffer that has a trigger
level of 1 then the task will be unblocked when a single byte is written to the buffer or
the task’s block time expires. As another example, if a task is blocked on a read of an
empty stream buffer that has a trigger level of 10 then the task will not be unblocked until
the stream buffer contains at least 10 bytes or the task’s block time expires. If a reading
task’s block time expires before the trigger level is reached then the task will still receive
however many bytes are actually available. Setting a trigger level of 0 will result in a trigger
level of 1 being used. It is not valid to specify a trigger level that is greater than the buffer
size.
• pucStreamBufferStorageArea –Must point to a uint8_t array that is at least
xBufferSizeBytes + 1 big. This is the array to which streams are copied when they are
written to the stream buffer.
• pxStaticStreamBuffer –Must point to a variable of type StaticStreamBuffer_t,
which will be used to hold the stream buffer’s data structure.
Returns If the stream buffer is created successfully then a handle to the created stream buffer
is returned. If either pucStreamBufferStorageArea or pxStaticstreamBuffer are NULL then
NULL is returned.
Type Definitions
Header File
• components/freertos/FreeRTOS-Kernel/include/freertos/message_buffer.h
Macros
xMessageBufferCreate(xBufferSizeBytes)
Creates a new message buffer using dynamically allocated memory. See xMessageBufferCreateStatic() for a
version that uses statically allocated memory (memory that is allocated at compile time).
configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in FreeRTOSConfig.h for
xMessageBufferCreate() to be available.
Example use:
// Create a message buffer that can hold 100 bytes. The memory used to hold
// both the message buffer structure and the messages themselves is allocated
// dynamically. Each message added to the buffer consumes an additional 4
// bytes which are used to hold the lengh of the message.
xMessageBuffer = xMessageBufferCreate( xMessageBufferSizeBytes );
Parameters
• xBufferSizeBytes –The total number of bytes (not messages) the message buffer
will be able to hold at any one time. When a message is written to the message buffer an
additional sizeof( size_t ) bytes are also written to store the message’s length. sizeof(
size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architectures a 10
byte message will take up 14 bytes of message buffer space.
Returns If NULL is returned, then the message buffer cannot be created because there is insuffi-
cient heap memory available for FreeRTOS to allocate the message buffer data structures and
storage area. A non-NULL value being returned indicates that the message buffer has been
created successfully - the returned value should be stored as the handle to the created message
buffer.
xMessageBufferCreateStatic(xBufferSizeBytes, pucMessageBufferStorageArea,
pxStaticMessageBuffer)
Creates a new message buffer using statically allocated memory. See xMessageBufferCreate() for a version
that uses dynamically allocated memory.
Example use:
// Used to dimension the array used to hold the messages. The available space
// will actually be one less than this, so 999.
#define STORAGE_SIZE_BYTES 1000
// Defines the memory that will actually hold the messages within the message
// buffer.
static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ];
Parameters
• xBufferSizeBytes –The size, in bytes, of the buffer pointed to by the pucMessage-
BufferStorageArea parameter. When a message is written to the message buffer an addi-
tional sizeof( size_t ) bytes are also written to store the message’s length. sizeof( size_t
) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture a 10 byte
message will take up 14 bytes of message buffer space. The maximum number of bytes
that can be stored in the message buffer is actually (xBufferSizeBytes - 1).
• pucMessageBufferStorageArea –Must point to a uint8_t array that is at least
xBufferSizeBytes + 1 big. This is the array to which messages are copied when they are
written to the message buffer.
• pxStaticMessageBuffer –Must point to a variable of type StaticMessageBuffer_t,
which will be used to hold the message buffer’s data structure.
Returns If the message buffer is created successfully then a handle to the created message buffer
is returned. If either pucMessageBufferStorageArea or pxStaticmessageBuffer are NULL then
NULL is returned.
inside a critical section and set the send block time to 0. Likewise, if there are to be multiple different readers
then the application writer must place each call to a reading API function (such as xMessageBufferRead())
inside a critical section and set the receive block time to 0.
Use xMessageBufferSend() to write to a message buffer from a task. Use xMessageBufferSendFromISR() to
write to a message buffer from an interrupt service routine (ISR).
Example use:
Parameters
• xMessageBuffer –The handle of the message buffer to which a message is being sent.
• pvTxData –A pointer to the message that is to be copied into the message buffer.
• xDataLengthBytes –The length of the message. That is, the number of bytes to copy
from pvTxData into the message buffer. When a message is written to the message buffer
an additional sizeof( size_t ) bytes are also written to store the message’s length. sizeof(
size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture setting
xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 bytes (20
bytes of message data and 4 bytes to hold the message length).
• xTicksToWait –The maximum amount of time the calling task should remain in the
Blocked state to wait for enough space to become available in the message buffer, should
the message buffer have insufficient space when xMessageBufferSend() is called. The
calling task will never block if xTicksToWait is zero. The block time is specified in tick
periods, so the absolute time it represents is dependent on the tick frequency. The macro
pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into a time
specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait
indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeR-
TOSConfig.h. Tasks do not use any CPU time when they are in the Blocked state.
Returns The number of bytes written to the message buffer. If the call to xMessageBufferSend()
times out before there was enough space to write the message into the message buffer then zero
is returned. If the call did not time out then xDataLengthBytes is returned.
Example use:
Parameters
• xMessageBuffer –The handle of the message buffer to which a message is being sent.
• pvTxData –A pointer to the message that is to be copied into the message buffer.
• xDataLengthBytes –The length of the message. That is, the number of bytes to copy
from pvTxData into the message buffer. When a message is written to the message buffer
an additional sizeof( size_t ) bytes are also written to store the message’s length. sizeof(
size_t ) is typically 4 bytes on a 32-bit architecture, so on most 32-bit architecture setting
xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 bytes (20
Example use:
// Receive the next message from the message buffer. Wait in the Blocked
// state (so not using any CPU processing time) for a maximum of 100ms for
// a message to become available.
xReceivedBytes = xMessageBufferReceive( xMessageBuffer,
( void * ) ucRxData,
sizeof( ucRxData ),
xBlockTime );
Parameters
• xMessageBuffer –The handle of the message buffer from which a message is being
received.
• pvRxData –A pointer to the buffer into which the received message is to be copied.
• xBufferLengthBytes –The length of the buffer pointed to by the pvRxData parame-
ter. This sets the maximum length of the message that can be received. If xBufferLength-
Bytes is too small to hold the next message then the message will be left in the message
buffer and 0 will be returned.
• xTicksToWait –The maximum amount of time the task should remain in the Blocked
state to wait for a message, should the message buffer be empty. xMessageBufferReceive()
will return immediately if xTicksToWait is zero and the message buffer is empty. The
block time is specified in tick periods, so the absolute time it represents is dependent
on the tick frequency. The macro pdMS_TO_TICKS() can be used to convert a time
specified in milliseconds into a time specified in ticks. Setting xTicksToWait to port-
MAX_DELAY will cause the task to wait indefinitely (without timing out), provided IN-
CLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any CPU time
when they are in the Blocked state.
Returns The length, in bytes, of the message read from the message buffer, if any. If xMessage-
BufferReceive() times out before a message became available then zero is returned. If the
length of the message is greater than xBufferLengthBytes then the message will be left in the
message buffer and zero is returned.
Example use:
// A message buffer that has already been created.
MessageBuffer_t xMessageBuffer;
Parameters
• xMessageBuffer –The handle of the message buffer from which a message is being
received.
• pvRxData –A pointer to the buffer into which the received message is to be copied.
• xBufferLengthBytes –The length of the buffer pointed to by the pvRxData parame-
ter. This sets the maximum length of the message that can be received. If xBufferLength-
Bytes is too small to hold the next message then the message will be left in the message
buffer and 0 will be returned.
• pxHigherPriorityTaskWoken –It is possible that a message buffer will have a task
blocked on it waiting for space to become available. Calling xMessageBufferReceive-
FromISR() can make space available, and so cause a task that is waiting for space to leave
the Blocked state. If calling xMessageBufferReceiveFromISR() causes a task to leave the
Blocked state, and the unblocked task has a priority higher than the currently executing
task (the task that was interrupted), then, internally, xMessageBufferReceiveFromISR()
will set *pxHigherPriorityTaskWoken to pdTRUE. If xMessageBufferReceiveFromISR()
sets this value to pdTRUE, then normally a context switch should be performed before the
interrupt is exited. That will ensure the interrupt returns directly to the highest priority
Ready state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is
passed into the function. See the code example below for an example.
Returns The length, in bytes, of the message read from the message buffer, if any.
vMessageBufferDelete(xMessageBuffer)
Deletes a message buffer that was previously created using a call to xMessageBufferCreate() or xMessage-
BufferCreateStatic(). If the message buffer was created using dynamic memory (that is, by xMessageBuffer-
Create()), then the allocated memory is freed.
A message buffer handle must not be used after the message buffer has been deleted.
Parameters
• xMessageBuffer –The handle of the message buffer to be deleted.
xMessageBufferIsFull(xMessageBuffer)
Tests to see if a message buffer is full. A message buffer is full if it cannot accept any more messages, of any
size, until space is made available by a message being removed from the message buffer.
Parameters
• xMessageBuffer –The handle of the message buffer being queried.
Returns If the message buffer referenced by xMessageBuffer is full then pdTRUE is returned.
Otherwise pdFALSE is returned.
xMessageBufferIsEmpty(xMessageBuffer)
Tests to see if a message buffer is empty (does not contain any messages).
Parameters
• xMessageBuffer –The handle of the message buffer being queried.
Returns If the message buffer referenced by xMessageBuffer is empty then pdTRUE is returned.
Otherwise pdFALSE is returned.
xMessageBufferReset(xMessageBuffer)
Resets a message buffer to its initial empty state, discarding any message it contained.
A message buffer can only be reset if there are no tasks blocked on it.
Parameters
• xMessageBuffer –The handle of the message buffer being reset.
Returns If the message buffer was reset then pdPASS is returned. If the message buffer could
not be reset because either there was a task blocked on the message queue to wait for space to
become available, or to wait for a a message to be available, then pdFAIL is returned.
xMessageBufferSpaceAvailable(xMessageBuffer)
Returns the number of bytes of free space in the message buffer.
Parameters
• xMessageBuffer –The handle of the message buffer being queried.
Returns The number of bytes that can be written to the message buffer before the message buffer
would be full. When a message is written to the message buffer an additional sizeof( size_t )
bytes are also written to store the message’s length. sizeof( size_t ) is typically 4 bytes on
a 32-bit architecture, so if xMessageBufferSpacesAvailable() returns 10, then the size of the
largest message that can be written to the message buffer is 6 bytes.
xMessageBufferSpacesAvailable(xMessageBuffer)
xMessageBufferNextLengthBytes(xMessageBuffer)
Returns the length (in bytes) of the next message in a message buffer. Useful if xMessageBufferReceive()
returned 0 because the size of the buffer passed into xMessageBufferReceive() was too small to hold the next
message.
Parameters
• xMessageBuffer –The handle of the message buffer being queried.
Returns The length (in bytes) of the next message in the message buffer, or 0 if the message buffer
is empty.
xMessageBufferSendCompletedFromISR(xMessageBuffer, pxHigherPriorityTaskWoken)
For advanced users only.
The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when data is sent to a message
buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting for data to
arrive then the sbSEND_COMPLETED() macro sends a notification to the task to remove it from the Blocked
state. xMessageBufferSendCompletedFromISR() does the same thing. It is provided to enable application
writers to implement their own version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY
OTHER TIME.
See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information.
Parameters
• xMessageBuffer –The handle of the stream buffer to which data was written.
• pxHigherPriorityTaskWoken –*pxHigherPriorityTaskWoken should be ini-
tialised to pdFALSE before it is passed into xMessageBufferSendCompletedFromISR().
If calling xMessageBufferSendCompletedFromISR() removes a task from the Blocked
state, and the task has a priority above the priority of the currently running task, then *px-
HigherPriorityTaskWoken will get set to pdTRUE indicating that a context switch should
be performed before exiting the ISR.
Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise
pdFALSE is returned.
xMessageBufferReceiveCompletedFromISR(xMessageBuffer, pxHigherPriorityTaskWoken)
For advanced users only.
The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when data is read out of
a message buffer or stream buffer. If there was a task that was blocked on the message or stream buffer waiting
for data to arrive then the sbRECEIVE_COMPLETED() macro sends a notification to the task to remove it
from the Blocked state. xMessageBufferReceiveCompletedFromISR() does the same thing. It is provided to
enable application writers to implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT
BE USED AT ANY OTHER TIME.
See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information.
Parameters
• xMessageBuffer –The handle of the stream buffer from which data was read.
• pxHigherPriorityTaskWoken –*pxHigherPriorityTaskWoken should be ini-
tialised to pdFALSE before it is passed into xMessageBufferReceiveCompleted-
FromISR(). If calling xMessageBufferReceiveCompletedFromISR() removes a task from
the Blocked state, and the task has a priority above the priority of the currently running
task, then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a context
switch should be performed before exiting the ISR.
Returns If a task was removed from the Blocked state then pdTRUE is returned. Otherwise
pdFALSE is returned.
Type Definitions
ESP-IDF uses a modified version of FreeRTOS v10.4.3 that contains significant changes for SMP compatibility (see
ESP-IDF FreeRTOS SMP Changes). However, in addition to ESP-IDF FreeRTOS, various features are also provided
by ESP-IDF to supplement the features offered by FreeRTOS.
This document describes these supplemental features added to ESP-IDF. This document is split into the following
sections:
Contents
Overview
ESP-IDF FreeRTOS is modified version of based on the Xtensa port of FreeRTOS v10.4.3 with significant modi-
fications for SMP compatibility (see ESP-IDF FreeRTOS SMP Changes). However, various new features specific to
ESP-IDF FreeRTOS have been added. The features are as follows:
• Ring buffers: Ring buffers provide a FIFO buffer that can accept entries of arbitrary lengths.
• ESP-IDF Tick and Idle Hooks: ESP-IDF provides multiple custom tick interrupt hooks and idle task hooks
that are more numerous and more flexible when compared to FreeRTOS tick and idle hooks.
• Thread Local Storage Pointer (TLSP) Deletion Callbacks: TLSP Deletion callbacks are run automatically
when a task is deleted, thus allowing users to clean up their TLSPs automatically.
• Component Specific Properties: Currently added only one component specific property
ORIG_INCLUDE_PATH.
Ring Buffers
The ESP-IDF FreeRTOS ring buffer is a strictly FIFO buffer that supports arbitrarily sized items. Ring buffers are a
more memory efficient alternative to FreeRTOS queues in situations where the size of items is variable. The capacity
of a ring buffer is not measured by the number of items it can store, but rather by the amount of memory used for
storing items. The ring buffer provides API to send an item, or to allocate space for an item in the ring buffer to be
filled manually by the user. For efficiency reasons, items are always retrieved from the ring buffer by reference.
As a result, all retrieved items must also be returned to the ring buffer by using vRingbufferReturnItem()
or vRingbufferReturnItemFromISR(), in order for them to be removed from the ring buffer completely.
The ring buffers are split into the three following types:
No-Split buffers will guarantee that an item is stored in contiguous memory and will not attempt to split an item
under any circumstances. Use No-Split buffers when items must occupy contiguous memory. Only this buffer type
allows you to get the data item address and write to the item by yourself. Refer the documentation of the functions
xRingbufferSendAcquire() and xRingbufferSendComplete() for more details.
Allow-Split buffers will allow an item to be split in two parts when wrapping around the end of the buffer if there is
enough space at the tail and the head of the buffer combined to store the item. Allow-Split buffers are more memory
efficient than No-Split buffers but can return an item in two parts when retrieving.
Byte buffers do not store data as separate items. All data is stored as a sequence of bytes, and any number of bytes
can be sent or retrieved each time. Use byte buffers when separate items do not need to be maintained (e.g. a byte
stream).
Note: No-Split buffers and Allow-Split buffers will always store items at 32-bit aligned addresses. Therefore, when
retrieving an item, the item pointer is guaranteed to be 32-bit aligned. This is useful especially when you need to
send some data to the DMA.
Note: Each item stored in No-Split or Allow-Split buffers will require an additional 8 bytes for a header. Item
sizes will also be rounded up to a 32-bit aligned size (multiple of 4 bytes), however the true item size is recorded
within the header. The sizes of No-Split and Allow-Split buffers will also be rounded up when created.
Usage The following example demonstrates the usage of xRingbufferCreate() and xRing-
bufferSend() to create a ring buffer and then send an item to it.
#include "freertos/ringbuf.h"
static char tx_item[] = "test_item";
...
//Send an item
UBaseType_t res = xRingbufferSend(buf_handle, tx_item, sizeof(tx_item), pdMS_
,→TO_TICKS(1000));
if (res != pdTRUE) {
printf("Failed to send item\n");
}
#include "freertos/ringbuf.h"
#include "soc/lldesc.h"
typedef struct {
lldesc_t dma_desc;
uint8_t buf[1];
} dma_item_t;
...
dma_item_t item;
UBaseType_t res = xRingbufferSendAcquire(buf_handle,
&item, DMA_ITEM_SIZE(buffer_size), pdMS_TO_TICKS(1000));
if (res != pdTRUE) {
printf("Failed to acquire memory for item\n");
}
item->dma_desc = (lldesc_t) {
.size = buffer_size,
.length = buffer_size,
.eof = 0,
.owner = 1,
.buf = &item->buf,
};
//Actually send to the ring buffer for consumer to use
res = xRingbufferSendComplete(buf_handle, &item);
if (res != pdTRUE) {
printf("Failed to send item\n");
}
The following example demonstrates retrieving and returning an item from a No-Split ring buffer using xRing-
bufferReceive() and vRingbufferReturnItem()
...
The following example demonstrates retrieving and returning an item from an Allow-Split ring buffer using xRing-
bufferReceiveSplit() and vRingbufferReturnItem()
...
The following example demonstrates retrieving and returning an item from a byte buffer using xRingbuffer-
ReceiveUpTo() and vRingbufferReturnItem()
...
For ISR safe versions of the functions used above, call xRingbufferSendFromISR(), xRing-
bufferReceiveFromISR(), xRingbufferReceiveSplitFromISR(), xRingbufferReceive-
UpToFromISR(), and vRingbufferReturnItemFromISR()
Note: Two calls to RingbufferReceive[UpTo][FromISR]() are required if the bytes wraps around the end of the
ring buffer.
Sending to Ring Buffer The following diagrams illustrate the differences between No-Split and Allow-Split buffers
as compared to byte buffers with regard to sending items/data. The diagrams assume that three items of sizes 18, 3,
and 27 bytes are sent respectively to a buffer of 128 bytes.
For No-Split and Allow-Split buffers, a header of 8 bytes precedes every data item. Furthermore, the space occu-
pied by each item is rounded up to the nearest 32-bit aligned size in order to maintain overall 32-bit alignment.
However, the true size of the item is recorded inside the header which will be returned when the item is retrieved.
Referring to the diagram above, the 18, 3, and 27 byte items are rounded up to 20, 4, and 28 bytes respectively.
An 8 byte header is then added in front of each item.
Byte buffers treat data as a sequence of bytes and does not incur any overhead (no headers). As a result, all data sent
to a byte buffer is merged into a single item.
Referring to the diagram above, the 18, 3, and 27 byte items are sequentially written to the byte buffer and merged
into a single item of 48 bytes.
Using SendAcquire and SendComplete Items in No-Split buffers are acquired (by SendAcquire) in strict
FIFO order and must be sent to the buffer by SendComplete for the data to be accessible by the consumer.
Multiple items can be sent or acquired without calling SendComplete, and the items do not necessarily need to be
completed in the order they were acquired. However, the receiving of data items must occur in FIFO order, therefore
not calling SendComplete for the earliest acquired item will prevent the subsequent items from being received.
The following diagrams illustrate what will happen when SendAcquire and SendComplete don’t happen in the
same order. At the beginning, there is already a data item of 16 bytes sent to the ring buffer. Then SendAcquire
is called to acquire space of 20, 8, 24 bytes on the ring buffer.
After that, we fill (use) the buffers, and send them to the ring buffer by SendComplete in the order of 8, 24,
20. When 8 bytes and 24 bytes data are sent, the consumer still can only get the 16 bytes data item. Hence, if
SendComplete is not called for the 20 bytes, it will not be available, nor will the data items following the 20 bytes
item.
When the 20 bytes item is finally completed, all the 3 data items can be received now, in the order of 20, 8, 24 bytes,
right after the 16 bytes item existing in the buffer at the beginning.
Allow-Split buffers and byte buffers do not allow using SendAcquire or SendComplete since acquired buffers
are required to be complete (not wrapped).
Wrap around The following diagrams illustrate the differences between No-Split, Allow-Split, and byte buffers
when a sent item requires a wrap around. The diagrams assume a buffer of 128 bytes with 56 bytes of free space
that wraps around and a sent item of 28 bytes.
No-Split buffers will only store an item in continuous free space and will not split an item under any circum-
stances. When the free space at the tail of the buffer is insufficient to completely store the item and its header, the
free space at the tail will be marked as dummy data. The buffer will then wrap around and store the item in the
free space at the head of the buffer.
Referring to the diagram above, the 16 bytes of free space at the tail of the buffer is insufficient to store the 28 byte
item. Therefore, the 16 bytes is marked as dummy data and the item is written to the free space at the head of the
buffer instead.
Allow-Split buffers will attempt to split the item into two parts when the free space at the tail of the buffer is
insufficient to store the item data and its header. Both parts of the split item will have their own headers (therefore
incurring an extra 8 bytes of overhead).
Referring to the diagram above, the 16 bytes of free space at the tail of the buffer is insufficient to store the 28 byte
item. Therefore, the item is split into two parts (8 and 20 bytes) and written as two parts to the buffer.
Note: Allow-Split buffers treat both parts of the split item as two separate items, therefore call xRingbuffer-
ReceiveSplit() instead of xRingbufferReceive() to receive both parts of a split item in a thread safe
manner.
Byte buffers will store as much data as possible into the free space at the tail of buffer. The remaining data will
then be stored in the free space at the head of the buffer. No overhead is incurred when wrapping around in byte
buffers.
Referring to the diagram above, the 16 bytes of free space at the tail of the buffer is insufficient to completely store
the 28 bytes of data. Therefore, the 16 bytes of free space is filled with data, and the remaining 12 bytes are written
to the free space at the head of the buffer. The buffer now contains data in two separate continuous parts, and each
continuous part will be treated as a separate item by the byte buffer.
Retrieving/Returning The following diagrams illustrate the differences between No-Split and Allow-Split buffers
as compared to byte buffers in retrieving and returning data.
Items in No-Split buffers and Allow-Split buffers are retrieved in strict FIFO order and must be returned for the
occupied space to be freed. Multiple items can be retrieved before returning, and the items do not necessarily need
to be returned in the order they were retrieved. However, the freeing of space must occur in FIFO order, therefore
not returning the earliest retrieved item will prevent the space of subsequent items from being freed.
Referring to the diagram above, the 16, 20, and 8 byte items are retrieved in FIFO order. However, the items are
not returned in the order they were retrieved. First, the 20 byte item is returned followed by the 8 byte and the 16
byte items. The space is not freed until the first item, i.e., the 16 byte item is returned.
Byte buffers do not allow multiple retrievals before returning (every retrieval must be followed by a return
before another retrieval is permitted). When using xRingbufferReceive() or xRingbufferReceive-
FromISR(), all continuous stored data will be retrieved. xRingbufferReceiveUpTo() or xRingbuf-
ferReceiveUpToFromISR() can be used to restrict the maximum number of bytes retrieved. Since every
retrieval must be followed by a return, the space will be freed as soon as the data is returned.
Referring to the diagram above, the 38 bytes of continuous stored data at the tail of the buffer is retrieved, returned,
and freed. The next call to xRingbufferReceive() or xRingbufferReceiveFromISR() then wraps
around and does the same to the 30 bytes of continuous stored data at the head of the buffer.
Ring Buffers with Queue Sets Ring buffers can be added to FreeRTOS queue sets using xRingbufferAd-
dToQueueSetRead() such that every time a ring buffer receives an item or data, the queue set is notified. Once
added to a queue set, every attempt to retrieve an item from a ring buffer should be preceded by a call to xQueue-
SelectFromSet(). To check whether the selected queue set member is the ring buffer, call xRingbuffer-
CanRead().
The following example demonstrates queue set usage with ring buffers.
#include "freertos/queue.h"
#include "freertos/ringbuf.h"
...
...
//Handle item
...
} else {
...
}
Ring Buffers with Static Allocation The xRingbufferCreateStatic() can be used to create ring buffers
with specific memory requirements (such as a ring buffer being allocated in external RAM). All blocks of memory
used by a ring buffer must be manually allocated beforehand then passed to the xRingbufferCreateStatic()
to be initialized as a ring buffer. These blocks include the following:
• The ring buffer’s data structure of type StaticRingbuffer_t
• The ring buffer’s storage area of size xBufferSize. Note that xBufferSize must be 32-bit aligned
for No-Split and Allow-Split buffers.
The manner in which these blocks are allocated will depend on the users requirements (e.g. all blocks being statically
declared, or dynamically allocated with specific capabilities such as external RAM).
Note: When deleting a ring buffer created via xRingbufferCreateStatic(), the function vRing-
bufferDelete() will not free any of the memory blocks. This must be done manually by the user after vRing-
bufferDelete() is called.
The code snippet below demonstrates a ring buffer being allocated entirely in external RAM.
#include "freertos/ringbuf.h"
#include "freertos/semphr.h"
#include "esp_heap_caps.h"
//Allocate ring buffer data structure and storage area into external RAM
StaticRingbuffer_t *buffer_struct = (StaticRingbuffer_t *)heap_caps_
,→malloc(sizeof(StaticRingbuffer_t), MALLOC_CAP_SPIRAM);
...
Priority Inversion Ideally, ring buffers can be used with multiple tasks in an SMP fashion where the highest
priority task will always be serviced first. However due to the usage of binary semaphores in the ring buffer’s
underlying implementation, priority inversion may occur under very specific circumstances.
The ring buffer governs sending by a binary semaphore which is given whenever space is freed on the ring buffer. The
highest priority task waiting to send will repeatedly take the semaphore until sufficient free space becomes available
or until it times out. Ideally this should prevent any lower priority tasks from being serviced as the semaphore should
always be given to the highest priority task.
However, in between iterations of acquiring the semaphore, there is a gap in the critical section which may permit
another task (on the other core or with an even higher priority) to free some space on the ring buffer and as a result give
the semaphore. Therefore, the semaphore will be given before the highest priority task can re-acquire the semaphore.
This will result in the semaphore being acquired by the second-highest priority task waiting to send, hence
causing priority inversion.
This side effect will not affect ring buffer performance drastically given if the number of tasks using the ring buffer
simultaneously is low, and the ring buffer is not operating near maximum capacity.
FreeRTOS allows applications to provide a tick hook and an idle hook at compile time:
• FreeRTOS tick hook can be enabled via the CONFIG_FREERTOS_USE_TICK_HOOK option. The application
must provide the void vApplicationTickHook( void ) callback.
• FreeRTOS idle hook can be enabled via the CONFIG_FREERTOS_USE_IDLE_HOOK option. The application
must provide the void vApplicationIdleHook( void ) callback.
However, the FreeRTOS tick hook and idle hook have the following draw backs:
• The FreeRTOS hooks are registered at compile time
• Only one of each hook can be registered
• On multi-core targets, the FreeRTOS hooks are symmetric, meaning each CPU’s tick interrupt and idle tasks
ends up calling the same hook.
Therefore, ESP-IDF tick and idle hooks are provided to supplement the features of FreeRTOS tick and idle hooks.
The ESP-IDF hooks have the following features:
• The hooks can be registered and deregistered at run-time
• Multiple hooks can be registered (with a maximum of 8 hooks of each type per CPU)
• On multi-core targets, the hooks can be asymmetric, meaning different hooks can be registered to each CPU
ESP-IDF hooks can be registered and deregistered using the following API:
• For tick hooks:
– Register using esp_register_freertos_tick_hook() or
esp_register_freertos_tick_hook_for_cpu()
– Deregister using esp_deregister_freertos_tick_hook() or
esp_deregister_freertos_tick_hook_for_cpu()
• For idle hooks:
– Register using esp_register_freertos_idle_hook() or
esp_register_freertos_idle_hook_for_cpu()
– Deregister using esp_deregister_freertos_idle_hook() or
esp_deregister_freertos_idle_hook_for_cpu()
Note: The tick interrupt stays active while the cache is disabled, therefore any tick hook (FreeRTOS or ESP-IDF)
functions must be placed in internal RAM. Please refer to the SPI flash API documentation for more details.
Vanilla FreeRTOS provides a Thread Local Storage Pointers (TLSP) feature. These are pointers stored directly in
the Task Control Block (TCB) of a particular task. TLSPs allow each task to have its own unique set of pointers to
data structures. Vanilla FreeRTOS expects users to…
• set a task’s TLSPs by calling vTaskSetThreadLocalStoragePointer() after the task has been
created.
• get a task’s TLSPs by calling pvTaskGetThreadLocalStoragePointer() during the task’s life-
time.
• free the memory pointed to by the TLSPs before the task is deleted.
However, there can be instances where users may want the freeing of TLSP memory to be automatic. Therefore, ESP-
IDF FreeRTOS provides the additional feature of TLSP deletion callbacks. These user provided deletion callbacks
are called automatically when a task is deleted, thus allows the TLSP memory to be cleaned up without needing to
add the cleanup logic explicitly to the code of every task.
The TLSP deletion callbacks are set in a similar fashion to the TLSPs themselves.
• vTaskSetThreadLocalStoragePointerAndDelCallback() sets both a particular TLSP and its
associated callback.
• Calling the Vanilla FreeRTOS function vTaskSetThreadLocalStoragePointer() will simply set
the TLSP’s associated Deletion Callback to NULL meaning that no callback will be called for that TLSP
during task deletion.
When implementing TLSP callbacks, users should note the following:
• The callback must never attempt to block or yield and critical sections should be kept as short as possible
• The callback is called shortly before a deleted task’s memory is freed. Thus, the callback can either be called
from vTaskDelete() itself, or from the idle task.
Besides standard component variables that are available with basic cmake build properties, FreeRTOS component
also provides arguments (only one so far) for simpler integration with other modules:
• ORIG_INCLUDE_PATH - contains an absolute path to freertos root include folder. Thus instead of #include
“freertos/FreeRTOS.h” you can refer to headers directly: #include “FreeRTOS.h”.
API Reference
Header File
• components/esp_ringbuf/include/freertos/ringbuf.h
Functions
RingbufHandle_t xRingbufferCreate(size_t xBufferSize, RingbufferType_t xBufferType)
Create a ring buffer.
Note: xBufferSize of no-split/allow-split buffers will be rounded up to the nearest 32-bit aligned size.
Parameters
• xBufferSize –[in] Size of the buffer in bytes. Note that items require space for a
header in no-split/allow-split buffers
• xBufferType –[in] Type of ring buffer, see documentation.
Returns A handle to the created ring buffer, or NULL in case of error.
RingbufHandle_t xRingbufferCreateNoSplit(size_t xItemSize, size_t xItemNum)
Create a ring buffer of type RINGBUF_TYPE_NOSPLIT for a fixed item_size.
This API is similar to xRingbufferCreate(), but it will internally allocate additional space for the headers.
Parameters
• xItemSize –[in] Size of each item to be put into the ring buffer
• xItemNum –[in] Maximum number of items the buffer needs to hold simultaneously
Returns A RingbufHandle_t handle to the created ring buffer, or NULL in case of error.
RingbufHandle_t xRingbufferCreateStatic(size_t xBufferSize, RingbufferType_t xBufferType, uint8_t
*pucRingbufferStorage, StaticRingbuffer_t
*pxStaticRingbuffer)
Create a ring buffer but manually provide the required memory.
Parameters
• xBufferSize –[in] Size of the buffer in bytes.
• xBufferType –[in] Type of ring buffer, see documentation
• pucRingbufferStorage –[in] Pointer to the ring buffer’s storage area. Storage
area must have the same size as specified by xBufferSize
Note: For no-split/allow-split ring buffers, the actual size of memory that the item will occupy will be rounded
up to the nearest 32-bit aligned size. This is done to ensure all items are always stored in 32-bit aligned fashion.
Parameters
• xRingbuffer –[in] Ring buffer to insert the item into
• pvItem –[in] Pointer to data to insert. NULL is allowed if xItemSize is 0.
• xItemSize –[in] Size of data to insert.
• xTicksToWait –[in] Ticks to wait for room in the ring buffer.
Returns
• pdTRUE if succeeded
• pdFALSE on time-out or when the data is larger than the maximum permissible size of
the buffer
Note: For no-split/allow-split ring buffers, the actual size of memory that the item will occupy will be rounded
up to the nearest 32-bit aligned size. This is done to ensure all items are always stored in 32-bit aligned fashion.
Parameters
• xRingbuffer –[in] Ring buffer to insert the item into
• pvItem –[in] Pointer to data to insert. NULL is allowed if xItemSize is 0.
• xItemSize –[in] Size of data to insert.
• pxHigherPriorityTaskWoken –[out] Value pointed to will be set to pdTRUE if
the function woke up a higher priority task.
Returns
• pdTRUE if succeeded
• pdFALSE when the ring buffer does not have space.
Note: Only applicable for no-split ring buffers now, the actual size of memory that the item will occupy will
be rounded up to the nearest 32-bit aligned size. This is done to ensure all items are always stored in 32-bit
aligned fashion.
Parameters
• xRingbuffer –[in] Ring buffer to allocate the memory
• ppvItem –[out] Double pointer to memory acquired (set to NULL if no memory were
retrieved)
• xItemSize –[in] Size of item to acquire.
• xTicksToWait –[in] Ticks to wait for room in the ring buffer.
Returns
• pdTRUE if succeeded
• pdFALSE on time-out or when the data is larger than the maximum permissible size of
the buffer
Note: Only applicable for no-split ring buffers. Only call for items allocated by xRingbufferSendAc-
quire.
Parameters
• xRingbuffer –[in] Ring buffer to insert the item into
• pvItem –[in] Pointer to item in allocated memory to insert.
Returns
• pdTRUE if succeeded
• pdFALSE if fail for some reason.
Note: A call to vRingbufferReturnItem() is required after this to free the item retrieved.
Parameters
• xRingbuffer –[in] Ring buffer to retrieve the item from
• pxItemSize –[out] Pointer to a variable to which the size of the retrieved item will be
written.
• xTicksToWait –[in] Ticks to wait for items in the ring buffer.
Returns
• Pointer to the retrieved item on success; *pxItemSize filled with the length of the item.
• NULL on timeout, *pxItemSize is untouched in that case.
Note: A call to vRingbufferReturnItemFromISR() is required after this to free the item retrieved.
Note: Byte buffers do not allow multiple retrievals before returning an item
Note: Two calls to RingbufferReceiveFromISR() are required if the bytes wrap around the end of the ring
buffer.
Parameters
• xRingbuffer –[in] Ring buffer to retrieve the item from
• pxItemSize –[out] Pointer to a variable to which the size of the retrieved item will be
written.
Returns
• Pointer to the retrieved item on success; *pxItemSize filled with the length of the item.
• NULL when the ring buffer is empty, *pxItemSize is untouched in that case.
Note: Call(s) to vRingbufferReturnItem() is required after this to free up the item(s) retrieved.
Parameters
• xRingbuffer –[in] Ring buffer to retrieve the item from
• ppvHeadItem –[out] Double pointer to first part (set to NULL if no items were re-
trieved)
• ppvTailItem –[out] Double pointer to second part (set to NULL if item is not split)
• pxHeadItemSize –[out] Pointer to size of first part (unmodified if no items were
retrieved)
• pxTailItemSize –[out] Pointer to size of second part (unmodified if item is not split)
• xTicksToWait –[in] Ticks to wait for items in the ring buffer.
Returns
• pdTRUE if an item (split or unsplit) was retrieved
• pdFALSE when no item was retrieved
Note: Calls to vRingbufferReturnItemFromISR() is required after this to free up the item(s) retrieved.
Parameters
Note: A call to vRingbufferReturnItem() is required after this to free up the data retrieved.
Note: Byte buffers do not allow multiple retrievals before returning an item
Note: Two calls to RingbufferReceiveUpTo() are required if the bytes wrap around the end of the ring buffer.
Parameters
• xRingbuffer –[in] Ring buffer to retrieve the item from
• pxItemSize –[out] Pointer to a variable to which the size of the retrieved item will be
written.
• xTicksToWait –[in] Ticks to wait for items in the ring buffer.
• xMaxSize –[in] Maximum number of bytes to return.
Returns
• Pointer to the retrieved item on success; *pxItemSize filled with the length of the item.
• NULL on timeout, *pxItemSize is untouched in that case.
Note: A call to vRingbufferReturnItemFromISR() is required after this to free up the data received.
Note: Byte buffers do not allow multiple retrievals before returning an item
Parameters
• xRingbuffer –[in] Ring buffer to retrieve the item from
• pxItemSize –[out] Pointer to a variable to which the size of the retrieved item will be
written.
• xMaxSize –[in] Maximum number of bytes to return.
Returns
• Pointer to the retrieved item on success; *pxItemSize filled with the length of the item.
• NULL when the ring buffer is empty, *pxItemSize is untouched in that case.
Note: If a split item is retrieved, both parts should be returned by calling this function twice
Parameters
• xRingbuffer –[in] Ring buffer the item was retrieved from
• pvItem –[in] Item that was received earlier
Note: If a split item is retrieved, both parts should be returned by calling this function twice
Parameters
• xRingbuffer –[in] Ring buffer the item was retrieved from
• pvItem –[in] Item that was received earlier
• pxHigherPriorityTaskWoken –[out] Value pointed to will be set to pdTRUE if
the function woke up a higher priority task.
Note: This function will not deallocate any memory if the ring buffer was created using xRingbufferCreat-
eStatic(). Deallocation must be done manually be the user.
Note: The max item size for a no-split buffer is limited to ((buffer_size/2)-header_size). This limit is imposed
so that an item of max item size can always be sent to an empty no-split buffer regardless of the internal positions
of the buffer’s read/write/free pointers.
Note: An empty no-split buffer has a max current free size for an item that is limited to ((buffer_size/2)-
header_size). See API reference for xRingbufferGetMaxItemSize().
Warning: This API is not thread safe. So, if multiple threads are accessing the same ring buffer, it is the
application’s responsibility to ensure atomic access to this API and the subsequent Send
Structures
struct xSTATIC_RINGBUFFER
Struct that is equivalent in size to the ring buffer’s data structure.
The contents of this struct are not meant to be used directly. This structure is meant to be used when creating
a statically allocated ring buffer where this struct is of the exact size required to store a ring buffer’s control
data structure.
Type Definitions
Enumerations
enum RingbufferType_t
Values:
enumerator RINGBUF_TYPE_NOSPLIT
No-split buffers will only store an item in contiguous memory and will never split an item. Each item
requires an 8 byte overhead for a header and will always internally occupy a 32-bit aligned size of space.
enumerator RINGBUF_TYPE_ALLOWSPLIT
Allow-split buffers will split an item into two parts if necessary in order to store it. Each item requires
an 8 byte overhead for a header, splitting incurs an extra header. Each item will always internally occupy
a 32-bit aligned size of space.
enumerator RINGBUF_TYPE_BYTEBUF
Byte buffers store data as a sequence of bytes and do not maintain separate items, therefore byte buffers
have no overhead. All data is stored as a sequence of byte and any number of bytes can be sent or retrieved
each time.
enumerator RINGBUF_TYPE_MAX
Hooks API
Header File
• components/esp_system/include/esp_freertos_hooks.h
Functions
esp_err_t esp_register_freertos_idle_hook_for_cpu(esp_freertos_idle_cb_t new_idle_cb,
UBaseType_t cpuid)
Register a callback to be called from the specified core’s idle hook. The callback should return true if it
should be called by the idle hook once per interrupt (or FreeRTOS tick), and return false if it should be called
repeatedly as fast as possible by the idle hook.
Warning: Idle callbacks MUST NOT, UNDER ANY CIRCUMSTANCES, CALL A FUNCTION
THAT MIGHT BLOCK.
Parameters
• new_idle_cb –[in] Callback to be called
• cpuid –[in] id of the core
Returns
• ESP_OK: Callback registered to the specified core’s idle hook
• ESP_ERR_NO_MEM: No more space on the specified core’s idle hook to register call-
back
• ESP_ERR_INVALID_ARG: cpuid is invalid
esp_err_t esp_register_freertos_idle_hook(esp_freertos_idle_cb_t new_idle_cb)
Register a callback to the idle hook of the core that calls this function. The callback should return true if it
should be called by the idle hook once per interrupt (or FreeRTOS tick), and return false if it should be called
repeatedly as fast as possible by the idle hook.
Warning: Idle callbacks MUST NOT, UNDER ANY CIRCUMSTANCES, CALL A FUNCTION
THAT MIGHT BLOCK.
Returns
• ESP_OK: Callback registered to specified core’s tick hook
• ESP_ERR_NO_MEM: No more space on the specified core’s tick hook to register the
callback
• ESP_ERR_INVALID_ARG: cpuid is invalid
esp_err_t esp_register_freertos_tick_hook(esp_freertos_tick_cb_t new_tick_cb)
Register a callback to be called from the calling core’s tick hook.
Parameters new_tick_cb –[in] Callback to be called
Returns
• ESP_OK: Callback registered to the calling core’s tick hook
• ESP_ERR_NO_MEM: No more space on the calling core’s tick hook to register the
callback
void esp_deregister_freertos_idle_hook_for_cpu(esp_freertos_idle_cb_t old_idle_cb,
UBaseType_t cpuid)
Unregister an idle callback from the idle hook of the specified core.
Parameters
• old_idle_cb –[in] Callback to be unregistered
• cpuid –[in] id of the core
void esp_deregister_freertos_idle_hook(esp_freertos_idle_cb_t old_idle_cb)
Unregister an idle callback. If the idle callback is registered to the idle hooks of both cores, the idle hook will
be unregistered from both cores.
Parameters old_idle_cb –[in] Callback to be unregistered
void esp_deregister_freertos_tick_hook_for_cpu(esp_freertos_tick_cb_t old_tick_cb,
UBaseType_t cpuid)
Unregister a tick callback from the tick hook of the specified core.
Parameters
• old_tick_cb –[in] Callback to be unregistered
• cpuid –[in] id of the core
void esp_deregister_freertos_tick_hook(esp_freertos_tick_cb_t old_tick_cb)
Unregister a tick callback. If the tick callback is registered to the tick hooks of both cores, the tick hook will
be unregistered from both cores.
Parameters old_tick_cb –[in] Callback to be unregistered
Type Definitions
ESP-IDF applications use the common computer architecture patterns of stack (dynamic memory allocated by pro-
gram control flow) and heap (dynamic memory allocated by function calls), as well as statically allocated memory
(allocated at compile time).
Because ESP-IDF is a multi-threaded RTOS environment, each RTOS task has its own stack. By default, each of
these stacks is allocated from the heap when the task is created. (See xTaskCreateStatic() for the alternative
where stacks are statically allocated.)
Because ESP32 uses multiple types of RAM, it also contains multiple heaps with different capabilities. A capabilities-
based memory allocator allows apps to make heap allocations for different purposes.
For most purposes, the standard libc malloc() and free() functions can be used for heap allocation without any
special consideration.
However, in order to fully make use of all of the memory types and their characteristics, ESP-IDF also has a
capabilities-based heap memory allocator. If you want to have memory with certain properties (for example, DMA-
Capable Memory or executable-memory), you can create an OR-mask of the required capabilities and pass that to
heap_caps_malloc().
Memory Capabilities
Available Heap
DRAM At startup, the DRAM heap contains all data memory which is not statically allocated by the app. Reducing
statically allocated buffers will increase the amount of available free heap.
To find the amount of statically allocated memory, use the idf.py size command.
Note: Due to a technical limitation, the maximum statically allocated DRAM usage is 160KB. The remaining
160KB (for a total of 320KB of DRAM) can only be allocated at runtime as heap.
Note: At runtime, the available heap DRAM may be less than calculated at compile time, because at startup some
memory is allocated from the heap before the FreeRTOS scheduler is started (including memory for the stacks of
initial FreeRTOS tasks).
IRAM At startup, the IRAM heap contains all instruction memory which is not used by the app executable code.
The idf.py size command can be used to find the amount of IRAM used by the app.
D/IRAM Some memory in the ESP32 is available as either DRAM or IRAM. If memory is allocated from a
D/IRAM region, the free heap size for both types of memory will decrease.
Heap Sizes At startup, all ESP-IDF apps log a summary of all heap addresses (and sizes) at level Info:
Special Capabilities
DMA-Capable Memory Use the MALLOC_CAP_DMA flag to allocate memory which is suitable for use with
hardware DMA engines (for example SPI and I2S). This capability flag excludes any external PSRAM.
32-Bit Accessible Memory If a certain memory structure is only addressed in 32-bit units, for example an array
of ints or pointers, it can be useful to allocate it with the MALLOC_CAP_32BIT flag. This also allows the allocator
to give out IRAM memory; something which it can’t do for a normal malloc() call. This can help to use all the
available memory in the ESP32.
Memory allocated with MALLOC_CAP_32BIT can only be accessed via 32-bit reads and writes, any other type of
access will generate a fatal LoadStoreError exception.
External SPI Memory When external RAM is enabled, external SPI RAM under 4MiB in size can be allocated
using standard malloc calls, or via heap_caps_malloc(MALLOC_CAP_SPIRAM), depending on configura-
tion. See Configuring External RAM for more details.
To use the region above the 4MiB limit, you can use the himem API.
Header File
• components/heap/include/esp_heap_caps.h
Functions
esp_err_t heap_caps_register_failed_alloc_callback(esp_alloc_failed_hook_t callback)
registers a callback function to be invoked if a memory allocation operation fails
Parameters callback –caller defined callback to be invoked
Returns ESP_OK if callback was registered.
void *heap_caps_malloc(size_t size, uint32_t caps)
Allocate a chunk of memory which has the given capabilities.
Equivalent semantics to libc malloc(), for capability-aware memory.
In IDF, malloc(p) is equivalent to heap_caps_malloc(p, MALLOC_CAP_8BIT).
Parameters
• size –Size, in bytes, of the amount of memory to allocate
• caps –Bitwise OR of MALLOC_CAP_* flags indicating the type of memory to be re-
turned
Returns A pointer to the memory allocated on success, NULL on failure
Note: Note that because of heap fragmentation it is probably not possible to allocate a single block of memory
of this size. Use heap_caps_get_largest_free_block() for this purpose.
Note: Note the result may be less than the global all-time minimum available heap of this kind, as “low
watermarks”are tracked per-region. Individual regions’heaps may have reached their“low watermarks”at
different points in time. However, this result still gives a “worst case”indication for all-time minimum free
heap.
Parameters
• info –Pointer to a structure which will be filled with relevant heap metadata.
• caps –Bitwise OR of MALLOC_CAP_* flags indicating the type of memory
void heap_caps_print_heap_info(uint32_t caps)
Print a summary of all memory with the given capabilities.
Calls multi_heap_info on all heaps which share the given capabilities, and prints a two-line summary for each,
then a total summary.
Parameters caps –Bitwise OR of MALLOC_CAP_* flags indicating the type of memory
bool heap_caps_check_integrity_all(bool print_errors)
Check integrity of all heap memory in the system.
Calls multi_heap_check on all heaps. Optionally print errors if heaps are corrupt.
Calling this function is equivalent to calling heap_caps_check_integrity with the caps argument set to MAL-
LOC_CAP_INVALID.
Parameters print_errors –Print specific errors if heap corruption is found.
Returns True if all heaps are valid, False if at least one heap is corrupt.
bool heap_caps_check_integrity(uint32_t caps, bool print_errors)
Check integrity of all heaps with the given capabilities.
Calls multi_heap_check on all heaps which share the given capabilities. Optionally print errors if the heaps are
corrupt.
See also heap_caps_check_integrity_all to check all heap memory in the system and
heap_caps_check_integrity_addr to check memory around a single address.
Parameters
• caps –Bitwise OR of MALLOC_CAP_* flags indicating the type of memory
• print_errors –Print specific errors if heap corruption is found.
Returns True if all heaps are valid, False if at least one heap is corrupt.
bool heap_caps_check_integrity_addr(intptr_t addr, bool print_errors)
Check integrity of heap memory around a given address.
This function can be used to check the integrity of a single region of heap memory, which contains the given
address.
This can be useful if debugging heap integrity for corruption at a known address, as it has a lower over-
head than checking all heap regions. Note that if the corrupt address moves around between runs (due to
timing or other factors) then this approach won’t work, and you should call heap_caps_check_integrity or
heap_caps_check_integrity_all instead.
Note: The entire heap region around the address is checked, not only the adjacent heap blocks.
Parameters
• addr –Address in memory. Check for corruption in region containing this address.
• print_errors –Print specific errors if heap corruption is found.
Returns True if the heap containing the specified address is valid, False if at least one heap is
corrupt or the address doesn’t belong to a heap region.
Attention The variable parameters are bitwise OR of MALLOC_CAP_* flags indicating the type of memory.
This API prefers to allocate memory with the first parameter. If failed, allocate memory with the next
parameter. It will try in this order until allocating a chunk of memory successfully or fail to allocate
memories with any of the parameters.
Parameters
• size –Size, in bytes, of the amount of memory to allocate
• num –Number of variable parameters
Returns A pointer to the memory allocated on success, NULL on failure
• Block address (the data buffer returned by malloc is 4 bytes after this if heap debugging is set to Basic,
or 8 bytes otherwise).
• Data size (the data size may be larger than the size requested by malloc, either due to heap fragmentation
or because of heap debugging level).
• Address of next block in the heap.
• If the block is free, the address of the next free block is also printed.
void heap_caps_dump_all(void)
Dump the full structure of all heaps.
Covers all registered heaps. Prints a large amount of output to serial.
Output is the same as for heap_caps_dump.
size_t heap_caps_get_allocated_size(void *ptr)
Return the size that a particular pointer was allocated with.
Note: The app will crash with an assertion failure if the pointer is not valid.
Parameters ptr –Pointer to currently allocated heap memory. Must be a pointer value previously
returned by heap_caps_malloc, malloc, calloc, etc. and not yet freed.
Returns Size of the memory allocated at this block.
Macros
MALLOC_CAP_EXEC
Flags to indicate the capabilities of the various memory systems.
Memory must be able to run executable code
MALLOC_CAP_32BIT
Memory must allow for aligned 32-bit data accesses.
MALLOC_CAP_8BIT
Memory must allow for 8/16/…-bit data accesses.
MALLOC_CAP_DMA
Memory must be able to accessed by DMA.
MALLOC_CAP_PID2
Memory must be mapped to PID2 memory space (PIDs are not currently used)
MALLOC_CAP_PID3
Memory must be mapped to PID3 memory space (PIDs are not currently used)
MALLOC_CAP_PID4
Memory must be mapped to PID4 memory space (PIDs are not currently used)
MALLOC_CAP_PID5
Memory must be mapped to PID5 memory space (PIDs are not currently used)
MALLOC_CAP_PID6
Memory must be mapped to PID6 memory space (PIDs are not currently used)
MALLOC_CAP_PID7
Memory must be mapped to PID7 memory space (PIDs are not currently used)
MALLOC_CAP_SPIRAM
Memory must be in SPI RAM.
MALLOC_CAP_INTERNAL
Memory must be internal; specifically it should not disappear when flash/spiram cache is switched off.
MALLOC_CAP_DEFAULT
Memory can be returned in a non-capability-specific memory allocation (e.g. malloc(), calloc()) call.
MALLOC_CAP_IRAM_8BIT
Memory must be in IRAM and allow unaligned access.
MALLOC_CAP_RETENTION
MALLOC_CAP_RTCRAM
Memory must be in RTC fast memory.
MALLOC_CAP_INVALID
Memory can’t be used / list end marker.
Type Definitions
Thread Safety Heap functions are thread safe, meaning they can be called from different tasks simultaneously
without any limitations.
It is technically possible to call malloc, free, and related functions from interrupt handler (ISR) context. However
this is not recommended, as heap function calls may delay other interrupts. It is strongly recommended to refactor
applications so that any buffers used by an ISR are pre-allocated outside of the ISR. Support for calling heap functions
from ISRs may be removed in a future update.
The following features are documented on the Heap Memory Debugging page:
• Heap Information (free space, etc.)
• Heap Corruption Detection
• Heap Tracing (memory leak detection, monitoring, etc.)
Header File
• components/heap/include/esp_heap_caps_init.h
Functions
void heap_caps_init(void)
Initialize the capability-aware heap allocator.
This is called once in the IDF startup code. Do not call it at other times.
void heap_caps_enable_nonos_stack_heaps(void)
Enable heap(s) in memory regions where the startup stacks are located.
On startup, the pro/app CPUs have a certain memory region they use as stack, so we cannot do allocations
in the regions these stack frames are. When FreeRTOS is completely started, they do not use that memory
anymore and heap(s) there can be enabled.
Note: Please refer to following example for memory regions allowed for addition to heap based on an existing
region (address range for demonstration purpose only):
Parameters
• start –Start address of new region.
• end –End address of new region.
Returns ESP_OK on success, ESP_ERR_INVALID_ARG if a parameter is invalid,
ESP_ERR_NOT_FOUND if the specified start address doesn’t reside in a known
region, or any error returned by heap_caps_add_region_with_caps().
Note: Please refer to following example for memory regions allowed for addition to heap based on an existing
region (address range for demonstration purpose only):
Parameters
• caps –Ordered array of capability masks for the new region, in order of priority. Must
have length SOC_MEMORY_TYPE_NO_PRIOS. Does not need to remain valid after
the call returns.
• start –Start address of new region.
• end –End address of new region.
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if a parameter is invalid
• ESP_ERR_NO_MEM if no memory to register new heap.
• ESP_ERR_INVALID_SIZE if the memory region is too small to fit a heap
• ESP_FAIL if region overlaps the start and/or end of an existing region
Implementation Notes
Knowledge about the regions of memory in the chip comes from the “soc”component, which contains memory
layout information for the chip, and the different capabilities of each region. Each region’s capabilities are prioritised,
so that (for example) dedicated DRAM and IRAM regions will be used for allocations ahead of the more versatile
D/IRAM regions.
Each contiguous region of memory contains its own memory heap. The heaps are created using the multi_heap
functionality. multi_heap allows any contiguous region of memory to be used as a heap.
The heap capabilities allocator uses knowledge of the memory regions to initialize each individual heap. Allocation
functions in the heap capabilities API will find the most appropriate heap for the allocation (based on desired capa-
bilities, available space, and preferences for each region’s use) and then calling multi_heap_malloc() for
the heap situated in that particular region.
Calling free() involves finding the particular heap corresponding to the freed address, and then calling
multi_heap_free() on that particular multi_heap instance.
(Note: The multi heap API is used internally by the heap capabilities allocator. Most IDF programs will never need
to call this API directly.)
Header File
• components/heap/include/multi_heap.h
Functions
void *multi_heap_aligned_alloc(multi_heap_handle_t heap, size_t size, size_t alignment)
allocate a chunk of memory with specific alignment
Parameters
• heap –Handle to a registered heap.
• size –size in bytes of memory chunk
• alignment –how the memory must be aligned
Returns pointer to the memory allocated, NULL on failure
void *multi_heap_malloc(multi_heap_handle_t heap, size_t size)
malloc() a buffer in a given heap
Semantics are the same as standard malloc(), only the returned buffer will be allocated in the specified heap.
Parameters
• heap –Handle to a registered heap.
• size –Size of desired buffer.
Returns Pointer to new memory, or NULL if allocation fails.
Parameters
• heap –Handle to a registered heap.
• p –NULL, or a pointer previously returned from multi_heap_aligned_alloc() for the same
heap.
The lock argument is supplied to the MULTI_HEAP_LOCK() and MULTI_HEAP_UNLOCK() macros, de-
fined in multi_heap_platform.h.
The lock in question must be recursive.
When the heap is first registered, the associated lock is NULL.
Parameters
• heap –Handle to a registered heap.
• lock –Optional pointer to a locking structure to associate with this heap.
void multi_heap_dump(multi_heap_handle_t heap)
Dump heap information to stdout.
For debugging purposes, this function dumps information about every block in the heap to stdout.
Parameters heap –Handle to a registered heap.
bool multi_heap_check(multi_heap_handle_t heap, bool print_errors)
Check heap integrity.
Walks the heap and checks all heap data structures are valid. If any errors are detected, an error-specific
message can be optionally printed to stderr. Print behaviour can be overridden at compile time by defining
MULTI_CHECK_FAIL_PRINTF in multi_heap_platform.h.
Parameters
• heap –Handle to a registered heap.
• print_errors –If true, errors will be printed to stderr.
Returns true if heap is valid, false otherwise.
size_t multi_heap_free_size(multi_heap_handle_t heap)
Return free heap size.
Returns the number of bytes available in the heap.
Equivalent to the total_free_bytes member returned by multi_heap_get_heap_info().
Note that the heap may be fragmented, so the actual maximum size for a single malloc() may be lower. To
know this size, see the largest_free_block member returned by multi_heap_get_heap_info().
Parameters heap –Handle to a registered heap.
Returns Number of free bytes.
size_t multi_heap_minimum_free_size(multi_heap_handle_t heap)
Return the lifetime minimum free heap size.
Equivalent to the minimum_free_bytes member returned by multi_heap_get_info().
Returns the lifetime“low watermark”of possible values returned from multi_free_heap_size(), for the specified
heap.
Parameters heap –Handle to a registered heap.
Returns Number of free bytes.
void multi_heap_get_info(multi_heap_handle_t heap, multi_heap_info_t *info)
Return metadata about a given heap.
Fills a multi_heap_info_t structure with information about the specified heap.
Parameters
• heap –Handle to a registered heap.
• info –Pointer to a structure to fill with heap metadata.
Structures
struct multi_heap_info_t
Structure to access heap metadata via multi_heap_get_info.
Public Members
size_t total_free_bytes
Total free bytes in the heap. Equivalent to multi_free_heap_size().
size_t total_allocated_bytes
Total bytes allocated to data in the heap.
size_t largest_free_block
Size of the largest free block in the heap. This is the largest malloc-able size.
size_t minimum_free_bytes
Lifetime minimum free heap size. Equivalent to multi_minimum_free_heap_size().
size_t allocated_blocks
Number of (variable size) blocks allocated in the heap.
size_t free_blocks
Number of (variable size) free blocks in the heap.
size_t total_blocks
Total number of (variable size) blocks in the heap.
Type Definitions
Overview
ESP-IDF integrates tools for requesting heap information, detecting heap corruption, and tracing memory leaks. These
can help track down memory-related bugs.
For general information about the heap memory allocator, see the Heap Memory Allocation page.
Heap Information
Heap corruption detection allows you to detect various types of heap memory errors:
• Out of bounds writes & buffer overflow.
• Writes to freed memory.
• Reads from freed or uninitialized memory,
Assertions The heap implementation (multi_heap.c, etc.) includes a lot of assertions which will fail if the
heap memory is corrupted. To detect heap corruption most effectively, ensure that assertions are enabled in the project
configuration menu under Compiler options -> CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL.
If a heap integrity assertion fails, a line will be printed like CORRUPT HEAP: multi_heap.c:225 detected
at 0x3ffbb71c. The memory address which is printed is the address of the heap structure which has corrupt
content.
It’s also possible to manually check heap integrity by calling heap_caps_check_integrity_all() or
related functions. This function checks all of requested heap memory for integrity, and can be used even if assertions
are disabled. If the integrity check prints an error, it will also contain the address(es) of corrupt heap structures.
{
printf("%s was called but failed to allocate %d bytes with 0x%X capabilities. \n
,→",function_name, requested_size, caps);
void app_main()
{
...
esp_err_t error = heap_caps_register_failed_alloc_callback(heap_caps_alloc_
,→failed_hook);
...
void *ptr = heap_caps_malloc(allocation_size, MALLOC_CAP_DEFAULT);
...
}
Finding Heap Corruption Memory corruption can be one of the hardest classes of bugs to find and fix, as one
area of memory can be corrupted from a totally different place. Some tips:
• A crash with a CORRUPT HEAP: message will usually include a stack trace, but this stack trace is rarely
useful. The crash is the symptom of memory corruption when the system realises the heap is corrupt, but
usually the corruption happened elsewhere and earlier in time.
• Increasing the Heap memory debugging Configuration level to“Light impact”or“Comprehensive”can give
you a more accurate message with the first corrupt memory address.
• Adding regular calls to heap_caps_check_integrity_all() or
heap_caps_check_integrity_addr() in your code will help you pin down the exact time
that the corruption happened. You can move these checks around to “close in on”the section of code that
corrupted the heap.
• Based on the memory address which is being corrupted, you can use JTAG debugging to set a watchpoint on
this address and have the CPU halt when it is written to.
• If you don’t have JTAG, but you do know roughly when the corruption happens, then you can set
a watchpoint in software just beforehand via esp_cpu_set_watchpoint(). A fatal exception
will occur when the watchpoint triggers. The following is an example of how to use the function -
esp_cpu_set_watchpoint(0, (void *)addr, 4, ESP_WATCHPOINT_STORE). Note that
watchpoints are per-CPU and are set on the current running CPU only, so if you don’t know which CPU is
corrupting memory then you will need to call this function on both CPUs.
• For buffer overflows, heap tracing in HEAP_TRACE_ALL mode lets you see which callers are allocating which
addresses from the heap. See Heap Tracing To Find Heap Corruption for more details. If you can find the
function which allocates memory with an address immediately before the address which is corrupted, this will
probably be the function which overflows the buffer.
• Calling heap_caps_dump() or heap_caps_dump_all() can give an indication of what heap blocks
are surrounding the corrupted region and may have overflowed/underflowed/etc.
Configuration Temporarily increasing the heap corruption detection level can give more detailed information about
heap corruption errors.
In the project configuration menu, under Component config there is a menu Heap memory debugging.
The setting CONFIG_HEAP_CORRUPTION_DETECTION can be set to one of three levels:
Basic (no poisoning) This is the default level. No special heap corruption features are enabled, but provided
assertions are enabled (the default configuration) then a heap corruption error will be printed if any of the heap’s
internal data structures appear overwritten or corrupted. This usually indicates a buffer overrun or out of bounds
write.
If assertions are enabled, an assertion will also trigger if a double-free occurs (the same memory is freed twice).
Calling heap_caps_check_integrity() in Basic mode will check the integrity of all heap structures, and
print errors if any appear to be corrupted.
Light Impact At this level, heap memory is additionally “poisoned”with head and tail “canary bytes”before
and after each block which is allocated. If an application writes outside the bounds of allocated buffers, the canary
bytes will be corrupted and the integrity check will fail.
The head canary word is 0xABBA1234 (3412BAAB in byte order), and the tail canary word is 0xBAAD5678
(7856ADBA in byte order).
“Basic”heap corruption checks can also detect most out of bounds writes, but this setting is more precise as even a
single byte overrun can be detected. With Basic heap checks, the number of overrun bytes before a failure is detected
will depend on the properties of the heap.
Enabling “Light Impact”checking increases memory usage, each individual allocation will use 9 to 12 additional
bytes of memory (depending on alignment).
Each time free() is called in Light Impact mode, the head and tail canary bytes of the buffer being freed are
checked against the expected values.
When heap_caps_check_integrity() is called, all allocated blocks of heap memory have their canary bytes
checked against the expected values.
In both cases, the check is that the first 4 bytes of an allocated block (before the buffer returned to the user) should
be the word 0xABBA1234. Then the last 4 bytes of the allocated block (after the buffer returned to the user) should
be the word 0xBAAD5678.
Comprehensive This level incorporates the “light impact”detection features plus additional checks for
uninitialised-access and use-after-free bugs. In this mode, all freshly allocated memory is filled with the pattern
0xCE, and all freed memory is filled with the pattern 0xFE.
Enabling “Comprehensive”detection has a substantial runtime performance impact (as all memory needs to be set
to the allocation patterns each time a malloc/free completes, and the memory also needs to be checked each time.)
However, it allows easier detection of memory corruption bugs which are much more subtle to find otherwise. It is
recommended to only enable this mode when debugging, not in production.
Manual Heap Checks in Comprehensive Mode Calls to heap_caps_check_integrity() may print er-
rors relating to 0xFEFEFEFE, 0xABBA1234 or 0xBAAD5678. In each case the checker is expecting to find a given
pattern, and will error out if this is not found:
• For free heap blocks, the checker expects to find all bytes set to 0xFE. Any other values indicate a use-after-free
bug where free memory has been incorrectly overwritten.
• For allocated heap blocks, the behaviour is the same as for Light Impact mode. The canary bytes 0xABBA1234
and 0xBAAD5678 are checked at the head and tail of each allocated buffer, and any variation indicates a buffer
overrun/underrun.
Heap Task Tracking can be used to get per task info for heap memory allocation. Application has to specify the heap
capabilities for which the heap allocation is to be tracked.
Example code is provided in system/heap_task_tracking
Heap Tracing
Heap Tracing allows tracing of code which allocates/frees memory. Two tracing modes are supported:
• Standalone. In this mode trace data are kept on-board, so the size of gathered information is limited by the
buffer assigned for that purposes. Analysis is done by the on-board code. There are a couple of APIs available
for accessing and dumping collected info.
• Host-based. This mode does not have the limitation of the standalone mode, because trace data are sent to the
host over JTAG connection using app_trace library. Later on they can be analysed using special tools.
Heap tracing can perform two functions:
• Leak checking: find memory which is allocated and never freed.
• Heap use analysis: show all functions that are allocating/freeing memory while the trace is running.
How To Diagnose Memory Leaks If you suspect a memory leak, the first step is to figure out which part of the
program is leaking memory. Use the xPortGetFreeHeapSize(), heap_caps_get_free_size(), or
related functions to track memory use over the life of the application. Try to narrow the leak down to a single function
or sequence of functions where free memory always decreases and never recovers.
Standalone Mode Once you’ve identified the code which you think is leaking:
• In the project configuration menu, navigate to Component settings -> Heap Memory Debugging
-> Heap tracing and select Standalone option (see CONFIG_HEAP_TRACING_DEST).
• Call the function heap_trace_init_standalone() early in the program, to register a buffer which
can be used to record the memory trace.
• Call the function heap_trace_start() to begin recording all mallocs/frees in the system. Call this
immediately before the piece of code which you suspect is leaking memory.
• Call the function heap_trace_stop() to stop the trace once the suspect piece of code has finished exe-
cuting.
• Call the function heap_trace_dump() to dump the results of the heap trace.
An example:
#include "esp_heap_trace.h"
...
void app_main()
{
...
ESP_ERROR_CHECK( heap_trace_init_standalone(trace_record, NUM_RECORDS) );
...
}
void some_function()
{
ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_LEAKS) );
do_something_you_suspect_is_leaking();
ESP_ERROR_CHECK( heap_trace_stop() );
heap_trace_dump();
...
}
The output from the heap trace will look something like this:
(Above example output is using IDF Monitor to automatically decode PC addresses to their source files & line number.)
The first line indicates how many allocation entries are in the buffer, compared to its total size.
In HEAP_TRACE_LEAKS mode, for each traced memory allocation which has not already been freed a line is printed
with:
Host-Based Mode Once you’ve identified the code which you think is leaking:
• In the project configuration menu, navigate to Component settings -> Heap Memory Debugging
-> CONFIG_HEAP_TRACING_DEST and select Host-Based.
• In the project configuration menu, navigate to Component settings -> Application Level Trac-
ing -> CONFIG_APPTRACE_DESTINATION1 and select Trace memory.
• In the project configuration menu, navigate to Component settings -> Application Level Trac-
ing -> FreeRTOS SystemView Tracing and enable CONFIG_APPTRACE_SV_ENABLE.
• Call the function heap_trace_init_tohost() early in the program, to initialize JTAG heap tracing
module.
• Call the function heap_trace_start() to begin recording all mallocs/frees in the system. Call this
immediately before the piece of code which you suspect is leaking memory. In host-based mode, the argument
to this function is ignored, and the heap tracing module behaves like HEAP_TRACE_ALL was passed: all
allocations and deallocations are sent to the host.
• Call the function heap_trace_stop() to stop the trace once the suspect piece of code has finished exe-
cuting.
An example:
#include "esp_heap_trace.h"
...
void app_main()
{
...
ESP_ERROR_CHECK( heap_trace_init_tohost() );
...
}
(continues on next page)
void some_function()
{
ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_LEAKS) );
do_something_you_suspect_is_leaking();
ESP_ERROR_CHECK( heap_trace_stop() );
...
}
Note: In order to use this feature you need OpenOCD version v0.10.0-esp32-20181105 or later.
3. You can use GDB to start and/or stop tracing automatically. To do this you need to prepare special gdbinit
file:
tb heap_trace_start
commands
mon esp sysview start file:///tmp/heap.svdat
c
end
tb heap_trace_stop
commands
mon esp sysview stop
end
Using this file GDB will connect to the target, reset it, and start tracing when program hits breakpoint at
heap_trace_start(). Trace data will be saved to /tmp/heap_log.svdat. Tracing will be stopped when
program hits breakpoint at heap_trace_stop().
4. Run GDB using the following command xtensa-esp32-elf-gdb -x gdbinit </path/to/
program/elf>
5. Quit GDB when program stops at heap_trace_stop(). Trace data are saved in /tmp/heap.svdat
6. Run processing script $IDF_PATH/tools/esp_app_trace/sysviewtrace_proc.py -p -b
</path/to/program/elf> /tmp/heap_log.svdat
The output from the heap trace will look something like this:
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
[0.002258425] HEAP: Allocated 2 bytes @ 0x3ffaffe0 from task "alloc" on core 0 by:
(continues on next page)
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
[0.002563725] HEAP: Freed bytes @ 0x3ffaffe0 from task "free" on core 0 by:
/home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/
,→sysview_heap_log.c:31 (discriminator 9)
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
[0.002782950] HEAP: Freed bytes @ 0x3ffb40b8 from task "main" on core 0 by:
/home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590
/home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590
[0.002798700] HEAP: Freed bytes @ 0x3ffb50bc from task "main" on core 0 by:
/home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590
/home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590
[0.102436025] HEAP: Allocated 2 bytes @ 0x3ffaffe0 from task "alloc" on core 0 by:
/home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/
,→sysview_heap_log.c:47
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
[0.102449800] HEAP: Allocated 4 bytes @ 0x3ffaffe8 from task "alloc" on core 0 by:
/home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/
,→sysview_heap_log.c:48
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
[0.102666150] HEAP: Freed bytes @ 0x3ffaffe8 from task "free" on core 0 by:
/home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/
,→sysview_heap_log.c:31 (discriminator 9)
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
[0.202436200] HEAP: Allocated 3 bytes @ 0x3ffaffe8 from task "alloc" on core 0 by:
/home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/
,→sysview_heap_log.c:47
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
[0.202451725] HEAP: Allocated 6 bytes @ 0x3ffafff0 from task "alloc" on core 0 by:
/home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/
,→sysview_heap_log.c:48
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
[0.202667075] HEAP: Freed bytes @ 0x3ffafff0 from task "free" on core 0 by:
/home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/
,→sysview_heap_log.c:31 (discriminator 9)
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
[0.302436000] HEAP: Allocated 4 bytes @ 0x3ffafff0 from task "alloc" on core 0 by:
/home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/
,→sysview_heap_log.c:47
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
[0.302451475] HEAP: Allocated 8 bytes @ 0x3ffb40b8 from task "alloc" on core 0 by:
/home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/
,→sysview_heap_log.c:48
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
[0.302667500] HEAP: Freed bytes @ 0x3ffb40b8 from task "free" on core 0 by:
/home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/
,→sysview_heap_log.c:31 (discriminator 9)
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
(continues on next page)
Processing completed.
Processed 1019 events
=============== HEAP TRACE REPORT ===============
Processed 14 heap events.
[0.002244575] HEAP: Allocated 1 bytes @ 0x3ffaffd8 from task "alloc" on core 0 by:
/home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/
,→sysview_heap_log.c:47
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
[0.102436025] HEAP: Allocated 2 bytes @ 0x3ffaffe0 from task "alloc" on core 0 by:
/home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/
,→sysview_heap_log.c:47
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
[0.202436200] HEAP: Allocated 3 bytes @ 0x3ffaffe8 from task "alloc" on core 0 by:
/home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/
,→sysview_heap_log.c:47
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
[0.302436000] HEAP: Allocated 4 bytes @ 0x3ffafff0 from task "alloc" on core 0 by:
/home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/
,→sysview_heap_log.c:47
/home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
Heap Tracing To Find Heap Corruption Heap tracing can also be used to help track down heap corruption.
When a region in heap is corrupted, it may be from some other part of the program which allocated memory at a
nearby address.
If you have some idea at what time the corruption occurred, enabling heap tracing in HEAP_TRACE_ALL mode
allows you to record all the functions which allocated memory, and the addresses of the allocations.
Using heap tracing in this way is very similar to memory leak detection as described above. For memory which is
allocated and not freed, the output is the same. However, records will also be shown for memory which has been
freed.
Performance Impact Enabling heap tracing in menuconfig increases the code size of your program, and has a very
small negative impact on performance of heap allocation/free operations even when heap tracing is not running.
When heap tracing is running, heap allocation/free operations are substantially slower than when heap tracing is
stopped. Increasing the depth of stack frames recorded for each allocation (see above) will also increase this perfor-
mance impact.
False-Positive Memory Leaks Not everything printed by heap_trace_dump() is necessarily a memory leak.
Among things which may show up here, but are not memory leaks:
• Any memory which is allocated after heap_trace_start() but then freed after
heap_trace_stop() will appear in the leak dump.
• Allocations may be made by other tasks in the system. Depending on the timing of these tasks, it’s quite
possible this memory is freed after heap_trace_stop() is called.
• The first time a task uses stdio - for example, when it calls printf() - a lock (RTOS mutex semaphore) is
allocated by the libc. This allocation lasts until the task is deleted.
• Certain uses of printf(), such as printing floating point numbers, will allocate some memory from the heap
on demand. These allocations last until the task is deleted.
• The Bluetooth, Wi-Fi, and TCP/IP libraries will allocate heap memory buffers to handle incoming or outgoing
data. These memory buffers are usually short-lived, but some may be shown in the heap leak trace if the data
was received/transmitted by the lower levels of the network while the leak trace was running.
• TCP connections will continue to use some memory after they are closed, because of the TIME_WAIT state.
After the TIME_WAIT period has completed, this memory will be freed.
One way to differentiate between “real”and “false positive”memory leaks is to call the suspect code multiple
times while tracing is running, and look for patterns (multiple matching allocations) in the heap trace output.
Header File
• components/heap/include/esp_heap_trace.h
Functions
esp_err_t heap_trace_init_standalone(heap_trace_record_t *record_buffer, size_t num_records)
Initialise heap tracing in standalone mode.
This function must be called before any other heap tracing functions.
To disable heap tracing and allow the buffer to be freed, stop tracing and then call
heap_trace_init_standalone(NULL, 0);
Parameters
• record_buffer –Provide a buffer to use for heap trace data. Must remain valid any
time heap tracing is enabled, meaning it must be allocated from internal memory not in
PSRAM.
• num_records –Size of the heap trace buffer, as number of record structures.
Returns
• ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in
menuconfig.
• ESP_ERR_INVALID_STATE Heap tracing is currently in progress.
• ESP_OK Heap tracing initialised successfully.
esp_err_t heap_trace_init_tohost(void)
Initialise heap tracing in host-based mode.
This function must be called before any other heap tracing functions.
Returns
• ESP_ERR_INVALID_STATE Heap tracing is currently in progress.
• ESP_OK Heap tracing initialised successfully.
esp_err_t heap_trace_start(heap_trace_mode_t mode)
Start heap tracing. All heap allocations & frees will be traced, until heap_trace_stop() is called.
Note: heap_trace_init_standalone() must be called to provide a valid buffer, before this function is called.
Note: Calling this function while heap tracing is running will reset the heap trace state and continue tracing.
esp_err_t heap_trace_stop(void)
Stop heap tracing.
Returns
• ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in
menuconfig.
• ESP_ERR_INVALID_STATE Heap tracing was not in progress.
• ESP_OK Heap tracing stopped..
esp_err_t heap_trace_resume(void)
Resume heap tracing which was previously stopped.
Unlike heap_trace_start(), this function does not clear the buffer of any pre-existing trace records.
The heap trace mode is the same as when heap_trace_start() was last called (or HEAP_TRACE_ALL if
heap_trace_start() was never called).
Returns
• ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in
menuconfig.
• ESP_ERR_INVALID_STATE Heap tracing was already started.
• ESP_OK Heap tracing resumed.
size_t heap_trace_get_count(void)
Return number of records in the heap trace buffer.
It is safe to call this function while heap tracing is running.
esp_err_t heap_trace_get(size_t index, heap_trace_record_t *record)
Return a raw record from the heap trace buffer.
Note: It is safe to call this function while heap tracing is running, however in HEAP_TRACE_LEAK mode
record indexing may skip entries unless heap tracing is stopped first.
Parameters
• index –Index (zero-based) of the record to return.
• record –[out] Record where the heap trace record will be copied.
Returns
• ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in
menuconfig.
• ESP_ERR_INVALID_STATE Heap tracing was not initialised.
• ESP_ERR_INVALID_ARG Index is out of bounds for current heap trace record count.
• ESP_OK Record returned successfully.
void heap_trace_dump(void)
Dump heap trace record data to stdout.
Note: It is safe to call this function while heap tracing is running, however in HEAP_TRACE_LEAK mode
the dump may skip entries unless heap tracing is stopped first.
Structures
struct heap_trace_record_t
Trace record data type. Stores information about an allocated region of memory.
Public Members
uint32_t ccount
CCOUNT of the CPU when the allocation was made. LSB (bit value 1) is the CPU number (0 or 1).
void *address
Address which was allocated.
size_t size
Size of the allocation.
void *alloced_by[CONFIG_HEAP_TRACING_STACK_DEPTH]
Call stack of the caller which allocated the memory.
void *freed_by[CONFIG_HEAP_TRACING_STACK_DEPTH]
Call stack of the caller which freed the memory (all zero if not freed.)
Macros
CONFIG_HEAP_TRACING_STACK_DEPTH
Enumerations
enum heap_trace_mode_t
Values:
enumerator HEAP_TRACE_ALL
enumerator HEAP_TRACE_LEAKS
Overview
Although FreeRTOS provides software timers, these timers have a few limitations:
• Maximum resolution is equal to RTOS tick period
• Timer callbacks are dispatched from a low-priority task
Hardware timers are free from both of the limitations, but often they are less convenient to use. For example,
application components may need timer events to fire at certain times in the future, but the hardware timer only
contains one “compare”value used for interrupt generation. This means that some facility needs to be built on top
of the hardware timer to manage the list of pending events can dispatch the callbacks for these events as corresponding
hardware interrupts happen.
An interrupt level of the handler depends on the CONFIG_ESP_TIMER_INTERRUPT_LEVEL option. It allows to set
this: 1, 2 or 3 level (by default 1). Raising the level, the interrupt handler can reduce the timer processing delay.
esp_timer set of APIs provides one-shot and periodic timers, microsecond time resolution, and 64-bit range.
Internally, esp_timer uses a 64-bit hardware timer, where the implementation depends on the target. LAC timer
is used for ESP32.
Timer callbacks can be dispatched by two methods:
• ESP_TIMER_TASK
• ESP_TIMER_ISR. Available only if CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is en-
abled (by default disabled).
ESP_TIMER_TASK. Timer callbacks are dispatched from a high-priority esp_timer task. Because all the call-
backs are dispatched from the same task, it is recommended to only do the minimal possible amount of work from
the callback itself, posting an event to a lower priority task using a queue instead.
If other tasks with priority higher than esp_timer are running, callback dispatching will be delayed until
esp_timer task has a chance to run. For example, this will happen if an SPI Flash operation is in progress.
ESP_TIMER_ISR. Timer callbacks are dispatched directly from the timer interrupt handler. This method is useful
for some simple callbacks which aim for lower latency.
Creating and starting a timer, and dispatching the callback takes some time. Therefore, there is a lower limit to the
timeout value of one-shot esp_timer. If esp_timer_start_once() is called with a timeout value less than
20us, the callback will be dispatched only after approximately 20us.
Periodic esp_timer also imposes a 50us restriction on the minimal timer period. Periodic software timers with
period of less than 50us are not practical since they would consume most of the CPU time. Consider using dedicated
hardware peripherals or DMA features if you find that a timer with small period is required.
Single timer is represented by esp_timer_handle_t type. Timer has a callback function associated with it.
This callback function is called from the esp_timer task each time the timer elapses.
• To create a timer, call esp_timer_create().
• To delete the timer when it is no longer needed, call esp_timer_delete().
The timer can be started in one-shot mode or in periodic mode.
• To start the timer in one-shot mode, call esp_timer_start_once(), passing the time interval after
which the callback should be called. When the callback gets called, the timer is considered to be stopped.
• To start the timer in periodic mode, call esp_timer_start_periodic(), passing the period with which
the callback should be called. The timer keeps running until esp_timer_stop() is called.
Note that the timer must not be running when esp_timer_start_once() or
esp_timer_start_periodic() is called. To restart a running timer, call esp_timer_stop()
first, then call one of the start functions.
Callback functions
Note: Keep the callback functions as short as possible otherwise it will affect all timers.
Timer callbacks which are processed by ESP_TIMER_ISR method should not call the
context switch call - portYIELD_FROM_ISR(), instead of this you should use the
esp_timer_isr_dispatch_need_yield() function. The context switch will be done after all ISR
dispatch timers have been processed, if required by the system.
During light sleep, the esp_timer counter stops and no callback functions are called. Instead, the time is counted
by the RTC counter. Upon waking up, the system gets the difference between the counters and calls a function that
advances the esp_timer counter. Since the counter has been advanced, the system starts calling callbacks that were
not called during sleep. The number of callbacks depends on the duration of the sleep and the period of the timers.
It can lead to overflow of some queues. This only applies to periodic timers, one-shot timers will be called once.
This behavior can be changed by calling esp_timer_stop() before sleeping. In some cases, this can
be inconvenient, and instead of the stop function, you can use the skip_unhandled_events option during
esp_timer_create(). When the skip_unhandled_events is true, if a periodic timer expires one or more times
during light sleep then only one callback is called on wake.
Using the skip_unhandled_events option with automatic light sleep (see Power Management APIs) helps to reduce the
consumption of the system when it is in light sleep. The duration of light sleep is also determined by esp_timers.
Timers with skip_unhandled_events option will not wake up the system.
Handling callbacks
esp_timer is designed to achieve a high-resolution low latency timer and the ability to handle delayed events. If the
timer is late then the callback will be called as soon as possible, it will not be lost. In the worst case, when the timer has
not been processed for more than one period (for periodic timers), in this case the callbacks will be called one after
the other without waiting for the set period. This can be bad for some applications, and the skip_unhandled_events
option was introduced to eliminate this behavior. If skip_unhandled_events is set then a periodic timer that has expired
multiple times without being able to call the callback will still result in only one callback event once processing is
possible.
esp_timer also provides a convenience function to obtain the time passed since start-up, with microsecond pre-
cision: esp_timer_get_time(). This function returns the number of microseconds since esp_timer was
initialized, which usually happens shortly before app_main function is called.
Unlike gettimeofday function, values returned by esp_timer_get_time():
• Start from zero after the chip wakes up from deep sleep
• Do not have timezone or DST adjustments applied
Application Example
API Reference
Header File
• components/esp_timer/include/esp_timer.h
Functions
esp_err_t esp_timer_early_init(void)
Minimal initialization of esp_timer.
This function can be called very early in startup process, after this call only esp_timer_get_time function can
be used.
Note: This function is called from startup code. Applications do not need to call this function before using
other esp_timer APIs.
Returns
• ESP_OK on success
esp_err_t esp_timer_init(void)
Initialize esp_timer library.
Note: This function is called from startup code. Applications do not need to call this function before using
other esp_timer APIs. Before calling this function, esp_timer_early_init must be called by the startup code.
Returns
• ESP_OK on success
• ESP_ERR_NO_MEM if allocation has failed
• ESP_ERR_INVALID_STATE if already initialized
• other errors from interrupt allocator
esp_err_t esp_timer_deinit(void)
De-initialize esp_timer library.
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if not yet initialized
Note: When done using the timer, delete it with esp_timer_delete function.
Parameters
• create_args –Pointer to a structure with timer creation arguments. Not saved by the
library, can be allocated on the stack.
• out_handle –[out] Output, pointer to esp_timer_handle_t variable which will hold the
created timer handle.
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if some of the create_args are not valid
• ESP_ERR_INVALID_STATE if esp_timer library is not initialized yet
• ESP_ERR_NO_MEM if memory allocation fails
Parameters
• timer –timer handle created using esp_timer_create
• period –timer period, in microseconds
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if the handle is invalid
• ESP_ERR_INVALID_STATE if the timer is already running
esp_err_t esp_timer_stop(esp_timer_handle_t timer)
Stop the timer.
This function stops the timer previously started using esp_timer_start_once or esp_timer_start_periodic.
Parameters timer –timer handle created using esp_timer_create
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if the timer is not running
esp_err_t esp_timer_delete(esp_timer_handle_t timer)
Delete an esp_timer instance.
The timer must be stopped before deleting. A one-shot timer which has expired does not need to be stopped.
Parameters timer –timer handle allocated using esp_timer_create
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if the timer is running
int64_t esp_timer_get_time(void)
Get time in microseconds since boot.
Returns number of microseconds since underlying timer has been started
int64_t esp_timer_get_next_alarm(void)
Get the timestamp when the next timeout is expected to occur.
Returns Timestamp of the nearest timer event, in microseconds. The timebase is the same as for
the values returned by esp_timer_get_time.
int64_t esp_timer_get_next_alarm_for_wake_up(void)
Get the timestamp when the next timeout is expected to occur skipping those which have
skip_unhandled_events flag.
Returns Timestamp of the nearest timer event, in microseconds. The timebase is the same as for
the values returned by esp_timer_get_time.
esp_err_t esp_timer_get_period(esp_timer_handle_t timer, uint64_t *period)
Get the period of a timer.
This function fetches the timeout period of a timer.
Note: The timeout period is the time interval with which a timer restarts after expiry. For one-shot timers,
the period is 0 as there is no periodicity associated with such timers.
Parameters
• timer –timer handle allocated using esp_timer_create
• period –memory to store the timer period value in microseconds
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if the arguments are invalid
Note: This API returns a valid expiry time only for a one-shot timer. It returns an error if the timer handle
passed to the function is for a periodic timer.
Parameters
• timer –timer handle allocated using esp_timer_create
• expiry –memory to store the timeout value in microseconds
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if the arguments are invalid
• ESP_ERR_NOT_SUPPORTED if the timer type is periodic
Structures
struct esp_timer_create_args_t
Timer configuration passed to esp_timer_create.
Public Members
esp_timer_cb_t callback
Function to call when timer expires.
void *arg
Argument to pass to the callback.
esp_timer_dispatch_t dispatch_method
Call the callback from task or from ISR.
bool skip_unhandled_events
Skip unhandled events for periodic timers.
Type Definitions
Enumerations
enum esp_timer_dispatch_t
Method for dispatching timer callback.
Values:
enumerator ESP_TIMER_TASK
Callback is called from timer task.
enumerator ESP_TIMER_MAX
Count of the methods for dispatching timer callback.
This section is listing some APIs that are internal or likely to be changed or removed in the next releases of ESP-IDF.
API Reference
Header File
• components/esp_rom/include/esp_rom_sys.h
Functions
int esp_rom_printf(const char *fmt, ...)
Print formated string to console device.
Parameters
• fmt –Format string
• ... –Additional arguments, depending on the format string
Returns int: Total number of characters written on success; A negative number on failure.
void esp_rom_delay_us(uint32_t us)
Pauses execution for us microseconds.
Parameters us –Number of microseconds to pause
void esp_rom_install_channel_putc(int channel, void (*putc)(char c))
esp_rom_printf can print message to different channels simultaneously. This function can help install the low
level putc function for esp_rom_printf.
Parameters
• channel –Channel number (startting from 1)
• putc –Function pointer to the putc implementation. Set NULL can disconnect
esp_rom_printf with putc.
void esp_rom_install_uart_printf(void)
Install UART1 as the default console channel, equivalent to esp_rom_install_channel_putc(1,
esp_rom_uart_putc)
soc_reset_reason_t esp_rom_get_reset_reason(int cpu_no)
Get reset reason of CPU.
Parameters cpu_no –CPU number
Returns Reset reason code (see in soc/reset_reasons.h)
void esp_rom_route_intr_matrix(int cpu_core, uint32_t periph_intr_id, uint32_t cpu_intr_num)
Route peripheral interrupt sources to CPU’s interrupt port by matrix.
Usually there’re 4 steps to use an interrupt:
a. Route peripheral interrupt source to CPU. e.g. esp_rom_route_intr_matrix(0,
ETS_WIFI_MAC_INTR_SOURCE, ETS_WMAC_INUM)
b. Set interrupt handler for CPU
c. Enable CPU interupt
d. Enable peripheral interrupt
Parameters
• cpu_core –The CPU number, which the peripheral interupt will inform to
• periph_intr_id –The peripheral interrupt source number
• cpu_intr_num –The CPU interrupt number
uint32_t esp_rom_get_cpu_ticks_per_us(void)
Get the real CPU ticks per us.
Returns CPU ticks per us
Note: The IPC is an Inter-Processor Call and NOT Inter-Process Communication as found on other operating
systems.
Overview
Due to the dual core nature of the ESP32, there are instances where a certain callback must be run in the context of
a particular CPU such as:
• When allocating an ISR to an interrupt source of a particular CPU (applies to freeing a particular CPU’s
interrupt source as well).
• On particular chips (such as the ESP32), accessing memory that is exclusive to a particular CPU (such as RTC
Fast Memory).
• Reading the registers/state of another CPU.
The IPC (Inter-Processor Call) feature allows a particular CPU (the calling CPU) to trigger the execution of a callback
function on another CPU (the target CPU). The IPC feature allows execution of a callback function on the target CPU
in either a task context, or a High Priority Interrupt context (see High-Level Interrupts for more details). Depending on
the context that the callback function is executed in, different restrictions apply to the implementation of the callback
function.
The IPC feature implements callback execution in a task context by creating an IPC task for each CPU during
application startup. When the calling CPU needs to execute a callback on the target CPU, the callback will execute
in the context of the target CPU’s IPC task.
When using IPCs in a task context, users need to consider the following:
• IPC callbacks should ideally be simple and short. An IPC callback should avoid attempting to block or
yield.
• The IPC tasks are created at the highest possible priority (i.e., configMAX_PRIORITIES - 1) thus the
callback should also run at that priority as a result. However, CONFIG_ESP_IPC_USES_CALLERS_PRIORITY
is enabled by default which will temporarily lower the priority of the target CPU’s IPC task to the calling
CPU before executing the callback.
• Depending on the complexity of the callback, users may need to configure the stack size of the IPC task via
CONFIG_ESP_IPC_TASK_STACK_SIZE.
• The IPC feature is internally protected by a mutex. Therefore, simultaneous IPC calls from two or more calling
CPUs will be handled on a first come first serve basis.
API Usage Task Context IPC callbacks have the following restrictions:
• The callback must be of type void func(void *arg)
• The callback should avoid attempting to block or yield as this will result in the target CPU’s IPC task blocking
or yielding.
• The callback must avoid changing any aspect of the IPC task (e.g., by calling vTaskPrioritySet(NULL,
x)).
The IPC feature offers the API listed below to execute a callback in a task context on a target CPU. The API allows
the calling CPU to block until the callback’s execution has completed, or return immediately once the callback’s
execution has started.
• esp_ipc_call() will trigger an IPC call on the target CPU. This function will block until the target CPU’
s IPC task begins execution of the callback.
• esp_ipc_call_blocking() will trigger an IPC on the target CPU. This function will block until the
target CPU’s IPC task completes execution of the callback.
In some cases, we need to quickly obtain the state of another CPU such as in a core dump, GDB stub, various
unit tests, and DPORT workaround. For such scenarios, the IPC feature supports execution of callbacks in a High
Priority Interrupt context. The IPC feature implements the High Priority Interrupt context by reserving a High Priority
Interrupt on each CPU for IPC usage. When a calling CPU needs to execute a callback on the target CPU, the callback
will execute in the context of the High Priority Interrupt of the target CPU.
When using IPCs in High Priority Interrupt context, users need to consider the following:
• Since the callback is executed in a High Priority Interrupt context, the callback must be written entirely in
assembly. See the API Usage below for more details regarding writing assembly callbacks.
• The priority of the reserved High Priority Interrupt is dependent on the CON-
FIG_ESP_SYSTEM_CHECK_INT_LEVEL option
• When the callback executes:
– The calling CPU will disable interrupts of level 3 and lower
– Although the priority of the reserved interrupt depends on CON-
FIG_ESP_SYSTEM_CHECK_INT_LEVEL, during the execution IPC ISR callback, the
target CPU will disable interrupts of level 5 and lower regardless of what CON-
FIG_ESP_SYSTEM_CHECK_INT_LEVEL is set to.
API Usage High Priority Interrupt IPC callbacks have the following restrictions:
• The callback must be of type void func(void *arg) but implemented entirely in assembly
• The callback is invoked via the CALLX0 instruction with register windowing disabled, thus the callback:
– Must not call any register window related instructions (e.g., entry and retw).
– Must not call other C functions as register windowing is disabled
• The callback should be placed in IRAM at a 4-byte aligned address
• (On invocation of/after returning from) the callback, the registers a2, a3, a4 are (saved/restored) automatically thu
/* esp_test_ipc_isr_get_cycle_count_other_cpu(void *arg) */
// this function reads CCOUNT of the target CPU and stores it in arg.
// use only a2, a3 and a4 regs here.
.section .iram1, "ax"
.align 4
.global esp_test_ipc_isr_get_cycle_count_other_cpu
.type esp_test_ipc_isr_get_cycle_count_other_cpu, @function
// Args:
// a2 - void* arg
esp_test_ipc_isr_get_cycle_count_other_cpu:
rsr.ccount a3
s32i a3, a2, 0
ret
unit32_t cycle_count;
esp_ipc_isr_asm_call_blocking(esp_test_ipc_isr_get_cycle_count_other_cpu, (void␣
,→*)cycle_count);
Note: The number of scratch registers available for use is sufficient for most simple use cases. But if your callback
requires more scratch registers, void *arg can point to a buffer that is used as a register save area. The callback
can then save and restore more registers. See the system/ipc/ipc_isr.
Note: For more examples of High Priority Interrupt IPC callbacks, see compo-
nents/esp_system/port/arch/xtensa/esp_ipc_isr_routines.S and :components/esp_system/test/test_ipc_isr.S
The High Priority Interrupt IPC API also provides the following convenience functions that can stall/resume the target
CPU. These API utilize the High Priority Interrupt IPC, but supply their own internal callbacks:
• esp_ipc_isr_stall_other_cpu() stalls the target CPU. The calling CPU disables interrupts of level
3 and lower while the target CPU will busy-wait with interrupts of level 5 and lower disabled. The target CPU
will busy-wait until esp_ipc_isr_release_other_cpu() is called.
• esp_ipc_isr_release_other_cpu() resumes the target CPU.
API Reference
Header File
• components/esp_system/include/esp_ipc.h
Functions
esp_err_t esp_ipc_call(uint32_t cpu_id, esp_ipc_func_t func, void *arg)
Execute a callback on a given CPU.
Execute a given callback on a particular CPU. The callback must be of type “esp_ipc_func_t”and will be
invoked in the context of the target CPU’s IPC task.
• This function will block the target CPU’s IPC task has begun execution of the callback
• If another IPC call is ongoing, this function will block until the ongoing IPC call completes
• The stack size of the IPC task can be configured via the CONFIG_ESP_IPC_TASK_STACK_SIZE
option
Parameters
• cpu_id –[in] CPU where the given function should be executed (0 or 1)
• func –[in] Pointer to a function of type void func(void* arg) to be executed
• arg –[in] Arbitrary argument of type void* to be passed into the function
Returns
• ESP_ERR_INVALID_ARG if cpu_id is invalid
• ESP_ERR_INVALID_STATE if the FreeRTOS scheduler is not running
• ESP_OK otherwise
esp_err_t esp_ipc_call_blocking(uint32_t cpu_id, esp_ipc_func_t func, void *arg)
Execute a callback on a given CPU until and block until it completes.
This function is identical to esp_ipc_call() except that this function will block until the execution of the callback
completes.
Parameters
• cpu_id –[in] CPU where the given function should be executed (0 or 1)
• func –[in] Pointer to a function of type void func(void* arg) to be executed
• arg –[in] Arbitrary argument of type void* to be passed into the function
Returns
• ESP_ERR_INVALID_ARG if cpu_id is invalid
• ESP_ERR_INVALID_STATE if the FreeRTOS scheduler is not running
• ESP_OK otherwise
Type Definitions
Header File
• components/esp_system/include/esp_ipc_isr.h
Functions
void esp_ipc_isr_asm_call(esp_ipc_isr_func_t func, void *arg)
Execute an assembly callback on the other CPU.
Execute a given callback on the other CPU in the context of a High Priority Interrupt.
• This function will busy-wait in a critical section until the other CPU has started execution of the callback
• The callback must be written in assembly, is invoked using a CALLX0 instruction, and has a2, a3, a4 as
scratch registers. See docs for more details
Parameters
• func –[in] Pointer to a function of type void func(void* arg) to be executed
• arg –[in] Arbitrary argument of type void* to be passed into the function
void esp_ipc_isr_asm_call_blocking(esp_ipc_isr_func_t func, void *arg)
Execute an assembly callback on the other CPU and busy-wait until it completes.
This function is identical to esp_ipc_isr_asm_call() except that this function will busy-wait until the execution
of the callback completes.
Parameters
• func –[in] Pointer to a function of type void func(void* arg) to be executed
• arg –[in] Arbitrary argument of type void* to be passed into the function
void esp_ipc_isr_stall_other_cpu(void)
Stall the other CPU.
This function will stall the other CPU. The other CPU is stalled by busy-waiting in the context of a High
Priority Interrupt. The other CPU will not be resumed until esp_ipc_isr_release_other_cpu() is called.
void esp_ipc_isr_release_other_cpu(void)
Release the other CPU.
This function will release the other CPU that was previously stalled from calling esp_ipc_isr_stall_other_cpu()
void esp_ipc_isr_stall_pause(void)
Puase the CPU stall feature.
This function will pause the CPU stall feature. Once paused, calls to esp_ipc_isr_stall_other_cpu() and
esp_ipc_isr_release_other_cpu() will have no effect. If a IPC ISR call is already in progress, this function
will busy-wait until the call completes before pausing the CPU stall feature.
void esp_ipc_isr_stall_abort(void)
Abort a CPU stall.
This function will abort any stalling routine of the other CPU due to a pervious call to
esp_ipc_isr_stall_other_cpu(). This function aborts the stall in a non-recoverable manner, thus should
only be called in case of a panic().
Type Definitions
Overview
The ESP32 has two cores, with 32 interrupts each. Each interrupt has a certain priority level, most (but not all)
interrupts are connected to the interrupt mux.
Because there are more interrupt sources than interrupts, sometimes it makes sense to share an interrupt in multiple
drivers. The esp_intr_alloc() abstraction exists to hide all these implementation details.
A driver can allocate an interrupt for a certain peripheral by calling esp_intr_alloc() (or
esp_intr_alloc_intrstatus()). It can use the flags passed to this function to set the type of inter-
rupt allocated, specifying a particular level or trigger method. The interrupt allocation code will then find an
applicable interrupt, use the interrupt mux to hook it up to the peripheral, and install the given interrupt handler and
ISR to it.
This code presents two different types of interrupts, handled differently: shared interrupts and non-shared interrupts.
The simplest ones are non-shared interrupts: a separate interrupt is allocated per esp_intr_alloc() call and
this interrupt is solely used for the peripheral attached to it, with only one ISR that will get called. On the other
hand, shared interrupts can have multiple peripherals triggering them, with multiple ISRs being called when one of
the peripherals attached signals an interrupt. Thus, ISRs that are intended for shared interrupts should check the
interrupt status of the peripheral they service in order to check if any action is required.
Non-shared interrupts can be either level- or edge-triggered. Shared interrupts can only be level interrupts due to the
chance of missed interrupts when edge interrupts are used.
For example, let’s say DevA and DevB share an interrupt. DevB signals an interrupt, so INT line goes high. The
ISR handler calls code for DevA but does nothing. Then, ISR handler calls code for DevB, but while doing that,
DevA signals an interrupt. DevB’s ISR is done, it clears interrupt status for DevB and exits interrupt code. Now,
an interrupt for DevA is still pending, but because the INT line never went low, as DevA kept it high even when the
interrupt for DevB was cleared, the interrupt is never serviced.
Multicore issues
Internal peripheral interrupts Each Xtensa CPU core has its own set of six internal peripherals:
• Three timer comparators
• A performance monitor
• Two software interrupts.
Internal interrupt sources are defined in esp_intr_alloc.h as ETS_INTERNAL_*_INTR_SOURCE.
These peripherals can only be configured from the core they are associated with. When generating an interrupt, the
interrupt they generate is hard-wired to their associated core; it’s not possible to have, for example, an internal timer
comparator of one core generate an interrupt on another core. That is why these sources can only be managed using
a task running on that specific core. Internal interrupt sources are still allocatable using esp_intr_alloc() as
normal, but they cannot be shared and will always have a fixed interrupt level (namely, the one associated in hardware
with the peripheral).
External Peripheral Interrupts The remaining interrupt sources are from external peripherals. These are defined
in soc/soc.h as ETS_*_INTR_SOURCE.
Non-internal interrupt slots in both CPU cores are wired to an interrupt multiplexer, which can be used to route any
external interrupt source to any of these interrupt slots.
• Allocating an external interrupt will always allocate it on the core that does the allocation.
• Freeing an external interrupt must always happen on the same core it was allocated on.
• Disabling and enabling external interrupts from another core is allowed.
• Multiple external interrupt sources can share an interrupt slot by passing ESP_INTR_FLAG_SHARED as a
flag to esp_intr_alloc().
Care should be taken when calling esp_intr_alloc() from a task which is not pinned to a core. During task
switching, these tasks can migrate between cores. Therefore it is impossible to tell which CPU the interrupt is
allocated on, which makes it difficult to free the interrupt handle and may also cause debugging difficulties. It is
advised to use xTaskCreatePinnedToCore() with a specific CoreID argument to create tasks that will allocate
interrupts. In the case of internal interrupt sources, this is required.
The ESP_INTR_FLAG_IRAM flag registers an interrupt handler that always runs from IRAM (and reads all its data
from DRAM), and therefore does not need to be disabled during flash erase and write operations.
This is useful for interrupts which need a guaranteed minimum execution latency, as flash write and erase operations
can be slow (erases can take tens or hundreds of milliseconds to complete).
It can also be useful to keep an interrupt handler in IRAM if it is called very frequently, to avoid flash cache misses.
Refer to the SPI flash API documentation for more details.
Several handlers can be assigned to a same source, given that all handlers are allocated using the
ESP_INTR_FLAG_SHARED flag. They will all be allocated to the interrupt, which the source is attached to, and
called sequentially when the source is active. The handlers can be disabled and freed individually. The source is
attached to the interrupt (enabled), if one or more handlers are enabled, otherwise detached. A handler will never be
called when disabled, while its source may still be triggered if any one of its handler enabled.
Sources attached to non-shared interrupt do not support this feature.
Though the framework support this feature, you have to use it very carefully. There usually exist two ways to stop
an interrupt from being triggered: disable the source or mask peripheral interrupt status. IDF only handles enabling
and disabling of the source itself, leaving status and mask bits to be handled by users. Status bits shall either
be masked before the handler responsible for it is disabled, either be masked and then properly handled
in another enabled interrupt. Please note that leaving some status bits unhandled without masking them, while
disabling the handlers for them, will cause the interrupt(s) to be triggered indefinitely, resulting therefore in a system
crash.
API Reference
Header File
• components/esp_hw_support/include/esp_intr_alloc.h
Functions
esp_err_t esp_intr_mark_shared(int intno, int cpu, bool is_in_iram)
Mark an interrupt as a shared interrupt.
This will mark a certain interrupt on the specified CPU as an interrupt that can be used to hook shared interrupt
handlers to.
Parameters
• intno –The number of the interrupt (0-31)
• cpu –CPU on which the interrupt should be marked as shared (0 or 1)
• is_in_iram –Shared interrupt is for handlers that reside in IRAM and the int can be
left enabled while the flash cache is disabled.
Returns ESP_ERR_INVALID_ARG if cpu or intno is invalid ESP_OK otherwise
esp_err_t esp_intr_reserve(int intno, int cpu)
Reserve an interrupt to be used outside of this framework.
This will mark a certain interrupt on the specified CPU as reserved, not to be allocated for any reason.
Parameters
• intno –The number of the interrupt (0-31)
• cpu –CPU on which the interrupt should be marked as shared (0 or 1)
Returns ESP_ERR_INVALID_ARG if cpu or intno is invalid ESP_OK otherwise
esp_err_t esp_intr_alloc(int source, int flags, intr_handler_t handler, void *arg, intr_handle_t *ret_handle)
Allocate an interrupt with the given parameters.
This finds an interrupt that matches the restrictions as given in the flags parameter, maps the given interrupt
source to it and hooks up the given interrupt handler (with optional argument) as well. If needed, it can return
a handle for the interrupt as well.
The interrupt will always be allocated on the core that runs this function.
If ESP_INTR_FLAG_IRAM flag is used, and handler address is not in IRAM or RTC_FAST_MEM, then
ESP_ERR_INVALID_ARG is returned.
Parameters
• source –The interrupt source. One of the ETS_*_INTR_SOURCE
interrupt mux sources, as defined in soc/soc.h, or one of the internal
ETS_INTERNAL_*_INTR_SOURCE sources as defined in this header.
• flags –An ORred mask of the ESP_INTR_FLAG_* defines. These restrict the choice
of interrupts that this routine can choose from. If this value is 0, it will default to allocating
a non-shared interrupt of level 1, 2 or 3. If this is ESP_INTR_FLAG_SHARED, it will
allocate a shared interrupt of level 1. Setting ESP_INTR_FLAG_INTRDISABLED will
return from this function with the interrupt disabled.
• handler –The interrupt handler. Must be NULL when an interrupt of level >3 is re-
quested, because these types of interrupts aren’t C-callable.
• arg –Optional argument for passed to the interrupt handler
• ret_handle –Pointer to an intr_handle_t to store a handle that can later be used to
request details or free the interrupt. Can be NULL if no handle is required.
Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid.
ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_OK
otherwise
esp_err_t esp_intr_alloc_intrstatus(int source, int flags, uint32_t intrstatusreg, uint32_t
intrstatusmask, intr_handler_t handler, void *arg, intr_handle_t
*ret_handle)
Allocate an interrupt with the given parameters.
This essentially does the same as esp_intr_alloc, but allows specifying a register and mask combo. For shared
interrupts, the handler is only called if a read from the specified register, ANDed with the mask, returns non-
zero. By passing an interrupt status register address and a fitting mask, this can be used to accelerate interrupt
handling in the case a shared interrupt is triggered; by checking the interrupt statuses first, the code can decide
which ISRs can be skipped
Parameters
• source –The interrupt source. One of the ETS_*_INTR_SOURCE
interrupt mux sources, as defined in soc/soc.h, or one of the internal
ETS_INTERNAL_*_INTR_SOURCE sources as defined in this header.
• flags –An ORred mask of the ESP_INTR_FLAG_* defines. These restrict the choice
of interrupts that this routine can choose from. If this value is 0, it will default to allocating
a non-shared interrupt of level 1, 2 or 3. If this is ESP_INTR_FLAG_SHARED, it will
allocate a shared interrupt of level 1. Setting ESP_INTR_FLAG_INTRDISABLED will
return from this function with the interrupt disabled.
• intrstatusreg –The address of an interrupt status register
• intrstatusmask –A mask. If a read of address intrstatusreg has any of the bits that
are 1 in the mask set, the ISR will be called. If not, it will be skipped.
• handler –The interrupt handler. Must be NULL when an interrupt of level >3 is re-
quested, because these types of interrupts aren’t C-callable.
• arg –Optional argument for passed to the interrupt handler
Note: When the handler shares its source with other handlers, the interrupt status bits it’s responsible for
should be managed properly before freeing it. see esp_intr_disable for more details. Please do not call
this function in esp_ipc_call_blocking.
Note:
a. For local interrupts (ESP_INTERNAL_* sources), this function has to be called on the CPU the interrupt
is allocated on. Other interrupts have no such restriction.
b. When several handlers sharing a same interrupt source, interrupt status bits, which are handled in the
handler to be disabled, should be masked before the disabling, or handled in other enabled interrupts
properly. Miss of interrupt status handling will cause infinite interrupt calls and finally system crash.
Note: For local interrupts (ESP_INTERNAL_* sources), this function has to be called on the CPU the
interrupt is allocated on. Other interrupts have no such restriction.
Parameters
• handle –The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus
• is_in_iram –Whether the handler associated with this handle resides in IRAM. Han-
dlers residing in IRAM can be called when cache is disabled.
Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_OK oth-
erwise
void esp_intr_noniram_disable(void)
Disable interrupts that aren’t specifically marked as running from IRAM.
void esp_intr_noniram_enable(void)
Re-enable interrupts disabled by esp_intr_noniram_disable.
void esp_intr_enable_source(int inum)
enable the interrupt source based on its number
Parameters inum –interrupt number from 0 to 31
void esp_intr_disable_source(int inum)
disable the interrupt source based on its number
Parameters inum –interrupt number from 0 to 31
static inline int esp_intr_flags_to_level(int flags)
Get the lowest interrupt level from the flags.
Parameters flags –The same flags that pass to esp_intr_alloc_intrstatus API
Macros
ESP_INTR_FLAG_LEVEL1
Interrupt allocation flags.
These flags can be used to specify which interrupt qualities the code calling esp_intr_alloc* needs. Accept a
Level 1 interrupt vector (lowest priority)
ESP_INTR_FLAG_LEVEL2
Accept a Level 2 interrupt vector.
ESP_INTR_FLAG_LEVEL3
Accept a Level 3 interrupt vector.
ESP_INTR_FLAG_LEVEL4
Accept a Level 4 interrupt vector.
ESP_INTR_FLAG_LEVEL5
Accept a Level 5 interrupt vector.
ESP_INTR_FLAG_LEVEL6
Accept a Level 6 interrupt vector.
ESP_INTR_FLAG_NMI
Accept a Level 7 interrupt vector (highest priority)
ESP_INTR_FLAG_SHARED
Interrupt can be shared between ISRs.
ESP_INTR_FLAG_EDGE
Edge-triggered interrupt.
ESP_INTR_FLAG_IRAM
ISR can be called if cache is disabled.
ESP_INTR_FLAG_INTRDISABLED
Return with this interrupt disabled.
ESP_INTR_FLAG_LOWMED
Low and medium prio interrupts. These can be handled in C.
ESP_INTR_FLAG_HIGH
High level interrupts. Need to be handled in assembly.
ESP_INTR_FLAG_LEVELMASK
Mask for all level flags.
ETS_INTERNAL_TIMER0_INTR_SOURCE
Platform timer 0 interrupt source.
The esp_intr_alloc* functions can allocate an int for all ETS_*_INTR_SOURCE interrupt sources that are
routed through the interrupt mux. Apart from these sources, each core also has some internal sources that do
not pass through the interrupt mux. To allocate an interrupt for these sources, pass these pseudo-sources to the
functions.
ETS_INTERNAL_TIMER1_INTR_SOURCE
Platform timer 1 interrupt source.
ETS_INTERNAL_TIMER2_INTR_SOURCE
Platform timer 2 interrupt source.
ETS_INTERNAL_SW0_INTR_SOURCE
Software int source 1.
ETS_INTERNAL_SW1_INTR_SOURCE
Software int source 2.
ETS_INTERNAL_PROFILING_INTR_SOURCE
Int source for profiling.
ETS_INTERNAL_INTR_SOURCE_OFF
Provides SystemView with positive IRQ IDs, otherwise scheduler events are not shown properly
ESP_INTR_ENABLE(inum)
Enable interrupt by interrupt number
ESP_INTR_DISABLE(inum)
Disable interrupt by interrupt number
Type Definitions
Overview
The logging library provides two ways for setting log verbosity:
• At compile time: in menuconfig, set the verbosity level using the option CONFIG_LOG_DEFAULT_LEVEL.
• Optionally, also in menuconfig, set the maximum verbosity level using the option CON-
FIG_LOG_MAXIMUM_LEVEL. By default this is the same as the default level, but it can be set higher
in order to compile more optional logs into the firmware.
• At runtime: all logs for verbosity levels lower than CONFIG_LOG_DEFAULT_LEVEL are enabled by default.
The function esp_log_level_set() can be used to set a logging level on a per module basis. Modules
are identified by their tags, which are human-readable ASCII zero-terminated strings.
There are the following verbosity levels:
• Error (lowest)
• Warning
• Info
• Debug
• Verbose (highest)
Note: The function esp_log_level_set() cannot set logging levels higher than specified by CON-
FIG_LOG_MAXIMUM_LEVEL. To increase log level for a specific file above this maximum at compile time, use
the macro LOG_LOCAL_LEVEL (see the details below).
In each C file that uses logging functionality, define the TAG variable as shown below:
ESP_LOGW(TAG, "Baud rate error %.1f%%. Requested: %d baud, actual: %d baud", error␣
,→* 100, baud_req, baud_real);
Note: Inside critical sections interrupts are disabled so it’s only possible to use ESP_DRAM_LOGx (preferred)
or ESP_EARLY_LOGx. Even though it’s possible to log in these situations, it’s better if your program can be
structured not to require it.
To override default verbosity level at file or component scope, define the LOG_LOCAL_LEVEL macro.
At file scope, define it before including esp_log.h, e.g.:
To configure logging output per module at runtime, add calls to the function esp_log_level_set() as follows:
Note: The “DRAM”and “EARLY”log macro variants documented above do not support per module setting of
log verbosity. These macros will always log at the “default”verbosity level, which can only be changed at runtime
by calling esp_log_level("*", level).
Logging to Host via JTAG By default, the logging library uses the vprintf-like function to write formatted output
to the dedicated UART. By calling a simple API, all log output may be routed to JTAG instead, making logging
several times faster. For details, please refer to Section Logging to Host.
Application Example
The logging library is commonly used by most esp-idf components and examples. For demonstration of log function-
ality, check ESP-IDF’s examples directory. The most relevant examples that deal with logging are the following:
• system/ota
• storage/sd_card
• protocols/https_request
API Reference
Header File
• components/log/include/esp_log.h
Functions
void esp_log_level_set(const char *tag, esp_log_level_t level)
Set log level for given tag.
If logging for given component has already been enabled, changes previous setting.
Note: Note that this function can not raise log level above the level set using CON-
FIG_LOG_MAXIMUM_LEVEL setting in menuconfig. To raise log level above the default one for a
given file, define LOG_LOCAL_LEVEL to one of the ESP_LOG_* values, before including esp_log.h in
this file.
Parameters
• tag –Tag of the log entries to enable. Must be a non-NULL zero terminated string. Value
“*”resets log level for all tags to the given value.
• level –Selects log level to enable. Only logs at this and lower verbosity levels will be
shown.
esp_log_level_t esp_log_level_get(const char *tag)
Get log level for a given tag, can be used to avoid expensive log statements.
Parameters tag –Tag of the log to query current level. Must be a non-NULL zero terminated
string.
Returns The current log level for the given tag
vprintf_like_t esp_log_set_vprintf(vprintf_like_t func)
Set function used to output log entries.
By default, log output goes to UART0. This function can be used to redirect log output to some other destina-
tion, such as file or network. Returns the original log handler, which may be necessary to return output to the
previous destination.
Note: Please note that function callback here must be re-entrant as it can be invoked in parallel from multiple
thread context.
Parameters func –new Function used for output. Must have same signature as vprintf.
Returns func old Function used for output.
uint32_t esp_log_timestamp(void)
Function which returns timestamp to be used in log output.
This function is used in expansion of ESP_LOGx macros. In the 2nd stage bootloader, and at early application
startup stage this function uses CPU cycle counter as time source. Later when FreeRTOS scheduler start
running, it switches to FreeRTOS tick count.
For now, we ignore millisecond counter overflow.
Returns timestamp, in milliseconds
char *esp_log_system_timestamp(void)
Function which returns system timestamp to be used in log output.
This function is used in expansion of ESP_LOGx macros to print the system time as“HH:MM:SS.sss”. The
system time is initialized to 0 on startup, this can be set to the correct time with an SNTP sync, or manually
with standard POSIX time functions.
Currently, this will not get used in logging from binary blobs (i.e. Wi-Fi & Bluetooth libraries), these will still
print the RTOS tick time.
Returns timestamp, in “HH:MM:SS.sss”
uint32_t esp_log_early_timestamp(void)
Function which returns timestamp to be used in log output.
This function uses HW cycle counter and does not depend on OS, so it can be safely used after application
crash.
Returns timestamp, in milliseconds
void esp_log_write(esp_log_level_t level, const char *tag, const char *format, ...)
Write message into the log.
This function is not intended to be used directly. Instead, use one of ESP_LOGE, ESP_LOGW, ESP_LOGI,
ESP_LOGD, ESP_LOGV macros.
This function or these macros should not be used from an interrupt.
void esp_log_writev(esp_log_level_t level, const char *tag, const char *format, va_list args)
Write message into the log, va_list variant.
This function is provided to ease integration toward other logging framework, so that esp_log can be used as a
log sink.
See also:
esp_log_write()
Macros
ESP_LOG_BUFFER_HEX_LEVEL(tag, buffer, buff_len, level)
Log a buffer of hex bytes at specified level, separated into 16 bytes each line.
Parameters
• tag –description tag
• buffer –Pointer to the buffer array
• buff_len –length of buffer in bytes
• level –level of the log
ESP_LOG_BUFFER_CHAR_LEVEL(tag, buffer, buff_len, level)
Log a buffer of characters at specified level, separated into 16 bytes each line. Buffer should contain only
printable characters.
Parameters
• tag –description tag
• buffer –Pointer to the buffer array
• buff_len –length of buffer in bytes
• level –level of the log
ESP_LOG_BUFFER_HEXDUMP(tag, buffer, buff_len, level)
Dump a buffer to the log at specified level.
The dump log shows just like the one below:
See also:
esp_log_buffer_hex_level
Parameters
• tag –description tag
• buffer –Pointer to the buffer array
• buff_len –length of buffer in bytes
See also:
esp_log_buffer_char_level
Parameters
• tag –description tag
• buffer –Pointer to the buffer array
• buff_len –length of buffer in bytes
See also:
ESP_EARLY_LOGE,ESP_LOGE, printf
See also:
ESP_EARLY_LOGE,ESP_LOGE, printf
ESP_EARLY_LOGD(tag, format, ...)
macro to output logs in startup code at ESP_LOG_DEBUG level.
See also:
ESP_EARLY_LOGE,ESP_LOGE, printf
ESP_EARLY_LOGV(tag, format, ...)
macro to output logs in startup code at ESP_LOG_VERBOSE level.
See also:
ESP_EARLY_LOGE,ESP_LOGE, printf
_ESP_LOG_EARLY_ENABLED(log_level)
See also:
printf
Parameters
• tag –tag of the log, which can be used to change the log level by esp_log_level_set
at runtime.
• level –level of the output log.
• format –format of the output log. See printf
• ... –variables to be replaced into the log. See printf
See also:
printf, ESP_LOG_LEVEL
Similar to
Usage: ESP_DRAM_LOGE(DRAM_STR("my_tag"), "format", orESP_DRAM_LOGE(TAG,
“format”, …)`, where TAG is a char* that points to a str in the DRAM.
See also:
ESP_EARLY_LOGE, the log level cannot be changed per-tag, however esp_log_level_set(“*”, level) will set
the default level which controls these log lines also.
See also:
esp_rom_printf,ESP_LOGE
Note: Unlike normal logging macros, it’s possible to use this macro when interrupts are disabled or inside
an ISR.
Note: Placing log strings in DRAM reduces available DRAM, so only use when absolutely essential.
See also:
ESP_DRAM_LOGW,ESP_LOGW, esp_rom_printf
ESP_DRAM_LOGI(tag, format, ...)
macro to output logs when the cache is disabled at ESP_LOG_INFO level.
See also:
ESP_DRAM_LOGI,ESP_LOGI, esp_rom_printf
ESP_DRAM_LOGD(tag, format, ...)
macro to output logs when the cache is disabled at ESP_LOG_DEBUG level.
See also:
ESP_DRAM_LOGD,ESP_LOGD, esp_rom_printf
ESP_DRAM_LOGV(tag, format, ...)
macro to output logs when the cache is disabled at ESP_LOG_VERBOSE level.
See also:
ESP_DRAM_LOGV,ESP_LOGV, esp_rom_printf
Type Definitions
Enumerations
enum esp_log_level_t
Log level.
Values:
enumerator ESP_LOG_NONE
No log output
enumerator ESP_LOG_ERROR
Critical errors, software module can not recover on its own
enumerator ESP_LOG_WARN
Error conditions from which recovery measures have been taken
enumerator ESP_LOG_INFO
Information messages which describe normal flow of events
enumerator ESP_LOG_DEBUG
Extra information which is not necessary for normal use (values, pointers, sizes, etc).
enumerator ESP_LOG_VERBOSE
Bigger chunks of debugging information, or frequent messages which can potentially flood the output.
Software Reset
To perform software reset of the chip, the esp_restart() function is provided. When the function is called,
execution of the program stops, both CPUs are reset, and the application is loaded by the bootloader and starts
execution again.
Additionally, the esp_register_shutdown_handler() function can register a routine that will be automat-
ically called before a restart (that is triggered by esp_restart()) occurs. This is similar to the functionality of
atexit POSIX function.
Reset Reason
ESP-IDF applications can be started or restarted due to a variety of reasons. To get the last reset reason, call
esp_reset_reason() function. See description of esp_reset_reason_t for the list of possible reset
reasons.
Heap Memory
Note that ESP-IDF supports multiple heaps with different capabilities. The functions mentioned in this section return
the size of heap memory that can be allocated using the malloc family of functions. For further information about
heap memory, see Heap Memory Allocation.
MAC Address
These APIs allow querying and customizing MAC addresses for different supported network interfaces (e.g., Wi-Fi,
Bluetooth, Ethernet).
To fetch the MAC address for a specific network interface (e.g., Wi-Fi, Bluetooth, Ethernet), call the function
esp_read_mac().
In ESP-IDF, the MAC addresses for the various network interfaces are calculated from a single base MAC address.
By default, the Espressif base MAC address is used. This base MAC address is pre-programmed into the ESP32
eFuse in the factory during production.
Note: The configuration configures the number of universally administered MAC addresses that are provided by
Espressif.
Custom Base MAC The default base MAC is pre-programmed by Espressif in eFuse BLK0. To set a custom
base MAC instead, call the function esp_base_mac_addr_set() before initializing any network interfaces or
calling the esp_read_mac() function. The custom MAC address can be stored in any supported storage device
(e.g., flash, NVS).
The custom base MAC addresses should be allocated such that derived MAC addresses will not overlap. Based on
the table above, users can configure the option CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES to set the number
of valid universal MAC addresses that can be derived from the custom base MAC.
Note: It is also possible to call the function esp_netif_set_mac() to set the specific MAC used by a network
interface after network initialization. But it is recommended to use the base MAC approach documented here to
avoid the possibility of the original MAC address briefly appearing on the network before being changed.
Custom MAC Address in eFuse When reading custom MAC addresses from eFuse, ESP-IDF provides a helper
function esp_efuse_mac_get_custom(). This loads the MAC address from eFuse BLK3. This function
assumes that the custom base MAC address is stored in the following format:
Note: If the 3/4 coding scheme is enabled, all eFuse fields in this block must be burnt at the same time.
Local vs Universal MAC Addresses ESP32 comes pre-programmed with enough valid Espressif universally ad-
ministered MAC addresses for all internal interfaces. The table above shows how to calculate and derive the MAC
address for a specific interface according to the base MAC address.
When using a custom MAC address scheme, it is possible that not all interfaces can be assigned with a universally
administered MAC address. In these cases, a locally administered MAC address is assigned. Note that these addresses
are intended for use on a single local network only.
See this article for the definition of locally and universally administered MAC addresses.
Function esp_derive_local_mac() is called internally to derive a local MAC address from a universal MAC
address. The process is as follows:
1. The U/L bit (bit value 0x2) is set in the first octet of the universal MAC address, creating a local MAC address.
2. If this bit is already set in the supplied universal MAC address (i.e., the supplied “universal”MAC address
was in fact already a local MAC address), then the first octet of the local MAC address is XORed with 0x4.
Chip Version
esp_chip_info() function fills esp_chip_info_t structure with information about the chip. This includes
the chip revision, number of CPU cores, and a bit mask of features enabled in the chip.
SDK Version
esp_get_idf_version() returns a string describing the ESP-IDF version which is used to compile the appli-
cation. This is the same value as the one available through IDF_VER variable of the build system. The version string
generally has the format of git describe output.
To get the version at build time, additional version macros are provided. They can be used to enable or disable parts
of the program depending on the ESP-IDF version.
• ESP_IDF_VERSION_MAJOR, ESP_IDF_VERSION_MINOR, ESP_IDF_VERSION_PATCH are de-
fined to integers representing major, minor, and patch version.
• ESP_IDF_VERSION_VAL and ESP_IDF_VERSION can be used when implementing version checks:
#include "esp_idf_version.h"
App Version
The application version is stored in esp_app_desc_t structure. It is located in DROM sector and has a
fixed offset from the beginning of the binary file. The structure is located after esp_image_header_t and
esp_image_segment_header_t structures. The type of the field version is string and it has a maximum
length of 32 chars.
To set the version in your project manually, you need to set the PROJECT_VER variable in the CMakeLists.txt
of your project. In application CMakeLists.txt, put set(PROJECT_VER "0.1.0.1") before including
project.cmake.
If the CONFIG_APP_PROJECT_VER_FROM_CONFIG option is set, the value of CONFIG_APP_PROJECT_VER
will be used. Otherwise, if the PROJECT_VER variable is not set in the project, it will be retrieved either
from the $(PROJECT_PATH)/version.txt file (if present) or using git command git describe.
If neither is available, PROJECT_VER will be set to “1”. Application can make use of this by calling
esp_ota_get_app_description() or esp_ota_get_partition_description() functions.
API Reference
Header File
• components/esp_system/include/esp_system.h
Functions
esp_err_t esp_register_shutdown_handler(shutdown_handler_t handle)
Register shutdown handler.
This function allows you to register a handler that gets invoked before the application is restarted using
esp_restart function.
Parameters handle –function to execute on restart
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if the handler has already been registered
• ESP_ERR_NO_MEM if no more shutdown handler slots are available
esp_err_t esp_unregister_shutdown_handler(shutdown_handler_t handle)
Unregister shutdown handler.
This function allows you to unregister a handler which was previously registered using
esp_register_shutdown_handler function.
• ESP_OK on success
• ESP_ERR_INVALID_STATE if the given handler hasn’t been registered before
void esp_restart(void)
Restart PRO and APP CPUs.
This function can be called both from PRO and APP CPUs. After successful restart, CPU reset reason will be
SW_CPU_RESET. Peripherals (except for Wi-Fi, BT, UART0, SPI1, and legacy timers) are not reset. This
function does not return.
esp_reset_reason_t esp_reset_reason(void)
Get reason of last reset.
Returns See description of esp_reset_reason_t for explanation of each value.
uint32_t esp_get_free_heap_size(void)
Get the size of available heap.
Note: Note that the returned value may be larger than the maximum contiguous block which can be allocated.
uint32_t esp_get_free_internal_heap_size(void)
Get the size of available internal heap.
Note: Note that the returned value may be larger than the maximum contiguous block which can be allocated.
uint32_t esp_get_minimum_free_heap_size(void)
Get the minimum heap that has ever been available.
Returns Minimum free heap ever available
void esp_system_abort(const char *details)
Trigger a software abort.
Parameters details –Details that will be displayed during panic handling.
Type Definitions
Enumerations
enum esp_reset_reason_t
Reset reasons.
Values:
enumerator ESP_RST_UNKNOWN
Reset reason can not be determined.
enumerator ESP_RST_POWERON
Reset due to power-on event.
enumerator ESP_RST_EXT
Reset by external pin (not applicable for ESP32)
enumerator ESP_RST_SW
Software reset via esp_restart.
enumerator ESP_RST_PANIC
Software reset due to exception/panic.
enumerator ESP_RST_INT_WDT
Reset (software or hardware) due to interrupt watchdog.
enumerator ESP_RST_TASK_WDT
Reset due to task watchdog.
enumerator ESP_RST_WDT
Reset due to other watchdogs.
enumerator ESP_RST_DEEPSLEEP
Reset after exiting deep sleep mode.
enumerator ESP_RST_BROWNOUT
Brownout reset (software or hardware)
enumerator ESP_RST_SDIO
Reset over SDIO.
Header File
• components/esp_common/include/esp_idf_version.h
Functions
const char *esp_get_idf_version(void)
Return full IDF version string, same as ‘git describe’output.
Note: If you are printing the ESP-IDF version in a log file or other information, this function provides
more information than using the numerical version macros. For example, numerical version macros don’t
differentiate between development, pre-release and release versions, but the output of this function does.
Macros
ESP_IDF_VERSION_MAJOR
Major version number (X.x.x)
ESP_IDF_VERSION_MINOR
Minor version number (x.X.x)
ESP_IDF_VERSION_PATCH
Patch version number (x.x.X)
ESP_IDF_VERSION_VAL(major, minor, patch)
Macro to convert IDF version number into an integer
To be used in comparisons, such as ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0)
ESP_IDF_VERSION
Current IDF version, as an integer
To be used in comparisons, such as ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0)
Header File
• components/esp_hw_support/include/esp_mac.h
Functions
esp_err_t esp_base_mac_addr_set(const uint8_t *mac)
Set base MAC address with the MAC address which is stored in BLK3 of EFUSE or external storage e.g. flash
and EEPROM.
Base MAC address is used to generate the MAC addresses used by network interfaces.
If using a custom base MAC address, call this API before initializing any network interfaces. Refer to the
ESP-IDF Programming Guide for details about how the Base MAC is used.
Note: Base MAC must be a unicast MAC (least significant bit of first byte must be zero).
Note: If not using a valid OUI, set the “locally administered”bit (bit value 0x02 in the first byte) to avoid
collisions.
Parameters mac –base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8
bytes for EUI-64(used for IEEE 802.15.4)
Returns ESP_OK on success ESP_ERR_INVALID_ARG If mac is NULL or is not a unicast
MAC
esp_err_t esp_base_mac_addr_get(uint8_t *mac)
Return base MAC address which is set using esp_base_mac_addr_set.
Note: If no custom Base MAC has been set, this returns the pre-programmed Espressif base MAC address.
Parameters mac –base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8
bytes for EUI-64(used for IEEE 802.15.4)
Returns ESP_OK on success ESP_ERR_INVALID_ARG mac is NULL
ESP_ERR_INVALID_MAC base MAC address has not been set
Parameters mac –base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8
bytes for EUI-64(used for IEEE 802.15.4)
Returns ESP_OK on success ESP_ERR_INVALID_ARG mac is NULL
ESP_ERR_INVALID_MAC CUSTOM_MAC address has not been set, all zeros (for
esp32-xx) ESP_ERR_INVALID_VERSION An invalid MAC version field was read from
BLK3 of EFUSE (for esp32) ESP_ERR_INVALID_CRC An invalid MAC CRC was read
from BLK3 of EFUSE (for esp32)
This function copies a universal MAC address and then sets the “locally
administered”bit (bit 0x2) in the first octet, creating a locally administered MAC address.
If the universal MAC address argument is already a locally administered MAC address, then the first octet is
XORed with 0x4 in order to create a different locally administered MAC address.
Parameters
• local_mac –base MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48
8 bytes for EUI-64(used for IEEE 802.15.4)
• universal_mac –Source universal MAC address, length: 6 bytes.
Returns ESP_OK on success
Macros
MAC2STR(a)
MACSTR
Enumerations
enum esp_mac_type_t
Values:
enumerator ESP_MAC_WIFI_STA
enumerator ESP_MAC_WIFI_SOFTAP
enumerator ESP_MAC_BT
enumerator ESP_MAC_ETH
enumerator ESP_MAC_IEEE802154
Header File
• components/esp_hw_support/include/esp_chip_info.h
Functions
void esp_chip_info(esp_chip_info_t *out_info)
Fill an esp_chip_info_t structure with information about the chip.
Parameters out_info –[out] structure to be filled
Structures
struct esp_chip_info_t
The structure represents information about the chip.
Public Members
esp_chip_model_t model
chip model, one of esp_chip_model_t
uint32_t features
bit mask of CHIP_FEATURE_x feature flags
uint16_t revision
chip revision number (in format MXX; where M - wafer major version, XX - wafer minor version)
uint8_t cores
number of CPU cores
Macros
CHIP_FEATURE_EMB_FLASH
Chip has embedded flash memory.
CHIP_FEATURE_WIFI_BGN
Chip has 2.4GHz WiFi.
CHIP_FEATURE_BLE
Chip has Bluetooth LE.
CHIP_FEATURE_BT
Chip has Bluetooth Classic.
CHIP_FEATURE_IEEE802154
Chip has IEEE 802.15.4.
CHIP_FEATURE_EMB_PSRAM
Chip has embedded psram.
Enumerations
enum esp_chip_model_t
Chip models.
Values:
enumerator CHIP_ESP32
ESP32.
enumerator CHIP_ESP32S2
ESP32-S2.
enumerator CHIP_ESP32S3
ESP32-S3.
enumerator CHIP_ESP32C3
ESP32-C3.
enumerator CHIP_ESP32H2
ESP32-H2.
enumerator CHIP_ESP32C2
ESP32-C2.
Header File
• components/esp_hw_support/include/esp_cpu.h
Functions
void esp_cpu_stall(int core_id)
Stall a CPU core.
Parameters core_id –The core’s ID
void esp_cpu_unstall(int core_id)
Resume a previously stalled CPU core.
Parameters core_id –The core’s ID
void esp_cpu_reset(int core_id)
Reset a CPU core.
Parameters core_id –The core’s ID
void esp_cpu_wait_for_intr(void)
Wait for Interrupt.
This function causes the current CPU core to execute its Wait For Interrupt (WFI or equivalent) instruction.
After executing this function, the CPU core will stop execution until an interrupt occurs.
int esp_cpu_get_core_id(void)
Get the current core’s ID.
This function will return the ID of the current CPU (i.e., the CPU that calls this function).
Returns The current core’s ID [0..SOC_CPU_CORES_NUM - 1]
void *esp_cpu_get_sp(void)
Read the current stack pointer address.
Returns Stack pointer address
esp_cpu_cycle_count_t esp_cpu_get_cycle_count(void)
Get the current CPU core’s cycle count.
Each CPU core maintains an internal counter (i.e., cycle count) that increments every CPU clock cycle.
Returns Current CPU’s cycle count, 0 if not supported.
void esp_cpu_set_cycle_count(esp_cpu_cycle_count_t cycle_count)
Set the current CPU core’s cycle count.
Set the given value into the internal counter that increments every CPU clock cycle.
Parameters cycle_count –CPU cycle count
void *esp_cpu_pc_to_addr(uint32_t pc)
Convert a program counter (PC) value to address.
If the architecture does not store the true virtual address in the CPU’s PC or return addresses, this function
will convert the PC value to a virtual address. Otherwise, the PC is just returned
Parameters pc –PC value
Returns Virtual address
Note: This function simply checks if the IVT of the current CPU already has a handler assigned.
Note: This function simply sets the handler function (in the IVT) and does not actually enable the interrupt.
Parameters
• intr_num –Interrupt number (from 0 to 31)
• handler –Handler function
• handler_arg –Argument passed to the handler function
Note: This function is meant to be called by the panic handler to set a breakpoint for an attached debugger
during a panic.
Parameters
• bp_num –Hardware breakpoint number [0..SOC_CPU_BREAKPOINTS_NUM - 1]
• bp_addr –Address to set a breakpoint on
Returns ESP_OK if breakpoint is set. Failure otherwise
Parameters
• wp_num –Hardware watchpoint number [0..SOC_CPU_WATCHPOINTS_NUM - 1]
• wp_addr –Watchpoint’s base address
• size –Size of the region to watch. Must be one of 2^n, with n in [0..6].
• trigger –Trigger type
Returns ESP_ERR_INVALID_ARG on invalid arg, ESP_OK otherwise
bool esp_cpu_dbgr_is_attached(void)
Check if the current CPU has a debugger attached.
Returns True if debugger is attached, false otherwise
void esp_cpu_dbgr_break(void)
Trigger a call to the current CPU’s attached debugger.
bool esp_cpu_compare_and_set(volatile uint32_t *addr, uint32_t compare_value, uint32_t new_value)
Atomic compare-and-set operation.
Parameters
• addr –Address of atomic variable
• compare_value –Value to compare the atomic variable to
• new_value –New value to set the atomic variable to
Returns Whether the atomic variable was set or not
bool esp_cpu_in_ocd_debug_mode(void)
Returns true if a JTAG debugger is attached to CPU OCD (on chip debug) port.
[refactor-todo] See if this can be replaced with esp_cpu_dbgr_is_attached directly
Structures
struct esp_cpu_intr_desc_t
CPU interrupt descriptor.
Each particular CPU interrupt has an associated descriptor describing that particular interrupt’s characteristics.
Call esp_cpu_intr_get_desc() to get the descriptors of a particular interrupt.
Public Members
int priority
Priority of the interrupt if it has a fixed priority, (-1) if the priority is configurable.
esp_cpu_intr_type_t type
Whether the interrupt is an edge or level type interrupt, ESP_CPU_INTR_TYPE_NA if the type is
configurable.
uint32_t flags
Flags indicating extra details.
Macros
ESP_CPU_INTR_DESC_FLAG_SPECIAL
Interrupt descriptor flags of esp_cpu_intr_desc_t.
The interrupt is a special interrupt (e.g., a CPU timer interrupt)
ESP_CPU_INTR_DESC_FLAG_RESVD
The interrupt is reserved for internal use
esp_cpu_get_ccount()
esp_cpu_set_ccount(ccount)
Type Definitions
Enumerations
enum esp_cpu_intr_type_t
CPU interrupt type.
Values:
enumerator ESP_CPU_INTR_TYPE_LEVEL
enumerator ESP_CPU_INTR_TYPE_EDGE
enumerator ESP_CPU_INTR_TYPE_NA
enum esp_cpu_watchpoint_trigger_t
CPU watchpoint trigger type.
Values:
enumerator ESP_CPU_WATCHPOINT_LOAD
enumerator ESP_CPU_WATCHPOINT_STORE
enumerator ESP_CPU_WATCHPOINT_ACCESS
The OTA update mechanism allows a device to update itself based on data received while the normal firmware is
running (for example, over Wi-Fi or Bluetooth.)
OTA requires configuring the Partition Table of the device with at least two “OTA app slot”partitions (i.e. ota_0
and ota_1) and an “OTA Data Partition”.
The OTA operation functions write a new app firmware image to whichever OTA app slot that is currently not selected
for booting. Once the image is verified, the OTA Data partition is updated to specify that this image should be used
for the next boot.
An OTA data partition (type data, subtype ota) must be included in the Partition Table of any project which uses
the OTA functions.
For factory boot settings, the OTA data partition should contain no data (all bytes erased to 0xFF). In this case the
esp-idf software bootloader will boot the factory app if it is present in the partition table. If no factory app is included
in the partition table, the first available OTA slot (usually ota_0) is booted.
After the first OTA update, the OTA data partition is updated to specify which OTA app slot partition should be
booted next.
The OTA data partition is two flash sectors (0x2000 bytes) in size, to prevent problems if there is a power failure
while it is being written. Sectors are independently erased and written with matching data, and if they disagree a
counter field is used to determine which sector was written more recently.
App rollback
The main purpose of the application rollback is to keep the device working after the update. This feature allows
you to roll back to the previous working application in case a new application has critical errors. When the rollback
process is enabled and an OTA update provides a new version of the app, one of three things can happen:
• The application works fine, esp_ota_mark_app_valid_cancel_rollback() marks the running
application with the state ESP_OTA_IMG_VALID. There are no restrictions on booting this application.
• The application has critical errors and further work is not possible, a rollback to the previous application is re-
quired, esp_ota_mark_app_invalid_rollback_and_reboot() marks the running application
with the state ESP_OTA_IMG_INVALID and reset. This application will not be selected by the bootloader
for boot and will boot the previously working application.
• If the CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE option is set, and a reset occurs without calling
either function then the application is rolled back.
Note: The state is not written to the binary image of the application but rather to the otadata partition. The
partition contains a ota_seq counter which is a pointer to the slot (ota_0, ota_1, …) from which the application
will be selected for boot.
App OTA State States control the process of selecting a boot app:
Unexpected Reset If a power loss or an unexpected crash occurs at the time of the first boot of a new application,
it will roll back the application.
Recommendation: Perform the self-test procedure as quickly as possible, to prevent rollback due to power loss.
Only OTA partitions can be rolled back. Factory partition is not rolled back.
Booting invalid/aborted apps Booting an application which was previously set to ESP_OTA_IMG_INVALID or
ESP_OTA_IMG_ABORTED is possible:
• Get the last invalid application partition esp_ota_get_last_invalid_partition().
• Pass the received partition to esp_ota_set_boot_partition(), this will update the otadata.
• Restart esp_restart(). The bootloader will boot the specified application.
To determine if self-tests should be run during startup of an application, call the
esp_ota_get_state_partition() function. If result is ESP_OTA_IMG_PENDING_VERIFY then
self-testing and subsequent confirmation of operability is required.
Where the states are set A brief description of where the states are set:
• ESP_OTA_IMG_VALID state is set by esp_ota_mark_app_valid_cancel_rollback() func-
tion.
• ESP_OTA_IMG_UNDEFINED state is set by esp_ota_set_boot_partition() function if CON-
FIG_BOOTLOADER_APP_ROLLBACK_ENABLE option is not enabled.
• ESP_OTA_IMG_NEW state is set by esp_ota_set_boot_partition() function if CON-
FIG_BOOTLOADER_APP_ROLLBACK_ENABLE option is enabled.
• ESP_OTA_IMG_INVALID state is set by esp_ota_mark_app_invalid_rollback_and_reboot()
function.
• ESP_OTA_IMG_ABORTED state is set if there was no confirmation of the application operability and occurs
reboots (if CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE option is enabled).
• ESP_OTA_IMG_PENDING_VERIFY state is set in a bootloader if CON-
FIG_BOOTLOADER_APP_ROLLBACK_ENABLE option is enabled and selected app has
ESP_OTA_IMG_NEW state.
Anti-rollback
Anti-rollback prevents rollback to application with security version lower than one programmed in eFuse of chip.
This function works if set CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK option. In the bootloader, when se-
lecting a bootable application, an additional security version check is added which is on the chip and in the application
image. The version in the bootable firmware must be greater than or equal to the version in the chip.
CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK and CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE op-
tions are used together. In this case, rollback is possible only on the security version which is equal or higher than
the version in the chip.
Recommendation:
If you want to avoid the download/erase overhead in case of the app from the server has security version lower than
the running app, you have to get new_app_info.secure_version from the first package of an image and
compare it with the secure version of efuse. Use esp_efuse_check_secure_version(new_app_info.
secure_version) function if it is true then continue downloading otherwise abort.
....
bool image_header_was_checked = false;
while (1) {
int data_read = esp_http_client_read(client, ota_write_data, BUFFSIZE);
...
if (data_read > 0) {
if (image_header_was_checked == false) {
esp_app_desc_t new_app_info;
if (data_read > sizeof(esp_image_header_t) + sizeof(esp_image_segment_
,→header_t) + sizeof(esp_app_desc_t)) {
http_cleanup(client);
task_fatal_error();
}
image_header_was_checked = true;
Restrictions:
• The number of bits in the secure_version field is limited to 32 bits. This means that only
32 times you can do an anti-rollback. You can reduce the length of this efuse field using CON-
FIG_BOOTLOADER_APP_SEC_VER_SIZE_EFUSE_FIELD option.
• Anti-rollback works only if the encoding scheme for efuse is set to NONE.
• Factory and Test partitions are not supported in anti rollback scheme and hence partition table should not have
partition with SubType set to factory or test.
security_version:
• In application image it is stored in esp_app_desc structure. The number is set CON-
FIG_BOOTLOADER_APP_SECURE_VERSION.
• In ESP32 it is stored in efuse EFUSE_BLK3_RDATA4_REG. (when a eFuse bit is programmed to 1, it can
never be reverted to 0). The number of bits set in this register is the security_version from app.
The verification of signed OTA updates can be performed even without enabling hardware secure
boot. This can be achieved by setting CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT and CON-
FIG_SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT
For more information refer to Signed App Verification Without Hardware Secure Boot
The component app_update provides a tool otatool.py for performing OTA partition-related operations on a target
device. The following operations can be performed using the tool:
• read contents of otadata partition (read_otadata)
• erase otadata partition, effectively resetting device to factory app (erase_otadata)
• switch OTA partitions (switch_ota_partition)
• erasing OTA partition (erase_ota_partition)
• write to OTA partition (write_ota_partition)
• read contents of OTA partition (read_ota_partition)
The tool can either be imported and used from another Python script or invoked from shell script for users wanting
to perform operation programmatically. This is facilitated by the tool’s Python API and command-line interface,
respectively.
Python API Before anything else, make sure that the otatool module is imported.
import sys
import os
The starting point for using the tool’s Python API to do is create a OtatoolTarget object:
The created object can now be used to perform operations on the target device:
# Read OTA partition 'ota_3' and save contents to a file named 'ota_3.bin'
target.read_ota_partition("ota_3", "ota_3.bin")
The OTA partition to operate on is specified using either the app slot number or the partition name.
More information on the Python API is available in the docstrings for the tool.
Command-line Interface The command-line interface of otatool.py has the following structure:
- command-args - these are arguments that are needed for executing the main␣
,→command (parttool.py), mostly pertaining to the target device
# Read OTA partition 'ota_3' and save contents to a file named 'ota_3.bin'
otatool.py --port "/dev/ttyUSB1" read_ota_partition --name=ota_3 --output=ota_3.bin
See also
Application Example
API Reference
Header File
• components/app_update/include/esp_ota_ops.h
Functions
const esp_app_desc_t *esp_ota_get_app_description(void)
Return esp_app_desc structure. This structure includes app version.
Return description for running app.
Returns Pointer to esp_app_desc structure.
int esp_ota_get_app_elf_sha256(char *dst, size_t size)
Fill the provided buffer with SHA256 of the ELF file, formatted as hexadecimal, null-terminated. If the buffer
size is not sufficient to fit the entire SHA256 in hex plus a null terminator, the largest possible number of bytes
will be written followed by a null.
Parameters
• dst –Destination buffer
• size –Size of the buffer
Returns Number of bytes written to dst (including null terminator)
esp_err_t esp_ota_begin(const esp_partition_t *partition, size_t image_size, esp_ota_handle_t *out_handle)
Commence an OTA update writing to the specified partition.
The specified partition is erased to the specified image size.
If image size is not yet known, pass OTA_SIZE_UNKNOWN which will cause the entire partition to be erased.
On success, this function allocates memory that remains in use until esp_ota_end() is called with the returned
handle.
Note: If the rollback option is enabled and the running application has
the ESP_OTA_IMG_PENDING_VERIFY state then it will lead to the
ESP_ERR_OTA_ROLLBACK_INVALID_STATE error. Confirm the running app before to run download
a new app, use esp_ota_mark_app_valid_cancel_rollback() function for it (this should be done as early as
possible when you first download a new application).
Parameters
• partition –Pointer to info for partition which will receive the OTA update. Required.
• image_size –Size of new OTA app image. Partition will be erased in order to receive
this size of image. If 0 or OTA_SIZE_UNKNOWN, the entire partition is erased.
• out_handle –On success, returns a handle which should be used for subsequent
esp_ota_write() and esp_ota_end() calls.
Returns
• ESP_OK: OTA operation commenced successfully.
• ESP_ERR_INVALID_ARG: partition or out_handle arguments were NULL, or partition
doesn’t point to an OTA app partition.
• ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation.
• ESP_ERR_OTA_PARTITION_CONFLICT: Partition holds the currently running
firmware, cannot update in place.
• ESP_ERR_NOT_FOUND: Partition argument not found in partition table.
• ESP_ERR_OTA_SELECT_INFO_INVALID: The OTA data partition contains invalid
data.
• ESP_ERR_INVALID_SIZE: Partition doesn’t fit in configured flash size.
• ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write
failed.
• ESP_ERR_OTA_ROLLBACK_INVALID_STATE: If the running app has not con-
firmed state. Before performing an update, the application must be valid.
esp_err_t esp_ota_write(esp_ota_handle_t handle, const void *data, size_t size)
Write OTA update data to partition.
This function can be called multiple times as data is received during the OTA operation. Data is written
sequentially to the partition.
Parameters
• handle –Handle obtained from esp_ota_begin
• data –Data buffer to write
• size –Size of data buffer in bytes.
Returns
• ESP_OK: Data was written to flash successfully.
• ESP_ERR_INVALID_ARG: handle is invalid.
• ESP_ERR_OTA_VALIDATE_FAILED: First byte of image contains invalid app image
magic byte.
• ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write
failed.
• ESP_ERR_OTA_SELECT_INFO_INVALID: OTA data partition has invalid contents
esp_err_t esp_ota_write_with_offset(esp_ota_handle_t handle, const void *data, size_t size, uint32_t
offset)
Write OTA update data to partition at an offset.
This function can write data in non-contiguous manner. If flash encryption is enabled, data should be 16 bytes
aligned.
Note: While performing OTA, if the packets arrive out of order, esp_ota_write_with_offset() can be used to
write data in non-contiguous manner. Use of esp_ota_write_with_offset() in combination with esp_ota_write()
is not recommended.
Parameters
• handle –Handle obtained from esp_ota_begin
• data –Data buffer to write
• size –Size of data buffer in bytes
• offset –Offset in flash partition
Returns
• ESP_OK: Data was written to flash successfully.
• ESP_ERR_INVALID_ARG: handle is invalid.
• ESP_ERR_OTA_VALIDATE_FAILED: First byte of image contains invalid app image
magic byte.
• ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write
failed.
• ESP_ERR_OTA_SELECT_INFO_INVALID: OTA data partition has invalid contents
Note: After calling esp_ota_end(), the handle is no longer valid and any memory associated with it is freed
(regardless of result).
Note: If this function returns ESP_OK, calling esp_restart() will boot the newly configured app partition.
Parameters partition –Pointer to info for partition containing app image to boot.
Returns
• ESP_OK: OTA data updated, next reboot will use specified partition.
• ESP_ERR_INVALID_ARG: partition argument was NULL or didn’t point to a valid
OTA partition of type “app”.
• ESP_ERR_OTA_VALIDATE_FAILED: Partition contained invalid app image. Also re-
turned if secure boot is enabled and signature validation failed.
• ESP_ERR_NOT_FOUND: OTA data partition not found.
Macros
OTA_SIZE_UNKNOWN
Used for esp_ota_begin() if new image size is unknown
OTA_WITH_SEQUENTIAL_WRITES
Used for esp_ota_begin() if new image size is unknown and erase can be done in incremental manner (assuming
write operation is in continuous sequence)
ESP_ERR_OTA_BASE
Base error code for ota_ops api
ESP_ERR_OTA_PARTITION_CONFLICT
Error if request was to write or erase the current running partition
ESP_ERR_OTA_SELECT_INFO_INVALID
Error if OTA data partition contains invalid content
ESP_ERR_OTA_VALIDATE_FAILED
Error if OTA app image is invalid
ESP_ERR_OTA_SMALL_SEC_VER
Error if the firmware has a secure version less than the running firmware.
ESP_ERR_OTA_ROLLBACK_FAILED
Error if flash does not have valid firmware in passive partition and hence rollback is not possible
ESP_ERR_OTA_ROLLBACK_INVALID_STATE
Error if current active firmware is still marked in pending validation state
(ESP_OTA_IMG_PENDING_VERIFY), essentially first boot of firmware image post upgrade and
hence firmware upgrade is not possible
Type Definitions
The Performance Monitor component provides APIs to use ESP32 internal performance counters to profile functions
and applications.
Application Example
Header Files
• perfmon/include/perfmon.h
API Reference
Header File
• components/perfmon/include/xtensa_perfmon_access.h
Functions
esp_err_t xtensa_perfmon_init(int id, uint16_t select, uint16_t mask, int kernelcnt, int tracelevel)
Init Performance Monitoor.
Initialize performance monitor register with define values
Parameters
• id –[in] performance counter number
• select –[in] select value from PMCTRLx register
• mask –[in] mask value from PMCTRLx register
• kernelcnt –[in] kernelcnt value from PMCTRLx register
• tracelevel –[in] tracelevel value from PMCTRLx register
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if one of the arguments is not correct
esp_err_t xtensa_perfmon_reset(int id)
Reset PM counter.
Reset PM counter. Writes 0 to the PMx register.
Parameters id –[in] performance counter number
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if id out of range
void xtensa_perfmon_start(void)
Start PM counters.
Start all PM counters synchronously. Write 1 to the PGM register
void xtensa_perfmon_stop(void)
Stop PM counters.
Stop all PM counters synchronously. Write 0 to the PGM register
uint32_t xtensa_perfmon_value(int id)
Read PM counter.
Read value of defined PM counter.
Parameters id –[in] performance counter number
Returns
• Performance counter value
esp_err_t xtensa_perfmon_overflow(int id)
Read PM overflow state.
Read overflow value of defined PM counter.
Parameters id –[in] performance counter number
Returns
Header File
• components/perfmon/include/xtensa_perfmon_apis.h
Functions
esp_err_t xtensa_perfmon_exec(const xtensa_perfmon_config_t *config)
Execute PM.
Execute performance counter for dedicated function with defined parameters
Parameters config –[in] pointer to the configuration structure
Returns
• ESP_OK if no errors
• ESP_ERR_INVALID_ARG if one of the required parameters not defined
• ESP_FAIL - counter overflow
void xtensa_perfmon_view_cb(void *params, uint32_t select, uint32_t mask, uint32_t value)
Dump PM results.
Callback to dump perfmon result to a FILE* stream specified in perfmon_config_t::callback_params. If call-
back_params is set to NULL, will print to stdout
Parameters
• params –[in] used parameters passed from configuration (callback_params). This pa-
rameter expected as FILE* hanle, where data will be stored. If this parameter NULL,
then data will be stored to the stdout.
• select –[in] select value for current counter
• mask –[in] mask value for current counter
• value –[in] counter value for current counter
Structures
struct xtensa_perfmon_config
Performance monitor configuration structure.
Structure to configure performance counter to measure dedicated function
Public Members
int repeat_count
how much times function will be called before the calback will be repeated
float max_deviation
Difference between min and max counter number 0..1, 0 - no difference, 1 - not used
void *call_params
This pointer will be passed to the call_function as a parameter
void *callback_params
parameter that will be passed to the callback
int tracelevel
trace level for all counters. In case of negative value, the filter will be ignored. If it’s >=0, then the
perfmon will count only when interrupt level > tracelevel. It’s useful to monitor interrupts.
uint32_t counters_size
amount of counter in the list
Type Definitions
Overview
Power management algorithm included in ESP-IDF can adjust the advanced peripheral bus (APB) frequency, CPU
frequency, and put the chip into light sleep mode to run an application at smallest possible power consumption, given
the requirements of application components.
Application components can express their requirements by creating and acquiring power management locks.
For example:
• Driver for a peripheral clocked from APB can request the APB frequency to be set to 80 MHz while the
peripheral is used.
• RTOS can request the CPU to run at the highest configured frequency while there are tasks ready to run.
• A peripheral driver may need interrupts to be enabled, which means it will have to request disabling light sleep.
Since requesting higher APB or CPU frequencies or disabling light sleep causes higher current consumption, please
keep the usage of power management locks by components to a minimum.
Configuration
Power management can be enabled at compile time, using the option CONFIG_PM_ENABLE.
Enabling power management features comes at the cost of increased interrupt latency. Extra latency depends on
a number of factors, such as the CPU frequency, single/dual core mode, whether or not frequency switch needs
to be done. Minimum extra latency is 0.2 us (when the CPU frequency is 240 MHz and frequency scaling is not
enabled). Maximum extra latency is 40 us (when frequency scaling is enabled, and a switch from 40 MHz to 80 MHz
is performed on interrupt entry).
Dynamic frequency scaling (DFS) and automatic light sleep can be enabled in an application by calling
the function esp_pm_configure(). Its argument is a structure defining the frequency scaling settings,
esp_pm_config_esp32_t. In this structure, three fields need to be initialized:
• max_freq_mhz: Maximum CPU frequency in MHz, i.e., the frequency used when the
ESP_PM_CPU_FREQ_MAX lock is acquired. This field will usually be set to the default CPU frequency.
• min_freq_mhz: Minimum CPU frequency in MHz, i.e., the frequency used when only the
ESP_PM_APB_FREQ_MAX lock is acquired. This field can be set to the XTAL frequency value, or the XTAL
frequency divided by an integer. Note that 10 MHz is the lowest frequency at which the default REF_TICK
clock of 1 MHz can be generated.
• light_sleep_enable: Whether the system should automatically enter light sleep when no locks are
acquired (true/false).
Alternatively, if you enable the option CONFIG_PM_DFS_INIT_AUTO in menuconfig, the maximum CPU
frequency will be determined by the CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ setting, and the minimum
CPU frequency will be locked to the XTAL frequency.
Note: Automatic light sleep is based on FreeRTOS Tickless Idle functionality. If automatic light
sleep is requested while the option CONFIG_FREERTOS_USE_TICKLESS_IDLE is not enabled in menuconfig,
esp_pm_configure() will return the error ESP_ERR_NOT_SUPPORTED.
Note: In light sleep, peripherals are clock gated, and interrupts (from GPIOs and internal peripherals) will not be
generated. A wakeup source described in the Sleep Modes documentation can be used to trigger wakeup from the
light sleep state.
For example, the EXT0 and EXT1 wakeup sources can be used to wake up the chip via a GPIO.
Applications have the ability to acquire/release locks in order to control the power management algorithm. When an
application acquires a lock, the power management algorithm operation is restricted in a way described below. When
the lock is released, such restrictions are removed.
Power management locks have acquire/release counters. If the lock has been acquired a number of times, it needs to
be released the same number of times to remove associated restrictions.
ESP32 supports three types of locks described in the table below.
Lock Description
ESP_PM_CPU_FREQ_MAX Requests CPU frequency to be at the maximum value set
with esp_pm_configure(). For ESP32, this value can be set to 80
MHz, 160 MHz, or 240 MHz.
ESP_PM_APB_FREQ_MAX Requests the APB frequency to be at the maximum supported value. For
ESP32, this is 80 MHz.
ESP_PM_NO_LIGHT_SLEEP Disables automatic switching to light sleep.
The table below shows how CPU and APB frequencies will be switched if dynamic frequency scaling is
enabled. You can specify the maximum CPU frequency with either esp_pm_configure() or CON-
FIG_ESP_DEFAULT_CPU_FREQ_MHZ.
Max CPU Frequency Set Lock Acquisition CPU and APB Frequncies
240
Any of CPU: 240 MHz
ESP_PM_CPU_FREQ_MAX APB: 80 MHz
or ESP_PM_APB_FREQ_MAX
acquired
ESP_PM_APB_FREQ_MAX
acquired,
CPU: 80 MHz
ESP_PM_CPU_FREQ_MAX
not acquired APB: 80 MHz
If none of the locks are acquired, and light sleep is enabled in a call to esp_pm_configure(), the system will
go into light sleep mode. The duration of light sleep will be determined by:
• FreeRTOS tasks blocked with finite timeouts
• Timers registered with High resolution timer APIs
Light sleep duration will be chosen to wake up the chip before the nearest event (task being unblocked, or timer
elapses).
To skip unnecessary wake-up, you can consider initializing an esp_timer with the skip_unhandled_events option as
true. Timers with this flag will not wake up the system and it helps to reduce consumption.
When DFS is enabled, the APB frequency can be changed multiple times within a single RTOS tick. The APB
frequency change does not affect the operation of some peripherals, while other peripherals may have issues. For
example, Timer Group peripheral timers will keep counting, however, the speed at which they count will change
proportionally to the APB frequency.
The following peripherals work normally even when the APB frequency is changing:
• UART: if REF_TICK or XTAL is used as a clock source. See uart_config_t::source_clk.
• LEDC: if REF_TICK is used as a clock source. See ledc_timer_config() function.
• RMT: if REF_TICK or XTAL is used as a clock source. See rmt_config_t::flags and macro
RMT_CHANNEL_FLAGS_AWARE_DFS.
• GPTimer: if APB is used as the clock source. See gptimer_config_t::clk_src.
• TSENS: XTAL or RTC_8M is used as a clock source. So, APB frequency changing will not influence it.
Currently, the following peripheral drivers are aware of DFS and will use the ESP_PM_APB_FREQ_MAX lock for
the duration of the transaction:
• SPI master
• I2C
• I2S (If the APLL clock is used, then it will use the ESP_PM_NO_LIGHT_SLEEP lock)
• SDMMC
The following drivers will hold the ESP_PM_APB_FREQ_MAX lock while the driver is enabled:
• PCNT
• Sigma-delta
• The legacy timer group driver
• MCPWM
API Reference
Header File
• components/esp_pm/include/esp_pm.h
Functions
esp_err_t esp_pm_configure(const void *config)
Set implementation-specific power management configuration.
Parameters config –pointer to implementation-specific configuration structure (e.g.
esp_pm_config_esp32)
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if the configuration values are not correct
• ESP_ERR_NOT_SUPPORTED if certain combination of values is not supported, or if
CONFIG_PM_ENABLE is not enabled in sdkconfig
esp_err_t esp_pm_get_configuration(void *config)
Get implementation-specific power management configuration.
Parameters config –pointer to implementation-specific configuration structure (e.g.
esp_pm_config_esp32)
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if the pointer is null
esp_err_t esp_pm_lock_create(esp_pm_lock_type_t lock_type, int arg, const char *name,
esp_pm_lock_handle_t *out_handle)
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if the handle argument is NULL
• ESP_ERR_INVALID_STATE if the lock is still acquired
• ESP_ERR_NOT_SUPPORTED if CONFIG_PM_ENABLE is not enabled in sdkconfig
esp_err_t esp_pm_dump_locks(FILE *stream)
Dump the list of all locks to stderr
This function dumps debugging information about locks created using esp_pm_lock_create to an output stream.
This function must not be called from an ISR. If esp_pm_lock_acquire/release are called while this function
is running, inconsistent results may be reported.
Parameters stream –stream to print information to; use stdout or stderr to print to the console;
use fmemopen/open_memstream to print to a string buffer.
Returns
• ESP_OK on success
• ESP_ERR_NOT_SUPPORTED if CONFIG_PM_ENABLE is not enabled in sdkconfig
Type Definitions
Enumerations
enum esp_pm_lock_type_t
Power management constraints.
Values:
enumerator ESP_PM_CPU_FREQ_MAX
Require CPU frequency to be at the maximum value set via esp_pm_configure. Argument is unused and
should be set to 0.
enumerator ESP_PM_APB_FREQ_MAX
Require APB frequency to be at the maximum value supported by the chip. Argument is unused and
should be set to 0.
enumerator ESP_PM_NO_LIGHT_SLEEP
Prevent the system from going into light sleep. Argument is unused and should be set to 0.
Header File
• components/esp_pm/include/esp32/pm.h
Structures
struct esp_pm_config_esp32_t
Power management config for ESP32.
Pass a pointer to this structure as an argument to esp_pm_configure function.
Public Members
int max_freq_mhz
Maximum CPU frequency, in MHz
int min_freq_mhz
Minimum CPU frequency to use when no locks are taken, in MHz
bool light_sleep_enable
Enter light sleep when no locks are taken
Overview
ESP-IDF is based on FreeRTOS but offers a range of POSIX-compatible APIs that allow easy porting of third party
code. This includes support for common parts of the POSIX Threads “pthreads”API.
POSIX Threads are implemented in ESP-IDF as wrappers around equivalent FreeRTOS features. The runtime
memory or performance overhead of using the pthreads API is quite low, but not every feature available in either
pthreads or FreeRTOS is available via the ESP-IDF pthreads support.
Pthreads can be used in ESP-IDF by including standard pthread.h header, which is included in the toolchain libc.
An additional ESP-IDF specific header, esp_pthread.h, provides additional non-POSIX APIs for using some
ESP-IDF features with pthreads.
C++ Standard Library implementations for std::thread, std::mutex, std::condition_variable,
etc. are implemented using pthreads (via GCC libstdc++). Therefore, restrictions mentioned here also apply to the
equivalent C++ standard library functionality.
RTOS Integration
Unlike many operating systems using POSIX Threads, ESP-IDF is a real-time operating system with a real-time
scheduler. This means that a thread will only stop running if a higher priority task is ready to run, the thread blocks
on an OS synchronization structure like a mutex, or the thread calls any of the functions sleep, vTaskDelay(),
or usleep.
Note: If calling a standard libc or C++ sleep function, such as usleep defined in unistd.h, then the task will
only block and yield the CPU if the sleep time is longer than one FreeRTOS tick period. If the time is shorter, the
thread will busy-wait instead of yielding to another RTOS task.
By default, all POSIX Threads have the same RTOS priority, but it is possible to change this by calling a custom API.
Standard features
Thread APIs
• pthread_create() - The attr argument is supported for setting stack size and detach state only. Other
attribute fields are ignored. - Unlike FreeRTOS task functions, the start_routine function is allowed to
return. A “detached”type thread is automatically deleted if the function returns. The default “joinable”
type thread will be suspended until pthread_join() is called on it.
• pthread_join()
• pthread_detach()
• pthread_exit()
• sched_yield()
• pthread_self() - An assert will fail if this function is called from a FreeRTOS task which is not a pthread.
• pthread_equal()
Thread Attributes
• pthread_attr_init()
• pthread_attr_destroy() - This function doesn’t need to free any resources and instead resets the
attr structure to defaults (implementation is same as pthread_attr_init()).
• pthread_attr_getstacksize() / pthread_attr_setstacksize()
• pthread_attr_getdetachstate() / pthread_attr_setdetachstate()
Once
• pthread_once()
Static initializer constant PTHREAD_ONCE_INIT is supported.
Note: This function can be called from tasks created using either pthread or FreeRTOS APIs
Mutexes POSIX Mutexes are implemented as FreeRTOS Mutex Semaphores (normal type for “fast”or “error
check”mutexes, and Recursive type for“recursive”mutexes). This means that they have the same priority inheritance
behaviour as mutexes created with xSemaphoreCreateMutex().
• pthread_mutex_init()
• pthread_mutex_destroy()
• pthread_mutex_lock()
• pthread_mutex_timedlock()
• pthread_mutex_trylock()
• pthread_mutex_unlock()
• pthread_mutexattr_init()
• pthread_mutexattr_destroy()
• pthread_mutexattr_gettype() / pthread_mutexattr_settype()
Static initializer constant PTHREAD_MUTEX_INITIALIZER is supported, but the non-standard static initializer
constants for other mutex types are not supported.
Note: These functions can be called from tasks created using either pthread or FreeRTOS APIs
Condition Variables
• pthread_cond_init() - The attr argument is not implemented and is ignored.
• pthread_cond_destroy()
• pthread_cond_signal()
• pthread_cond_broadcast()
• pthread_cond_wait()
• pthread_cond_timedwait()
Note: These functions can be called from tasks created using either pthread or FreeRTOS APIs
Read/Write Locks
• pthread_rwlock_init() - The attr argument is not implemented and is ignored.
• pthread_rwlock_destroy()
• pthread_rwlock_rdlock()
• pthread_rwlock_wrlock()
• pthread_rwlock_unlock()
Static initializer constant PTHREAD_RWLOCK_INITIALIZER is supported.
Note: These functions can be called from tasks created using either pthread or FreeRTOS APIs
Thread-Specific Data
• pthread_key_create() - The destr_function argument is supported and will be called if a thread
function exits normally, calls pthread_exit(), or if the underlying task is deleted directly using the FreeR-
TOS function vTaskDelete().
• pthread_key_delete()
• pthread_setspecific() / pthread_getspecific()
Note: These functions can be called from tasks created using either pthread or FreeRTOS APIs
Note: There are other options for thread local storage in ESP-IDF, including options with higher performance. See
Thread Local Storage.
Not Implemented
The pthread.h header is a standard header and includes additional APIs and features which are not implemented
in ESP-IDF. These include:
• pthread_cancel() returns ENOSYS if called.
• pthread_condattr_init() returns ENOSYS if called.
Other POSIX Threads functions (not listed here) are not implemented and will produce either a compiler or a linker
error if referenced from an ESP-IDF application. If you identify a useful API that you would like to see implemented
in ESP-IDF, please open a feature request on GitHub <https://github.com/espressif/esp-idf/issues> with the details.
ESP-IDF Extensions
The API esp_pthread_set_cfg() defined in the esp_pthreads.h header offers custom extensions to
control how subsequent calls to pthread_create() will behave. Currently, the following configuration can be
set:
• Default stack size of new threads, if not specified when calling pthread_create() (overrides CON-
FIG_PTHREAD_TASK_STACK_SIZE_DEFAULT).
• RTOS priority of new threads (overrides CONFIG_PTHREAD_TASK_PRIO_DEFAULT).
• Core affinity / core pinning of new threads (overrides CONFIG_PTHREAD_TASK_CORE_DEFAULT).
• FreeRTOS task name for new threads (overrides CONFIG_PTHREAD_TASK_NAME_DEFAULT)
This configuration is scoped to the calling thread (or FreeRTOS task), meaning that esp_pthread_set_cfg()
can be called independently in different threads or tasks. If the inherit_cfg flag is set in the current configuration
then any new thread created will inherit the creator’s configuration (if that thread calls pthread_create()
recursively), otherwise the new thread will have the default configuration.
Examples
API Reference
Header File
• components/pthread/include/esp_pthread.h
Functions
esp_pthread_cfg_t esp_pthread_get_default_config(void)
Creates a default pthread configuration based on the values set via menuconfig.
Returns A default configuration structure.
esp_err_t esp_pthread_set_cfg(const esp_pthread_cfg_t *cfg)
Configure parameters for creating pthread.
This API allows you to configure how the subsequent pthread_create() call will behave. This call can be used
to setup configuration parameters like stack size, priority, configuration inheritance etc.
If the ‘inherit’flag in the configuration structure is enabled, then the same configuration is also inherited in
the thread subtree.
Note: Passing non-NULL attributes to pthread_create() will override the stack_size parameter set using this
API
Structures
struct esp_pthread_cfg_t
pthread configuration structure that influences pthread creation
Public Members
size_t stack_size
The stack size of the pthread.
size_t prio
The thread’s priority.
bool inherit_cfg
Inherit this configuration further.
int pin_to_core
The core id to pin the thread to. Has the same value range as xCoreId argument of xTaskCreatePinned-
ToCore.
Macros
PTHREAD_STACK_MIN
ESP32 contains a hardware random number generator, values from it can be obtained using the APIs
esp_random() and esp_fill_random().
The hardware RNG produces true random numbers under any of the following conditions:
• RF subsystem is enabled (i.e. Wi-Fi or Bluetooth are enabled).
• An internal entropy source has been enabled by calling bootloader_random_enable() and not yet
disabled by calling bootloader_random_disable().
• While the ESP-IDF Second stage bootloader is running. This is because the default ESP-IDF boot-
loader implementation calls bootloader_random_enable() when the bootloader starts, and boot-
loader_random_disable() before executing the app.
When any of these conditions are true, samples of physical noise are continuously mixed into the internal hardware
RNG state to provide entropy. Consult the ESP32 Technical Reference Manual > Random Number Generator (RNG)
[PDF] chapter for more details.
If none of the above conditions are true, the output of the RNG should be considered pseudo-random only.
Startup
During startup, ESP-IDF bootloader temporarily enables a non-RF entropy source (internal reference voltage noise)
that provides entropy for any first boot key generation. However, after the app starts executing then normally only
pseudo-random numbers are available until Wi-Fi or Bluetooth are initialized.
To re-enable the entropy source temporarily during app startup, or for an application that does not use Wi-Fi or
Bluetooth, call the function bootloader_random_enable() to re-enable the internal entropy source. The
function bootloader_random_disable() must be called to disable the entropy source again before using
ADC, I2S, Wi-Fi or Bluetooth.
Note: The entropy source enabled during the boot process by the ESP-IDF Second Stage Bootloader will seed the
internal RNG state with some entropy. However, the internal hardware RNG state is not large enough to provide a
continuous stream of true random numbers. This is why a continuous entropy source must be enabled whenever true
random numbers are required.
Note: If an application requires a source of true random numbers but it is not possible to permanently enable a
hardware entropy source, consider using a strong software DRBG implementation such as the mbedTLS CTR-DRBG
or HMAC-DRBG, with an initial seed of entropy from hardware RNG true random numbers.
API Reference
Header File
• components/esp_hw_support/include/esp_random.h
Functions
uint32_t esp_random(void)
Get one random 32-bit word from hardware RNG.
If Wi-Fi or Bluetooth are enabled, this function returns true random numbers. In other situations, if true
random numbers are required then consult the ESP-IDF Programming Guide“Random Number Generation”
section for necessary prerequisites.
This function automatically busy-waits to ensure enough external entropy has been introduced into the hardware
RNG state, before returning a new random number. This delay is very short (always less than 100 CPU cycles).
Returns Random value between 0 and UINT32_MAX
void esp_fill_random(void *buf, size_t len)
Fill a buffer with random bytes from hardware RNG.
Note: This function is implemented via calls to esp_random(), so the same constraints apply.
Parameters
• buf –Pointer to buffer to fill with random numbers.
• len –Length of buffer in bytes
Header File
• components/bootloader_support/include/bootloader_random.h
Functions
void bootloader_random_enable(void)
Enable an entropy source for RNG if RF subsystem is disabled.
The exact internal entropy source mechanism depends on the chip in use but all SoCs use the SAR ADC
to continuously mix random bits (an internal noise reading) into the HWRNG. Consult the SoC Technical
Reference Manual for more information.
Can also be called from app code, if true random numbers are required without initialized RF subsystem. This
might be the case in early startup code of the application when the RF subsystem has not started yet or if the
RF subsystem should not be enabled for power saving.
Consult ESP-IDF Programming Guide “Random Number Generation”section for details.
Warning: This function is not safe to use if any other subsystem is accessing the RF subsystem or the
ADC at the same time!
void bootloader_random_disable(void)
Disable entropy source for RNG.
Disables internal entropy source. Must be called after bootloader_random_enable() and before RF subsystem
features, ADC, or I2S (ESP32 only) are initialized.
Consult the ESP-IDF Programming Guide “Random Number Generation”section for details.
void bootloader_fill_random(void *buffer, size_t length)
Fill buffer with ‘length’random bytes.
Note: If this function is being called from app code only, and never from the bootloader, then it’s better to
call esp_fill_random().
Parameters
• buffer –Pointer to buffer
• length –This many bytes of random data will be copied to buffer
getrandom
A compatible version of the Linux getrandom() function is also provided for ease of porting:
#include <sys/random.h>
Overview
ESP32 contains the following power saving modes: Light-sleep, and Deep-sleep.
In Light-sleep mode, the digital peripherals, most of the RAM, and CPUs are clock-gated and their supply voltage is
reduced. Upon exit from Light-sleep, the digital peripherals, RAM, and CPUs resume operation and their internal
states are preserved.
In Deep-sleep mode, the CPUs, most of the RAM, and all digital peripherals that are clocked from APB_CLK are
powered off. The only parts of the chip that remain powered on are:
• RTC controller
• RTC peripherals
• ULP coprocessor
• RTC fast memory
• RTC slow memory
There are several wakeup sources in Deep-sleep and Light-sleep modes. These sources can also
be combined so that the chip will wake up when any of the sources are triggered. Wakeup
sources can be enabled using esp_sleep_enable_X_wakeup APIs and can be disabled using
esp_sleep_disable_wakeup_source() API. Next section describes these APIs in detail. Wakeup
sources can be configured at any moment before entering Light-sleep or Deep-sleep mode.
Additionally, the application can force specific powerdown modes for RTC peripherals and RTC memories using
esp_sleep_pd_config() API.
Once wakeup sources are configured, the application can enter sleep mode using esp_light_sleep_start()
or esp_deep_sleep_start() APIs. At this point, the hardware will be configured according to the requested
wakeup sources, and the RTC controller will either power down or power off the CPUs and digital peripherals.
If Wi-Fi connections need to be maintained, enable Wi-Fi Modem-sleep mode and automatic Light-sleep feature
(see Power Management APIs). This will allow the system to wake up from sleep automatically when required by the
Wi-Fi driver, thereby maintaining a connection to the AP.
In Deep-sleep and Light-sleep modes, the wireless peripherals are powered down. Before entering Deep-
sleep or Light-sleep modes, the application must disable Wi-Fi and Bluetooth using the appropriate calls (i.e.,
esp_bluedroid_disable(), esp_bt_controller_disable(), esp_wifi_stop()). Wi-Fi and
Bluetooth connections will not be maintained in Deep-sleep or Light-sleep mode, even if these functions are not
called.
Wakeup Sources
Timer The RTC controller has a built-in timer which can be used to wake up the chip after a predefined amount
of time. Time is specified at microsecond precision, but the actual resolution depends on the clock source selected
for RTC SLOW_CLK.
For details on RTC clock options, see ESP32 Technical Reference Manual > ULP Coprocessor [PDF].
RTC peripherals or RTC memories don’t need to be powered on during sleep in this wakeup mode.
esp_sleep_enable_timer_wakeup() function can be used to enable sleep wakeup using a timer.
Touchpad The RTC IO module contains the logic to trigger wakeup when a touch sensor interrupt occurs. To
wakeup from a touch sensor interrupt, users need to configure the touch pad interrupt before the chip enters Deep-
sleep or Light-sleep modes.
Revisions 0 and 1 of ESP32 only support this wakeup mode when RTC peripherals are not forced to be powered on
(i.e., ESP_PD_DOMAIN_RTC_PERIPH should be set to ESP_PD_OPTION_AUTO).
esp_sleep_enable_touchpad_wakeup() function can be used to enable this wakeup source.
External Wakeup (ext0) The RTC IO module contains the logic to trigger wakeup when one of RTC GPIOs is set
to a predefined logic level. RTC IO is part of the RTC peripherals power domain, so RTC peripherals will be kept
powered on during Deep-sleep if this wakeup source is requested.
The RTC IO module is enabled in this mode, so internal pullup or pulldown resistors can also be used. They need to be
configured by the application using rtc_gpio_pullup_en() and rtc_gpio_pulldown_en() functions
before calling esp_deep_sleep_start().
In revisions 0 and 1 of ESP32, this wakeup source is incompatible with ULP and touch wakeup sources.
Warning: After waking up from sleep, the IO pad used for wakeup will be configured as RTC IO. Therefore,
before using this pad as digital GPIO, users need to reconfigure it using rtc_gpio_deinit() function.
External Wakeup (ext1) The RTC controller contains the logic to trigger wakeup using multiple RTC GPIOs.
One of the following two logic functions can be used to trigger wakeup:
• wake up if any of the selected pins is high (ESP_EXT1_WAKEUP_ANY_HIGH)
• wake up if all the selected pins are low (ESP_EXT1_WAKEUP_ALL_LOW)
This wakeup source is implemented by the RTC controller. As such, RTC peripherals and RTC memories can be
powered down in this mode. However, if RTC peripherals are powered down, internal pullup and pulldown resistors
will be disabled. To use internal pullup or pulldown resistors, request the RTC peripherals power domain to be kept
on during sleep, and configure pullup/pulldown resistors using rtc_gpio_ functions before entering sleep:
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
gpio_pullup_dis(gpio_num);
gpio_pulldown_en(gpio_num);
Warning: After waking up from sleep, IO pad(s) used for wakeup will be configured as RTC IO. Before using
these pads as digital GPIOs, reconfigure them using rtc_gpio_deinit() function.
ULP Coprocessor Wakeup ULP coprocessor can run while the chip is in sleep mode, and may be used to poll
sensors, monitor ADC or touch sensor values, and wake up the chip when a specific event is detected. ULP copro-
cessor is part of the RTC peripherals power domain, and it runs the program stored in RTC slow memory. RTC slow
memory will be powered on during sleep if this wakeup mode is requested. RTC peripherals will be automatically
powered on before ULP coprocessor starts running the program; once the program stops running, RTC peripherals
are automatically powered down again.
Revisions 0 and 1 of ESP32 only support this wakeup mode when RTC peripherals are not forced to be powered on
(i.e., ESP_PD_DOMAIN_RTC_PERIPH should be set to ESP_PD_OPTION_AUTO).
esp_sleep_enable_ulp_wakeup() function can be used to enable this wakeup source.
GPIO Wakeup (Light-sleep Only) In addition to EXT0 and EXT1 wakeup sources described above, one more
method of wakeup from external inputs is available in Light-sleep mode. With this wakeup source, each pin can be
individually configured to trigger wakeup on high or low level using gpio_wakeup_enable() function. Unlike
EXT0 and EXT1 wakeup sources, which can only be used with RTC IOs, this wakeup source can be used with any
IO (RTC or digital).
esp_sleep_enable_gpio_wakeup() function can be used to enable this wakeup source.
Warning: Before entering Light-sleep mode, check if any GPIO pin to be driven is part of the VDD_SDIO
power domain. If so, this power domain must be configured to remain ON during sleep.
For example, on ESP32-WROOM-32 board, GPIO16 and GPIO17 are linked to VDD_SDIO power domain. If
they are configured to remain high during Light-sleep, the power domain should be configured to remain powered
ON. This can be done with esp_sleep_pd_config():
esp_sleep_pd_config(ESP_PD_DOMAIN_VDDSDIO, ESP_PD_OPTION_ON);
UART Wakeup (Light-sleep Only) When ESP32 receives UART input from external devices, it is often necessary
to wake up the chip when input data is available. The UART peripheral contains a feature which allows waking up
the chip from Light-sleep when a certain number of positive edges on RX pin are seen. This number of positive edges
can be set using uart_set_wakeup_threshold() function. Note that the character which triggers wakeup
(and any characters before it) will not be received by the UART after wakeup. This means that the external device
typically needs to send an extra character to the ESP32 to trigger wakeup before sending the data.
esp_sleep_enable_uart_wakeup() function can be used to enable this wakeup source.
Power-down of Flash
Warning: If a filter capacitor is added to your flash power supply circuit, please do everything possible to avoid
powering down flash.
Therefore, it’s recommended not to power down flash when using ESP-IDF. For power-sensitive applications, it’
s recommended to use Kconfig option CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND to reduce the
power consumption of the flash during light sleep, instead of powering down the flash.
It is worth mentioning that PSRAM has a similar Kconfig option CON-
FIG_ESP_SLEEP_PSRAM_LEAKAGE_WORKAROUND.
However, for those who have fully understood the risk and are still willing to power down the flash to further reduce
the power consumption, please check the following mechanisms:
Note: ESP-IDF does not provide any mechanism that can power down the flash in all conditions.
Entering Light-sleep
esp_light_sleep_start() function can be used to enter Light-sleep once wakeup sources are configured. It
is also possible to enter Light-sleep with no wakeup sources configured. In this case, the chip will be in Light-sleep
mode indefinitely until external reset is applied.
Entering Deep-sleep
esp_deep_sleep_start() function can be used to enter Deep-sleep once wakeup sources are configured. It
is also possible to enter Deep-sleep with no wakeup sources configured. In this case, the chip will be in Deep-sleep
mode indefinitely until external reset is applied.
Configuring IOs
Some ESP32 IOs have internal pullups or pulldowns, which are enabled by default. If an external circuit drives this pin
in Deep-sleep mode, current consumption may increase due to current flowing through these pullups and pulldowns.
To isolate a pin to prevent extra current draw, call rtc_gpio_isolate() function.
For example, on ESP32-WROVER module, GPIO12 is pulled up externally, and it also has an internal pulldown in
the ESP32 chip. This means that in Deep-sleep, some current will flow through these external and internal resistors,
increasing Deep-sleep current above the minimal possible value.
Add the following code before esp_deep_sleep_start() to remove such extra current:
rtc_gpio_isolate(GPIO_NUM_12);
Before entering sleep mode, esp_deep_sleep_start() will flush the contents of UART FIFOs.
When entering Light-sleep mode using esp_light_sleep_start(), UART FIFOs will not be flushed. In-
stead, UART output will be suspended, and remaining characters in the FIFO will be sent out after wakeup from
Light-sleep.
esp_sleep_get_wakeup_cause() function can be used to check which wakeup source has triggered wakeup
from sleep mode.
For touchpad, it is possible to identify which touch pin has caused wakeup using
esp_sleep_get_touchpad_wakeup_status() functions.
For ext1 wakeup sources, it is possible to identify which touch pin has caused wakeup using
esp_sleep_get_ext1_wakeup_status() functions.
Application Example
• protocols/sntp: the implementation of basic functionality of Deep-sleep, where ESP module is periodically
waken up to retrieve time from NTP server.
• wifi/power_save: the implementation of modem sleep example.
• system/deep_sleep: the usage of various Deep-sleep wakeup triggers and ULP coprocessor programming.
API Reference
Header File
• components/esp_hw_support/include/esp_sleep.h
Functions
esp_err_t esp_sleep_disable_wakeup_source(esp_sleep_source_t source)
Disable wakeup source.
This function is used to deactivate wake up trigger for source defined as parameter of the function.
Note: This function does not modify wake up configuration in RTC. It will be performed in
esp_deep_sleep_start/esp_light_sleep_start function.
Note: In revisions 0 and 1 of the ESP32, ULP wakeup source cannot be used when RTC_PERIPH power
domain is forced to be powered on (ESP_PD_OPTION_ON) or when ext0 wakeup source is used.
Returns
• ESP_OK on success
• ESP_ERR_NOT_SUPPORTED if additional current by touch (CON-
FIG_RTC_EXT_CRYST_ADDIT_CURRENT) is enabled.
• ESP_ERR_INVALID_STATE if ULP co-processor is not enabled or if wakeup triggers
conflict
esp_err_t esp_sleep_enable_touchpad_wakeup(void)
Enable wakeup by touch sensor.
Note: In revisions 0 and 1 of the ESP32, touch wakeup source can not be used when RTC_PERIPH power
domain is forced to be powered on (ESP_PD_OPTION_ON) or when ext0 wakeup source is used.
Note: The FSM mode of the touch button should be configured as the timer trigger mode.
Returns
• ESP_OK on success
• ESP_ERR_NOT_SUPPORTED if additional current by touch (CON-
FIG_RTC_EXT_CRYST_ADDIT_CURRENT) is enabled.
• ESP_ERR_INVALID_STATE if wakeup triggers conflict
touch_pad_t esp_sleep_get_touchpad_wakeup_status(void)
Get the touch pad which caused wakeup.
If wakeup was caused by another source, this function will return TOUCH_PAD_MAX;
Returns touch pad which caused wakeup
bool esp_sleep_is_valid_wakeup_gpio(gpio_num_t gpio_num)
Returns true if a GPIO number is valid for use as wakeup source.
Note: For SoCs with RTC IO capability, this can be any valid RTC IO input pin.
Parameters gpio_num –Number of the GPIO to test for wakeup source capability
Returns True if this GPIO number will be accepted as a sleep wakeup source.
Note: This function does not modify pin configuration. The pin is configured in
esp_deep_sleep_start/esp_light_sleep_start, immediately before entering sleep mode.
Note: In revisions 0 and 1 of the ESP32, ext0 wakeup source can not be used together with touch or ULP
wakeup sources.
Parameters
• gpio_num –GPIO number used as wakeup source. Only GPIOs which are have RTC
functionality can be used: 0,2,4,12-15,25-27,32-39.
• level –input level which will trigger wakeup (0=low, 1=high)
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if the selected GPIO is not an RTC GPIO, or the mode is
invalid
Note: This function does not modify pin configuration. The pins are configured in
esp_deep_sleep_start/esp_light_sleep_start, immediately before entering sleep mode.
Note: Internal pullups and pulldowns don’t work when RTC peripherals are shut down. In this case, external
resistors need to be added. Alternatively, RTC peripherals (and pullups/pulldowns) may be kept enabled using
esp_sleep_pd_config function.
Parameters
• mask –bit mask of GPIO numbers which will cause wakeup. Only GPIOs which have
RTC functionality can be used in this bit map: 0,2,4,12-15,25-27,32-39.
• mode –select logic function used to determine wakeup condition:
– ESP_EXT1_WAKEUP_ALL_LOW: wake up when all selected GPIOs are low
– ESP_EXT1_WAKEUP_ANY_HIGH: wake up when any of the selected GPIOs is high
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if any of the selected GPIOs is not an RTC GPIO, or mode
is invalid
esp_err_t esp_sleep_enable_gpio_wakeup(void)
Enable wakeup from light sleep using GPIOs.
Each GPIO supports wakeup function, which can be triggered on either low level or high level. Unlike EXT0
and EXT1 wakeup sources, this method can be used both for all IOs: RTC IOs and digital IOs. It can only be
used to wakeup from light sleep though.
To enable wakeup, first call gpio_wakeup_enable, specifying gpio number and wakeup level, for each GPIO
which is used for wakeup. Then call this function to enable wakeup feature.
Note: In revisions 0 and 1 of the ESP32, GPIO wakeup source can not be used together with touch or ULP
wakeup sources.
Returns
• ESP_OK on success
• ESP_ERR_INVALID_STATE if wakeup triggers conflict
esp_err_t esp_sleep_enable_bt_wakeup(void)
Enable wakeup by bluetooth.
Returns
• ESP_OK on success
• ESP_ERR_NOT_SUPPORTED if wakeup from bluetooth is not supported
esp_err_t esp_sleep_disable_bt_wakeup(void)
Disable wakeup by bluetooth.
Returns
• ESP_OK on success
• ESP_ERR_NOT_SUPPORTED if wakeup from bluetooth is not supported
esp_err_t esp_sleep_enable_wifi_wakeup(void)
Enable wakeup by WiFi MAC.
Returns
• ESP_OK on success
esp_err_t esp_sleep_disable_wifi_wakeup(void)
Disable wakeup by WiFi MAC.
Returns
• ESP_OK on success
uint64_t esp_sleep_get_ext1_wakeup_status(void)
Get the bit mask of GPIOs which caused wakeup (ext1)
If wakeup was caused by another source, this function will return 0.
Returns bit mask, if GPIOn caused wakeup, BIT(n) will be set
esp_err_t esp_sleep_pd_config(esp_sleep_pd_domain_t domain, esp_sleep_pd_option_t option)
Set power down mode for an RTC power domain in sleep mode.
If not set set using this API, all power domains default to ESP_PD_OPTION_AUTO.
Parameters
• domain –power domain to configure
• option –power down option (ESP_PD_OPTION_OFF, ESP_PD_OPTION_ON, or
ESP_PD_OPTION_AUTO)
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if either of the arguments is out of range
void esp_deep_sleep_start(void)
Enter deep sleep with the configured wakeup options.
This function does not return.
esp_err_t esp_light_sleep_start(void)
Enter light sleep with the configured wakeup options.
Returns
• ESP_OK on success (returned after wakeup)
• ESP_ERR_INVALID_STATE if WiFi or BT is not stopped
Note: The device will wake up immediately if the deep-sleep time is set to 0
esp_sleep_wakeup_cause_t esp_sleep_get_wakeup_cause(void)
Get the wakeup source which caused wakeup from sleep.
Returns cause of wake up from last sleep (deep sleep or light sleep)
void esp_wake_deep_sleep(void)
Default stub to run on wake from deep sleep.
Allows for executing code immediately on wake from sleep, before the software bootloader or ESP-IDF app
has started up.
This function is weak-linked, so you can implement your own version to run code immediately when the chip
wakes from sleep.
See docs/deep-sleep-stub.rst for details.
void esp_set_deep_sleep_wake_stub(esp_deep_sleep_wake_stub_fn_t new_stub)
Install a new stub at runtime to run on wake from deep sleep.
If implementing esp_wake_deep_sleep() then it is not necessary to call this function.
However, it is possible to call this function to substitute a different deep sleep stub. Any function
used as a deep sleep stub must be marked RTC_IRAM_ATTR, and must obey the same rules given for
esp_wake_deep_sleep().
esp_deep_sleep_wake_stub_fn_t esp_get_deep_sleep_wake_stub(void)
Get current wake from deep sleep stub.
Returns Return current wake from deep sleep stub, or NULL if no stub is installed.
void esp_default_wake_deep_sleep(void)
The default esp-idf-provided esp_wake_deep_sleep() stub.
See docs/deep-sleep-stub.rst for details.
void esp_deep_sleep_disable_rom_logging(void)
Disable logging from the ROM code after deep sleep.
Using LSB of RTC_STORE4.
void esp_sleep_config_gpio_isolate(void)
Configure to isolate all GPIO pins in sleep state.
void esp_sleep_enable_gpio_switch(bool enable)
Enable or disable GPIO pins status switching between slept status and waked status.
Parameters enable –decide whether to switch status or not
Type Definitions
Enumerations
enum esp_sleep_ext1_wakeup_mode_t
Logic function used for EXT1 wakeup mode.
Values:
enumerator ESP_EXT1_WAKEUP_ALL_LOW
Wake the chip when all selected GPIOs go low.
enumerator ESP_EXT1_WAKEUP_ANY_HIGH
Wake the chip when any of the selected GPIOs go high.
enum esp_sleep_pd_domain_t
Power domains which can be powered down in sleep mode.
Values:
enumerator ESP_PD_DOMAIN_RTC_PERIPH
RTC IO, sensors and ULP co-processor.
enumerator ESP_PD_DOMAIN_RTC_SLOW_MEM
RTC slow memory.
enumerator ESP_PD_DOMAIN_RTC_FAST_MEM
RTC fast memory.
enumerator ESP_PD_DOMAIN_XTAL
XTAL oscillator.
enumerator ESP_PD_DOMAIN_RTC8M
Internal 8M oscillator.
enumerator ESP_PD_DOMAIN_VDDSDIO
VDD_SDIO.
enumerator ESP_PD_DOMAIN_MAX
Number of domains.
enum esp_sleep_pd_option_t
Power down options.
Values:
enumerator ESP_PD_OPTION_OFF
Power down the power domain in sleep mode.
enumerator ESP_PD_OPTION_ON
Keep power domain enabled during sleep mode.
enumerator ESP_PD_OPTION_AUTO
Keep power domain enabled in sleep mode, if it is needed by one of the wakeup options. Otherwise
power it down.
enum esp_sleep_source_t
Sleep wakeup cause.
Values:
enumerator ESP_SLEEP_WAKEUP_UNDEFINED
In case of deep sleep, reset was not caused by exit from deep sleep.
enumerator ESP_SLEEP_WAKEUP_ALL
Not a wakeup cause, used to disable all wakeup sources with esp_sleep_disable_wakeup_source.
enumerator ESP_SLEEP_WAKEUP_EXT0
Wakeup caused by external signal using RTC_IO.
enumerator ESP_SLEEP_WAKEUP_EXT1
Wakeup caused by external signal using RTC_CNTL.
enumerator ESP_SLEEP_WAKEUP_TIMER
Wakeup caused by timer.
enumerator ESP_SLEEP_WAKEUP_TOUCHPAD
Wakeup caused by touchpad.
enumerator ESP_SLEEP_WAKEUP_ULP
Wakeup caused by ULP program.
enumerator ESP_SLEEP_WAKEUP_GPIO
Wakeup caused by GPIO (light sleep only)
enumerator ESP_SLEEP_WAKEUP_UART
Wakeup caused by UART (light sleep only)
enumerator ESP_SLEEP_WAKEUP_WIFI
Wakeup caused by WIFI (light sleep only)
enumerator ESP_SLEEP_WAKEUP_COCPU
Wakeup caused by COCPU int.
enumerator ESP_SLEEP_WAKEUP_COCPU_TRAP_TRIG
Wakeup caused by COCPU crash.
enumerator ESP_SLEEP_WAKEUP_BT
Wakeup caused by BT (light sleep only)
This section lists definitions of the ESP32’s SoC hardware capabilities. These definitions are commonly used in IDF
to control which hardware dependent features are supported and thus compiled into the binary.
Note: These defines are currently not considered to be part of the public API, and may be changed at any time.
API Reference
Header File
• components/soc/esp32/include/soc/soc_caps.h
Macros
SOC_CAPS_ECO_VER_MAX
SOC_ADC_SUPPORTED
SOC_DAC_SUPPORTED
SOC_MCPWM_SUPPORTED
SOC_SDMMC_HOST_SUPPORTED
SOC_BT_SUPPORTED
SOC_CLASSIC_BT_SUPPORTED
SOC_PCNT_SUPPORTED
SOC_WIFI_SUPPORTED
SOC_SDIO_SLAVE_SUPPORTED
SOC_TWAI_SUPPORTED
SOC_EMAC_SUPPORTED
SOC_ULP_SUPPORTED
SOC_CCOMP_TIMER_SUPPORTED
SOC_RTC_FAST_MEM_SUPPORTED
SOC_RTC_SLOW_MEM_SUPPORTED
SOC_I2S_SUPPORTED
SOC_RMT_SUPPORTED
SOC_SIGMADELTA_SUPPORTED
SOC_SUPPORT_COEXISTENCE
SOC_AES_SUPPORTED
SOC_MPI_SUPPORTED
SOC_SHA_SUPPORTED
SOC_FLASH_ENC_SUPPORTED
SOC_SECURE_BOOT_SUPPORTED
SOC_DPORT_WORKAROUND
SOC_DPORT_WORKAROUND_DIS_INTERRUPT_LVL
SOC_ADC_SUPPORT_DMA_MODE(PERIPH_NUM)
TO BE REMOVED Check if adc support digital controller (DMA) mode.
• 1 : support;
• 0 : not support; SAR ADC Module
SOC_ADC_RTC_CTRL_SUPPORTED
SOC_ADC_DIG_CTRL_SUPPORTED
SOC_ADC_PERIPH_NUM
SOC_ADC_CHANNEL_NUM(PERIPH_NUM)
SOC_ADC_MAX_CHANNEL_NUM
SOC_ADC_ATTEN_NUM
Digital
SOC_ADC_DIGI_CONTROLLER_NUM
SOC_ADC_PATT_LEN_MAX
SOC_ADC_DIGI_MIN_BITWIDTH
SOC_ADC_DIGI_MAX_BITWIDTH
F_sample = F_digi_con / 2 / interval. F_digi_con = 5M for now. 30 <= interva <= 4095
SOC_ADC_SAMPLE_FREQ_THRES_HIGH
SOC_ADC_SAMPLE_FREQ_THRES_LOW
RTC
SOC_ADC_RTC_MIN_BITWIDTH
SOC_ADC_RTC_MAX_BITWIDTH
SOC_RTC_SLOW_CLOCK_SUPPORT_8MD256
SOC_SHARED_IDCACHE_SUPPORTED
SOC_CPU_CORES_NUM
SOC_CPU_INTR_NUM
SOC_CPU_HAS_FPU
SOC_CPU_BREAKPOINTS_NUM
SOC_CPU_WATCHPOINTS_NUM
SOC_CPU_WATCHPOINT_SIZE
SOC_DAC_PERIPH_NUM
SOC_DAC_RESOLUTION
SOC_GPIO_PORT
SOC_GPIO_PIN_COUNT
SOC_GPIO_VALID_GPIO_MASK
SOC_GPIO_VALID_OUTPUT_GPIO_MASK
SOC_GPIO_SUPPORT_SLP_SWITCH
SOC_I2C_NUM
SOC_I2C_FIFO_LEN
I2C hardware FIFO depth
SOC_I2C_SUPPORT_SLAVE
SOC_I2C_SUPPORT_APB
SOC_CLK_APLL_SUPPORTED
SOC_APLL_MULTIPLIER_OUT_MIN_HZ
SOC_APLL_MULTIPLIER_OUT_MAX_HZ
SOC_APLL_MIN_HZ
SOC_APLL_MAX_HZ
SOC_I2S_NUM
SOC_I2S_HW_VERSION_1
SOC_I2S_SUPPORTS_APLL
SOC_I2S_SUPPORTS_PDM
SOC_I2S_SUPPORTS_PDM_TX
SOC_I2S_SUPPORTS_PDM_RX
SOC_I2S_SUPPORTS_ADC_DAC
SOC_I2S_SUPPORTS_ADC
SOC_I2S_SUPPORTS_DAC
SOC_I2S_SUPPORTS_LCD_CAMERA
SOC_I2S_TRANS_SIZE_ALIGN_WORD
SOC_I2S_LCD_I80_VARIANT
SOC_LCD_I80_SUPPORTED
Intel 8080 LCD is supported
SOC_LCD_I80_BUSES
Both I2S0/1 have LCD mode
SOC_LCD_I80_BUS_WIDTH
Intel 8080 bus width
SOC_LEDC_HAS_TIMER_SPECIFIC_MUX
SOC_LEDC_SUPPORT_APB_CLOCK
SOC_LEDC_SUPPORT_REF_TICK
SOC_LEDC_SUPPORT_HS_MODE
SOC_LEDC_CHANNEL_NUM
SOC_LEDC_TIMER_BIT_WIDE_NUM
SOC_MCPWM_GROUPS
2 MCPWM groups on the chip (i.e., the number of independent MCPWM peripherals)
SOC_MCPWM_TIMERS_PER_GROUP
The number of timers that each group has.
SOC_MCPWM_OPERATORS_PER_GROUP
The number of operators that each group has.
SOC_MCPWM_COMPARATORS_PER_OPERATOR
The number of comparators that each operator has.
SOC_MCPWM_GENERATORS_PER_OPERATOR
The number of generators that each operator has.
SOC_MCPWM_TRIGGERS_PER_OPERATOR
The number of triggers that each operator has.
SOC_MCPWM_GPIO_FAULTS_PER_GROUP
The number of GPIO fault signals that each group has.
SOC_MCPWM_CAPTURE_TIMERS_PER_GROUP
The number of capture timers that each group has.
SOC_MCPWM_CAPTURE_CHANNELS_PER_TIMER
The number of capture channels that each capture timer has.
SOC_MCPWM_GPIO_SYNCHROS_PER_GROUP
The number of GPIO synchros that each group has.
SOC_MPU_CONFIGURABLE_REGIONS_SUPPORTED
SOC_MPU_MIN_REGION_SIZE
SOC_MPU_REGIONS_MAX_NUM
SOC_MPU_REGION_RO_SUPPORTED
SOC_MPU_REGION_WO_SUPPORTED
SOC_PCNT_GROUPS
SOC_PCNT_UNITS_PER_GROUP
SOC_PCNT_CHANNELS_PER_UNIT
SOC_PCNT_THRES_POINT_PER_UNIT
SOC_RMT_GROUPS
One RMT group
SOC_RMT_TX_CANDIDATES_PER_GROUP
Number of channels that capable of Transmit in each group
SOC_RMT_RX_CANDIDATES_PER_GROUP
Number of channels that capable of Receive in each group
SOC_RMT_CHANNELS_PER_GROUP
Total 8 channels
SOC_RMT_MEM_WORDS_PER_CHANNEL
Each channel owns 64 words memory
SOC_RMT_SUPPORT_REF_TICK
Support set REF_TICK as the RMT clock source
SOC_RMT_SUPPORT_APB
Support set APB as the RMT clock source
SOC_RMT_CHANNEL_CLK_INDEPENDENT
Can select different source clock for each channel
SOC_RTCIO_PIN_COUNT
SOC_RTCIO_INPUT_OUTPUT_SUPPORTED
SOC_RTCIO_HOLD_SUPPORTED
SOC_RTCIO_WAKE_SUPPORTED
SOC_SIGMADELTA_NUM
SOC_SIGMADELTA_CHANNEL_NUM
SOC_SPI_HD_BOTH_INOUT_SUPPORTED
SOC_SPI_AS_CS_SUPPORTED
SOC_SPI_PERIPH_NUM
SOC_SPI_DMA_CHAN_NUM
SOC_SPI_PERIPH_CS_NUM(i)
SOC_SPI_MAXIMUM_BUFFER_SIZE
SOC_SPI_MAX_PRE_DIVIDER
SOC_MEMSPI_SRC_FREQ_80M_SUPPORTED
SOC_MEMSPI_SRC_FREQ_40M_SUPPORTED
SOC_MEMSPI_SRC_FREQ_26M_SUPPORTED
SOC_MEMSPI_SRC_FREQ_20M_SUPPORTED
SOC_SPI_PERIPH_SUPPORT_MULTILINE_MODE(spi_host)
SOC_TIMER_GROUPS
SOC_TIMER_GROUP_TIMERS_PER_GROUP
SOC_TIMER_GROUP_COUNTER_BIT_WIDTH
SOC_TIMER_GROUP_TOTAL_TIMERS
SOC_TIMER_GROUP_SUPPORT_APB
SOC_TOUCH_VERSION_1
Hardware version of touch sensor
SOC_TOUCH_SENSOR_NUM
SOC_TOUCH_PAD_MEASURE_WAIT_MAX
The timer frequency is 8Mhz, the max value is 0xff
SOC_TOUCH_PAD_THRESHOLD_MAX
If set touch threshold max value, The touch sensor can’t be in touched status
SOC_TWAI_BRP_MIN
SOC_TWAI_BRP_MAX
SOC_TWAI_SUPPORT_MULTI_ADDRESS_LAYOUT
SOC_UART_NUM
SOC_UART_SUPPORT_REF_TICK
Support REF_TICK as the clock source
SOC_UART_FIFO_LEN
The UART hardware FIFO length
SOC_UART_BITRATE_MAX
Max bit rate supported by UART
SOC_SPIRAM_SUPPORTED
SOC_SPI_MEM_SUPPORT_CONFIG_GPIO_BY_EFUSE
SOC_SHA_SUPPORT_PARALLEL_ENG
SOC_SHA_SUPPORT_SHA1
SOC_SHA_SUPPORT_SHA256
SOC_SHA_SUPPORT_SHA384
SOC_SHA_SUPPORT_SHA512
SOC_RSA_MAX_BIT_LEN
SOC_AES_SUPPORT_AES_128
SOC_AES_SUPPORT_AES_192
SOC_AES_SUPPORT_AES_256
SOC_SECURE_BOOT_V1
SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS
SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX
SOC_PHY_DIG_REGS_MEM_SIZE
SOC_PM_SUPPORT_EXT_WAKEUP
SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP
Supports waking up from touch pad trigger
SOC_PM_SUPPORT_RTC_PERIPH_PD
SOC_PM_SUPPORT_RTC_FAST_MEM_PD
SOC_PM_SUPPORT_RTC_SLOW_MEM_PD
SOC_CAN_SUPPORTED
CAN_BRP_MIN
CAN_BRP_MAX
CAN_SUPPORT_MULTI_ADDRESS_LAYOUT
SOC_SDMMC_USE_IOMUX
SOC_SDMMC_NUM_SLOTS
SOC_BLE_DONT_UPDATE_OWN_RPA
SOC_WIFI_HW_TSF
Hardware TSF is not supported
SOC_WIFI_FTM_SUPPORT
FTM is not supported
SOC_WIFI_GCMP_SUPPORT
GCMP is not supported(GCMP128 and GCMP256)
SOC_WIFI_WAPI_SUPPORT
Support WAPI
SOC_WIFI_CSI_SUPPORT
Support CSI
SOC_WIFI_MESH_SUPPORT
Support WIFI MESH
Overview
ESP32 uses two hardware timers for the purpose of keeping system time. System time can be kept by using either
one or both of the hardware timers depending on the application’s purpose and accuracy requirements for system
time. The two hardware timers are:
• RTC timer: This timer allows time keeping in various sleep modes, and can also persist time keeping across
any resets (with the exception of power-on resets which reset the RTC timer). The frequency deviation depends
on the RTC Timer Clock Sources and affects the accuracy only in sleep modes, in which case the time will be
measured at 6.6667 μs resolution.
• High-resolution timer: This timer is not available in sleep modes and will not persist over a reset, but has
greater accuracy. The timer uses the APB_CLK clock source (typically 80 MHz), which has a frequency
deviation of less than ±10 ppm. Time will be measured at 1 μs resolution.
The possible combinations of hardware timers used to keep system time are listed below:
• RTC and high-resolution timer (default)
• RTC
• High-resolution timer
• None
It is recommended that users stick to the default option as it provides the highest accuracy. However, users can also
select a different setting via the CONFIG_NEWLIB_TIME_SYSCALL configuration option.
• Internal 150 kHz RC oscillator (default): Features the lowest Deep-sleep current consumption
and no dependence on any external components. However, the frequency stability of this clock source is
affected by temperature fluctuations, so time may drift in both Deep-sleep and Light-sleep modes.
• External 32 kHz crystal: Requires a 32 kHz crystal to be connected to the 32K_XP and 32K_XN
pins. This source provides a better frequency stability at the expense of a slightly higher (by 1 μA) Deep-sleep
current consumption.
• External 32 kHz oscillator at 32K_XN pin: Allows using 32 kHz clock generated by an
external circuit. The external clock signal must be connected to the 32K_XN pin. The amplitude should be
less than 1.2 V for sine wave signal and less than 1 V for square wave signal. Common mode voltage should be
in the range of 0.1 < Vcm < 0.5xVamp, where Vamp stands for signal amplitude. In this case, the 32K_XN
pin cannot be used as a GPIO pin.
• Internal 8.5 MHz oscillator, divided by 256 (~33 kHz): Provides better frequency
stability than the Internal 150 kHz RC oscillator at the expense of a higher (by 5 μA) Deep-sleep
current consumption. It also does not require external components.
The choice depends on your requirements for system time accuracy and power consumption in sleep modes. To
modify the RTC clock source, set CONFIG_RTC_CLK_SRC in project configuration.
More details about the wiring requirements for the external crystal or external oscillator, please refer to ESP32
Hardware Design Guidelines.
To get the current time, use the POSIX function gettimeofday(). Additionally, you can use the following
standard C library functions to obtain time and manipulate it:
gettimeofday
time
asctime
clock
ctime
difftime
gmtime
localtime
mktime
strftime
adjtime*
To stop smooth time adjustment and update the current time immediately, use the POSIX function settimeof-
day().
If you need to obtain time with one second resolution, use the following code snippet:
time_t now;
char strftime_buf[64];
struct tm timeinfo;
time(&now);
// Set timezone to China Standard Time
setenv("TZ", "CST-8", 1);
tzset();
localtime_r(&now, &timeinfo);
strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);
If you need to obtain time with one microsecond resolution, use the code snippet below:
To set the current time, you can use the POSIX functions settimeofday() and adjtime(). They are used
internally in the lwIP SNTP library to set current time when a response from the NTP server is received. These
functions can also be used separately from the lwIP SNTP library.
The function to use inside the lwIP SNTP library depends on the sync mode for system time. Use the function
sntp_set_sync_mode() to set one of the following sync modes:
• SNTP_SYNC_MODE_IMMED (default): Updates system time immediately upon receiving a response from
the SNTP server after using settimeofday().
• SNTP_SYNC_MODE_SMOOTH: Updates time smoothly by gradually reducing time error using the function
adjtime(). If the difference between the SNTP response time and system time is more than 35 minutes,
update system time immediately by using settimeofday().
The lwIP SNTP library has API functions for setting a callback function for a certain event. You might need the
following functions:
• sntp_set_time_sync_notification_cb(): Can be used to set a callback function that will notify
of the time synchronization process.
sntp_setoperatingmode(SNTP_OPMODE_POLL);
sntp_setservername(0, "pool.ntp.org");
sntp_init();
An application with this initialization code will periodically synchronize the time. The time synchronization period
is determined by CONFIG_LWIP_SNTP_UPDATE_DELAY (the default value is one hour). To modify the variable,
set CONFIG_LWIP_SNTP_UPDATE_DELAY in project configuration.
A code example that demonstrates the implementation of time synchronization based on the lwIP SNTP library is
provided in the protocols/sntp directory.
Timezones
64-bit time_t
ESP-IDF uses 32-bit time_t type by default. To address the Y2K38 issue, you may need to use 64-bit time_t
type when building the application.
Currently, this requires building the cross-compiler toolchain from scratch. See the instructions for building the
toolchain in Standard Toolchain Setup for Linux and macOS. To enable 64-bit time_t support in the toolchain,
you need to remove the --enable-newlib-long-time_t option from the crosstool-NG/samples/
xtensa-esp32-elf/crosstool.config file before building the toolchain.
If you need to make the program compatible with both 32-bit and 64-bit time_t, you may use the following
methods:
• In C or C++ source files, _USE_LONG_TIME_T preprocessor macro will be defined if 32-bit time_t is
used. You need to include <sys/types.h> to make this macro available.
• In CMake files, TIME_T_SIZE IDF build property will be set to the size of time_t in bytes.
You may call idf_build_get_property(var TIME_T_SIZE) to get the value of this prop-
erty into a CMake variable var. See ESP-IDF CMake Build System API for more information about
idf_build_get_property.
Note that the size of time_t type also affects the sizes of other types, for example, struct timeval, struct
stat, and struct utimbuf.
API Reference
Header File
• components/lwip/include/apps/esp_sntp.h
Functions
void sntp_sync_time(struct timeval *tv)
This function updates the system time.
This is a weak-linked function. It is possible to replace all SNTP update functionality by placing a
sntp_sync_time() function in the app firmware source. If the default implementation is used, calling
sntp_set_sync_mode() allows the time synchronization mode to be changed to instant or smooth. If a callback
function is registered via sntp_set_time_sync_notification_cb(), it will be called following time synchroniza-
tion.
Parameters tv –Time received from SNTP server.
void sntp_set_sync_mode(sntp_sync_mode_t sync_mode)
Set the sync mode.
Modes allowed: SNTP_SYNC_MODE_IMMED and SNTP_SYNC_MODE_SMOOTH.
Parameters sync_mode –Sync mode.
sntp_sync_mode_t sntp_get_sync_mode(void)
Get set sync mode.
Returns SNTP_SYNC_MODE_IMMED: Update time immediately.
SNTP_SYNC_MODE_SMOOTH: Smooth time updating.
sntp_sync_status_t sntp_get_sync_status(void)
Get status of time sync.
After the update is completed, the status will be returned as SNTP_SYNC_STATUS_COMPLETED. After
that, the status will be reset to SNTP_SYNC_STATUS_RESET. If the update operation is not completed yet,
the status will be SNTP_SYNC_STATUS_RESET. If a smooth mode was chosen and the synchronization is
still continuing (adjtime works), then it will be SNTP_SYNC_STATUS_IN_PROGRESS.
Returns SNTP_SYNC_STATUS_RESET: Reset status. SNTP_SYNC_STATUS_COMPLETED:
Time is synchronized. SNTP_SYNC_STATUS_IN_PROGRESS: Smooth time sync in
progress.
void sntp_set_sync_status(sntp_sync_status_t sync_status)
Set status of time sync.
Parameters sync_status –status of time sync (see sntp_sync_status_t)
void sntp_set_time_sync_notification_cb(sntp_sync_time_cb_t callback)
Set a callback function for time synchronization notification.
Parameters callback –a callback function
void sntp_set_sync_interval(uint32_t interval_ms)
Set the sync interval of SNTP operation.
Note: SNTPv4 RFC 4330 enforces a minimum sync interval of 15 seconds. This sync interval will be used in
the next attempt update time throught SNTP. To apply the new sync interval call the sntp_restart() function,
otherwise, it will be applied after the last interval expired.
Parameters interval_ms –The sync interval in ms. It cannot be lower than 15 seconds, oth-
erwise 15 seconds will be set.
uint32_t sntp_get_sync_interval(void)
Get the sync interval of SNTP operation.
Returns the sync interval
bool sntp_restart(void)
Restart SNTP.
Returns True - Restart False - SNTP was not initialized yet
Type Definitions
Enumerations
enum sntp_sync_mode_t
SNTP time update mode.
Values:
enumerator SNTP_SYNC_MODE_IMMED
Update system time immediately when receiving a response from the SNTP server.
enumerator SNTP_SYNC_MODE_SMOOTH
Smooth time updating. Time error is gradually reduced using adjtime function. If the difference between
SNTP response time and system time is large (more than 35 minutes) then update immediately.
enum sntp_sync_status_t
SNTP sync status.
Values:
enumerator SNTP_SYNC_STATUS_RESET
enumerator SNTP_SYNC_STATUS_COMPLETED
enumerator SNTP_SYNC_STATUS_IN_PROGRESS
Overview
The ESP32 can access external SPI RAM transparently, so you can use it as normal memory in your program code.
However, because the address space for external memory is limited in size, only the first 4MiB can be used as such.
Access to the remaining memory is still possible, however this needs to go through a bankswitching scheme controlled
by the himem API.
Specifically, what is implemented by the himem API is a bankswitching scheme. Hardware-wise, the 4MiB region
for external SPI RAM is mapped into the CPU address space by a MMU, which maps a configurable 32K bank/page
of external SPI RAM into each of the 32K pages in the 4MiB region accessed by the CPU. For external memories
that are <=4MiB, this MMU is configured to unity mapping, effectively mapping each CPU address 1-to-1 to the
external SPI RAM address.
In order to use the himem API, you have to enable it in the menuconfig using CON-
FIG_SPIRAM_BANKSWITCH_ENABLE, as well as set the amount of banks reserved for this in CON-
FIG_SPIRAM_BANKSWITCH_RESERVE. This decreases the amount of external memory allocated by functions like
malloc(), but it allows you to use the himem api to map any of the remaining memory into the reserved banks.
The himem API is more-or-less an abstraction of the bankswitching scheme: it allows you to claim one or more banks
of address space (called ‘regions’in the API) as well as one or more of banks of memory to map into the ranges.
Example
An example doing a simple memory test of the high memory range is available in esp-idf: system/himem
API Reference
Header File
• components/esp_psram/include/esp32/himem.h
Functions
esp_err_t esp_himem_alloc(size_t size, esp_himem_handle_t *handle_out)
Allocate a block in high memory.
Parameters
• size –Size of the to-be-allocated block, in bytes. Note that this needs to be a multiple
of the external RAM mmu block size (32K).
• handle_out –[out] Handle to be returned
Returns - ESP_OK if succesful
• ESP_ERR_NO_MEM if out of memory
• ESP_ERR_INVALID_SIZE if size is not a multiple of 32K
esp_err_t esp_himem_alloc_map_range(size_t size, esp_himem_rangehandle_t *handle_out)
Allocate a memory region to map blocks into.
This allocates a contiguous CPU memory region that can be used to map blocks of physical memory into.
Parameters
• size –Size of the range to be allocated. Note this needs to be a multiple of the external
RAM mmu block size (32K).
• handle_out –[out] Handle to be returned
Returns - ESP_OK if succesful
• ESP_ERR_NO_MEM if out of memory or address space
• ESP_ERR_INVALID_SIZE if size is not a multiple of 32K
esp_err_t esp_himem_map(esp_himem_handle_t handle, esp_himem_rangehandle_t range, size_t ram_offset,
size_t range_offset, size_t len, int flags, void **out_ptr)
Map a block of high memory into the CPUs address space.
This effectively makes the block available for read/write operations.
Note: The region to be mapped needs to have offsets and sizes that are aligned to the SPI RAM MMU block
size (32K)
Parameters
• handle –Handle to the block of memory, as given by esp_himem_alloc
• range –Range handle to map the memory in
• ram_offset –Offset into the block of physical memory of the block to map
• range_offset –Offset into the address range where the block will be mapped
• len –Length of region to map
• flags –One of ESP_HIMEM_MAPFLAG_*
• out_ptr –[out] Pointer to variable to store resulting memory pointer in
Returns - ESP_OK if the memory could be mapped
• ESP_ERR_INVALID_ARG if offset, range or len aren’t MMU-block-aligned (32K)
• ESP_ERR_INVALID_SIZE if the offsets/lengths don’t fit in the allocated memory or
range
• ESP_ERR_INVALID_STATE if a block in the selected ram offset/length is already
mapped, or if a block in the selected range offset/length already has a mapping.
Note: This is also weakly defined in esp32/spiram.c and returns 0 there, so if no other function in this file is
used, no memory is reserved.
Macros
ESP_HIMEM_BLKSZ
ESP_HIMEM_MAPFLAG_RO
Indicates that a mapping will only be read from. Note that this is unused for now.
Type Definitions
The Ultra Low Power (ULP) coprocessor is a simple finite state machine (FSM) which is designed to perform mea-
surements using the ADC, temperature sensor, and external I2C sensors, while the main processors are in deep sleep
mode. The ULP coprocessor can access the RTC_SLOW_MEM memory region, and registers in the RTC_CNTL,
RTC_IO, and SARADC peripherals. The ULP coprocessor uses fixed-width 32-bit instructions, 32-bit memory
addressing, and has 4 general-purpose 16-bit registers. This coprocessor is referred to as ULP FSM in ESP-IDF.
The ULP FSM coprocessor code is written in assembly and compiled using the binutils-esp32ulp toolchain.
If you have already set up ESP-IDF with CMake build system according to the Getting Started Guide, then the ULP
FSM toolchain will already be installed.
The ULP FSM can be programmed using the supported instruction set. Alternatively, the ULP FSM coprocessor can
also be programmed using C Macros on the main CPU. Theses two methods are described in the following section:
ESP32 ULP coprocessor instruction set This document provides details about the instructions used by ESP32
ULP FSM coprocessor assembler.
ULP FSM coprocessor has 4 16-bit general purpose registers, labeled R0, R1, R2, R3. It also has an 8-bit counter
register (stage_cnt) which can be used to implement loops. Stage count register is accessed using special instructions.
ULP coprocessor can access 8k bytes of RTC_SLOW_MEM memory region. Memory is addressed in 32-bit word
units. It can also access peripheral registers in RTC_CNTL, RTC_IO, and SENS peripherals.
All instructions are 32-bit. Jump instructions, ALU instructions, peripheral register and memory access instructions
are executed in 1 cycle. Instructions which work with peripherals (TSENS, ADC, I2C) take variable number of
cycles, depending on peripheral operation.
The instruction syntax is case insensitive. Upper and lower case letters can be used and intermixed arbitrarily. This
is true both for register names and instruction names.
Note about addressing ESP32 ULP FSM coprocessor’s JUMP, ST, LD family of instructions expect the address
argument to be expressed in the following way depending on the type of address argument used:
• When the address argument is presented as a label then the instruction expects the address to be expressed as
32-bit words.
Consider the following example program:
entry:
NOP
NOP
NOP
NOP
loop:
MOVE R1, loop
JUMP R1
When this program is assembled and linked, address of label loop will be equal to 16 (expressed in bytes).
However JUMP instruction expects the address stored in register R1 to be expressed in 32-bit words. To
account for this common use case, the assembler will convert the address of label loop from bytes to words,
when generating the MOVE instruction. Hence, the code generated code will be equivalent to:
0000 NOP
0004 NOP
0008 NOP
000c NOP
0010 MOVE R1, 4
0014 JUMP R1
• The other case is when the argument of MOVE instruction is not a label but a constant. In this case assembler
will use the value as is, without any conversion:
In this case, the value in R1 is stored at the memory location pointed by [R2 + offset / 4]
Consider the following code:
.global array
array: .long 0
.long 0
.long 0
.long 0
Note about instruction execution time ULP coprocessor is clocked from RTC_FAST_CLK, which is normally
derived from the internal 8MHz oscillator. Applications which need to know exact ULP clock frequency can calibrate
it against the main XTAL clock:
#include "soc/rtc.h"
ULP coprocessor needs certain number of clock cycles to fetch each instruction, plus certain number of cycles to
execute it, depending on the instruction. See description of each instruction below for details on the execution time.
Instruction fetch time is:
• 2 clock cycles —for instructions following ALU and branch instructions.
• 4 clock cycles —in other cases.
Note that when accessing RTC memories and RTC registers, ULP coprocessor has lower priority than the main
CPUs. This means that ULP coprocessor execution may be suspended while the main CPUs access same memory
region as the ULP.
The detailed description of all instructions is presented below:
NOP - no operation
Syntax NOP
Operands None
Cycles 2 cycle to execute, 4 cycles to fetch next instruction
Description No operation is performed. Only the PC is incremented.
Example:
1: NOP
1: OR R1, R2, R3 // R1 = R2 || R3
Note: Note that when a label is used as an immediate, the address of the label will be converted from bytes to words.
This is because LD, ST, and JUMP instructions expect the address register value to be expressed in words rather than
bytes. See the section Note about addressing for more details.
Examples:
1: MOVE R1, R2 // R1 = R2
The application can use the higher 16 bits to determine which instruction in the ULP program has written any
particular word into memory.
Note: Note that the offset specified in bytes is converted to a 32-bit word offset before execution. See the section
Note about addressing for more details.
Examples:
Note: Note that the offset specified in bytes is converted to a 32-bit word offset before execution. See the section
Note about addressing for more details.
Examples:
1: LD R1, R2, 0x12 // R1 = MEM[R2 + 0x12 / 4]
Therefore the execution time will depend on the branches taken: either 2 cycles to execute + 2 cycles to fetch,
or 4 cycles to execute + 4 cycles to fetch.
Description The instruction makes a jump to a relative address if condition is true. Condition is the result of
comparison of R0 register value and the threshold value.
Examples:
• Condition:
– EQ (equal) –jump if value in stage_cnt == threshold
– LT (less than) –jump if value in stage_cnt < threshold
– LE (less or equal) - jump if value in stage_cnt <= threshold
– GT (greater than) –jump if value in stage_cnt > threshold
– GE (greater or equal) —jump if value in stage_cnt >= threshold
Cycles 2 cycles to execute, 2 cycles to fetch next instruction:
// JUMPS target, threshold, EQ is implemented as:
Therefore the execution time will depend on the branches taken: either 2 cycles to execute + 2 cycles to fetch,
or 4 cycles to execute + 4 cycles to fetch.
Description The instruction makes a jump to a relative address if condition is true. Condition is the result of
comparison of count register value and threshold value.
Examples:
1:pos: JUMPS 16, 20, EQ // Jump to (position + 16 bytes) if stage_cnt␣
,→== 20
.. only:: esp32
1: ADC R1, 0, 1 // Measure value using ADC1 channel 0 and store result into R1
Examples:
Examples:
Convenience macros for peripheral registers access ULP source files are passed through C preprocessor before
the assembler. This allows certain macros to be used to facilitate access to peripheral registers.
Some existing macros are defined in soc/soc_ulp.h header file. These macros allow access to the fields of
peripheral registers by their names. Peripheral registers names which can be used with these macros are the ones
defined in soc/rtc_cntl_reg.h, soc/rtc_io_reg.h, soc/sens_reg.h, and soc/rtc_i2c_reg.
h.
READ_RTC_REG(rtc_reg, low_bit, bit_width) Read up to 16 bits from rtc_reg[low_bit + bit_width - 1 :
low_bit] into R0. For example:
#include "soc/soc_ulp.h"
#include "soc/rtc_cntl_reg.h"
READ_RTC_FIELD(rtc_reg, field) Read from a field in rtc_reg into R0, up to 16 bits. For example:
#include "soc/soc_ulp.h"
#include "soc/sens_reg.h"
WRITE_RTC_REG(rtc_reg, low_bit, bit_width, value) Write immediate value into rtc_reg[low_bit + bit_width
- 1 : low_bit], bit_width <= 8. For example:
#include "soc/soc_ulp.h"
#include "soc/rtc_io_reg.h"
WRITE_RTC_FIELD(rtc_reg, field, value) Write immediate value into a field in rtc_reg, up to 8 bits. For ex-
ample:
#include "soc/soc_ulp.h"
#include "soc/rtc_cntl_reg.h"
Programming ULP FSM coprocessor using C macros (legacy) In addition to the existing binutils port for the
ESP32 ULP coprocessor, it is possible to generate programs for the ULP FSM coprocessor by embedding assembly-
like macros into an ESP32 application. Here is an example how this can be done:
The program array is an array of ulp_insn_t, i.e. ULP coprocessor instructions. Each I_XXX preprocessor
define translates into a single 32-bit instruction. Arguments of these preprocessor defines can be register numbers (R0
—R3) and literal constants. See the API reference section at the end of this guide for descriptions of instructions and
arguments they take.
Note: Because some of the instruction macros expand to inline function calls, defining such array in global scope
will cause the compiler to produce an“initializer element is not constant”error. To fix this error, move the definition
of instructions array into local scope.
Note: Load, store and move instructions use addresses expressed in 32-bit words. Address 0 corresponds to the
first word of RTC_SLOW_MEM. This is different to how address arguments are handled in assembly code of the same
instructions. See the section Note about addressing for more details for reference.
To generate branch instructions, special M_ preprocessor defines are used. M_LABEL define can be used to define a
branch target. Label identifier is a 16-bit integer. M_Bxxx defines can be used to generate branch instructions with
target set to a particular label.
Implementation note: these M_ preprocessor defines will be translated into two ulp_insn_t values: one is a token
value which contains label number, and the other is the actual instruction. ulp_process_macros_and_load
function resolves the label number to the address, modifies the branch instruction to use the correct address, and
removes the the extra ulp_insn_t token which contains the label numer.
Here is an example of using labels and branches:
API Reference
Header File
• components/ulp/ulp_fsm/include/esp32/ulp.h
Functions
static inline uint32_t SOC_REG_TO_ULP_PERIPH_SEL(uint32_t reg)
Map SoC peripheral register to periph_sel field of RD_REG and WR_REG instructions.
Parameters reg –peripheral register in RTC_CNTL_, RTC_IO_, SENS_, RTC_I2C peripher-
als.
Returns periph_sel value for the peripheral to which this register belongs.
Unions
union ulp_insn
#include <ulp.h> Instruction format structure.
All ULP instructions are 32 bit long. This union contains field layouts used by all of the supported instructions.
This union also includes a special“macro”instruction layout. This is not a real instruction which can be executed
by the CPU. It acts as a token which is removed from the program by the ulp_process_macros_and_load
function.
These structures are not intended to be used directly. Preprocessor definitions provided below fill the fields of
these structure with the right arguments.
Public Members
uint32_t cycles
Number of cycles to sleep
TBD, cycles used for measurement
uint32_t unused
Unused
uint32_t opcode
Opcode (OPCODE_DELAY)
Opcode (OPCODE_ST)
Opcode (OPCODE_LD)
Opcode (OPCODE_HALT)
Opcode (OPCODE_BRANCH)
Opcode (OPCODE_ALU)
Opcode (OPCODE_WR_REG)
Opcode (OPCODE_RD_REG)
Opcode (OPCODE_ADC)
Opcode (OPCODE_TSENS)
Opcode (OPCODE_I2C)
Opcode (OPCODE_END)
Opcode (OPCODE_MACRO)
uint32_t dreg
Register which contains data to store
Register where the data should be loaded to
Register which contains target PC, expressed in words (used if .reg == 1)
Destination register
Register where to store ADC result
Register where to store temperature measurement result
Destination register (for SUB_OPCODE_MACRO_LABELPC) >
uint32_t sreg
Register which contains address in RTC memory (expressed in words)
Register with operand A
uint32_t unused1
Unused
uint32_t offset
Offset to add to sreg
Absolute value of target PC offset w.r.t. current PC, expressed in words
uint32_t unused2
Unused
uint32_t sub_opcode
Sub opcode (SUB_OPCODE_ST)
Sub opcode (SUB_OPCODE_BX)
Sub opcode (SUB_OPCODE_B)
Sub opcode (SUB_OPCODE_BS)
Sub opcode (SUB_OPCODE_ALU_REG)
Sub opcode (SUB_OPCODE_ALU_CNT)
Sub opcode (SUB_OPCODE_ALU_IMM)
Sub opcode (SUB_OPCODE_WAKEUP)
Sub opcode (SUB_OPCODE_SLEEP)
SUB_OPCODE_MACRO_LABEL or SUB_OPCODE_MACRO_BRANCH or
SUB_OPCODE_MACRO_LABELPC
struct ulp_insn::[anonymous] st
Format of ST instruction
struct ulp_insn::[anonymous] ld
Format of LD instruction
uint32_t addr
Target PC, expressed in words (used if .reg == 0)
Address within either RTC_CNTL, RTC_IO, or SARADC
uint32_t reg
Target PC in register (1) or immediate (0)
uint32_t type
Jump condition (BX_JUMP_TYPE_xxx)
struct ulp_insn::[anonymous] bx
Format of BRANCH instruction (absolute address)
uint32_t imm
Immediate value to compare against
Immediate value of operand
Immediate value of operand B
uint32_t cmp
Comparison to perform: B_CMP_L or B_CMP_GE
Comparison to perform: JUMPS_LT, JUMPS_GE or JUMPS_LE
uint32_t sign
Sign of target PC offset: 0: positive, 1: negative
struct ulp_insn::[anonymous] b
Format of BRANCH instruction (relative address, conditional on R0)
struct ulp_insn::[anonymous] bs
Format of BRANCH instruction (relative address, conditional on the stage counter)
uint32_t treg
Register with operand B
uint32_t sel
Operation to perform, one of ALU_SEL_xxx
Operation to perform, one of ALU_SEL_Sxxx
uint32_t periph_sel
Select peripheral: RTC_CNTL (0), RTC_IO(1), SARADC(2)
uint32_t data
8 bits of data to write
8 bits of data for write operation
uint32_t low
Low bit
uint32_t high
High bit
uint32_t mux
Select SARADC pad (mux + 1)
uint32_t sar_sel
Select SARADC0 (0) or SARADC1 (1)
uint32_t wait_delay
Cycles to wait after measurement is done
uint32_t reserved
Reserved, set to 0
uint32_t i2c_addr
I2C slave address
uint32_t low_bits
low bit of range for write operation (lower bits are masked)
uint32_t high_bits
high bit of range for write operation (higher bits are masked)
uint32_t i2c_sel
index of slave address register [7:0]
uint32_t rw
Write (1) or read (0)
uint32_t wakeup
Set to 1 to wake up chip
uint32_t cycle_sel
Select which one of SARADC_ULP_CP_SLEEP_CYCx_REG to get the sleep duration from
uint32_t label
Label number
uint32_t instruction
Encoded instruction for ULP coprocessor
Macros
R0
general purpose register 0
R1
general purpose register 1
R2
general purpose register 2
R3
general purpose register 3
OPCODE_WR_REG
Instruction: write peripheral register (RTC_CNTL/RTC_IO/SARADC)
OPCODE_RD_REG
Instruction: read peripheral register (RTC_CNTL/RTC_IO/SARADC)
RD_REG_PERIPH_RTC_CNTL
Identifier of RTC_CNTL peripheral for RD_REG and WR_REG instructions
RD_REG_PERIPH_RTC_IO
Identifier of RTC_IO peripheral for RD_REG and WR_REG instructions
RD_REG_PERIPH_SENS
Identifier of SARADC peripheral for RD_REG and WR_REG instructions
RD_REG_PERIPH_RTC_I2C
Identifier of RTC_I2C peripheral for RD_REG and WR_REG instructions
OPCODE_I2C
Instruction: read/write I2C
SUB_OPCODE_I2C_RD
I2C read
SUB_OPCODE_I2C_WR
I2C write
OPCODE_DELAY
Instruction: delay (nop) for a given number of cycles
OPCODE_ADC
Instruction: SAR ADC measurement
OPCODE_ST
Instruction: store indirect to RTC memory
SUB_OPCODE_ST
Store 32 bits, 16 MSBs contain PC, 16 LSBs contain value from source register
OPCODE_ALU
Arithmetic instructions
SUB_OPCODE_ALU_REG
Arithmetic instruction, both source values are in register
SUB_OPCODE_ALU_IMM
Arithmetic instruction, one source value is an immediate
SUB_OPCODE_ALU_CNT
Arithmetic instruction, stage counter and an immediate
ALU_SEL_ADD
Addition
ALU_SEL_SUB
Subtraction
ALU_SEL_AND
Logical AND
ALU_SEL_OR
Logical OR
ALU_SEL_MOV
Copy value (immediate to destination register or source register to destination register
ALU_SEL_LSH
Shift left by given number of bits
ALU_SEL_RSH
Shift right by given number of bits
ALU_SEL_SINC
Increment the stage counter
ALU_SEL_SDEC
Decrement the stage counter
ALU_SEL_SRST
Reset the stage counter
OPCODE_BRANCH
Branch instructions
SUB_OPCODE_BX
Branch to absolute PC (immediate or in register)
SUB_OPCODE_BR
Branch to relative PC, conditional on R0
SUB_OPCODE_BS
Branch to relative PC, conditional on the stage counter
BX_JUMP_TYPE_DIRECT
Unconditional jump
BX_JUMP_TYPE_ZERO
Branch if last ALU result is zero
BX_JUMP_TYPE_OVF
Branch if last ALU operation caused and overflow
SUB_OPCODE_B
Branch to a relative offset
B_CMP_L
Branch if R0 is less than an immediate
B_CMP_GE
Branch if R0 is greater than or equal to an immediate
JUMPS_LT
Branch if the stage counter <
JUMPS_GE
Branch if the stage counter >=
JUMPS_LE
Branch if the stage counter <=
OPCODE_END
Stop executing the program
SUB_OPCODE_END
Stop executing the program and optionally wake up the chip
SUB_OPCODE_SLEEP
Stop executing the program and run it again after selected interval
OPCODE_TSENS
Instruction: temperature sensor measurement
OPCODE_HALT
Halt the coprocessor
OPCODE_LD
Indirect load lower 16 bits from RTC memory
OPCODE_MACRO
Not a real opcode. Used to identify labels and branches in the program
SUB_OPCODE_MACRO_LABEL
Label macro
SUB_OPCODE_MACRO_BRANCH
Branch macro
SUB_OPCODE_MACRO_LABELPC
Label pointer macro
I_DELAY(cycles_)
Delay (nop) for a given number of cycles
I_HALT()
Halt the coprocessor.
This instruction halts the coprocessor, but keeps ULP timer active. As such, ULP program will be restarted
again by timer. To stop the program and prevent the timer from restarting the program, use I_END(0) instruc-
tion.
I_WR_REG(reg, low_bit, high_bit, val)
Write literal value to a peripheral register
reg[high_bit : low_bit] = val This instruction can access RTC_CNTL_, RTC_IO_, SENS_, and RTC_I2C
peripheral registers.
I_RD_REG(reg, low_bit, high_bit)
Read from peripheral register into R0
R0 = reg[high_bit : low_bit] This instruction can access RTC_CNTL_, RTC_IO_, SENS_, and RTC_I2C
peripheral registers.
I_WR_REG_BIT(reg, shift, val)
Set or clear a bit in the peripheral register.
Sets bit (1 << shift) of register reg to value val. This instruction can access RTC_CNTL_, RTC_IO_, SENS_,
and RTC_I2C peripheral registers.
I_WAKE()
Wake the SoC from deep sleep.
This instruction initiates wake up from deep sleep. Use esp_deep_sleep_enable_ulp_wakeup to enable deep
sleep wakeup triggered by the ULP before going into deep sleep. Note that ULP program will still keep running
until the I_HALT instruction, and it will still be restarted by timer at regular intervals, even when the SoC is
woken up.
To stop the ULP program, use I_HALT instruction.
To disable the timer which start ULP program, use I_END() instruction. I_END instruction clears the
RTC_CNTL_ULP_CP_SLP_TIMER_EN_S bit of RTC_CNTL_STATE0_REG register, which controls the
ULP timer.
I_END()
Stop ULP program timer.
This is a convenience macro which disables the ULP program timer. Once this instruction is used, ULP
program will not be restarted anymore until ulp_run function is called.
ULP program will continue running after this instruction. To stop the currently running program, use
I_HALT().
I_SLEEP_CYCLE_SEL(timer_idx)
Select the time interval used to run ULP program.
This instructions selects which of the SENS_SLEEP_CYCLES_Sx registers’value is used by the ULP pro-
gram timer. When the ULP program stops at I_HALT instruction, ULP program timer start counting. When
the counter reaches the value of the selected SENS_SLEEP_CYCLES_Sx register, ULP program start run-
ning again from the start address (passed to the ulp_run function). There are 5 SENS_SLEEP_CYCLES_Sx
registers, so 0 <= timer_idx < 5.
By default, SENS_SLEEP_CYCLES_S0 register is used by the ULP program timer.
I_TSENS(reg_dest, delay)
Perform temperature sensor measurement and store it into reg_dest.
Delay can be set between 1 and ((1 << 14) - 1). Higher values give higher measurement resolution.
I_ADC(reg_dest, adc_idx, pad_idx)
Perform ADC measurement and store result in reg_dest.
adc_idx selects ADC (0 or 1). pad_idx selects ADC pad (0 - 7).
I_ST(reg_val, reg_addr, offset_)
Store value from register reg_val into RTC memory.
The value is written to an offset calculated by adding value of reg_addr register and offset_ field (this offset is
expressed in 32-bit words). 32 bits written to RTC memory are built as follows:
• bits [31:21] hold the PC of current instruction, expressed in 32-bit words
• bits [20:18] = 3’b0
• bits [17:16] reg_addr (0..3)
• bits [15:0] are assigned the contents of reg_val
RTC_SLOW_MEM[addr + offset_] = { insn_PC[10:0], 3’b0, reg_addr, reg_val[15:0] }
I_LD(reg_dest, reg_addr, offset_)
Load value from RTC memory into reg_dest register.
Loads 16 LSBs from RTC memory word given by the sum of value in reg_addr and value of offset_.
I_BL(pc_offset, imm_value)
Branch relative if R0 less than immediate value.
pc_offset is expressed in words, and can be from -127 to 127 imm_value is a 16-bit value to compare R0
against
I_BGE(pc_offset, imm_value)
Branch relative if R0 greater or equal than immediate value.
pc_offset is expressed in words, and can be from -127 to 127 imm_value is a 16-bit value to compare R0
against
I_BXR(reg_pc)
Unconditional branch to absolute PC, address in register.
reg_pc is the register which contains address to jump to. Address is expressed in 32-bit words.
I_BXI(imm_pc)
Unconditional branch to absolute PC, immediate address.
Address imm_pc is expressed in 32-bit words.
I_BXZR(reg_pc)
Branch to absolute PC if ALU result is zero, address in register.
reg_pc is the register which contains address to jump to. Address is expressed in 32-bit words.
I_BXZI(imm_pc)
Branch to absolute PC if ALU result is zero, immediate address.
Address imm_pc is expressed in 32-bit words.
I_BXFR(reg_pc)
Branch to absolute PC if ALU overflow, address in register
reg_pc is the register which contains address to jump to. Address is expressed in 32-bit words.
I_BXFI(imm_pc)
Branch to absolute PC if ALU overflow, immediate address
Address imm_pc is expressed in 32-bit words.
I_ADDR(reg_dest, reg_src1, reg_src2)
Addition: dest = src1 + src2
I_SUBR(reg_dest, reg_src1, reg_src2)
Subtraction: dest = src1 - src2
I_ANDR(reg_dest, reg_src1, reg_src2)
Logical AND: dest = src1 & src2
I_ORR(reg_dest, reg_src1, reg_src2)
Logical OR: dest = src1 | src2
I_MOVR(reg_dest, reg_src)
Copy: dest = src
I_LSHR(reg_dest, reg_src, reg_shift)
Logical shift left: dest = src << shift
I_RSHR(reg_dest, reg_src, reg_shift)
Logical shift right: dest = src >> shift
I_ADDI(reg_dest, reg_src, imm_)
Add register and an immediate value: dest = src1 + imm
I_SUBI(reg_dest, reg_src, imm_)
Subtract register and an immediate value: dest = src - imm
I_ANDI(reg_dest, reg_src, imm_)
Logical AND register and an immediate value: dest = src & imm
I_ORI(reg_dest, reg_src, imm_)
Logical OR register and an immediate value: dest = src | imm
I_MOVI(reg_dest, imm_)
Copy an immediate value into register: dest = imm
I_STAGE_DEC(imm_)
Decrement the stage counter by immediate value
I_STAGE_RST()
Reset the stage counter
M_BSLT(label_num, imm_value)
Macro: branch to label if the stage counter is less than immediate value
This macro generates two ulp_insn_t values separated by a comma, and should be used when defining
contents of ulp_insn_t arrays. First value is not a real instruction; it is a token which is removed by
ulp_process_macros_and_load function.
M_BSGE(label_num, imm_value)
Macro: branch to label if the stage counter is greater than or equal to immediate value
This macro generates two ulp_insn_t values separated by a comma, and should be used when defining
contents of ulp_insn_t arrays. First value is not a real instruction; it is a token which is removed by
ulp_process_macros_and_load function.
M_BSLE(label_num, imm_value)
Macro: branch to label if the stage counter is less than or equal to immediate value
This macro generates two ulp_insn_t values separated by a comma, and should be used when defining
contents of ulp_insn_t arrays. First value is not a real instruction; it is a token which is removed by
ulp_process_macros_and_load function.
M_BSEQ(label_num, imm_value)
Macro: branch to label if the stage counter is equal to immediate value. Implemented using two JUMPS
instructions: JUMPS next, imm_value, LT JUMPS label_num, imm_value, LE
This macro generates three ulp_insn_t values separated by commas, and should be used when defining
contents of ulp_insn_t arrays. Second value is not a real instruction; it is a token which is removed by
ulp_process_macros_and_load function.
M_BSGT(label_num, imm_value)
Macro: branch to label if the stage counter is greater than immediate value. Implemented using two instruc-
tions: JUMPS next, imm_value, LE JUMPS label_num, imm_value, GE
This macro generates three ulp_insn_t values separated by commas, and should be used when defining
contents of ulp_insn_t arrays. Second value is not a real instruction; it is a token which is removed by
ulp_process_macros_and_load function.
I_JUMPS(pc_offset, imm_value, comp_type)
Branch relative if (stage counter [comp_type] [imm_value]) evaluates to true.
pc_offset is expressed in words, and can be from -127 to 127 imm_value is an 8-bit value to compare the
stage counter against comp_type is the type of comparison to perform: JUMPS_LT (<), JUMPS_GE (>=) or
JUMPS_LE (<=)
I_I2C_RW(sub_addr, val, low_bit, high_bit, slave_sel, rw_bit)
Perform an I2C transaction with a slave device. I_I2C_READ and I_I2C_WRITE are provided for conve-
nience, instead of using this directly.
Slave address (in 7-bit format) has to be set in advance into SENS_I2C_SLAVE_ADDRx register field, where
x == slave_sel. For read operations, 8 bits of read result is stored into R0 register. For write operations, val
will be written to sub_addr at [high_bit:low_bit]. Bits outside of this range are masked.
I_I2C_READ(slave_sel, sub_addr)
Read a byte from the sub address of an I2C slave, and store the result in R0.
Slave address (in 7-bit format) has to be set in advance into SENS_I2C_SLAVE_ADDRx register field, where
x == slave_sel.
To compile the ULP FSM code as part of the component, the following steps must be taken:
1. The ULP FSM code, written in assembly, must be added to one or more files with .S extension. These files
must be placed into a separate directory inside the component directory, for instance, ulp/.
2. Call ulp_embed_binary from the component CMakeLists.txt after registration. For example:
...
idf_component_register()
set(ulp_app_name ulp_${COMPONENT_NAME})
set(ulp_s_sources ulp/ulp_assembly_source_file.S)
set(ulp_exp_dep_srcs "ulp_c_source_file.c")
The first argument to ulp_embed_binary specifies the ULP FSM binary name. The name specified here will
also be used by other generated artifacts such as the ELF file, map file, header file and linker export file. The second
argument specifies the ULP FSM assembly source files. Finally, the third argument specifies the list of component
source files which include the header file to be generated. This list is needed to build the dependencies correctly and
ensure that the generated header file will be created before any of these files are compiled. See the section below for
the concept of generated header files for ULP applications.
3. Build the application as usual (e.g. idf.py app).
Inside, the build system will take the following steps to build ULP FSM program:
1. Run each assembly file (foo.S) through the C preprocessor. This step generates the preprocessed
assembly files (foo.ulp.S) in the component build directory. This step also generates dependency files
(foo.ulp.d).
2. Run preprocessed assembly sources through the assembler. This produces object (foo.ulp.o) and
listing (foo.ulp.lst) files. Listing files are generated for debugging purposes and are not used at later
stages of the build process.
3. Run the linker script template through the C preprocessor. The template is located in compo-
nents/ulp/ld directory.
4. Link the object files into an output ELF file (ulp_app_name.elf). The Map file
(ulp_app_name.map) generated at this stage may be useful for debugging purposes.
5. Dump the contents of the ELF file into a binary (ulp_app_name.bin) which can then be em-
bedded into the application.
6. Generate a list of global symbols (ulp_app_name.sym) in the ELF file using
esp32ulp-elf-nm.
7. Create an LD export script and a header file (ulp_app_name.ld and ulp_app_name.h) con-
taining the symbols from ulp_app_name.sym. This is done using the esp32ulp_mapgen.py
utility.
8. Add the generated binary to the list of binary files to be embedded into the application.
Global symbols defined in the ULP FSM program may be used inside the main program.
For example, the ULP FSM program may define a variable measurement_count which will define the number
of ADC measurements the program needs to make before waking up the chip from deep sleep:
.global measurement_count
measurement_count: .long 0
The main program needs to initialize this variable before the ULP program is started. The build system makes this
possible by generating the ${ULP_APP_NAME}.h and ${ULP_APP_NAME}.ld files which define the global
symbols present in the ULP program. Each global symbol defined in the ULP program is included in these files and
are prefixed with ulp_.
The header file contains the declaration of the symbol:
Note that all symbols (variables, arrays, functions) are declared as uint32_t. For functions and arrays, take the
address of the symbol and cast it to the appropriate type.
The generated linker script file defines the locations of symbols in RTC_SLOW_MEM:
To access the ULP program variables from the main program, the generated header file should be included using an
include statement. This will allow the ULP program variables to be accessed as regular variables:
#include "ulp_app_name.h"
// later
void init_ulp_vars() {
ulp_measurement_count = 64;
}
Note that the ULP FSM program can only use the lower 16 bits of each 32-bit word in RTC memory, because the
registers are 16-bit, and there is no instruction to load from the high part of the word. Likewise, the ULP store
instruction writes register values into the lower 16 bits of the 32-bit word in RTC memory. The upper 16 bits are
written with a value which depends on the address of the store instruction, thus when reading variables written by the
ULP coprocessor, the main application needs to mask the upper 16 bits, e.g.:
To run a ULP FSM program, the main application needs to load the ULP program into RTC memory using the
ulp_load_binary() function, and then start it using the ulp_run() function.
Note that the Enable Ultra Low Power (ULP) Coprocessor option must be enabled in menuconfig to
work with ULP. To select the type of ULP to be used, the ULP Co-processor type option must be set. To
reserve memory for the ULP, the RTC slow memory reserved for coprocessor option must be set to
a value big enough to store ULP code and data. If the application components contain multiple ULP programs, then
the size of the RTC memory must be sufficient to hold the largest one.
Each ULP program is embedded into the ESP-IDF application as a binary blob. The application can reference this
blob and load it in the following way (suppose ULP_APP_NAME was defined to ulp_app_name):
void start_ulp_program() {
ESP_ERROR_CHECK( ulp_load_binary(
(continues on next page)
Once the program is loaded into RTC memory, the application can start it by passing the address of the entry point
to the ulp_run function:
Declaration of the entry point symbol comes from the generated header file mentioned above,
${ULP_APP_NAME}.h. In the assembly source of the ULP FSM application, this symbol must be marked as
.global:
.global entry
entry:
// code starts here
ESP32 ULP coprocessor is started by a timer. The timer is started once ulp_run() is called. The timer counts
a number of RTC_SLOW_CLK ticks (by default, produced by an internal 150 kHz RC oscillator). The number of
ticks is set using SENS_ULP_CP_SLEEP_CYCx_REG registers (x = 0..4). When starting the ULP for the first
time, SENS_ULP_CP_SLEEP_CYC0_REG will be used to set the number of timer ticks. Later the ULP program
can select another SENS_ULP_CP_SLEEP_CYCx_REG register using sleep instruction.
The application can set ULP timer period values (SENS_ULP_CP_SLEEP_CYCx_REG, x = 0..4) using
ulp_set_wakeup_period function.
Once the timer counts the number of ticks set in the selected SENS_ULP_CP_SLEEP_CYCx_REG register, ULP
coprocessor powers up and starts running the program from the entry point set in the call to ulp_run().
The program runs until it encounters a halt instruction or an illegal instruction. Once the program halts the ULP
coprocessor powers down and the timer is started again.
To disable the timer (effectively preventing the ULP program from running again), clear the
RTC_CNTL_ULP_CP_SLP_TIMER_EN bit in the RTC_CNTL_STATE0_REG register. This can be done
both from ULP code and from the main program.
Application Examples
• ULP FSM Coprocessor counts pulses on an IO while main CPU is in deep sleep: system/ulp_fsm/ulp.
• ULP FSM Coprocessor polls ADC in while main CPU is in deep sleep: system/ulp_fsm/ulp_adc.
API Reference
Header File
• components/ulp/ulp_fsm/include/ulp_fsm_common.h
Functions
esp_err_t ulp_process_macros_and_load(uint32_t load_addr, const ulp_insn_t *program, size_t *psize)
Resolve all macro references in a program and load it into RTC memory.
Parameters
• load_addr –address where the program should be loaded, expressed in 32-bit words
• program –ulp_insn_t array with the program
Macros
ESP_ERR_ULP_BASE
Offset for ULP-related error codes
ESP_ERR_ULP_SIZE_TOO_BIG
Program doesn’t fit into RTC memory reserved for the ULP
ESP_ERR_ULP_INVALID_LOAD_ADDR
Load address is outside of RTC memory reserved for the ULP
ESP_ERR_ULP_DUPLICATE_LABEL
More than one label with the same number was defined
ESP_ERR_ULP_UNDEFINED_LABEL
Branch instructions references an undefined label
ESP_ERR_ULP_BRANCH_OUT_OF_RANGE
Branch target is out of range of B instruction (try replacing with BX)
Type Definitions
Header File
• components/ulp/ulp_common/include/ulp_common.h
Functions
esp_err_t ulp_set_wakeup_period(size_t period_index, uint32_t period_us)
Set one of ULP wakeup period values.
ULP coprocessor starts running the program when the wakeup timer counts up to a given value (called period).
There are 5 period values which can be programmed into SENS_ULP_CP_SLEEP_CYCx_REG registers, x =
0..4 for ESP32, and one period value which can be programmed into RTC_CNTL_ULP_CP_TIMER_1_REG
register for ESP32-S2/S3. By default, for ESP32, wakeup timer will use the period set into
SENS_ULP_CP_SLEEP_CYC0_REG, i.e. period number 0. ULP program code can use SLEEP instruction
to select which of the SENS_ULP_CP_SLEEP_CYCx_REG should be used for subsequent wakeups.
However, please note that SLEEP instruction issued (from ULP program) while the system is in deep sleep
mode does not have effect, and sleep cycle count 0 is used.
For ESP32-S2/S3 the SLEEP instruction not exist. Instead a WAKE instruction will be used.
Note: The ULP FSM requires two clock cycles to wakeup before being able to run the program. Then
additional 16 cycles are reserved after wakeup waiting until the 8M clock is stable. The FSM also requires two
more clock cycles to go to sleep after the program execution is halted. The minimum wakeup period that may
be set up for the ULP is equal to the total number of cycles spent on the above internal tasks. For a default
configuration of the ULP running at 150kHz it makes about 133us.
Parameters
• period_index –wakeup period setting number (0 - 4)
• period_us –wakeup period, us
Returns
• ESP_OK on success
• ESP_ERR_INVALID_ARG if period_index is out of range
void ulp_timer_stop(void)
Stop the ULP timer.
Note: This will stop the ULP from waking up if halted, but will not abort any program currently executing
on the ULP.
void ulp_timer_resume(void)
Resume the ULP timer.
Note: This will resume an already configured timer, but does no other configuration
Header File
• components/ulp/ulp_common/include/esp32/ulp_common_defs.h
Macros
RTC_SLOW_MEM
RTC slow memory, 8k size
2.10.29 Watchdogs
Overview
The ESP-IDF has support for multiple types of watchdogs, with the two main ones being: The Interrupt Watchdog
Timer and the Task Watchdog Timer (TWDT). The Interrupt Watchdog Timer and the TWDT can both be enabled
using Project Configuration Menu, however the TWDT can also be enabled during runtime. The Interrupt Watchdog
is responsible for detecting instances where FreeRTOS task switching is blocked for a prolonged period of time. The
TWDT is responsible for detecting instances of tasks running without yielding for a prolonged period.
ESP-IDF has support for the following types of watchdog timers:
The purpose of the IWDT is to ensure that interrupt service routines (ISRs) are not blocked from running for a pro-
longed period of time (i.e., the IWDT timeout period). Blocking ISRs from running in a timely manner is undesirable
as it can increases ISR latency, and also prevents task switching (as task switching is executed form an ISR). The
things that can block ISRs from running include:
• Disabling interrupts
• Critical Sections (also disables interrupts)
• Other same/higher priority ISRs (will block same/lower priority ISRs from running it completes execution)
The IWDT utilizes the watchdog timer in Timer Group 1 as its underlying hardware timer and leverages the FreeRTOS
tick interrupt on each CPU to feed the watchdog timer. If the tick interrupt on a particular CPU is not run at within
the IWDT timeout period, it is indicative that something is blocking ISRs from being run on that CPU (see the list
of reasons above).
When the IWDT times out, the default action is to invoke the panic handler and display the panic reason as Inter-
rupt wdt timeout on CPU0 or Interrupt wdt timeout on CPU1 (as applicable). Depending on
the panic handler’s configured behavior (see CONFIG_ESP_SYSTEM_PANIC), users can then debug the source of
the IWDT timeout (via the backtrace, OpenOCD, gdbstub etc) or simply reset the chip (which may be preferred in
a production environment).
If for whatever reason the panic handler is unable to run after an IWDT timeout, the IWDT has a secondary timeout
that will hard-reset the chip (i.e., a system reset).
Configuration
• The IWDT is enabled by default via the CONFIG_ESP_INT_WDT option.
• The IWDT’s timeout is configured by setting the CONFIG_ESP_INT_WDT_TIMEOUT_MS option.
– Note that the default timeout is higher if PSRAM support is enabled, as a critical section or interrupt
routine that accesses a large amount of PSRAM will take longer to complete in some circumstances.
– The timeout should always at least twice longer than the period between FreeRTOS ticks (see CON-
FIG_FREERTOS_HZ).
Tuning If you find the IWDT timeout is triggered because an interrupt or critical section is running longer than
the timeout period, consider rewriting the code:
• Critical sections should be made as short as possible. Any non-critical code/computation should be placed
outside the critical section.
• Interrupt handlers should also perform the minimum possible amount of computation. Users can consider
deferring any computation to a task by having the ISR push data to a task using queues.
Neither critical sections or interrupt handlers should ever block waiting for another event to occur. If chang-
ing the code to reduce the processing time is not possible or desirable, it’s possible to increase the CON-
FIG_ESP_INT_WDT_TIMEOUT_MS setting instead.
The Task Watchdog Timer (TWDT) is used to monitor particular tasks, ensuring that they are able to execute within
a given timeout period. The TWDT primarily watches the Idle Tasks of each CPU, however any task can subscribe to
be watched by the TWDT. By watching the Idle Tasks of each CPU, the TWDT can detect instances of tasks running
for a prolonged period of time wihtout yielding. This can be an indicator of poorly written code that spinloops on a
peripheral, or a task that is stuck in an infinite loop.
The TWDT is built around the Hardware Watchdog Timer in Timer Group 0. When a timeout occurs, an interrupt
is triggered. Users can redefine the function esp_task_wdt_isr_user_handler in the user code, in order to receive the
timeout event and handle it differently.
Usage The following functions can be used to watch tasks using the TWDT:
• esp_task_wdt_init() to initialize the TWDT and subscribe the idle tasks.
• esp_task_wdt_add() subscribes other tasks to the TWDT.
• Once subscribed, esp_task_wdt_reset() should be called from the task to feed the TWDT.
• esp_task_wdt_delete() unsubscribes a previously subscribed task
• esp_task_wdt_deinit() unsubscribes the idle tasks and deinitializes the TWDT
In the case where applications need to watch at a more granular level (i.e., ensure that a particular functions/stub/code-
path is called), the TWDT allows subscription of “users”.
• esp_task_wdt_add_user() to subscribe an arbitrary user of the TWDT. This function will return a
user handle to the added user.
• esp_task_wdt_reset_user() must be called using the user handle in order to prevent a TWDT time-
out.
• esp_task_wdt_delete_user() unsubscribes an arbitrary user of the TWDT.
Configuration The default timeout period for the TWDT is set using config item CON-
FIG_ESP_TASK_WDT_TIMEOUT_S. This should be set to at least as long as you expect any single task will
need to monopolize the CPU (for example, if you expect the app will do a long intensive calculation and should not
yield to other tasks). It is also possible to change this timeout at runtime by calling esp_task_wdt_init().
Note: Erasing large flash areas can be time consuming and can cause a task to run continuously, thus triggering a
TWDT timeout. The following two methods can be used to avoid this:
• Increase CONFIG_ESP_TASK_WDT_TIMEOUT_S in menuconfig for a larger watchdog timeout period.
• You can also call esp_task_wdt_init() to increase the watchdog timeout period before erasing a large
flash area.
For more information, you can refer to SPI Flash.
The following config options control TWDT configuration at startup. They are all enabled by default:
• CONFIG_ESP_TASK_WDT - the TWDT is initialized automatically during startup. If this option is disabled,
it is still possible to initialize the Task WDT at runtime by calling esp_task_wdt_init().
• CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0 - CPU0 Idle task is subscribed to the TWDT
during startup. If this option is disabled, it is still possible to subscribe the idle task by calling
esp_task_wdt_init() again.
• CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1 - CPU1 Idle task is subscribed to the TWDT during
startup.
While debugging using OpenOCD, the CPUs will be halted every time a breakpoint is reached. However if the
watchdog timers continue to run when a breakpoint is encountered, they will eventually trigger a reset making it
very difficult to debug code. Therefore OpenOCD will disable the hardware timers of both the interrupt and task
watchdogs at every breakpoint. Moreover, OpenOCD will not reenable them upon leaving the breakpoint. This
means that interrupt watchdog and task watchdog functionality will essentially be disabled. No warnings or panics
from either watchdogs will be generated when the ESP32 is connected to OpenOCD via JTAG.
API Reference
Task Watchdog A full example using the Task Watchdog is available in esp-idf: system/task_watchdog
Header File
• components/esp_system/include/esp_task_wdt.h
Functions
esp_err_t esp_task_wdt_init(const esp_task_wdt_config_t *config)
Initialize the Task Watchdog Timer (TWDT)
This function configures and initializes the TWDT. If the TWDT is already initialized when this function
is called, this function will update the TWDT’s current configuration. This funciton will also subscribe
the idle tasks if configured to do so. For other tasks, users can subscribe them using esp_task_wdt_add() or
esp_task_wdt_add_user().
This function will unsubscribe a user from the TWDT. After being unsubscribed, the user should no longer
call esp_task_wdt_reset_user().
Parameters user_handle –[in] User handle
Returns
• ESP_OK: Successfully unsubscribed the user from the TWDT
• Other: Failed to unsubscribe user
esp_err_t esp_task_wdt_status(TaskHandle_t task_handle)
Query whether a task is subscribed to the Task Watchdog Timer (TWDT)
This function will query whether a task is currently subscribed to the TWDT, or whether the TWDT is initial-
ized.
Parameters task_handle –[in] Handle of the task. Input NULL to query the current running
task.
Returns :
• ESP_OK: The task is currently subscribed to the TWDT
• ESP_ERR_NOT_FOUND: The task is not subscribed
• ESP_ERR_INVALID_STATE: TWDT was never initialized
Structures
struct esp_task_wdt_config_t
Task Watchdog Timer (TWDT) configuration structure.
Public Members
uint32_t timeout_ms
TWDT timeout duration in milliseconds
uint32_t idle_core_mask
Mask of the cores who’s idle task should be subscribed on initialization
bool trigger_panic
Trigger panic when timeout occurs
Type Definitions
The comparison below covers key features of chips supported by ESP-IDF. For the full list of features please refer
to respective datasheets in Section Related Documents.
2043
Chapter 3. ESP32 Hardware Reference
• Note 3: Die size: ESP32-C3 < ESP32-S2 < ESP32-S3 < ESP32
API Guides
4.1.1 Overview
ESP-IDF provides a useful feature for program behavior analysis: application level tracing. It is implemented in
the corresponding library and can be enabled in menuconfig. This feature allows to transfer arbitrary data between
host and ESP32 via JTAG, UART, or USB interfaces with small overhead on program execution. It is possible to
use JTAG and UART interfaces simultaneously. The UART interface is mostly used for connection with SEGGER
SystemView tool (see SystemView).
Developers can use this library to send application-specific state of execution to the host and receive commands or
other types of information from the opposite direction at runtime. The main use cases of this library are:
1. Collecting application-specific data. See Application Specific Tracing.
2. Lightweight logging to the host. See Logging to Host.
3. System behavior analysis. See System Behavior Analysis with SEGGER SystemView.
4. Source code coverage. See Gcov (Source Code Coverage).
Tracing components used when working over JTAG interface are shown in the figure below.
2047
Chapter 4. API Guides
CONFIG_APPTRACE_PENDING_DATA_SIZE_MAX. This macro specifies the size of data which can be buffered in
above conditions. The option can also help to overcome situation when data transfer to the host is temporarily slowed
down, e.g., due to USB bus congestions. But it will not help when the average bitrate of the trace data stream exceeds
the hardware interface capabilities.
Note: In order to achieve higher data rates and minimize the number of dropped packets, it is recommended to
optimize the setting of JTAG clock frequency, so that it is at maximum and still provides stable operation of JTAG.
See Optimize JTAG speed.
It can be insufficient to diagnose the problem. This menuconfig option allows avoiding such situations. It
controls the threshold for flushing data in case of apanic. For example, users can decide that it needs no less
than 512 bytes of the recent trace data, so if there is less then 512 bytes of pending data at the moment of
panic, they will not be flushed and will not overwrite the previous 16 KB. The option is only meaningful in
post-mortem mode and when working over JTAG.
2. Timeout for flushing last trace data to host on panic (CONFIG_APPTRACE_ONPANIC_HOST_FLUSH_TMO).
The option is only meaningful in streaming mode and it controls the maximum time that the tracing module
will wait for the host to read the last data in case of panic.
3. UART RX/TX ring buffer size (CONFIG_APPTRACE_UART_TX_BUFF_SIZE). The size of the buffer depends
on the amount of data transfered through the UART.
4. UART TX message size (CONFIG_APPTRACE_UART_TX_MSG_SIZE). The maximum size of the single mes-
sage to transfer.
This library provides APIs for transferring arbitrary data between the host and ESP32. When enabled in menuconfig,
the target application tracing module is initialized automatically at the system startup, so all what the user needs to
do is to call corresponding APIs to send, receive or flush the data.
In general, users should decide what type of data should be transferred in every direction and how these data must be
interpreted (processed). The following steps must be performed to transfer data between the target and the host:
1. On the target side, users should implement algorithms for writing trace data to the host. Piece of code below
shows an example on how to do this.
#include "esp_app_trace.h"
...
char buf[] = "Hello World!";
esp_err_t res = esp_apptrace_write(ESP_APPTRACE_DEST_TRAX, buf,␣
,→strlen(buf), ESP_APPTRACE_TMO_INFINITE);
if (res != ESP_OK) {
ESP_LOGE(TAG, "Failed to write data to host!");
return res;
}
esp_apptrace_write() function uses memcpy to copy user data to the internal buffer.
In some cases, it can be more optimal to use esp_apptrace_buffer_get() and
esp_apptrace_buffer_put() functions. They allow developers to allocate buffer and fill
it themselves. The following piece of code shows how to do this.
#include "esp_app_trace.h"
...
int number = 10;
char *ptr = (char *)esp_apptrace_buffer_get(ESP_APPTRACE_DEST_TRAX, 32,
,→ 100/*tmo in us*/);
if (ptr == NULL) {
ESP_LOGE(TAG, "Failed to get buffer!");
return ESP_FAIL;
}
sprintf(ptr, "Here is the number %d", number);
esp_err_t res = esp_apptrace_buffer_put(ESP_APPTRACE_DEST_TRAX, ptr,␣
,→100/*tmo in us*/);
if (res != ESP_OK) {
/* in case of error host tracing tool (e.g., OpenOCD) will report␣
,→incomplete user buffer */
Also according to his needs, the user may want to receive data from the host. Piece of code below
shows an example on how to do this.
#include "esp_app_trace.h"
...
char buf[32];
char down_buf[32];
size_t sz = sizeof(buf);
if (res != ESP_OK) {
ESP_LOGE(TAG, "Failed to read data from host!");
return res;
}
if (sz > 0) {
/* we have data, process them */
...
}
#include "esp_app_trace.h"
...
char down_buf[32];
uint32_t *number;
size_t sz = 32;
if (ptr == NULL) {
ESP_LOGE(TAG, "Failed to get buffer!");
return ESP_FAIL;
}
if (sz > 4) {
number = (uint32_t *)ptr;
printf("Here is the number %d", *number);
} else {
printf("No data");
}
esp_err_t res = esp_apptrace_down_buffer_put(ESP_APPTRACE_DEST_TRAX,␣
,→ptr, 100/*tmo in us*/);
if (res != ESP_OK) {
/* in case of error host tracing tool (e.g., OpenOCD) will report␣
,→incomplete user buffer */
2. The next step is to build the program image and download it to the target as described in the Getting Started
Guide.
3. Run OpenOCD (see JTAG Debugging).
4. Connect to OpenOCD telnet server. It can be done using the following command in terminal telnet
<oocd_host> 4444. If telnet session is opened on the same machine which runs OpenOCD, you can
use localhost as <oocd_host> in the command above.
5. Start trace data collection using special OpenOCD command. This command will transfer tracing data and
redirect them to the specified file or socket (currently only files are supported as trace data destination). For
description of the corresponding commands, see OpenOCD Application Level Tracing Commands.
6. The final step is to process received data. Since the format of data is defined by users, the processing stage is out
of the scope of this document. Good starting points for data processor are python scripts in $IDF_PATH/
tools/esp_app_trace: apptrace_proc.py (used for feature tests) and logtrace_proc.py
(see more details in section Logging to Host).
OpenOCD Application Level Tracing Commands HW UP BUFFER is shared between user data blocks and the
filling of the allocated memory is performed on behalf of the API caller (in task or ISR context). In multithreading
environment, it can happen that the task/ISR which fills the buffer is preempted by another high priority task/ISR.
So it is possible that the user data preparation process is not completed at the moment when that chunk is read by
the host. To handle such conditions, the tracing module prepends all user data chunks with header which contains
the allocated user buffer size (2 bytes) and the length of the actually written data (2 bytes). So the total length of
the header is 4 bytes. OpenOCD command which reads trace data reports error when it reads incomplete user data
chunk, but in any case, it puts the contents of the whole user chunk (including unfilled area) to the output file.
Below is the description of available OpenOCD application tracing commands.
Note: Currently, OpenOCD does not provide commands to send arbitrary user data to the target.
Command usage:
esp apptrace [start <options>] | [stop] | [status] | [dump <cores_num>
<outfile>]
Sub-commands:
start Start tracing (continuous streaming).
stop Stop tracing.
status Get tracing status.
dump Dump all data from (post-mortem dump).
Start command syntax:
start <outfile> [poll_period [trace_size [stop_tmo [wait4halt
[skip_size]]]]
outfile Path to file to save data from both CPUs. This argument should have the following format: file://
path/to/file.
poll_period Data polling period (in ms) for available trace data. If greater than 0, then command runs in non-
blocking mode. By default, 1 ms.
trace_size Maximum size of data to collect (in bytes). Tracing is stopped after specified amount of data is
received. By default, -1 (trace size stop trigger is disabled).
stop_tmo Idle timeout (in sec). Tracing is stopped if there is no data for specified period of time. By default, -1
(disable this stop trigger). Optionally set it to value longer than longest pause between tracing commands from
target.
wait4halt If 0, start tracing immediately, otherwise command waits for the target to be halted (after reset, by
breakpoint etc.) and then automatically resumes it and starts tracing. By default, 0.
skip_size Number of bytes to skip at the start. By default, 0.
Note: If poll_period is 0, OpenOCD telnet command line will not be available until tracing is stopped. You
must stop it manually by resetting the board or pressing Ctrl+C in OpenOCD window (not one with the telnet session).
Another option is to set trace_size and wait until this size of data is collected. At this point, tracing stops
automatically.
1. Collect 2048 bytes of tracing data to the file trace.log. The file will be saved in the openocd-esp32
directory.
The tracing data will be retrieved and saved in non-blocking mode. This process will stop automat-
ically after 2048 bytes are collected, or if no data are available for more than 5 seconds.
Note: Tracing data is buffered before it is made available to OpenOCD. If you see“Data timeout!”
message, then it is likely that the target is not sending enough data to empty the buffer to OpenOCD
before the timeout. Either increase the timeout or use the function esp_apptrace_flush()
to flush the data on specific intervals.
There is no limitation on the size of collected data and there is no data timeout set. This process may be
stopped by issuing esp apptrace stop command on OpenOCD telnet prompt, or by pressing Ctrl+C in
OpenOCD window.
3. Retrieve tracing data and save them indefinitely.
OpenOCD telnet command line prompt will not be available until tracing is stopped. To stop tracing, press
Ctrl+C in the OpenOCD window.
4. Wait for the target to be halted. Then resume the target’s operation and start data retrieval. Stop after collecting
2048 bytes of data:
To configure tracing immediately after reset, use the OpenOCD reset halt command.
Logging to Host
ESP-IDF implements a useful feature: logging to the host via application level tracing library. This is a kind of
semihosting when all ESP_LOGx calls send strings to be printed to the host instead of UART. This can be useful
because “printing to host”eliminates some steps performed when logging to UART. Most part of the work is done
on the host.
By default, ESP-IDF’s logging library uses vprintf-like function to write formatted output to dedicated UART. In
general, it involves the following steps:
1. Format string is parsed to obtain type of each argument.
2. According to its type, every argument is converted to string representation.
3. Format string combined with converted arguments is sent to UART.
Though the implementation of the vprintf-like function can be optimized to a certain level, all steps above have
to be performed in any case and every step takes some time (especially item 3). So it frequently occurs that with
additional log added to the program to identify the problem, the program behavior is changed and the problem cannot
be reproduced. And in the worst cases, the program cannot work normally at all and ends up with an error or even
hangs.
Possible ways to overcome this problem are to use higher UART bitrates (or another faster interface) and/or to move
string formatting procedure to the host.
The application level tracing feature can be used to transfer log information to the host using
esp_apptrace_vprintf function. This function does not perform full parsing of the format string and
arguments. Instead, it just calculates the number of arguments passed and sends them along with the format string
address to the host. On the host, log data is processed and printed out by a special Python script.
How To Use It In order to use logging via trace module, users need to perform the following steps:
1. On the target side, the special vprintf-like function esp_apptrace_vprintf needs to be installed. It
sends log data to the host. Example code is provided in system/app_trace_to_host.
2. Follow instructions in items 2-5 in Application Specific Tracing.
3. To print out collected log records, run the following command in terminal: $IDF_PATH/tools/
esp_app_trace/logtrace_proc.py /path/to/trace/file /path/to/program/
elf/file.
Another useful ESP-IDF feature built on top of application tracing library is the system level tracing which produces
traces compatible with SEGGER SystemView tool (see SystemView). SEGGER SystemView is a real-time recording
and visualization tool that allows to analyze runtime behavior of an application. It is possible to view events in real-
time through the UART interface.
How To Use It Support for this feature is enabled by Component config > Application Level Trac-
ing > FreeRTOS SystemView Tracing (CONFIG_APPTRACE_SV_ENABLE) menuconfig option. There
are several other options enabled under the same menu:
1. SytemView destination. Select the destination interface: JTAG or UART. In case of UART, it will be possible
to connect SystemView application to the ESP32 directly and receive data in real-time.
2. ESP32 timer to use as SystemView timestamp source: (CONFIG_APPTRACE_SV_TS_SOURCE) selects the
source of timestamps for SystemView events. In the single core mode, timestamps are generated using ESP32
internal cycle counter running at maximum 240 Mhz (~4 ns granularity). In the dual-core mode, external timer
working at 40 Mhz is used, so the timestamp granularity is 25 ns.
3. Individually enabled or disabled collection of SystemView events (CONFIG_APPTRACE_SV_EVT_XXX):
• Trace Buffer Overflow Event
• ISR Enter Event
• ISR Exit Event
• ISR Exit to Scheduler Event
• Task Start Execution Event
• Task Stop Execution Event
• Task Start Ready State Event
• Task Stop Ready State Event
• Task Create Event
• Task Terminate Event
• System Idle Event
• Timer Enter Event
• Timer Exit Event
ESP-IDF has all the code required to produce SystemView compatible traces, so users can just configure necessary
project options (see above), build, download the image to target, and use OpenOCD to collect data as described in
the previous sections.
4. Select Pro or App CPU in menuconfig options Component config > Application Level Tracing
> FreeRTOS SystemView Tracing to trace over the UART interface in real-time.
Note: If poll_period is 0, OpenOCD telnet command line will not be available until tracing is stopped. You
must stop it manually by resetting the board or pressing Ctrl+C in the OpenOCD window (not the one with the telnet
session). Another option is to set trace_size and wait until this size of data is collected. At this point, tracing
stops automatically.
The tracing data will be retrieved and saved in non-blocking mode. To stop this process, enter esp sysview
stop command on OpenOCD telnet prompt, optionally pressing Ctrl+C in the OpenOCD window.
2. Retrieve tracing data and save them indefinitely.
OpenOCD telnet command line prompt will not be available until tracing is stopped. To stop tracing, press
Ctrl+C in the OpenOCD window.
Data Visualization After trace data are collected, users can use a special tool to visualize the results and inspect
behavior of the program.
Unfortunately, SystemView does not support tracing from multiple cores. So when tracing from ESP32 with JTAG
interfaces in the dual-core mode, two files are generated: one for PRO CPU and another for APP CPU. Users can
load each file into separate instances of the tool. For tracing over UART, users can select Component config
> Application Level Tracing > FreeRTOS SystemView Tracing in menuconfig Pro or App to
choose which CPU has to be traced.
It is uneasy and awkward to analyze data for every core in separate instance of the tool. Fortunately, there is an Eclipse
plugin called Impulse which can load several trace files, thus making it possible to inspect events from both cores in
one view. Also, this plugin has no limitation of 1,000,000 events as compared to the free version of SystemView.
Good instructions on how to install, configure, and visualize data in Impulse from one core can be found here.
Note: ESP-IDF uses its own mapping for SystemView FreeRTOS events IDs, so users need to replace the original
file mapping $SYSVIEW_INSTALL_DIR/Description/SYSVIEW_FreeRTOS.txt with $IDF_PATH/
docs/api-guides/SYSVIEW_FreeRTOS.txt. Also, contents of that IDF-specific file should be used when
configuring SystemView serializer using the above link.
Configure Impulse for Dual Core Traces After installing Impulse and ensuring that it can successfully load trace
files for each core in separate tabs, users can add special Multi Adapter port and load both files into one view. To do
this, users need to do the following steps in Eclipse:
1. Open the Signal Ports view. Go to Windows > Show View > Other menu. Find the Signal
Ports view in Impulse folder and double-click it.
2. In the Signal Ports view, right-click Ports and select Add > New Multi Adapter Port.
3. In the open dialog box, click Add and select New Pipe/File.
4. In the open dialog box, select SystemView Serializer as Serializer and set path to PRO CPU trace
file. Click OK.
5. Repeat the steps 3-4 for APP CPU trace file.
6. Double-click the created port. View for this port should open.
7. Click the Start/Stop Streaming button. Data should be loaded.
8. Use the Zoom Out, Zoom In and Zoom Fit buttons to inspect data.
9. For settings measurement cursors and other features, please see Impulse documentation).
Note: If you have problems with visualization (no data is shown or strange behaviors of zoom action are observed),
you can try to delete current signal hierarchy and double-click on the necessary file or port. Eclipse will ask you to
create a new signal hierarchy.
Basics of Gcov and Gcovr Source code coverage is data indicating the count and frequency of every program
execution path that has been taken within a program’s runtime. Gcov is a GCC tool that, when used in concert with
the compiler, can generate log files indicating the execution count of each line of a source file. The Gcovr tool is a
utility for managing Gcov and generating summarized code coverage results.
Generally, using Gcov to compile and run programs on the host will undergo these steps:
1. Compile the source code using GCC with the --coverage option enabled. This will cause the compiler
to generate a .gcno notes files during compilation. The notes files contain information to reconstruct execu-
tion path block graphs and map each block to source code line numbers. Each source file compiled with the
--coverage option should have their own .gcno file of the same name (e.g., a main.c will generate a
main.gcno when compiled).
2. Execute the program. During execution, the program should generate .gcda data files. These data files
contain the counts of the number of times an execution path was taken. The program will generate a .gcda
file for each source file compiled with the --coverage option (e.g., main.c will generate a main.gcda).
3. Gcov or Gcovr can be used to generate a code coverage based on the .gcno, .gcda, and source files. Gcov
will generate a text-based coverage report for each source file in the form of a .gcov file, whilst Gcovr will
generate a coverage report in HTML format.
Gcov and Gcovr in ESP-IDF Using Gcov in ESP-IDF is complicated due to the fact that the program is running
remotely from the host (i.e., on the target). The code coverage data (i.e., the .gcda files) is initially stored on the
target itself. OpenOCD is then used to dump the code coverage data from the target to the host via JTAG during
runtime. Using Gcov in ESP-IDF can be split into the following steps.
1. Setting Up a Project for Gcov
2. Dumping Code Coverage Data
3. Generating Coverage Report
Compiler Option In order to obtain code coverage data in a project, one or more source files within the project
must be compiled with the --coverage option. In ESP-IDF, this can be achieved at the component level or the
individual source file level:
• To cause all source files in a component to be compiled with the --coverage option, you can add tar-
get_compile_options(${COMPONENT_LIB} PRIVATE --coverage) to the CMakeLists.
txt file of the component.
• To cause a select number of source files (e.g., source1.c and source2.c) in the same component to be
compiled with the --coverage option, you can add set_source_files_properties(source1.
c source2.c PROPERTIES COMPILE_FLAGS --coverage) to the CMakeLists.txt file of
the component.
When a source file is compiled with the --coverage option (e.g., gcov_example.c), the compiler will generate
the gcov_example.gcno file in the project’s build directory.
Project Configuration Before building a project with source code coverage, make sure that the following project
configuration options are enabled by running idf.py menuconfig.
• Enable the application tracing module by selecting Trace Memory for the CON-
FIG_APPTRACE_DESTINATION1 option.
• Enable Gcov to the host via the CONFIG_APPTRACE_GCOV_ENABLE.
Dumping Code Coverage Data Once a project has been complied with the --coverage option and flashed
onto the target, code coverage data will be stored internally on the target (i.e., in trace memory) whilst the application
runs. The process of transferring code coverage data from the target to the host is known as dumping.
The dumping of coverage data is done via OpenOCD (see JTAG Debugging on how to setup and run OpenOCD). A
dump is triggered by issuing commands to OpenOCD, therefore a telnet session to OpenOCD must be opened to issue
such commands (run telnet localhost 4444). Note that GDB could be used instead of telnet to issue com-
mands to OpenOCD, however all commands issued from GDB will need to be prefixed as mon <oocd_command>.
When the target dumps code coverage data, the .gcda files are stored in the project’s build directory. For ex-
ample, if gcov_example_main.c of the main component is compiled with the --coverage option, then
dumping the code coverage data would generate a gcov_example_main.gcda in build/esp-idf/main/
CMakeFiles/__idf_main.dir/gcov_example_main.c.gcda. Note that the .gcno files produced
during compilation are also placed in the same directory.
The dumping of code coverage data can be done multiple times throughout an application’s lifetime. Each dump
will simply update the .gcda file with the newest code coverage information. Code coverage data is accumulative,
thus the newest data will contain the total execution count of each code path over the application’s entire lifetime.
ESP-IDF supports two methods of dumping code coverage data form the target to the host:
• Instant Run-Time Dumpgit
• Hard-coded Dump
Instant Run-Time Dump An Instant Run-Time Dump is triggered by calling the ESP32 gcov OpenOCD
command (via a telnet session). Once called, OpenOCD will immediately preempt the ESP32’s current state and
execute a built-in ESP-IDF Gcov debug stub function. The debug stub function will handle the dumping of data to
the host. Upon completion, the ESP32 will resume its current state.
Hard-coded Dump A Hard-coded Dump is triggered by the application itself by calling esp_gcov_dump()
from somewhere within the application. When called, the application will halt and wait for OpenOCD to connect and
retrieve the code coverage data. Once esp_gcov_dump() is called, the host must execute the esp gcov dump
OpenOCD command (via a telnet session). The esp gcov dump command will cause OpenOCD to connect to
the ESP32, retrieve the code coverage data, then disconnect from the ESP32, thus allowing the application to resume.
Hard-coded Dumps can also be triggered multiple times throughout an application’s lifetime.
Hard-coded dumps are useful if code coverage data is required at certain points of an application’s lifetime by placing
esp_gcov_dump() where necessary (e.g., after application initialization, during each iteration of an application’
s main loop).
GDB can be used to set a breakpoint on esp_gcov_dump(), then call mon esp gcov dump automatically
via the use a gdbinit script (see Using GDB from Command Line).
The following GDB script will add a breakpoint at esp_gcov_dump(), then call the mon esp gcov dump
OpenOCD command.
b esp_gcov_dump
commands
mon esp gcov dump
end
Note: Note that all OpenOCD commands should be invoked in GDB as: mon <oocd_command>.
Generating Coverage Report Once the code coverage data has been dumped, the .gcno, .gcda and the source
files can be used to generate a code coverage report. A code coverage report is simply a report indicating the number
of times each line in a source file has been executed.
Both Gcov and Gcovr can be used to generate code coverage reports. Gcov is provided along with the Xtensa
toolchain, whilst Gcovr may need to be installed separately. For details on how to use Gcov or Gcovr, refer to
Gcov documentation and Gcovr documentation.
Adding Gcovr Build Target to Project To make report generation more convenient, users can define additional
build targets in their projects such that the report generation can be done with a single build command.
Add the following lines to the CMakeLists.txt file of your project.
include($ENV{IDF_PATH}/tools/cmake/gcov.cmake)
idf_create_coverage_report(${CMAKE_CURRENT_BINARY_DIR}/coverage_report)
idf_clean_coverage_report(${CMAKE_CURRENT_BINARY_DIR}/coverage_report)
This note explains various steps which happen before app_main function of an ESP-IDF application is called.
The high level view of startup process is as follows:
1. First stage bootloader in ROM loads second-stage bootloader image to RAM (IRAM & DRAM) from flash
offset 0x1000.
2. Second stage bootloader loads partition table and main app image from flash. Main app incorporates both RAM
segments and read-only segments mapped via flash cache.
3. Application startup executes. At this point the second CPU and RTOS scheduler are started.
This process is explained in detail in the following sections.
After SoC reset, PRO CPU will start running immediately, executing reset vector code, while APP CPU will be
held in reset. During startup process, PRO CPU does all the initialization. APP CPU reset is de-asserted in the
call_start_cpu0 function of application startup code. Reset vector code is located in the mask ROM of the
ESP32 chip and cannot be modified.
Startup code called from the reset vector determines the boot mode by checking GPIO_STRAP_REG register for
bootstrap pin states. Depending on the reset reason, the following takes place:
1. Reset from deep sleep: if the value in RTC_CNTL_STORE6_REG is non-zero, and CRC value of RTC mem-
ory in RTC_CNTL_STORE7_REG is valid, use RTC_CNTL_STORE6_REG as an entry point address and
jump immediately to it. If RTC_CNTL_STORE6_REG is zero, or RTC_CNTL_STORE7_REG contains in-
valid CRC, or once the code called via RTC_CNTL_STORE6_REG returns, proceed with boot as if it was a
power-on reset. Note: to run customized code at this point, a deep sleep stub mechanism is provided. Please
see deep sleep documentation for this.
2. For power-on reset, software SOC reset, and watchdog SOC reset: check the GPIO_STRAP_REG register
if a custom boot mode (such as UART Download Mode) is requested. If this is the case, this custom loader
mode is executed from ROM. Otherwise, proceed with boot as if it was due to software CPU reset. Consult
ESP32 datasheet for a description of SoC boot modes and how to execute them.
3. For software CPU reset and watchdog CPU reset: configure SPI flash based on EFUSE values, and attempt to
load the code from flash. This step is described in more detail in the next paragraphs.
Note: During normal boot modes the RTC watchdog is enabled when this happens, so if the process is interrupted
or stalled then the watchdog will reset the SOC automatically and repeat the boot process. This may cause the SoC
to strap into a new boot mode, if the strapping GPIOs have changed.
Second stage bootloader binary image is loaded from flash starting at address 0x1000. If Secure Boot is in use then
the first 4 kB sector of flash is used to store secure boot IV and digest of the bootloader image. Otherwise, this sector
is unused.
In ESP-IDF, the binary image which resides at offset 0x1000 in flash is the second stage bootloader. Second stage
bootloader source code is available in components/bootloader directory of ESP-IDF. Second stage bootloader is used
in ESP-IDF to add flexibility to flash layout (using partition tables), and allow for various flows associated with flash
encryption, secure boot, and over-the-air updates (OTA) to take place.
When the first stage bootloader is finished checking and loading the second stage bootloader, it jumps to the second
stage bootloader entry point found in the binary image header.
Second stage bootloader reads the partition table found by default at offset 0x8000 (configurable value). See partition
tables documentation for more information. The bootloader finds factory and OTA app partitions. If OTA app
partitions are found in the partition table, the bootloader consults the otadata partition to determine which one
should be booted. See Over The Air Updates (OTA) for more information.
For a full description of the configuration options available for the ESP-IDF bootloader, see Bootloader.
For the selected partition, second stage bootloader reads the binary image from flash one segment at a time:
• For segments with load addresses in internal IRAM (Instruction RAM) or DRAM (Data RAM), the contents are
copied from flash to the load address.
• For segments which have load addresses in DROM (data stored in flash) or IROM (code executed from flash)
regions, the flash MMU is configured to provide the correct mapping from the flash to the load address.
Note that the second stage bootloader configures flash MMU for both PRO and APP CPUs, but it only enables flash
MMU for PRO CPU. Reason for this is that second stage bootloader code is loaded into the memory region used by
APP CPU cache. The duty of enabling cache for APP CPU is passed on to the application.
Once all segments are processed - meaning code is loaded and flash MMU is set up, second stage bootloader verifies
the integrity of the application and then jumps to the application entry point found in the binary image header.
Application startup covers everything that happens after the app starts executing and before the app_main function
starts running inside the main task. This is split into three stages:
• Port initialization of hardware and basic C runtime environment.
• System initialization of software services and FreeRTOS.
• Running the main task and calling app_main.
Note: Understanding all stages of ESP-IDF app initialization is often not necessary. To understand initialization
from the application developer’s perspective only, skip forward to Running the main task.
Port Initialization
• Reconfigure CPU exceptions for the app (allowing app interrupt handlers to run, and causing Fatal Errors to
be handled using the options configured for the app rather than the simpler error handler provided by ROM).
• If the option CONFIG_BOOTLOADER_WDT_ENABLE is not set then the RTC watchdog timer is disabled.
• Initialize internal memory (data & bss).
• Finish configuring the MMU cache.
• Enable PSRAM if configured.
• Set the CPU clocks to the frequencies configured for the project.
• Reconfigure the main SPI flash based on the app header settings (necessary for compatibility with bootloader
versions before ESP-IDF V4.0, see Bootloader compatibility).
• If the app is configured to run on multiple cores, start the other core and wait for it to initialize as well (inside
the similar “port layer”initialization function call_start_cpu1).
Once call_start_cpu0 completes running, it calls the “system layer”initialization function start_cpu0
found in components/esp_system/startup.c. Other cores will also complete port-layer initialization and call
start_other_cores found in the same file.
System Initialization
The main system initialization function is start_cpu0. By default, this function is weak-linked to the function
start_cpu0_default. This means that it’s possible to override this function to add some additional initial-
ization steps.
The primary system initialization stage includes:
• Log information about this application (project name, App Version, etc.) if default log level enables this.
• Initialize the heap allocator (before this point all allocations must be static or on the stack).
• Initialize newlib component syscalls and time functions.
• Configure the brownout detector.
• Setup libc stdin, stdout, and stderr according to the serial console configuration.
• Perform any security-related checks, including burning efuses that should be burned for this configuration (in-
cluding disabling ROM download mode on ESP32 V3, CONFIG_ESP32_DISABLE_BASIC_ROM_CONSOLE).
• Initialize SPI flash API support.
• Call global C++ constructors and any C functions marked with __attribute__((constructor)).
Secondary system initialization allows individual components to be initialized. If a component has an initialization
function annotated with the ESP_SYSTEM_INIT_FN macro, it will be called as part of secondary initialization.
After all other components are initialized, the main task is created and the FreeRTOS scheduler starts running.
After doing some more initialization tasks (that require the scheduler to have started), the main task runs the
application-provided function app_main in the firmware.
The main task that runs app_main has a fixed RTOS priority (one higher than the minimum) and a configurable
stack size.
The main task core affinity is also configurable: CONFIG_ESP_MAIN_TASK_AFFINITY.
Unlike normal FreeRTOS tasks (or embedded C main functions), the app_main task is allowed to return. If this
happens, The task is cleaned up and the system will continue running with other RTOS tasks scheduled normally.
Therefore, it is possible to implement app_main as either a function that creates other application tasks and then
returns, or as a main application task itself.
4.3 BluFi
4.3.1 Overview
The BluFi for ESP32 is a Wi-Fi network configuration function via Bluetooth channel. It provides a secure protocol
to pass Wi-Fi configuration and credentials to ESP32. Using this information, ESP32 can then connect to an AP or
establish a SoftAP.
Fragmenting, data encryption, and checksum verification in the BluFi layer are the key elements of this process.
You can customize symmetric encryption, asymmetric encryption, and checksum support customization. Here we use
the DH algorithm for key negotiation, 128-AES algorithm for data encryption, and CRC16 algorithm for checksum
verification.
The BluFi networking flow includes the configuration of the SoftAP and Station.
The following uses Station as an example to illustrate the core parts of the procedure, including broadcast, connection,
service discovery, negotiation of the shared key, data transmission, and connection status backhaul.
1. Set the ESP32 into GATT Server mode and then it will send broadcasts with specific advertising data. You
can customize this broadcast as needed, which is not a part of the BluFi Profile.
2. Use the App installed on the mobile phone to search for this particular broadcast. The mobile phone will
connect to ESP32 as the GATT Client once the broadcast is confirmed. The App used during this part is up
to you.
3. After the GATT connection is successfully established, the mobile phone will send a data frame for key nego-
tiation to ESP32 (see the section The Frame Formats Defined in BluFi for details).
4. After ESP32 receives the data frame of key negotiation, it will parse the content according to the user-defined
negotiation method.
5. The mobile phone works with ESP32 for key negotiation using the encryption algorithms, such as DH, RSA,
or ECC.
6. After the negotiation process is completed, the mobile phone will send a control frame for security-mode setup
to ESP32.
7. When receiving this control frame, ESP32 will be able to encrypt and decrypt the communication data using
the shared key and the security configuration.
8. The mobile phone sends the data frame defined in the section of The Frame Formats Defined in BluFi,with
the Wi-Fi configuration information to ESP32, including SSID, password, etc.
9. The mobile phone sends a control frame of Wi-Fi connection request to ESP32. When receiving this control
frame, ESP32 will regard the communication of essential information as done and get ready to connect to the
Wi-Fi.
10. After connecting to the Wi-Fi, ESP32 will send a control frame of Wi-Fi connection status report to the mobile
phone. At this point, the networking procedure is completed.
Note:
1. After ESP32 receives the control frame of security-mode configuration, it will execute the operations in ac-
cordance with the defined security mode.
2. The data lengths before and after symmetric encryption/decryption must stay the same. It also supports in-place
encryption and decryption.
The frame formats for the communication between the mobile phone App and ESP32 are defined as follows:
The frame format with no fragment:
If the frag frame bit in the Frame Control field is enabled, there would be a 2-byte Total Content Length field in
the Data field. This Total Content Length field indicates the length of the remaining part of the frame and also tells
the remote how much memory needs to be allocated.
The frame format with fragments:
Normally, the control frame does not contain data bits, except for ACK Frame.
The format of ACK Frame:
1. Type
Type field takes 1 byte and is divided into Type and Subtype. Type uses the lower two bits, indicating whether
the frame is a data frame or a control frame. Subtype uses the upper six bits, indicating the specific meaning
of this data frame or control frame.
• The control frame is not encrypted for the time being and supports to be verified.
• The data frame supports to be encrypted and verified.
1.1 Control Frame (Binary: 0x0 b’00)
0x6 Disconnect the STA Data[0~5] is taken as the MAC address for the
(b’ device from the STA device. If there is a second STA device,
000110)SoftAP (in SoftAP then it uses data[6-11] and the rest can be done
mode). in the same manner.
0x7 Get the version infor-
(b’ mation.
000111)
0x8 Disconnect the BLE The ESP device will disconnect the BLE
(b’ GATT link. GATT link after receives this command.
001000)
0x9 Get the Wi-Fi list. To get the ESP device to No data field is contained. When receiving this
(b’ scan the Wi-Fi access points control frame, the ESP device will send back
Espressif Systems 2064 Release v5.0-dev-4037-g9b8c558e63
001001) around. a follow-up frame of Wi-Fi list report to the
Submit Document Feedback
mobile phone.
Chapter 4. API Guides
Note:
• Note 1: The length of the data depends on the data length field. When the transmission direction is from the
ESP device to the mobile phone, it means to provide the mobile phone with the needed information.
• Note 2: The length of the data depends on the data length field. The frame supports to be fragmented if the
data length is not long enough.
2. Frame Control
The Frame Control field takes one byte and each bit has a different meaning.
Bit Meaning
0x01 Indicates whether the frame is encrypted.
• 1 means encrypted.
• 0 means unencrypted.
The encrypted part of the frame includes the full clear data before the DATA field is
encrypted (no checksum). Control frame is not encrypted, so this bit is 0.
0x02 Indicates whether a frame contains a checksum (such as SHA1, MD5, CRC) for the end
of the frame. Data field includes sequence, data length, and clear text. Both the control
frame and the data frame can choose whether to contain a check bit or not.
0x04 Indicates the data direction.
• 0 means from the mobile phone to the ESP device.
• 1 means from the ESP device to the mobile phone.
3. Sequence Number
The Sequence Number field is the field for sequence control. When a frame is sent, the value of this field is
automatically incremented by 1 regardless of the type of frame, which prevents Replay Attack. The sequence
would be cleared after each reconnection.
4. Data Length
The Data Length field indicates the length of the data field, which does not include CheckSum.
5. Data
Content of the Data field can be different according to various values of Type or Subtype. Please refer to the
table above.
6. CheckSum
The CheckSum field takes two bytes, which is used to check “sequence + data length + clear text data”.
1. Securing Data
To ensure that the transmission of the Wi-Fi SSID and password is secure, the message needs to be encrypted
using symmetric encryption algorithms, such as AES, DES, and so on. Before using symmetric encryption
algorithms, the devices are required to negotiate (or generate) a shared key using an asymmetric encryption
algorithm (DH, RSA, ECC, etc).
2. Ensuring Data Integrity
To ensure data integrity, you need to add a checksum algorithm, such as SHA1, MD5, CRC, etc.
3. Securing Identity (Signature)
Algorithm like RSA can be used to secure identity. But for DH, it needs other algorithms as an companion for
signature.
4. Replay Attack Prevention
It is added to the Sequence Number field and used during the checksum verification.
For the coding of ESP32, you can determine and develop the security processing, such as key negotiation. The
mobile application sends the negotiation data to ESP32, and then the data will be sent to the application layer
for processing. If the application layer does not process it, you can use the DH encryption algorithm provided
by BluFi to negotiate the key.
The application layer needs to register several security-related functions to BluFi:
This function is for ESP32 to receive normal data during negotiation. After processing is completed, the data will be
transmitted using Output_data and Output_len.
BluFi will send output_data from Negotiate_data_handler after Negotiate_data_handler is called.
Here are two “*”, which means the length of the data to be emitted is unknown. Therefore, it requires the func-
tion to allocate itself (malloc) or point to the global variable to inform whether the memory needs to be freed by
NEED_FREE.
The data to be encrypted and decrypted must be in the same length. The IV8 is an 8-bit sequence value of frames,
which can be used as a 8-bit of IV.
The data to be encrypted and decrypted must be in the same length. The IV8 is an 8-bit sequence value of frames,
which can be used as an 8-bit of IV.
This function is used to compute CheckSum and return a value of CheckSum. BluFi uses the returned value to
compare the CheckSum of the frame.
UUID
4.4 Bootloader
4. Load this image to RAM (IRAM & DRAM) and transfer management to the image that was just loaded.
Bootloader is located at the address 0x1000 in the flash.
For a full description of the startup process including the the ESP-IDF bootloader, see Application Startup Flow.
It is recommended to update to newer versions of ESP-IDF: when they are released. The OTA (over the air) update
process can flash new apps in the field but cannot flash a new bootloader. For this reason, the bootloader supports
booting apps built from newer versions of ESP-IDF.
The bootloader does not support booting apps from older versions of ESP-IDF. When updating ESP-IDF manually
on an existing product that might need to downgrade the app to an older version, keep using the older ESP-IDF
bootloader binary as well.
Note: If testing an OTA update for an existing product in production, always test it using the same ESP-IDF
bootloader binary that is deployed in production.
Bootloaders built from very old versions of ESP-IDF (before ESP-IDF V2.1) perform less hardware configuration
than newer versions. When using a bootloader from these early ESP-IDF versions and building a new app, enable the
config option CONFIG_APP_COMPATIBLE_PRE_V2_1_BOOTLOADERS.
Bootloaders built from versions of ESP-IDF before V3.1 do not support MD5 checksums in the partition table bi-
nary. When using a bootloader from these ESP-IDF versions and building a new app, enable the config option
CONFIG_APP_COMPATIBLE_PRE_V3_1_BOOTLOADERS.
Each ESP-IDF application or bootloader .bin file contains a header with CONFIG_ESPTOOLPY_FLASHMODE, CON-
FIG_ESPTOOLPY_FLASHFREQ, CONFIG_ESPTOOLPY_FLASHSIZE embedded in it. These are used to configure
the SPI flash during boot.
The First stage bootloader in ROM reads the Second stage bootloader header information from flash and uses this
infomation to load the rest of the Second stage bootloader from flash. However, at this time the system clock speed
is lower than configured and not all flash modes are supported. When the Second stage bootloader then runs, it will
reconfigure the flash using values read from the currently selected app binary’s header (and NOT from the Second
stage bootloader header). This allows an OTA update to change the SPI flash settings in use.
Bootloaders prior to ESP-IDF V4.0 used the bootloader’s own header to configure the SPI flash, meaning these
values could not be changed in an update. To maintain compatibility with older bootloaders, the app re-initializes the
flash settings during app startup using the configuration found in the app header.
The default bootloader log level is “Info”. By setting the CONFIG_BOOTLOADER_LOG_LEVEL option, it’s
possible to increase or decrease this level. This log level is separate from the log level used in the app (see Logging
library).
Reducing bootloader log verbosity can improve the overall project boot time by a small amount.
Sometimes it is desirable to have a way for the device to fall back to a known-good state, in case of some problem
with an update.
To roll back to the original “factory”device configuration and clear any user settings, configure the config item
CONFIG_BOOTLOADER_FACTORY_RESET in the bootloader.
The factory reset mechanism allows the device to be factory reset in two ways:
• Clear one or more data partitions. The CONFIG_BOOTLOADER_DATA_FACTORY_RESET option allows
users to specify which data partitions will be erased when the factory reset is executed.
Users can specify the names of partitions as a comma-delimited list with optional spaces for readability. (Like
this: nvs, phy_init, nvs_custom).
Make sure that the names of partitions specified in the option are the same as those found in the partition table.
Partitions of type “app”cannot be specified here.
• Boot from “factory”app partition. Enabling the CONFIG_BOOTLOADER_OTA_DATA_ERASE option will
cause the device to boot from the default “factory”app partition after a factory reset (or if there is no factory
app partition in the partition table then the default ota app partition is selected instead). This reset process
involves erasing the OTA data partition which holds the currently selected OTA partition slot. The “factory”
app partition slot (if it exists) is never updated via OTA, so resetting to this allows reverting to a“known good”
firmware application.
Either or both of these configuration options can be enabled independently.
In addition, the following configuration options control the reset condition:
• CONFIG_BOOTLOADER_NUM_PIN_FACTORY_RESET- The input GPIO number used to trigger a factory
reset. This GPIO must be pulled low or high (configurable) on reset to trigger this.
• CONFIG_BOOTLOADER_HOLD_TIME_GPIO- this is hold time of GPIO for reset/test mode (by default 5
seconds). The GPIO must be held continuously for this period of time after reset before a factory reset or test
partition boot (as applicable) is performed.
• CONFIG_BOOTLOADER_FACTORY_RESET_PIN_LEVEL - configure whether a factory reset should trigger
on a high or low level of the GPIO. If the GPIO has an internal pullup then this is enabled before the pin is
sampled, consult the ESP32 datasheet for details on pin internal pullups.
It’s possible to write a special firmware app for testing in production, and boot this firmware when needed. The
project partition table will need a dedicated app partition entry for this testing app, type app and subtype test (see
Partition Tables).
Implementing a dedicated test app firmware requires creating a totally separate ESP-IDF project for the test app (each
project in ESP-IDF only builds one app). The test app can be developed and tested independently of the main project,
and then integrated at production testing time as a pre-compiled .bin file which is flashed to the address of the main
project’s test app partition.
To support this functionality in the main project’s bootloader, set the configuration item CON-
FIG_BOOTLOADER_APP_TEST and configure the following two items:
• CONFIG_BOOTLOADER_NUM_PIN_APP_TEST - GPIO number to boot TEST partition. The selected GPIO
will be configured as an input with internal pull-up enabled. To trigger a test app, this GPIO must be pulled
low on reset.
Once the GPIO input is released (allowing it to be pulled up) and the device has been reboot, the normally
configured application will boot (factory or any OTA app partition slot).
• CONFIG_BOOTLOADER_HOLD_TIME_GPIO - this is hold time of GPIO for reset/test mode (by default 5
seconds). The GPIO must be held low continuously for this period of time after reset before a factory reset or
test partition boot (as applicable) is performed.
4.4.5 Rollback
4.4.6 Watchdog
By default, the hardware RTC Watchdog timer remains running while the bootloader is running and will automatically
reset the chip if no app has successfully started after 9 seconds.
• The timeout period can be adjusted by setting CONFIG_BOOTLOADER_WDT_TIME_MS and recompiling the
bootloader.
• The app’s behaviour can be adjusted so the RTC Watchdog remains enabled after app startup. The Watch-
dog would need to be explicitly reset (i.e., fed) by the app to avoid a reset. To do this, set the CON-
FIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE option, modify the app as needed, and then recom-
pile the app.
• The RTC Watchdog can be disabled in the bootloader by disabling the CON-
FIG_BOOTLOADER_WDT_ENABLE setting and recompiling the bootloader. This is not recommended.
When enabling additional bootloader functions, including Flash Encryption or Secure Boot, and especially if setting
a high CONFIG_BOOTLOADER_LOG_LEVEL level, then it is important to monitor the bootloader .bin file’s size.
When using the default CONFIG_PARTITION_TABLE_OFFSET value 0x8000, the size limit is 0x7000 (28672) bytes.
If the bootloader binary is too large, then the bootloader build will fail with an error “Bootloader binary size [..] is
too large for partition table offset”. If the bootloader binary is flashed anyhow then the ESP32 will fail to boot -
errors will be logged about either invalid partition table or invalid bootloader checksum.
Options to work around this are:
• Set bootloader compiler optimization back to “Size”if it has been changed from this default value.
• Reduce bootloader log level. Setting log level to Warning, Error or None all significantly reduce the final binary
size (but may make it harder to debug).
• Set CONFIG_PARTITION_TABLE_OFFSET to a higher value than 0x8000, to place the partition table later
in the flash. This increases the space available for the bootloader. If the partition table CSV file con-
tains explicit partition offsets, they will need changing so no partition has an offset lower than CON-
FIG_PARTITION_TABLE_OFFSET + 0x1000. (This includes the default partition CSV files supplied
with ESP-IDF.)
When Secure Boot V2 is enabled, there is also an absolute binary size limit of 48KB (0xC000 bytes) (excluding the
4 KB signature), because the bootloader is first loaded into a fixed size buffer for verification.
The current bootloader implementation allows a project to extend it or modify it. There are two ways of doing it: by
implementing hooks or by overriding it. Both ways are presented in custom_bootloader folder in ESP-IDF examples:
• bootloader_hooks which presents how to connect some hooks to the bootloader initialization
• bootloader_override which presents how to override the bootloader implementation
In the bootloader space, you cannot use the drivers and functions from other components. If necessary, then the
required functionality should be placed in the project’s bootloader_components directory (note that this will increase
its size).
If the bootloader grows too large then it can collide with the partition table, which is flashed at offset 0x8000 by
default. Increase the partition table offset value to place the partition table later in the flash. This increases the space
available for the bootloader.
This document explains the implementation of the ESP-IDF build system and the concept of“components”. Read
this document if you want to know how to organize and build a new ESP-IDF project or component.
4.5.1 Overview
An ESP-IDF project can be seen as an amalgamation of a number of components. For example, for a webserver that
shows the current humidity, there could be:
• The ESP-IDF base libraries (libc, ROM bindings, etc)
• The Wi-Fi drivers
• A TCP/IP stack
• The FreeRTOS operating system
• A webserver
• A driver for the humidity sensor
• Main code tying it all together
ESP-IDF makes these components explicit and configurable. To do that, when a project is compiled, the build system
will look up all the components in the ESP-IDF directories, the project directories and (optionally) in additional
custom component directories. It then allows the user to configure the ESP-IDF project using a text-based menu
system to customize each component. After the components in the project are configured, the build system will
compile the project.
Concepts
• A “project”is a directory that contains all the files and configuration to build a single “app”(executable),
as well as additional supporting elements such as a partition table, data/filesystem partitions, and a bootloader.
• “Project configuration”is held in a single file called sdkconfig in the root directory of the project. This
configuration file is modified via idf.py menuconfig to customise the configuration of the project. A
single project contains exactly one project configuration.
• An“app”is an executable which is built by ESP-IDF. A single project will usually build two apps - a“project
app”(the main executable, ie your custom firmware) and a “bootloader app”(the initial bootloader program
which launches the project app).
• “components”are modular pieces of standalone code which are compiled into static libraries (.a files) and
linked into an app. Some are provided by ESP-IDF itself, others may be sourced from other places.
• “Target”is the hardware for which an application is built. A full list of supported targets in your version of
ESP-IDF can be seen by running idf.py –list-targets.
Some things are not part of the project:
• “ESP-IDF”is not part of the project. Instead it is standalone, and linked to the project via the IDF_PATH
environment variable which holds the path of the esp-idf directory. This allows the IDF framework to be
decoupled from your project.
• The toolchain for compilation is not part of the project. The toolchain should be installed in the system com-
mand line PATH.
idf.py
The idf.py command-line tool provides a front-end for easily managing your project builds. It manages the fol-
lowing tools:
• CMake, which configures the project to be built
• Ninja which builds the project
• esptool.py for flashing the target.
You can read more about configuring the build system using idf.py here.
idf.py is a wrapper around CMake for convenience. However, you can also invoke CMake directly if you prefer.
When idf.py does something, it prints each command that it runs for easy reference. For example, the idf.
py build command is the same as running these commands in a bash shell (or similar commands for Windows
Command Prompt):
mkdir -p build
cd build
cmake .. -G Ninja # or 'Unix Makefiles'
ninja
In the above list, the cmake command configures the project and generates build files for use with the final build
tool. In this case the final build tool is Ninja: running ninja actually builds the project.
It’s not necessary to run cmake more than once. After the first build, you only need to run ninja each time.
ninja will automatically re-invoke cmake if the project needs reconfiguration.
If using CMake with ninja or make, there are also targets for more of the idf.py sub-commands - for example
running make menuconfig or ninja menuconfig in the build directory will work the same as idf.py
menuconfig.
Note: If you’re already familiar with CMake, you may find the ESP-IDF CMake-based build system unusual
because it wraps a lot of CMake’s functionality to reduce boilerplate. See writing pure CMake components for some
information about writing more “CMake style”components.
Flashing with ninja or make It’s possible to build and flash directly from ninja or make by running a target like:
ninja flash
Or:
make app-flash
Available targets are: flash, app-flash (app only), bootloader-flash (bootloader only).
When flashing this way, optionally set the ESPPORT and ESPBAUD environment variables to specify the serial port
and baud rate. You can set environment variables in your operating system or IDE project. Alternatively, set them
directly on the command line:
Note: Providing environment variables at the start of the command like this is Bash shell Syntax. It will work on
Linux and macOS. It won’t work when using Windows Command Prompt, but it will work when using Bash-like
shells on Windows.
Or:
Note: Providing variables at the end of the command line is make syntax, and works for make on all platforms.
You can also use an IDE with CMake integration. The IDE will want to know the path to the project’s CMake-
Lists.txt file. IDEs with CMake integration often provide their own build tools (CMake calls these“generators”
) to build the source files as part of the IDE.
When adding custom non-build steps like “flash”to the IDE, it is recommended to execute idf.py for these
“special”commands.
For more detailed information about integrating ESP-IDF with CMake into an IDE, see Build System Metadata.
Possible issues The user of idf.py may sometimes experience ImportError described below.
import kconfiglib
ImportError: bad magic number in 'kconfiglib': b'\x03\xf3\r\n'
The exception is often caused by .pyc files generated by different Python versions. To solve the issue run the
following command:
idf.py python-clean
- myProject/
- CMakeLists.txt
- sdkconfig
- components/ - component1/ - CMakeLists.txt
- Kconfig
- src1.c
- component2/ - CMakeLists.txt
- Kconfig
- src1.c
- include/ - component2.h
- main/ - CMakeLists.txt
- src1.c
- src2.c
- build/
Each project has a single top-level CMakeLists.txt file that contains build settings for the entire project. By
default, the project CMakeLists can be quite minimal.
Minimal project:
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(myProject)
Mandatory Parts
The inclusion of these three lines, in the order shown above, is necessary for every project:
• cmake_minimum_required(VERSION 3.16) tells CMake the minimum version that is required to
build the project. ESP-IDF is designed to work with CMake 3.16 or newer. This line must be the first line in
the CMakeLists.txt file.
• include($ENV{IDF_PATH}/tools/cmake/project.cmake) pulls in the rest of the CMake
functionality to configure the project, discover all the components, etc.
• project(myProject) creates the project itself, and specifies the project name. The project name is used
for the final binary output files of the app - ie myProject.elf, myProject.bin. Only one project can
be defined per CMakeLists file.
These variables all have default values that can be overridden for custom behaviour. Look in
/tools/cmake/project.cmake for all of the implementation details.
• COMPONENT_DIRS: Directories to search for components. Defaults to IDF_PATH/components,
PROJECT_DIR/components, and EXTRA_COMPONENT_DIRS. Override this variable if you don’t
want to search for components in these places.
• EXTRA_COMPONENT_DIRS: Optional list of additional directories to search for components. Paths can be
relative to the project directory, or absolute.
• COMPONENTS: A list of component names to build into the project. Defaults to all components found in the
COMPONENT_DIRS directories. Use this variable to“trim down”the project for faster build times. Note that
any component which “requires”another component via the REQUIRES or PRIV_REQUIRES arguments
on component registration will automatically have it added to this list, so the COMPONENTS list can be very
short.
Any paths in these variables can be absolute paths, or set relative to the project directory.
To set these variables, use the cmake set command ie set(VARIABLE "VALUE"). The set() commands
should be placed after the cmake_minimum(...) line but before the include(...) line.
The build system provides special treatment to the main component. It is a component that gets automatically added
to the build provided that it is in the expected location, PROJECT_DIR/main. All other components in the build are
also added as its dependencies, saving the user from hunting down dependencies and providing a build that works right
out of the box. Renaming the main component causes the loss of these behind-the-scenes heavy lifting, requiring the
user to specify the location of the newly renamed component and manually specifying its dependencies. Specifically,
the steps to renaming main are as follows:
1. Rename main directory.
2. Set EXTRA_COMPONENT_DIRS in the project CMakeLists.txt to include the renamed main directory.
3. Specify the dependencies in the renamed component’s CMakeLists.txt file via REQUIRES or
PRIV_REQUIRES arguments on component registration.
The build sets some global build specifications (compile flags, definitions, etc.) that gets used in compiling all sources
from all components.
For example, one of the default build specifications set is the compile option -Wextra. Suppose a user wants to use
override this with -Wno-extra, it should be done after project():
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(myProject)
This ensures that the compile options set by the user won’t be overriden by the default build specifications, since the
latter are set inside project().
Each project contains one or more components. Components can be part of ESP-IDF, part of the project’s own
components directory, or added from custom component directories (see above).
A component is any directory in the COMPONENT_DIRS list which contains a CMakeLists.txt file.
The list of directories in COMPONENT_DIRS is searched for the project’s components. Directories in this list can
either be components themselves (ie they contain a CMakeLists.txt file), or they can be top-level directories whose
sub-directories are components.
When CMake runs to configure the project, it logs the components included in the build. This list can be useful for
debugging the inclusion/exclusion of certain components.
When ESP-IDF is collecting all the components to compile, it will do this in the order specified by COMPO-
NENT_DIRS; by default, this means ESP-IDF’s internal components first (IDF_PATH/components), then
any components in directories specified in EXTRA_COMPONENT_DIRS, and finally the project’s components
(PROJECT_DIR/components). If two or more of these directories contain component sub-directories with the
same name, the component in the last place searched is used. This allows, for example, overriding ESP-IDF com-
ponents with a modified version by copying that component from the ESP-IDF components directory to the project
components directory and then modifying it there. If used in this way, the ESP-IDF directory itself can remain
untouched.
Note: If a component is overridden in an existing project by moving it to a new location, the project will not
automatically see the new component path. Run idf.py reconfigure (or delete the project build folder) and
then build again.
The minimal component CMakeLists.txt file simply registers the component to the build system using
idf_component_register:
• SRCS is a list of source files (*.c, *.cpp, *.cc, *.S). These source files will be compiled into the com-
ponent library.
• INCLUDE_DIRS is a list of directories to add to the global include search path for any component which
requires this component, and also the main source files.
• REQUIRES is not actually required, but it is very often required to declare what other components this com-
ponent will use. See Component Requirements.
A library with the name of the component will be built and linked into the final app.
Directories are usually specified relative to the CMakeLists.txt file itself, although they can be absolute.
There are other arguments that can be passed to idf_component_register. These arguments are discussed
here.
See example component requirements and example component CMakeLists for more complete component CMake-
Lists.txt examples.
The following component-specific variables are available for use inside component CMakeLists, but should not be
modified:
• COMPONENT_DIR: The component directory. Evaluates to the absolute path of the directory con-
taining CMakeLists.txt. The component path cannot contain spaces. This is the same as the
CMAKE_CURRENT_SOURCE_DIR variable.
• COMPONENT_NAME: Name of the component. Same as the name of the component directory.
• COMPONENT_ALIAS: Alias of the library created internally by the build system for the component.
• COMPONENT_LIB: Name of the library created internally by the build system for the component.
The following variables are set at the project level, but available for use in component CMakeLists:
• CONFIG_*: Each value in the project configuration has a corresponding variable available in cmake. All
names begin with CONFIG_. More information here.
• ESP_PLATFORM: Set to 1 when the CMake file is processed within ESP-IDF build system.
Build/Project Variables
The following are some project/build variables that are available as build properties and whose values can be queried
using idf_build_get_property from the component CMakeLists.txt:
• PROJECT_NAME: Name of the project, as set in project CMakeLists.txt file.
• PROJECT_DIR: Absolute path of the project directory containing the project CMakeLists. Same as the
CMAKE_SOURCE_DIR variable.
• COMPONENTS: Names of all components that are included in this build, formatted as a semicolon-delimited
CMake list.
• IDF_VER: Git version of ESP-IDF (produced by git describe)
• IDF_VERSION_MAJOR, IDF_VERSION_MINOR, IDF_VERSION_PATCH: Components of ESP-IDF
version, to be used in conditional expressions. Note that this information is less precise than that provided
by IDF_VER variable. v4.0-dev-*, v4.0-beta1, v4.0-rc1 and v4.0 will all have the same values
of IDF_VERSION_* variables, but different IDF_VER values.
• IDF_TARGET: Name of the target for which the project is being built.
• PROJECT_VER: Project version.
– If CONFIG_APP_PROJECT_VER_FROM_CONFIG option is set, the value of CON-
FIG_APP_PROJECT_VER will be used.
– Else, if PROJECT_VER variable is set in project CMakeLists.txt file, its value will be used.
– Else, if the PROJECT_DIR/version.txt exists, its contents will be used as PROJECT_VER.
– Else, if the project is located inside a Git repository, the output of git describe will be used.
– Otherwise, PROJECT_VER will be “1”.
Other build properties are listed here.
To pass compiler options when compiling source files belonging to a particular component, use the tar-
get_compile_options function:
To apply the compilation flags to a single source file, use the CMake set_source_files_properties command:
set_source_files_properties(mysrc.c
PROPERTIES COMPILE_FLAGS
-Wno-unused-variable
)
Each component can also have a Kconfig file, alongside CMakeLists.txt. This contains configuration settings
to add to the configuration menu for this component.
These settings are found under the “Component Settings”menu when menuconfig is run.
To create a component Kconfig file, it is easiest to start with one of the Kconfig files distributed with ESP-IDF.
For an example, see Adding conditional configuration.
The ESP-IDF build system adds the following C preprocessor definitions on the command line:
• ESP_PLATFORM : Can be used to detect that build happens within ESP-IDF.
• IDF_VER : Defined to a git version string. E.g. v2.0 for a tagged release or v1.0-275-g0efaa4f for
an arbitrary commit.
When compiling each component, the ESP-IDF build system recursively evaluates its dependencies. This means each
component needs to declare the components that it depends on (“requires”).
idf_component_register(...
REQUIRES mbedtls
PRIV_REQUIRES console spiffs)
• REQUIRES should be set to all components whose header files are #included from the public header files of
this component.
• PRIV_REQUIRES should be set to all components whose header files are #included from any source files in
this component, unless already listed in REQUIRES. Also any component which is required to be linked in
order for this component to function correctly.
• The values of REQUIRES and PRIV_REQUIRES should not depend on any configuration choices (CON-
FIG_xxx macros). This is because requirements are expanded before configuration is loaded. Other compo-
nent variables (like include paths or source files) can depend on configuration choices.
• Not setting either or both REQUIRES variables is fine. If the component has no requirements except for the
Common component requirements needed for RTOS, libc, etc.
If a components only supports some target chips (values of IDF_TARGET) then it can specify RE-
QUIRED_IDF_TARGETS in the idf_component_register call to express these requirements. In this case
the build system will generate an error if the component is included into the build, but does not support the selected
target.
Note: In CMake terms, REQUIRES & PRIV_REQUIRES are approximate wrappers around the CMake functions
target_link_libraries(... PUBLIC ...) and target_link_libraries(... PRIVATE .
..).
Imagine there is a car component, which uses the engine component, which uses the spark_plug component:
- autoProject/
- CMakeLists.txt
- components/ - car/ - CMakeLists.txt
- car.c
- car.h
- engine/ - CMakeLists.txt
- engine.c
- include/ - engine.h
- spark_plug/ - CMakeLists.txt
- spark_plug.c
- spark_plug.h
Car component The car.h header file is the public interface for the car component. This header includes
engine.h directly because it uses some declarations from this header:
/* car.h */
#include "engine.h"
#ifdef ENGINE_IS_HYBRID
#define CAR_MODEL "Hybrid"
#endif
/* car.c */
#include "car.h"
This means the car/CMakeLists.txt file needs to declare that car requires engine:
idf_component_register(SRCS "car.c"
INCLUDE_DIRS "."
REQUIRES engine)
Engine component The engine component also has a public header file include/engine.h, but this header
is simpler:
/* engine.h */
#define ENGINE_IS_HYBRID
void engine_start(void);
/* engine.c */
#include "engine.h"
#include "spark_plug.h"
...
In this component, engine depends on spark_plug but this is a private dependency. spark_plug.h is needed
to compile engine.c, but not needed to include engine.h.
This means that the engine/CMakeLists.txt file can use PRIV_REQUIRES:
idf_component_register(SRCS "engine.c"
INCLUDE_DIRS "include"
PRIV_REQUIRES spark_plug)
As a result, source files in the car component don’t need the spark_plug include directories added to their
compiler search path. This can speed up compilation, and stops compiler command lines from becoming longer than
necessary.
Spark Plug Component The spark_plug component doesn’t depend on anything else. It has a public header
file spark_plug.h, but this doesn’t include headers from any other components.
This means that the spark_plug/CMakeLists.txt file doesn’t need any REQUIRES or PRIV_REQUIRES
clauses:
idf_component_register(SRCS "spark_plug.c"
INCLUDE_DIRS ".")
Each component’s source file is compiled with these include path directories, as specified in the passed arguments
to idf_component_register:
idf_component_register(..
INCLUDE_DIRS "include"
PRIV_INCLUDE_DIRS "other")
The component named main is special because it automatically requires all other components in the build. So it’s
not necessary to pass REQUIRES or PRIV_REQUIRES to this component. See renaming main for a description of
what needs to be changed if no longer using the main component.
To avoid duplication, every component automatically requires some “common”IDF components even if they are
not mentioned explicitly. Headers from these components can always be included.
The list of common components is: cxx, newlib, freertos, esp_hw_support, heap, log, soc, hal, esp_rom,
esp_common, esp_system, xtensa/riscv.
Circular Dependencies
It’s possible for a project to contain Component A that requires (REQUIRES or PRIV_REQUIRES) Component
B, and Component B that requires Component A. This is known as a dependency cycle or a circular dependency.
CMake will usually handle circular dependencies automatically by repeating the component library names twice on
the linker command line. However this strategy doesn’t always work, and it’s possible the build will fail with a
linker error about “Undefined reference to …”, referencing a symbol defined by one of the components inside the
circular dependency. This is particularly likely if there is a large circular dependency, i.e. A->B->C->D->A.
The best solution is to restructure the components to remove the circular dependency. In most cases, a software
architecture without circular dependencies has desirable properties of modularity and clean layering and will be more
maintainable in the long term. However, removing circular dependencies is not always possible.
To bypass a linker error caused by a circular dependency, the simplest workaround is to increase the CMake
LINK_INTERFACE_MULTIPLICITY property of one of the component libraries. This causes CMake to repeat
this library and its dependencies more than two times on the linker command line.
For example:
• This line should be placed after idf_component_register in the component CMakeLists.txt file.
• If possible, place this line in the component that creates the circular dependency by depending on a lot of
other components. However, the line can be placed inside any component that is part of the cycle. Choosing
the component that owns the source file shown in the linker error message, or the component that defines the
symbol(s) mentioned in the linker error message, is a good place to start.
• Usually increasing the value to 3 (default is 2) is enough, but if this doesn’t work then try increasing the
number further.
• Adding this option will make the linker command line longer, and the linking stage slower.
Advanced Workaround: Undefined Symbols If only one or two symbols is causing a circular dependency, and all
other dependencies are linear, then there is an alternative method to avoid linker errors: Specify the specific symbols
required for the “reverse”dependency as undefined symbols at link time.
For example, if component A depends on component B but component B also needs to reference reverse_ops
from component A (but nothing else), then you can add a line like the following to the component B CMakeLists.txt
to resolve the cycle at link time:
• The -u argument means that the linker will always include this symbol in the link, regardless of dependency
ordering.
• This line should be placed after idf_component_register in the component CMakeLists.txt file.
• If‘Component B’doesn’t need to access any headers of‘Component A’, only link to a few symbol(s), then
this line can be used instead of any REQUIRES from B to A. This further simplifies the component structure
in the build system.
See the target_link_libraries documentation for more information about this CMake function.
• Very early in the CMake configuration process, the script expand_requirements.cmake is run. This
script does a partial evaluation of all component CMakeLists.txt files and builds a graph of component require-
ments (this graph may have cycles). The graph is used to generate a file component_depends.cmake in
the build directory.
• The main CMake process then includes this file and uses it to determine the list of components to include
in the build (internal BUILD_COMPONENTS variable). The BUILD_COMPONENTS variable is sorted so
dependencies are listed first, however as the component dependency graph has cycles this cannot be guaranteed
for all components. The order should be deterministic given the same set of components and component
dependencies.
• The value of BUILD_COMPONENTS is logged by CMake as “Component names: “
• Configuration is then evaluated for the components included in the build.
• Each component is included in the build normally and the CMakeLists.txt file is evaluated again to add the
component libraries to the build.
Component Dependency Order The order of components in the BUILD_COMPONENTS variable determines
other orderings during the build:
• Order that project_include.cmake files are included into the project.
• Order that the list of header paths is generated for compilation (via -I argument). (Note that for a given
component’s source files, only that component’s dependency’s header paths are passed to the compiler.)
project_include.cmake
For components that have build requirements which must be evaluated before any component CMakeLists files are
evaluated, you can create a file called project_include.cmake in the component directory. This CMake file
is included when project.cmake is evaluating the entire project.
project_include.cmake files are used inside ESP-IDF, for defining project-wide build features such as es-
ptool.py command line arguments and the bootloader “special app”.
Unlike component CMakeLists.txt files, when including a project_include.cmake file the current
source directory (CMAKE_CURRENT_SOURCE_DIR and working directory) is the project directory. Use the vari-
able COMPONENT_DIR for the absolute directory of the component.
Note that project_include.cmake isn’t necessary for the most common component uses - such as adding
include directories to the project, or LDFLAGS to the final linking step. These values can be customised via the
CMakeLists.txt file itself. See Optional Project Variables for details.
project_include.cmake files are included in the order given in BUILD_COMPONENTS variable (as logged
by CMake). This means that a component’s project_include.cmake file will be included after it’s all
dependencies’project_include.cmake files, unless both components are part of a dependency cycle. This
is important if a project_include.cmake file relies on variables set by another component. See also above.
Take great care when setting variables or targets in a project_include.cmake file. As the values are included
into the top-level project CMake pass, they can influence or break functionality across all components!
KConfig.projbuild
This is an equivalent to project_include.cmake for Component Configuration KConfig files. If you want
to include configuration options at the top-level of menuconfig, rather than inside the “Component Configuration”
sub-menu, then these can be defined in the KConfig.projbuild file alongside the CMakeLists.txt file.
Take care when adding configuration values in this file, as they will be included across the entire project configuration.
Where possible, it’s generally better to create a KConfig file for Component Configuration.
project_include.cmake files are used inside ESP-IDF, for defining project-wide build features such as es-
ptool.py command line arguments and the bootloader “special app”.
Special components which contain no source files, only Kconfig.projbuild and KConfig, can have a one-line
CMakeLists.txt file which calls the function idf_component_register() with no arguments specified.
This function will include the component in the project build, but no library will be built and no header files will be
added to any include paths.
For full details about CMake and CMake commands, see the CMake v3.16 documentation.
Some tips for debugging the ESP-IDF CMake-based build system:
• When CMake runs, it prints quite a lot of diagnostic information including lists of components and component
paths.
• Running cmake -DDEBUG=1 will produce more verbose diagnostic output from the IDF build system.
• Running cmake with the --trace or --trace-expand options will give a lot of information about
control flow. See the cmake command line documentation.
When included from a project CMakeLists file, the project.cmake file defines some utility modules and global
variables and then sets IDF_PATH if it was not set in the system environment.
It also defines an overridden custom version of the built-in CMake project function. This function is overridden
to add all of the ESP-IDF specific project functionality.
By default, idf.py passes the --warn-uninitialized flag to CMake so it will print a warning if an undefined
variable is referenced in the build. This can be very useful to find buggy CMake files.
If you don’t want this behaviour, it can be disabled by passing --no-warnings to idf.py.
Browse the /tools/cmake/project.cmake file and supporting functions in /tools/cmake/ for more details.
Because the build environment tries to set reasonable defaults that will work most of the time, component CMake-
Lists.txt can be very small or even empty (see Minimal Component CMakeLists). However, overriding pre-
set_component_variables is usually required for some functionality.
Here are some more advanced examples of component CMakeLists files.
The configuration system can be used to conditionally compile some files depending on the options selected in the
project configuration.
Kconfig:
config FOO_ENABLE_BAR
bool "Enable the BAR feature."
help
This enables the BAR feature of the FOO component.
CMakeLists.txt:
if(CONFIG_FOO_ENABLE_BAR)
list(APPEND srcs "bar.c")
endif()
idf_component_register(SRCS "${srcs}"
...)
This example makes use of the CMake if function and list APPEND function.
This can also be used to select or stub out an implementation, as such:
Kconfig:
config ENABLE_LCD_OUTPUT
bool "Enable LCD output."
help
Select this if your board has a LCD.
config ENABLE_LCD_CONSOLE
bool "Output console text to LCD"
depends on ENABLE_LCD_OUTPUT
help
Select this to output debugging output to the lcd
config ENABLE_LCD_PLOT
bool "Output temperature plots to LCD"
depends on ENABLE_LCD_OUTPUT
help
Select this to output temperature plots
CMakeLists.txt:
if(CONFIG_ENABLE_LCD_OUTPUT)
set(srcs lcd-real.c lcd-spi.c)
else()
set(srcs lcd-dummy.c)
endif()
idf_component_register(SRCS "${srcs}"
...)
Some components will have a situation where a source file isn’t supplied with the component itself but has to be
generated from another file. Say our component has a header file that consists of the converted binary data of a BMP
file, converted using a hypothetical tool called bmp2h. The header file is then included in as C source file called
graphics_lib.c:
add_custom_command(OUTPUT logo.h
COMMAND bmp2h -i ${COMPONENT_DIR}/logo.bmp -o log.h
DEPENDS ${COMPONENT_DIR}/logo.bmp
VERBATIM)
This answer is adapted from the CMake FAQ entry, which contains some other examples that will also work with
ESP-IDF builds.
In this example, logo.h will be generated in the current directory (the build directory) while logo.bmp comes with the
component and resides under the component path. Because logo.h is a generated file, it should be cleaned when the
project is cleaned. For this reason it is added to the ADDITIONAL_MAKE_CLEAN_FILES property.
Note: If generating files as part of the project CMakeLists.txt file, not a component CMakeLists.txt, then use build
property PROJECT_DIR instead of ${COMPONENT_DIR} and ${PROJECT_NAME}.elf instead of ${COM-
PONENT_LIB}.)
If a a source file from another component included logo.h, then add_dependencies would need to be called
to add a dependency between the two components, to ensure that the component source files were always compiled
in the correct order.
Sometimes you have a file with some binary or text data that you’d like to make available to your component - but
you don’t want to reformat the file as C source.
You can specify argument EMBED_FILES in the component registration, giving space-delimited names of the files
to embed:
idf_component_register(...
EMBED_FILES server_root_cert.der)
Or if the file is a string, you can use the variable EMBED_TXTFILES. This will embed the contents of the text file
as a null-terminated string:
idf_component_register(...
EMBED_TXTFILES server_root_cert.pem)
The file’s contents will be added to the .rodata section in flash, and are available via symbol names as follows:
The names are generated from the full name of the file, as given in EMBED_FILES. Characters /, ., etc. are replaced
with underscores. The _binary prefix in the symbol name is added by objcopy and is the same for both text and binary
files.
To embed a file into a project, rather than a component, you can call the function target_add_binary_data
like this:
Place this line after the project() line in your project CMakeLists.txt file. Replace myproject.elf with your
project name. The final argument can be TEXT to embed a null-terminated string, or BINARY to embed the content
as-is.
For an example of using this technique, see the “main”component of the file_serving example proto-
cols/http_server/file_serving/main/CMakeLists.txt - two files are loaded at build time and linked into the firmware.
It is also possible embed a generated file:
add_custom_command(OUTPUT my_processed_file.bin
COMMAND my_process_file_cmd my_unprocessed_file.bin)
target_add_binary_data(my_target "my_processed_file.bin" BINARY)
The DEPENDS argument to target_add_binary_data ensures that the target executes first.
ESP-IDF has a feature called linker script generation that enables components to define where its code and data will
be placed in memory through linker fragment files. These files are processed by the build system, and is used to
augment the linker script used for linking app binary. See Linker Script Generation for a quick start guide as well as
a detailed discussion of the mechanism.
Obviously, there are cases where all these recipes are insufficient for a certain component, for example when the
component is basically a wrapper around another third-party component not originally intended to be compiled under
this build system. In that case, it’s possible to forego the ESP-IDF build system entirely by using a CMake feature
called ExternalProject. Example component CMakeLists:
(The above CMakeLists.txt can be used to create a component named quirc that builds the quirc project using its
own Makefile.)
• externalproject_add defines an external build system.
– SOURCE_DIR, CONFIGURE_COMMAND, BUILD_COMMAND and INSTALL_COMMAND should al-
ways be set. CONFIGURE_COMMAND can be set to an empty string if the build system has no“configure”
step. INSTALL_COMMAND will generally be empty for ESP-IDF builds.
– Setting BUILD_IN_SOURCE means the build directory is the same as the source directory. Otherwise
you can set BUILD_DIR.
– Consult the ExternalProject documentation for more details about externalproject_add()
• The second set of commands adds a library target, which points to the “imported”library file built by the
external system. Some properties need to be set in order to add include directories and tell CMake where this
file is.
• Finally, the generated library is added to ADDITIONAL_MAKE_CLEAN_FILES. This means make
clean will delete this library. (Note that the other object files from the build won’t be deleted.)
Note: When using an external build process with PSRAM, remember to add
-mfix-esp32-psram-cache-issue to the C compiler arguments. See CON-
FIG_SPIRAM_CACHE_WORKAROUND for details of this flag.
ExternalProject dependencies, clean builds CMake has some unusual behaviour around external project builds:
• ADDITIONAL_MAKE_CLEAN_FILES only works when “make”is used as the build system. If Ninja or
an IDE build system is used, it won’t delete these files when cleaning.
• However, the ExternalProject configure & build commands will always be re-run after a clean is run.
• Therefore, there are two alternative recommended ways to configure the external build command:
1. Have the external BUILD_COMMAND run a full clean compile of all sources. The build command will
be run if any of the dependencies passed to externalproject_add with DEPENDS have changed,
or if this is a clean build (ie any of idf.py clean, ninja clean, or make clean was run.)
2. Have the external BUILD_COMMAND be an incremental build command. Pass the parameter
BUILD_ALWAYS 1 to externalproject_add. This means the external project will be built
each time a build is run, regardless of dependencies. This is only recommended if the external project
has correct incremental build behaviour, and doesn’t take too long to run.
The best of these approaches for building an external project will depend on the project itself, its build system, and
whether you anticipate needing to frequently recompile the project.
For example projects or other projects where you don’t want to specify a full sdkconfig configuration, but you do
want to override some key values from the ESP-IDF defaults, it is possible to create a file sdkconfig.defaults
in the project directory. This file will be used when creating a new config from scratch, or when any new config value
hasn’t yet been set in the sdkconfig file.
To override the name of this file or to specify multiple files, set the SDKCONFIG_DEFAULTS environment variable
or set SDKCONFIG_DEFAULTS in top-level CMakeLists.txt. File names that are not specified as full paths
are resolved relative to current project’s diretory.
When specifying multiple files, use a semicolon as the list separator. Files listed first will be applied first. If a
particular key is defined in multiple files, the definition in the latter file will overide definitions from former files.
Some of the IDF examples include a sdkconfig.ci file. This is part of the continuous integration (CI) test
framework and is ignored by the normal build process.
In addition to sdkconfig.defaults file, build system will also load defaults from sdkconfig.defaults.
TARGET_NAME file, where TARGET_NAME is the value of IDF_TARGET. For example, for esp32 target, default
settings will be taken from sdkconfig.defaults first, and then from sdkconfig.defaults.esp32.
If SDKCONFIG_DEFAULTS is used to override the name of defaults file/files, the name of target-specific defaults
file will be derived from SDKCONFIG_DEFAULTS value/values using the rule above. When there are multiple files
in SDKCONFIG_DEFAULTS, target-specific file will be applied right after the file bringing it in, before all latter files
in SDKCONFIG_DEFAULTS
For example, if SDKCONFIG_DEFAULTS="sdkconfig.defaults;sdkconfig_devkit1", and there is
a file sdkconfig.defaults.esp32 in the same folder, then the files will be applied in the following order: (1)
sdkconfig.defaults (2) sdkconfig.defaults.esp32 (3) sdkconfig_devkit1.
There are some scenarios that we want to flash the target board without IDF. For this case we want to save the built
binaries, esptool.py and esptool write_flash arguments. It’s simple to write a script to save binaries and esptool.py.
After running a project build, the build directory contains binary output files (.bin files) for the project and also the
following flashing data files:
• flash_project_args contains arguments to flash the entire project (app, bootloader, partition table,
PHY data if this is configured).
• flash_app_args contains arguments to flash only the app.
• flash_bootloader_args contains arguments to flash only the bootloader.
You can pass any of these flasher argument files to esptool.py as follows:
Alternatively, it is possible to manually copy the parameters from the argument file and pass them on the command
line.
The build directory also contains a generated file flasher_args.json which contains project flash information,
in JSON format. This file is used by idf.py and can also be used by other tools which need information about the
project build.
The bootloader is a special “subproject”inside /components/bootloader/subproject. It has its own project CMake-
Lists.txt file and builds separate .ELF and .BIN files to the main project. However it shares its configuration and build
directory with the main project.
The subproject is inserted as an external project from the top-level project, by the file /compo-
nents/bootloader/project_include.cmake. The main build process runs CMake for the subproject, which includes
discovering components (a subset of the main components) and generating a bootloader-specific config (derived
from the main sdkconfig).
The ESP-IDF build system“wraps”CMake with the concept of“components”, and helper functions to automatically
integrate these components into a project build.
However, underneath the concept of “components”is a full CMake build system. It is also possible to make a
component which is pure CMake.
Here is an example minimal “pure CMake”component CMakeLists file for a component named json:
add_library(json STATIC
cJSON/cJSON.c
cJSON/cJSON_Utils.c)
CMake is used for a lot of open-source C and C++ projects —code that users can tap into for their applications.
One of the benefits of having a CMake build system is the ability to import these third-party projects, sometimes
even without modification! This allows for users to be able to get functionality that may not yet be provided by a
component, or use another library for the same functionality.
Importing a library might look like this for a hypothetical library foo to be used in the main component:
For an actual example, take a look at build_system/cmake/import_lib. Take note that what needs to be done in order
to import the library may vary. It is recommended to read up on the library’s documentation for instructions on
how to import it from other projects. Studying the library’s CMakeLists.txt and build structure can also be helpful.
It is also possible to wrap a third-party library to be used as a component in this manner. For example, the mbedtls
component is a wrapper for Espressif’s fork of mbedtls. See its component CMakeLists.txt .
The CMake variable ESP_PLATFORM is set to 1 whenever the ESP-IDF build system is being used. Tests such as
if (ESP_PLATFORM) can be used in generic CMake code if special IDF-specific logic is required.
The above example assumes that the external library foo (or tinyxml in the case of the import_lib example)
doesn’t need to use any ESP-IDF APIs apart from common APIs such as libc, libstdc++, etc. If the external library
needs to use APIs provided by other ESP-IDF components, this needs to be specified in the external CMakeLists.txt
file by adding a dependency on the library target idf::<componentname>.
For example, in the foo/CMakeLists.txt file:
add_library(foo bar.c fizz.cpp buzz.cpp)
if(ESP_PLATFORM)
# On ESP-IDF, bar.c needs to include esp_flash.h from the spi_flash component
target_link_libraries(foo PRIVATE idf::spi_flash)
endif()
Another possibility is that you have a prebuilt static library (.a file), built by some other build process.
The ESP-IDF build system provides a utility function add_prebuilt_library for users to be able to easily
import and use prebuilt libraries:
add_prebuilt_library(target_name lib_path [REQUIRES req1 req2 ...] [PRIV_REQUIRES␣
,→req1 req2 ...])
where:
• target_name- name that can be used to reference the imported library, such as when linking to other targets
• lib_path- path to prebuilt library; may be an absolute or relative path to the component directory
Optional arguments REQUIRES and PRIV_REQUIRES specify dependency on other components. These have the
same meaning as the arguments for idf_component_register.
Take note that the prebuilt library must have been compiled for the same target as the consuming project. Configu-
ration relevant to the prebuilt library must also match. If not paid attention to, these two factors may contribute to
subtle bugs in the app.
For an example, take a look at build_system/cmake/import_prebuilt.
ESP-IDF provides a template CMake project for easily creating an application. However, in some instances the user
might already have an existing CMake project or may want to create a custom one. In these cases it is desirable to be
able to consume IDF components as libraries to be linked to the user’s targets (libraries/ executables).
It is possible to do so by using the build system APIs provided by tools/cmake/idf.cmake. For example:
cmake_minimum_required(VERSION 3.16)
project(my_custom_app C)
# Include CMake file that provides ESP-IDF CMake build system APIs.
include($ENV{IDF_PATH}/tools/cmake/idf.cmake)
# Create the project executable and plainly link the newlib component to it using
(continues on next page)
# Let the build system know what the project executable is to attach more targets,␣
,→dependencies, etc.
idf_build_executable(${CMAKE_PROJECT_NAME}.elf)
The example in build_system/cmake/idf_as_lib demonstrates the creation of an application equivalent to hello world
application using a custom CMake project.
Note: The IDF build system can only set compiler flags for source files that it builds. When an external CMake-
Lists.txt file is used and PSRAM is enabled, remember to add -mfix-esp32-psram-cache-issue to the C
compiler arguments. See CONFIG_SPIRAM_CACHE_WORKAROUND for details of this flag.
idf-build-commands
Retrieve a build property property and store it in var accessible from the current scope. Specifying GENERA-
TOR_EXPRESSION will retrieve the generator expression string for that property, instead of the actual value, which
can be used with CMake commands that support generator expressions.
Set a build property property with value val. Specifying APPEND will append the specified value to the current value
of the property. If the property does not previously exist or it is currently empty, the specified value becomes the first
element/member instead.
idf_build_component(component_dir)
Present a directory component_dir that contains a component to the build system. Relative paths are converted to ab-
solute paths with respect to current directory. All calls to this command must be performed before idf_build_process.
This command does not guarantee that the component will be processed during build (see the COMPONENTS argu-
ment description for idf_build_process)
idf_build_process(target
[PROJECT_DIR project_dir]
[PROJECT_VER project_ver]
[PROJECT_NAME project_name]
[SDKCONFIG sdkconfig]
[SDKCONFIG_DEFAULTS sdkconfig_defaults]
[BUILD_DIR build_dir]
[COMPONENTS component1 component2 ...])
Performs the bulk of the behind-the-scenes magic for including ESP-IDF components such as component configu-
ration, libraries creation, dependency expansion and resolution. Among these functions, perhaps the most important
from a user’s perspective is the libraries creation by calling each component’s idf_component_register.
This command creates the libraries for each component, which are accessible using aliases in the form
idf::component_name. These aliases can be used to link the components to the user’s own targets, either libraries
or executables.
The call requires the target chip to be specified with target argument. Optional arguments for the call include:
• PROJECT_DIR - directory of the project; defaults to CMAKE_SOURCE_DIR
idf_build_executable(executable)
Specify the executable executable for ESP-IDF build. This attaches additional targets such as dependencies related
to flashing, generating additional binary files, etc. Should be called after idf_build_process.
Get the value of the specified config. Much like build properties, specifying GENERATOR_EXPRESSION will retrieve
the generator expression string for that config, instead of the actual value, which can be used with CMake commands
that support generator expressions. Actual config values are only known after call to idf_build_process,
however.
idf-build-properties
These are properties that describe the build. Values of build properties can be retrieved by using the build command
idf_build_get_property. For example, to get the Python interpreter used for the build:
idf_build_get_property(python PYTHON)
message(STATUS "The Python intepreter is: ${python}")
idf-component-commands
Retrieve a specified component’s component property, property and store it in var accessible from the current scope.
Specifying GENERATOR_EXPRESSION will retrieve the generator expression string for that property, instead of the
actual value, which can be used with CMake commands that support generator expressions.
Set a specified component’s component property, property with value val. Specifying APPEND will append the
specified value to the current value of the property. If the property does not previously exist or it is currently empty,
the specified value becomes the first element/member instead.
Register a component to the build system. Much like the project() CMake command, this should be called
from the component’s CMakeLists.txt directly (not through a function or macro) and is recommended to be
called before any other command. Here are some guidelines on what commands can not be called before
idf_component_register:
• commands that are not valid in CMake script mode
• custom commands defined in project_include.cmake
• build system API commands except idf_build_get_property; although consider whether the property
may not have been set yet
Commands that set and operate on variables are generally okay to call before idf_component_register.
The arguments for idf_component_register include:
• SRCS - component source files used for creating a static library for the component; if not specified, component
is a treated as a config-only component and an interface library is created instead.
• SRC_DIRS, EXCLUDE_SRCS - used to glob source files (.c, .cpp, .S) by specifying directories, instead of
specifying source files manually via SRCS. Note that this is subject to the limitations of globbing in CMake.
Source files specified in EXCLUDE_SRCS are removed from the globbed files.
• INCLUDE_DIRS - paths, relative to the component directory, which will be added to the include search path
for all other components which require the current component
• PRIV_INCLUDE_DIRS - directory paths, must be relative to the component directory, which will be added
to the include search path for this component’s source files only
• REQUIRES - public component requirements for the component
• PRIV_REQUIRES - private component requirements for the component; ignored on config-only components
• LDFRAGMENTS - component linker fragment files
• REQUIRED_IDF_TARGETS - specify the only target the component supports
• KCONFIG - override the default Kconfig file
• KCONFIG_PROJBUILD - override the default Kconfig.projbuild file
• WHOLE_ARCHIVE - if specified, the component library is surrounded by -Wl,--whole-archive,
-Wl,--no-whole-archive when linked. This has the same effect as setting WHOLE_ARCHIVE com-
ponent property.
The following are used for embedding data into the component, and is considered as source files when determining if
a component is config-only. This means that even if the component does not specify source files, a static library is
still created internally for the component if it specifies either:
• EMBED_FILES - binary files to be embedded in the component
• EMBED_TXTFILES - text files to be embedded in the component
idf-component-properties
These are properties that describe a component. Values of component properties can be retrieved by using the build
command idf_component_get_property. For example, to get the directory of the freertos component:
• COMPONENT_ALIAS - alias for COMPONENT_LIB used for linking the component to external targets;
set by idf_build_component and alias library itself is created by idf_component_register
• COMPONENT_DIR - component directory; set by idf_build_component
• COMPONENT_OVERRIDEN_DIR - contains the directory of the original component if this component over-
rides another component
• COMPONENT_LIB - name for created component static/interface library; set by
idf_build_component and library itself is created by idf_component_register
• COMPONENT_NAME - name of the component; set by idf_build_component based on the compo-
nent directory name
• COMPONENT_TYPE - type of the component, whether LIBRARY or CONFIG_ONLY. A component is of
type LIBRARY if it specifies source files or embeds a file
• EMBED_FILES - list of files to embed in component; set from idf_component_register EM-
BED_FILES argument
• EMBED_TXTFILES - list of text files to embed in component; set from idf_component_register
EMBED_TXTFILES argument
• INCLUDE_DIRS - list of component include directories; set from idf_component_register IN-
CLUDE_DIRS argument
• KCONFIG - component Kconfig file; set by idf_build_component
• KCONFIG_PROJBUILD - component Kconfig.projbuild; set by idf_build_component
• LDFRAGMENTS - list of component linker fragment files; set from idf_component_register LD-
FRAGMENTS argument
• MANAGED_PRIV_REQUIRES - list of private component dependencies added by the IDF component man-
ager from dependencies in idf_component.yml manifest file
• MANAGED_REQUIRES - list of public component dependencies added by the IDF component manager
from dependencies in idf_component.yml manifest file
• PRIV_INCLUDE_DIRS - list of component private include directories; set from
idf_component_register PRIV_INCLUDE_DIRS on components of type LIBRARY
The preferred way to include source files in an ESP-IDF component is to list them manually via SRCS argument to
idf_component_register:
This preference reflects the CMake best practice of manually listing source files. This could, however, be inconvenient
when there are lots of source files to add to the build. The ESP-IDF build system provides an alternative way for
specifying source files using SRC_DIRS:
This uses globbing behind the scenes to find source files in the specified directories. Be aware, however, that if a new
source file is added and this method is used, then CMake won’t know to automatically re-run and this file won’t
be added to the build.
The trade-off is acceptable when you’re adding the file yourself, because you can trigger a clean build or run idf.
py reconfigure to manually re-run CMake. However, the problem gets harder when you share your project
with others who may check out a new version using a source control tool like Git…
For components which are part of ESP-IDF, we use a third party Git CMake integration module
(/tools/cmake/third_party/GetGitRevisionDescription.cmake) which automatically re-runs CMake any time the
repository commit changes. This means if you check out a new ESP-IDF version, CMake will automatically re-
run.
For project components (not part of ESP-IDF), there are a few different options:
• If keeping your project file in Git, ESP-IDF will automatically track the Git revision and re-run CMake if the
revision changes.
• If some components are kept in a third git repository (not the project repository or ESP-IDF repository), you
can add a call to the git_describe function in a component CMakeLists file in order to automatically
trigger re-runs of CMake when the Git revision changes.
• If not using Git, remember to manually run idf.py reconfigure whenever a source file may change.
• To avoid this problem entirely, use SRCS argument to idf_component_register to list all source files
in project components.
The best option will depend on your particular project and its users.
For integration into IDEs and other build systems, when CMake runs the build process generates a number of metadata
files in the build/ directory. To regenerate these files, run cmake or idf.py reconfigure (or any other
idf.py build command).
• compile_commands.json is a standard format JSON file which describes every source file which is
compiled in the project. A CMake feature generates this file, and many IDEs know how to parse it.
• project_description.json contains some general information about the ESP-IDF project, configured
paths, etc.
• flasher_args.json contains esptool.py arguments to flash the project’s binary files. There are also
flash_*_args files which can be used directly with esptool.py. See Flash arguments.
• CMakeCache.txt is the CMake cache file which contains other information about the CMake process,
toolchain, etc.
• config/sdkconfig.json is a JSON-formatted version of the project configuration values.
• config/kconfig_menus.json is a JSON-formatted version of the menus shown in menuconfig, for
use in external IDE UIs.
A tool called confserver.py is provided to allow IDEs to easily integrate with the configuration system logic.
confserver.py is designed to run in the background and interact with a calling process by reading and writing
JSON over process stdin & stdout.
You can run confserver.py from a project via idf.py confserver or ninja confserver, or a similar
target triggered from a different build generator.
For more information about confserver.py, see tools/kconfig_new/README.md.
Build Scripts
The listfiles for the ESP-IDF build system reside in /tools/cmake. The modules which implement core build system
functionality are as follows:
• build.cmake - Build related commands i.e. build initialization, retrieving/setting build properties,
build processing.
• component.cmake - Component related commands i.e. adding components, retrieving/setting
component properties, registering components.
• kconfig.cmake - Generation of configuration files (sdkconfig, sdkconfig.h, sdkconfig.cmake, etc.)
from Kconfig files.
• ldgen.cmake - Generation of final linker script from linker fragment files.
• target.cmake - Setting build target and toolchain file.
• utilities.cmake - Miscellaneous helper commands.
Aside from these files, there are two other important CMake scripts in /tools/cmake:
• idf.cmake - Sets up the build and includes the core modules listed above. Included in CMake
projects in order to access ESP-IDF build system functionality.
• project.cmake - Includes idf.cmake and provides a custom project() command that takes
care of all the heavy lifting of building an executable. Included in the top-level CMakeLists.txt of
standard ESP-IDF projects.
The rest of the files in /tools/cmake are support or third-party scripts used in the build process.
Build Process
This section describes the standard ESP-IDF application build process. The build process can be broken down roughly
into four phases:
Enumeration
This phase builds a final list of components to be processed in the build, and is performed in the first
half of idf_build_process().
• Retrieve each component’s public and private requirements. A child process is cre-
ated which executes each component’s CMakeLists.txt in script mode. The values
of idf_component_register REQUIRES and PRIV_REQUIRES argument is re-
turned to the parent build process. This is called early expansion. The variable
CMAKE_BUILD_EARLY_EXPANSION is defined during this step.
• Recursively include components based on public and private requirements.
Processing
This phase processes the components in the build, and is the second half of idf_build_process().
• Load project configuration from sdkconfig file and generate an sdkconfig.cmake and sdkconfig.h
header. These define configuration variables/macros that are accessible from the build scripts and
C/C++ source/header files, respectively.
• Include each component’s project_include.cmake.
• Add each component as a subdirectory, processing its CMakeLists.txt. The component CMake-
Lists.txt calls the registration command, idf_component_register which adds source files,
include directories, creates component library, links dependencies, etc.
Finalization
This phase is everything after idf_build_process().
• Create executable and link the component libraries to it.
• Generate project metadata files such as project_description.json and display relevant information
about the project built.
Browse /tools/cmake/project.cmake for more details.
Some aspects of the CMake-based ESP-IDF build system are very similar to the older GNU Make-based system. The
developer needs to provide values the include directories, source files etc. There is a syntactical difference, however,
as the developer needs to pass these as arguments to the registration command, idf_component_register.
An automatic project conversion tool is available in tools/cmake/convert_to_cmake.py in ESP-IDF v4.x releases. The
script was removed in v5.0 because of its make build system dependency.
Some features are significantly different or removed in the CMake-based system. The following variables no longer
exist in the CMake-based build system:
• COMPONENT_BUILD_DIR: Use CMAKE_CURRENT_BINARY_DIR instead.
• COMPONENT_LIBRARY: Defaulted to $(COMPONENT_NAME).a, but the library name could be overriden
by the component. The name of the component library can no longer be overriden by the component.
• CC, LD, AR, OBJCOPY: Full paths to each tool from the gcc xtensa cross-toolchain. Use
CMAKE_C_COMPILER, CMAKE_C_LINK_EXECUTABLE, CMAKE_OBJCOPY, etc instead. Full list here.
• HOSTCC, HOSTLD, HOSTAR: Full names of each tool from the host native toolchain. These are no longer
provided, external projects should detect any required host toolchain manually.
• COMPONENT_ADD_LDFLAGS: Used to override linker flags. Use the CMake target_link_libraries command
instead.
• COMPONENT_ADD_LINKER_DEPS: List of files that linking should depend on. target_link_libraries will
usually infer these dependencies automatically. For linker scripts, use the provided custom CMake function
target_linker_scripts.
• COMPONENT_SUBMODULES: No longer used, the build system will automatically enumerate all submodules
in the ESP-IDF repository.
• COMPONENT_EXTRA_INCLUDES: Used to be an alternative to COMPONENT_PRIV_INCLUDEDIRS for
absolute paths. Use PRIV_INCLUDE_DIRS argument to idf_component_register for all cases now
(can be relative or absolute).
• COMPONENT_OBJS: Previously, component sources could be specified as a list of object files. Now they can
be specified as a list of source files via SRCS argument to idf_component_register.
• COMPONENT_OBJEXCLUDE: Has been replaced with EXCLUDE_SRCS argument to
idf_component_register. Specify source files (as absolute paths or relative to component di-
rectory), instead.
• COMPONENT_EXTRA_CLEAN: Set property ADDITIONAL_MAKE_CLEAN_FILES instead but note
CMake has some restrictions around this functionality.
• COMPONENT_OWNBUILDTARGET & COMPONENT_OWNCLEANTARGET: Use CMake ExternalProject in-
stead. See Fully Overriding The Component Build Process for full details.
• COMPONENT_CONFIG_ONLY: Call idf_component_register without any arguments instead. See
Configuration-Only Components.
• CFLAGS, CPPFLAGS, CXXFLAGS: Use equivalent CMake commands instead. See Controlling Component
Compilation.
No Default Values
Unlike in the legacy Make-based build system, the following have no default values:
• Source directories (COMPONENT_SRCDIRS variable in Make, SRC_DIRS argument to
idf_component_register in CMake)
• Include directories (COMPONENT_ADD_INCLUDEDIRS variable in Make, INCLUDE_DIRS argument to
idf_component_register in CMake)
No Longer Necessary
• In the legacy Make-based build system, it is required to also set COMPONENT_SRCDIRS if COM-
PONENT_SRCS is set. In CMake, the equivalent is not necessary i.e. specifying SRC_DIRS to
idf_component_register if SRCS is also specified (in fact, SRCS is ignored if SRC_DIRS is speci-
fied).
make flash and similar targets still work to build and flash. However, project sdkconfig no longer specifies
serial port and baud rate. Environment variables can be used to override these. See Flashing with ninja or make for
more details.
4.6.1 Overview
ESP-IDF provides support to generate core dumps on unrecoverable software errors. This useful technique allows
post-mortem analysis of software state at the moment of failure. Upon the crash system enters panic state, prints some
information and halts or reboots depending configuration. User can choose to generate core dump in order to analyse
the reason of failure on PC later on. Core dump contains snapshots of all tasks in the system at the moment of failure.
Snapshots include tasks control blocks (TCB) and stacks. So it is possible to find out what task, at what instruction
(line of code) and what callstack of that task lead to the crash. It is also possible dumping variables content on demand
if previously attributed accordingly. ESP-IDF provides special script espcoredump.py to help users to retrieve and
analyse core dumps. This tool provides two commands for core dumps analysis:
• info_corefile - prints crashed task’s registers, callstack, list of available tasks in the system, memory
regions and contents of memory stored in core dump (TCBs and stacks)
• dbg_corefile - creates core dump ELF file and runs GDB debug session with this file. User can examine
memory, variables and tasks states manually. Note that since not all memory is saved in core dump only values
of variables allocated on stack will be meaningful
For more information about core dump internals see the - Core dump internals
4.6.2 Configurations
There are a number of core dump related configuration options which user can choose in project configuration menu
(idf.py menuconfig).
Core dump data destination (Components -> Core dump -> Data destination)
• Save core dump to Flash (Flash)
• Print core dump to UART (UART)
• Disable core dump generation (None)
Core dump data format (Components -> Core dump -> Core dump data format)
• ELF format (Executable and Linkable Format file for core dump)
When this option is selected core dumps are saved to special partition on flash. When using default partition table
files which are provided with ESP-IDF it automatically allocates necessary space on flash, But if user wants to use its
own layout file together with core dump feature it should define separate partition for core dump as it is shown below:
There are no special requirements for partition name. It can be chosen according to the user application needs, but
partition type should be ‘data’and sub-type should be ‘coredump’. Also when choosing partition size note that
core dump data structure introduces constant overhead of 20 bytes and per-task overhead of 12 bytes. This overhead
does not include size of TCB and stack for every task. So partition size should be at least 20 + max tasks number x
(12 + TCB size + max task stack size) bytes.
The example of generic command to analyze core dump from flash is:
or
When this option is selected base64-encoded core dumps are printed on UART upon system panic. In this case user
should save core dump text body to some file manually and then run the following command:
or
Base64-encoded body of core dump will be between the following header and footer:
The CORE DUMP START and CORE DUMP END lines must not be included in core dump text file.
It is possible situation that at the moment of crash some tasks or/and crashed task itself have one or more ROM
functions in their callstacks. Since ROM is not part of the program ELF it will be impossible for GDB to parse such
callstacks, because it tries to analyse functions’prologues to accomplish that. In that case callstack printing will be
broken with error message at the first ROM function. To overcome this issue you can use ROM ELF provided by
Espressif (https://dl.espressif.com/dl/esp32_rom.elf) and pass it to ‘espcoredump.py’.
Sometimes you want to read the last value of a variable to understand the root cause of a crash. Core dump supports
retrieving variable data over GDB by attributing special notations declared variables.
• COREDUMP_DRAM_ATTR places variable into DRAM area which will be included into dump.
• COREDUMP_RTC_ATTR places variable into RTC area which will be included into dump.
• COREDUMP_RTC_FAST_ATTR places variable into RTC_FAST area which will be included into dump.
Example
1. In Project Configuration Menu, enable COREDUMP TO FLASH, then save and exit.
2. In your project, create a global variable in DRAM area as such as:
// uint8_t global_var;
COREDUMP_DRAM_ATTR uint8_t global_var;
3. In main application, set the variable to any value and assert(0) to cause a crash.
global_var = 25;
assert(0);
4. Build, flash and run the application on a target device and wait for the dumping information.
5. Run the command below to start core dumping in GDB, where PORT is the device USB port:
(gdb) p global_var
$1 = 25 '\031'
Related Documents
Anatomy of core dump image Core dump component can be configured to use old legacy binary format or the
new ELF one. The ELF format is recommended for new designs. It provides more information about the CPU and
memory state of a program at the moment when panic handler is entered. The memory state embeds a snapshot of
all tasks mapped in the memory space of the program. The CPU state contains register values when the core dump
has been generated. Core dump file uses a subset of the ELF structures to register these information. Loadable
ELF segments are used for the memory state of the process while ELF notes (ELF.PT_NOTE) are used for process
metadata (pid, registers, signal, …). Especially, the CPU status is stored in a note with a special name and type
(CORE, NT_PRSTATUS type).
Here is an overview of coredump layout:
Note: The format of image file showed on the above pictures represents current version of image and can be changed
in future releases.
Overview of implementation The figure below describes some basic aspects related to implementation of core
dump:
Note: The diagram above hide some details and represents current implementation of the core dump and can be
changed later.
The wake stub in esp-idf is called esp_wake_deep_sleep(). This function runs whenever the SoC wakes from
deep sleep. There is a default version of this function provided in esp-idf, but the default function is weak-linked so
if your app contains a function named esp_wake_deep_sleep() then this will override the default.
If supplying a custom wake stub, the first thing it does should be to call esp_default_wake_deep_sleep().
It is not necessary to implement esp_wake_deep_sleep() in your app in order to use deep sleep. It is only
necessary if you want to have special behaviour immediately on wake.
If you want to swap between different deep sleep stubs at runtime, it is also possible to do this by calling
the esp_set_deep_sleep_wake_stub() function. This is not necessary if you only use the default
esp_wake_deep_sleep() function.
All of these functions are declared in the esp_sleep.h header under components/esp32.
Wake stub code must be resident in RTC Fast Memory. This can be done in one of two ways.
The first way is to use the RTC_IRAM_ATTR attribute to place a function into RTC memory:
The second way is to place the function into any source file whose name starts with rtc_wake_stub. Files names
rtc_wake_stub* have their contents automatically put into RTC memory by the linker.
The first way is simpler for very short and simple code, or for source files where you want to mix “normal”and
“RTC”code. The second way is simpler when you want to write longer pieces of code for RTC memory.
The RTC memory area where this data will be placed can be configured via menuconfig option named CON-
FIG_ESP32_RTCDATA_IN_FAST_MEM. This option allows to keep slow memory area for ULP programs and
once it is enabled the data marked with RTC_DATA_ATTR and RTC_RODATA_ATTR are placed in the RTC
fast memory segment otherwise it goes to RTC slow memory (default option). This option depends on the CON-
FIG_FREERTOS_UNICORE because RTC fast memory can be accessed only by PRO_CPU.
The attributes RTC_FAST_ATTR and RTC_SLOW_ATTR can be used to specify data that will be force placed into
RTC_FAST and RTC_SLOW memory respectively. Any access to data marked with RTC_FAST_ATTR is allowed
by PRO_CPU only and it is responsibility of user to make sure about it.
Unfortunately, any string constants used in this way must be declared as arrays and marked with
RTC_RODATA_ATTR, as shown in the example above.
The second way is to place the data into any source file whose name starts with rtc_wake_stub.
For example, the equivalent example in rtc_wake_stub_counter.c:
int wake_count;
The second way is a better option if you need to use strings, or write other more complex code.
To reduce wake-up time use the CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP Kconfig option, see
more information in Fast boot from Deep Sleep.
During deep sleep, all RTC Fast memory areas will be validated with CRC. When ESP32 wakes up from deep sleep,
the RTC fast memory will be validated with CRC again. If the validation passes, the wake stubs code will be executed.
Otherwise, the normal initialization, bootloader and esp-idf codes will be executed.
Note: When the CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP option is enabled, all the RTC fast
memory except the wake stubs area is added to the heap.
4.8.1 Overview
Identifying and handling run-time errors is important for developing robust applications. There can be multiple kinds
of run-time errors:
• Recoverable errors:
– Errors indicated by functions through return values (error codes)
– C++ exceptions, thrown using throw keyword
• Unrecoverable (fatal) errors:
– Failed assertions (using assert macro and equivalent methods, see Assertions) and abort() calls.
– CPU exceptions: access to protected regions of memory, illegal instruction, etc.
– System level checks: watchdog timeout, cache access error, stack overflow, stack smashing, heap corrup-
tion, etc.
This guide explains ESP-IDF error handling mechanisms related to recoverable errors, and provides some common
error handling patterns.
For instructions on diagnosing unrecoverable errors, see Fatal Errors.
The majority of ESP-IDF-specific functions use esp_err_t type to return error codes. esp_err_t is a signed
integer type. Success (no error) is indicated with ESP_OK code, which is defined as zero.
Various ESP-IDF header files define possible error codes using preprocessor defines. Usually these defines start
with ESP_ERR_ prefix. Common error codes for generic failures (out of memory, timeout, invalid argument, etc.)
are defined in esp_err.h file. Various components in ESP-IDF may define additional error codes for specific
situations.
For the complete list of error codes, see Error Code Reference.
For each error code defined in ESP-IDF components, esp_err_t value can be converted to an error code
name using esp_err_to_name() or esp_err_to_name_r() functions. For example, passing 0x101 to
esp_err_to_name() will return “ESP_ERR_NO_MEM”string. Such strings can be used in log output to
make it easier to understand which error has happened.
Additionally, esp_err_to_name_r() function will attempt to interpret the error code as a standard POSIX error
code, if no matching ESP_ERR_ value is found. This is done using strerror_r function. POSIX error codes
(such as ENOENT, ENOMEM) are defined in errno.h and are typically obtained from errno variable. In ESP-IDF
this variable is thread-local: multiple FreeRTOS tasks have their own copies of errno. Functions which set errno
only modify its value for the task they run in.
This feature is enabled by default, but can be disabled to reduce application binary size. See CON-
FIG_ESP_ERR_TO_NAME_LOOKUP. When this feature is disabled, esp_err_to_name() and
esp_err_to_name_r() are still defined and can be called. In this case, esp_err_to_name() will
return UNKNOWN ERROR, and esp_err_to_name_r() will return Unknown error 0xXXXX(YYYYY),
where 0xXXXX and YYYYY are the hexadecimal and decimal representations of the error code, respectively.
ESP_ERROR_CHECK macro serves similar purpose as assert, except that it checks esp_err_t value rather
than a bool condition. If the argument of ESP_ERROR_CHECK is not equal ESP_OK, then an error message is
printed on the console, and abort() is called.
Error message will typically look like this:
Note: If IDF monitor is used, addresses in the backtrace will be converted to file names and line numbers.
• The first line mentions the error code as a hexadecimal value, and the identifier used for this error in source code.
The latter depends on CONFIG_ESP_ERR_TO_NAME_LOOKUP option being set. Address in the program
where error has occured is printed as well.
• Subsequent lines show the location in the program where ESP_ERROR_CHECK macro was called, and the
expression which was passed to the macro as an argument.
• Finally, backtrace is printed. This is part of panic handler output common to all fatal errors. See Fatal Errors
for more information about the backtrace.
ESP_RETURN_ON_ERROR macro checks the error code, if the error code is not equal ESP_OK, it prints the
message and returns.
ESP_GOTO_ON_ERROR macro checks the error code, if the error code is not equal ESP_OK, it prints the message,
sets the local variable ret to the code, and then exits by jumping to goto_tag.
ESP_RETURN_ON_FALSE macro checks the condition, if the condition is not equal true, it prints the message and
returns with the supplied err_code.
ESP_GOTO_ON_FALSE macro checks the condition, if the condition is not equal true, it prints the message, sets
the local variable ret to the supplied err_code, and then exits by jumping to goto_tag.
Some examples:
esp_err_t test_func(void)
{
esp_err_t ret = ESP_OK;
,→`err`.
err:
// clean up
return ret;
}
1. Attempt to recover. Depending on the situation, we may try the following methods:
• retry the call after some time;
• attempt to de-initialize the driver and re-initialize it again;
• fix the error condition using an out-of-band mechanism (e.g reset an external peripheral which is not
responding).
Example:
esp_err_t err;
do {
err = sdio_slave_send_queue(addr, len, arg, timeout);
// keep retrying while the sending queue is full
} while (err == ESP_ERR_TIMEOUT);
if (err != ESP_OK) {
// handle other errors
}
2. Propagate the error to the caller. In some middleware components this means that a function must exit with
the same error code, making sure any resource allocations are rolled back.
Example:
3. Convert into unrecoverable error, for example using ESP_ERROR_CHECK. See ESP_ERROR_CHECK macro
section for details.
Terminating the application in case of an error is usually undesirable behavior for middleware components, but
is sometimes acceptable at application level.
Many ESP-IDF examples use ESP_ERROR_CHECK to handle errors from various APIs. This is not the best
practice for applications, and is done to make example code more concise.
Example:
Support for C++ Exceptions in ESP-IDF is disabled by default, but can be enabled using CON-
FIG_COMPILER_CXX_EXCEPTIONS option.
Enabling exception handling normally increases application binary size by a few KB. Additionally it may be necessary
to reserve some amount of RAM for exception emergency pool. Memory from this pool will be used if it is not
possible to allocate exception object from the heap. Amount of memory in the emergency pool can be set using
CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE variable.
If an exception is thrown, but there is no catch block, the program will be terminated by abort function, and
backtrace will be printed. See Fatal Errors for more information about backtraces.
See cxx/exceptions for an example of C++ exception handling.
4.9 ESP-BLE-MESH
Bluetooth® mesh networking enables many-to-many (m:m) device communications and is optimized for creating
large-scale device networks.
Devices may relay data to other devices not in direct radio range of the originating device. In this way, mesh networks
can span very large physical areas and contain large numbers of devices. It is ideally suited for building automation,
sensor networks, and other IoT solutions where tens, hundreds, or thousands of devices need to reliably and securely
communicate with one another.
Bluetooth mesh is not a wireless communications technology, but a networking technology. This technology is de-
pendent upon Bluetooth Low Energy (BLE) - a wireless communications protocol stack.
Built on top of Zephyr Bluetooth Mesh stack, the ESP-BLE-MESH implementation supports device provisioning and
node control. It also supports such node features as Proxy, Relay, Low power and Friend.
Please see the ESP-BLE-MESH Architecture for information about the implementation of ESP-BLE-MESH architec-
ture and ESP-BLE-MESH API Reference for information about respective API.
ESP-BLE-MESH is implemented and certified based on the latest Mesh Profile v1.0.1, users can refer here for the
certification details of ESP-BLE-MESH.
Note: If you are looking for Wi-Fi based implementation of mesh for ESP32, please check another product by
Espressif called ESP-WIFI-MESH. For more information and documentation see ESP-WIFI-MESH.
This section is intended to help you get started with ESP-BLE-MESH for the hardware based on the ESP32 chip by
Espressif.
We are going to demonstrate process of setting and operation of a small ESP-BLE-MESH network of three nodes.
This process will cover device provisioning and node configuration, and then sending on/off commands to Generic
OnOff Server Models on specific nodes.
If you are new to ESP-IDF, please first set up development environment, compile , flash and run example application
following top level ESP-IDF Get Started documentation.
Hardware:
• Three ESP32 boards, see options.
• USB cables to connect the boards.
• Computer configured with ESP-IDF.
• Mobile phone or tablet running Android or iOS.
Software:
• Example application bluetooth/esp_ble_mesh/ble_mesh_node/onoff_server code to load to the ESP32 boards.
• Mobile App: nRF Mesh for Android or iOS. Optionally you can use some other Apps:
– EspBleMesh Android App
– Silicon Labs Android or iOS App
Step 1. Check Hardware Both ESP32-DevKitC and ESP-WROVER-KIT development boards are supported for
ESP-BLE-MESH implementation. You can choose particular board through menuconfig: idf.py menuconfig
> Example Configuration > Board selection for ESP-BLE-MESH
Note: If you plan to use ESP32-DevKitC, connect a RGB LED to GPIO pins 25, 26 and 27.
Step 4. Provision Nodes In this section, we will use the nRF Mesh Android App to demonstrate how to provision
an unprovisioned device. Users can also get its iOS version from the App Store.
4.1 Scanner The Scanner is App’s functionality to search for unprovisioned devices in range. Open the App,
press Scanner at the bottom and the search will start. After a short while we should see three unprovisioned devices
displayed.
4.2 Identify Users can select any unprovisioned device, then the App will try to set up a connection with the
selected device. After the BLE connection is established successfully (sometimes users need to try multiple times to
get connected), and proper ESP-BLE-MESH GATT Service is discovered, users can see the IDENTIFY interface
button on the screen. The IDENTIFY operation can be used to tell users which device is going to be provisioned.
Note: The IDENTIFY operation also needs some cooperation on the device side, then users can see which device is
in the provisioning process. Currently when pressing the IDENTIFY interface button, no signs can been seen from
the device except from the log on the serial monitor.
After the IDENTIFY interface button is pressed, users can see the PROVISION interface button.
4.3 Provision Then, the App will try to provision the unprovisioned device. When the device is provisioned suc-
cessfully, the RGB LED on the board will turn off, and the App will implement the following procedures:
1. Disconnect with the node
2. Try to reconnect with the node
3. Connect successfully and discover ESP-BLE-MESH GATT Service
4. Get Composition Data of the node and add AppKey to it
When all the procedures are finished, the node is configured properly. And after pressing OK, users can see that
unicast address is assigned, and Composition Data of the node is decoded successfully.
Sometimes in procedure 2, the App may fail to reconnect with the node. In this case, after pressing OK, users can
see that only unicast address of the node has been assigned, but no Composition Data has been got. Then users need
to press CONNECT on the top right, and the previously provisioned node will be displayed on the screen, and users
need to choose it and try to connect with the node.
After connecting successfully, the App will show the interface buttons which can be used to get Composition Data
and add AppKey.
If the device is the second or the third one which has been provisioned by the App, and after pressing CONNECT,
users can see two or three nodes on the screen. In this situation, users can choose any device to connect with, once
succeed then go back to the main screen to choose the node which needs to be configured.
Here an example of three devices listed.
• The left picture shows that the third device is provisioned successfully, but the App failed to connect with it.
When it tries to reconnect with the third node, three nodes are displayed on the App.
• The right picture shows that after connecting with any node successfully, the App displays the information of
the three nodes. Users can see that the App has got the Composition Data of the first and the second nodes,
but for the third one, only the unicast address has been assigned to it while the Composition Data is unknown.
4.4 Configuration When provisioning and initial configuration are finished, users can start to configure the node,
such as binding AppKey with each model with the elements, setting publication information to it, etc.
Example below shows how to bind AppKey with Generic OnOff Server Model within the Primary Element.
Note: No need to bind AppKey with the Configuration Server Model, since it only uses the DevKey to encrypt
messages in the Upper Transport Layer.
Step 5. Operate Network After all the Generic OnOff Server Models within the three elements are bound with
proper AppKey, users can use the App to turn on/off the RGB LED.
In the bluetooth/esp_ble_mesh/ble_mesh_node/onoff_server example, the first Generic OnOff Server Model is used
to control the RED color, the second one is used to control the GREEN color and the third one is used to control
the BLUE color.
The following screenshot shows different board with different color on.
Note: For nRF Mesh iOS App [version 1.0.4], when the node contains more than one element, the App is not
behaving correctly. If users try to turn on/off the second or the third Generic OnOff Server Model, the message sent
by the App is destinated to the first Generic OnOff Server Model within the Primary Element.
• ESP-BLE-MESH Node OnOff Server - shows the use of ESP-BLE-MESH as a node having a Configuration
Server model and a Generic OnOff Server model. A ESP-BLE-MESH Provisioner can then provision the
unprovisioned device and control a RGB LED representing on/off state, see example code .
• ESP-BLE-MESH Node OnOff Client - shows how a Generic OnOff Client model works within a node. The
node has a Configuration Server model and a Generic OnOff Client model, see example code .
• ESP-BLE-MESH Provisioner - shows how a device can act as an ESP-BLE-MESH Provisioner to provision
devices. The Provisioner has a Configuration Server model, a Configuration Client model and a Generic OnOff
Client model, see example code .
• ESP-BLE-MESH Fast Provisioning - Client and Server - this example is used for showing how fast provision-
ing can be used in order to create a mesh network. It takes no more than 60 seconds to provision 100 devices,
see example client code and example server code .
• ESP-BLE-MESH and Wi-Fi Coexistence - an example that demonstrates the Wi-Fi and Bluetooth
(BLE/BR/EDR) coexistence feature of ESP32. Simply put, users can use the Wi-Fi while operating Blue-
tooth, see example code .
• ESP-BLE-MESH Console - an example that implements BLE Mesh basic features. Within this example a node
can be scanned and provisioned by Provisioner and reply to get/set message from Provisioner, see example node
code .
• 1. Provisioner Development
• 2. Node Development
• 3. ESP-BLE-MESH and Wi-Fi Coexistence
• 4. Fast Provisioning
• 5. Log Help
• 6. Example Help
• 7. Others
Supported Features
Mesh Core
• Provisioning: Node Role
– PB-ADV and PB-GATT
– OOB Authentication
• Provisioning: Provisioner Role
– PB-ADV and PB-GATT
– OOB Authentication
• Networking
– Relay
– Segmentation and Reassembly
– Key Refresh Procedure
– IV Update Procedure
– Friend
– Low Power
– Proxy Server
– Proxy Client
• Multiple Client Models Run Simultaneously
– Support multiple client models send packets to different nodes simultaneously
– No blocking between client model and server model
• NVS Storing
– Store provisioning and configuration information of ESP-BLE-MESH Node
Mesh Models
• Foundation models
– Configuration Server model
– Configuration Client model
– Health Server model
– Health Client model
• Generic client models
– Generic OnOff Client
– Generic Level Client
– Generic Default Transition Time Client
– Generic Power OnOff Client
– Generic Power Level Client
– Generic Battery Client
– Generic Location Client
– Generic Property Client
• Sensor client models
– Sensor Client
Mesh Applications
• ESP-BLE-MESH Node
– Tutorial
– Tutorial
– Example
• ESP-BLE-MESH Provisioner
– Tutorial
– Example
• ESP-BLE-MESH Fast Provisioning
– Fast Provisioning Client Model Tutorial
– Fast Provisioning Server Model Tutorial
– Example
– Demo Video
• ESP-BLE-MESH and Wi-Fi Coexistence
– Tutorial
– Example
– Demo Video
• ESP-BLE-MESH Console Commands
– Example
Mesh Core
• Provisioner NVS Storage
Mesh Applications
• Fast OTA
• Friendship
ESP-BLE-MESH Architecture
– Includes Advertising Bearer and GATT Bearer. The bearer layer is crucial to ESP-BLE-
MESH protocol stack which is built on Bluetooth Low-Energy technology, because the protocol stack
must make use of the bearer layer to transmit data via the BLE advertising channel and connection chan-
nel.
• Applications
– Based on ESP-BLE-MESH protocol stack and Mesh Models.
– By calling API and handling Event, Applications interact with Mesh Networking and Mesh
Provisioning in ESP-BLE-MESH protocol stack, as well as a series of Models provided by Mesh
Models.
1.1.1 Mesh Networking Mesh Networking in the protocol stack architecture implements the following func-
tions:
• The communication between nodes in the Mesh network.
• Encryption and decryption of messages in the Mesh network.
• Management of Mesh network resources (Network Key, IV Index, etc.).
• Segmentation and reassembly of Mesh network messages.
• Model mapping of messages between different models.
• For more features, please see ESP-BLE-MESH Feature List.
The implementation of Mesh Networking functions is based on hierarchy structure. Functions of each layer are
shown in Table 1.1:
1.1.2 Mesh Provisioning Mesh Provisioning in the protocol stack architecture implements the following
functions:
• Provisioning of unprovisioned devices.
• Allocation of Mesh network resources (unicast address, IV Index, NetKey, etc.).
• Four authentication methods support during provisioning.
• For more features, please see ESP-BLE-MESH Feature List.
The implementation of Mesh Provisioning functions is based on hierarchy structure. Functions of each layer
are shown in Table 1.2:
1.1.3 Mesh Models Mesh Models in the protocol stack architecture implements the following functions:
• Configuration Client/Server Models
• Health Client/Server Models
• Generic Client/Server Models
• Sensor Client/Server Models
• Time and Scenes Client/Server Models
• Lighting Client/Server Models
Functions of each layer are shown in Table 1.3:
1.2 Mesh Network Management Network Management implements the following functions:
• Node removal procedure is used to remove a node from the network.
• IV Index recovery procedure is used to recover a node’s IV Index.
• IV update procedure is used to update the nodes’IV Index.
• Key refresh procedure is used to update the nodes’NetKey, AppKey, etc.
• Network creation procedure is used to create a mesh network.
• NVS storage is used to store node’s networking information.
1.4 Mesh Bearer Layer Bearers in the protocol stack architecture are responsible for passing of data between
ESP-BLE-MESH protocol stack and Bluetooth Low Energy Core.
Bearers can be taken as a carrier layer based on Bluetooth Low Energy Core, which implements the function of
receiving and transmitting data for the ESP-BLE-MESH protocol stack.
1.5 Mesh Applications The Applications in the protocol stack architecture implement the corresponding
functions by calling the API provided by the ESP-BLE-MESH protocol stack and processing the Event reported by
the protocol stack. There are some common applications, such as gateway, lighting and etc.
Interaction between application layer(Applications)and API / Event
• Application layer calls API
– Call the provisioning-related API for provisioning.
– Call the model-related API to send messages.
– Call the device-attributes-related API to get local information about the device.
• Application layer processes Event
The application layer is designed based on events, which take parameters to the application layer. Events are
mainly divided into two categories.
– The events completed by calling API.
∗ Such as nodes sending messages.
– The events that the protocol stack actively reports to the application layer.
∗ The Event that the protocol stack actively reports.
∗ The Event that Model actively reports.
• The event is reported by the callback function registered by the application layer, and the callback function also
contains the corresponding processing of the event.
Interaction between API / Event and ESP-BLE-MESH protocol stack
• API used by user mainly calls functions provided by Mesh Networking, Mesh Provisioning and
Mesh Models.
• The interaction between API / Event and the protocol stack does not operate across the hierarchy of the
protocol stack. For example, API does not call functions related to Network Layer.
2.1.1 Mesh Networking Implementation The list of files and the functions implemented in each file in Mesh
Networking are shown in Table 2.1:
2.1.2 Mesh Provisioning Implementation The implementation of Mesh Provisioning is divided into two chunks
due to the Node/Provisioner coexistence.
Specific files that provide implementation of provisioning of Node are shown in Table 2.2:
Specific files that implement functions of Provisioner are shown in Table 2.3:
2.1.3 Mesh Models Implementation Mesh Models are used to implement the specific functions of model in nodes.
Server model is used to maintain node status. Client model is used to obtain and modify node state.
2.2 Mesh Bearers Implementation Portability is fully considered in the implementation of Mesh Bearers.
When the ESP-BLE-MESH protocol stack is being ported to other platforms, users only need to modify
mesh_bearer_adapt.c (example of NimBLE version ).
Note: mesh_bearer_adapt.c is the implementation of Advertising Bearer and GATT Bearer in Mesh
Networking framework.
2.3 Mesh Applications Implementation We have provided a series of application examples for customer devel-
opment, and users can develop products based on ESP-BLE-MESH Examples.
3. Auxiliary Routine Auxiliary routine refers to optional functions in the ESP-BLE-MESH protocol stack. The
design of the auxiliary routine generally implement the truncation of code through CONFIG_BLE_MESH.
3.1 Features
• Low Power
• Friend
• Relay
• Proxy Client/Server
3.3 Auxiliary Routine Implementation When adopting the design of independent module, the two main factors
should be considered:
• The module can not be implemented hierarchically, and it can be completely independent, which means it does
not rely on the implementation of other modules.
• The functions in the module will be used repeatedly, so it is reasonable to design it into a module. Independent
module is shown in Table 3.1:
ESP-BLE-MESH FAQ
This document provides a summary of frequently asked questions about developing with ESP-BLE-MESH, and is
divided into seven sections:
• 1. Provisioner Development
• 2. Node Development
• 3. ESP-BLE-MESH and Wi-Fi Coexistence
• 4. Fast Provisioning
• 5. Log Help
• 6. Example Help
• 7. Others
Users could refer to the sections for quick answer to their questions. This document will be updated based on the
feedback collected via various channels.
1. Provisioner Development Generally, a Provisioner is used to provision unprovisioned devices and form a mesh
network. And after provisioning, roles of the unprovisioned devices will be changed to those of a node.
1.1 What is the flow for an unprovisioned device to join ESP-BLE-MESH network?
There are two phases for a device to join ESP-BLE-MESH network via a Provisioner, namely, provi-
sioning and configuration.
• The phase of provisioning is to assign unicast address, add NetKey and etc. to a device. By
provisioning, the device joins the ESP-BLE-MESH network and its role is changed from an un-
provisioned device to a node.
• The phase of configuration is to add AppKeys to the node and bind AppKeys to corresponding
models. And some items are optional during configuration, including adding subscription addresses
to the node, set publication information, etc. By configuration, the node can actually transmit
messages to a Provisioner and receive messages from it.
1.2 If a Provisioner wants to change states of a node, what requirements should be met for a Provisioner?
• Client model that corresponds to server model of the node is required.
• NetKey and AppKey used to encrypt messages shall be owned by both the node and the Provisioner.
• The address owned by the node shall be known, which could be its unicast address or subscription address.
1.4 How to generate a NetKey or AppKey for Provisioner? Can we use a fixed NetKey or AppKey?
• The API esp_ble_mesh_provisioner_add_local_net_key() can be used to add a NetKey with
a fixed or random value.
• The API esp_ble_mesh_provisioner_add_local_app_key() can be used to add an AppKey
with a fixed or random value.
1.6 Can the address of Provisioner serve as destination address of the node-reporting-status message?
The unicast address of Provisioner can be set only once during initialization and can’t be changed after-
wards. In theory, it can serve as the destination address of the node-reporting-status message, provided
that the unicast address of the Provisioner is known by nodes. Nodes can know the unicast address of
Provisioner during configuration since Provisioner sends messages to them with its unicast address used
as the source address.
Subscription address can also be used. Provisioner subscribes to a group address or virtual address, and
nodes send messages to the subscription address.
1.7 Is the unicast address of the node that is firstly provisioned by Provisioner to ESP-BLE-MESH network
fixed?
The value of prov_start_address in esp_ble_mesh_prov_t is used to set the starting ad-
dress when the Provisioner provisions unprovisioned devices, i.e. the unicast address of the node it firstly
provisioned. It can be set only once during initialization and can’t be changed afterwards.
1.8 Is the unicast address of the node that mobile App firstly provisioned fixed?
The App will decide the unicast address, and currently most of them are fixed.
1.9 How to know which unprovisioned device is the Provisioner that is provisioning currently?
The value of prov_attention in esp_ble_mesh_prov_t is used by Provisioner set to unpro-
visioned device during provisioning. It can be set only once during initialization and can’t be changed
afterwards. When the unprovisioned device is joining the mesh network, it can display in a specific way
like flashing light to notify Provisioner that it is being provisioned.
1.10 How many ways to authenticate the devices during provisioning? Which way was used in the provided
examples ?
There are four authentication methods, i.e. No OOB, Static OOB, Output OOB and Input OOB. In the
provided examples, No OOB is used.
1.11 What information can be carried by the advertising packets of the unprovisioned device before provi-
sioning into the network?
• Device UUID
• OOB Info
• URL Hash (optional)
1.13 How is the unicast address assigned when the node provisioned by Provisioner contains multiple ele-
ments?
• Provisioner will assign an unicast address for the primary element of the node, and unicast address of the
remaining elements are incremented one by one.
• For example: If an unprovisioned device has three elements, i.e. the primary element, the second element and
the third element. After provisioning, the primary element address of the n