data
stringlengths
512
2.99k
References API Reference Header File This header file can be included with: #include "hal/efuse_hal.h" Functions - void efuse_hal_get_mac(uint8_t *mac) get factory mac address - uint32_t efuse_hal_chip_revision(void) Returns chip version. - Returns Chip version in format: Major * 100 + Minor - uint32_t efuse_hal_blk_version(void) Return block version. - Returns Block version in format: Major * 100 + Minor - bool efuse_hal_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. - bool efuse_hal_get_disable_wafer_version_major(void) Returns the status of whether the bootloader (and OTA) will check the maximum chip version or not. - Returns true - Skip the maximum chip version check.
Console ESP-IDF provides console component, which includes building blocks needed to develop an interactive console over serial port. This component includes the following features: 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 features 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. Note When using a console application on a chip that supports a hardware USB serial interface, we suggest to disable the secondary serial console output. The secondary output will be output-only and consequently does not make sense in an interactive application. Line Editing Line editing feature lets users compose commands by typing them, erasing symbols using the backspace key, navigating within the command using the left/right keys, navigating to previously typed commands using the up/down keys, and performing autocompletion using the 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 esp-idf-monitor (which can be invoked using idf.py monitor from project directory). Here is an overview of functions provided by linenoise library.
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 command 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 mode 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.
Main Loop linenoise() In most cases, console applications have some form of read/eval loop. linenoise()is the single function which handles user's key presses and returns the completed line once the enterkey is pressed. As such, it handles the readpart of the loop. linenoiseFree() This function must be called to release the command line buffer obtained from linenoise()function. Hints and Completions linenoiseSetCompletionCallback() When the user presses the tabkey, linenoise library invokes the completion callback. The callback should inspect the contents of the command typed so far and provide a list of possible completions using calls to linenoiseAddCompletion()function. linenoiseSetCompletionCallback()function should be called to register this completion callback, if completion feature is desired. consolecomponent 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 the 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 the 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 linenoiseSetFreeHintsCallback(). History linenoiseHistorySetMaxLen() This function sets the number of most recently typed commands to be kept in memory. Users can navigate the history using the up/down arrows keys.
linenoiseHistoryAdd() Linenoise does not automatically add commands to history. Instead, applications need to call this function 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. Splitting of Command Line into Arguments console component provides esp_console_split_argv() function to split command line string into arguments. 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 produces a double quote. Arguments can be quoted using double quotes.
Please see tutorial for an introduction to argtable3. Github repository also includes examples. Command Registration and Dispatching 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 structure): 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 parsing, 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: 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 helpcommand to the list of registered commands. This command prints the list of all the registered commands, along with their arguments and help texts. Callback function to be used with linenoiseSetCompletionCallback()from linenoise library. Provides completions to linenoise based on the list of registered commands. Callback function to be used with linenoiseSetHintsCallback()from linenoise library. Provides argument hints for registered commands to linenoise. Initialize Console REPL Environment To establish a basic REPL environment, console component provides several useful APIs, combining those functions described above. In a typical application, you only need to call esp_console_new_repl_uart() to initialize the REPL environment 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 environment 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 are based on the console component and can be treated as "tools" when developing applications.
API Reference Header File This header file can be included with: #include "esp_console.h" This header file is a part of the API provided by the consolecomponent. To declare that your component depends on console, add the following to your CMakeLists.txt: REQUIRES console or PRIV_REQUIRES console 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 - Parameters config -- console configuration - Returns ESP_OK on success ESP_ERR_NO_MEM if out of memory ESP_ERR_INVALID_STATE if already initialized ESP_ERR_INVALID_ARG if the configuration is invalid - - esp_err_t esp_console_deinit(void) de-initialize console module Note Call this once when done using console module functions - Returns ESP_OK on success ESP_ERR_INVALID_STATE if not initialized yet - - esp_err_t esp_console_cmd_register(const esp_console_cmd_t *cmd) Register console command. - Parameters cmd -- pointer to the command description; can point to a temporary value - Returns ESP_OK on success ESP_ERR_NO_MEM if out of memory ESP_ERR_INVALID_ARG if command description includes invalid arguments - - esp_err_t esp_console_run(const char *cmdline, int *cmd_ret) Run command line. - Parameters cmdline -- command line (command name followed by a number of arguments)
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) - void esp_console_get_completion(const char *buf, linenoiseCompletions *lc) Callback which provides command completion for linenoise library. When using linenoise for line editing, command completion support can be enabled like this: linenoiseSetCompletionCallback(&esp_console_get_completion); - Parameters buf -- the string typed by the user lc -- linenoiseCompletions to be filled in - - const char *esp_console_get_hint(const char *buf, int *color, int *bold) Callback which provides command hints for linenoise library. When using linenoise for line editing, hints support can be enabled as follows: linenoiseSetHintsCallback((linenoiseHintsCallback*) &esp_console_get_hint); The extra cast is needed because linenoiseHintsCallback is defined as returning a char* instead of const char*. - Parameters buf -- line typed by the user color -- [out] ANSI color code to be used when displaying the hint bold -- [out] set to 1 if hint has to be displayed in bold - - Returns string containing the hint text. This string is persistent and should not be freed (i.e. linenoiseSetFreeHintsCallback should not be used). - esp_err_t esp_console_register_help_command(void)
Register a 'help' command. Default 'help' command prints the list of registered commands along with hints and help strings if no additional argument is given. If an additional argument is given, the help command will look for a command with the same name and only print the hints and help strings of that command. - Returns ESP_OK on success ESP_ERR_INVALID_STATE, if esp_console_init wasn't called - - esp_err_t esp_console_new_repl_uart(const esp_console_dev_uart_config_t *dev_config, const esp_console_repl_config_t *repl_config, esp_console_repl_t **ret_repl) Establish a console REPL environment over UART driver. - 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 --
Start REPL environment. Note Once the REPL gets started, it won't be stopped until the user calls repl->del(repl) to destroy the REPL environment. - Parameters repl -- [in] REPL handle returned from esp_console_new_repl_xxx - Returns 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 - uint32_t heap_alloc_caps where to (e.g. MALLOC_CAP_SPIRAM) allocate heap objects such as cmds used by esp_console - int hint_color ASCII color code of hint text. - int hint_bold Set to 1 to print hint text in bold. - size_t max_cmdline_length - 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 - const char *history_save_path file path used to save history commands, set to NULL won't save to file system - uint32_t task_stack_size repl task stack size - uint32_t task_priority repl task priority - const char *prompt prompt (NULL represents default: "esp> ") - size_t max_cmdline_length maximum length of a command line. If 0, default value will be used - uint32_t max_history_len - struct esp_console_dev_uart_config_t Parameters for console device: UART. - struct esp_console_cmd_t Console command description. Public Members - const char *command Command name.
Must not be NULL, must not contain spaces. The pointer must be valid until the call to esp_console_deinit. - const char *help Help text for the command, shown by help command. If set, the pointer must be valid until the call to esp_console_deinit. If not set, the command will not be listed in 'help' output. - const char *hint Hint text, usually lists possible arguments. If set to NULL, and 'argtable' field is non-NULL, hint will be generated automatically - 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. - const char *command - struct esp_console_repl_s Console REPL base structure. Public Members - esp_err_t (*del)(esp_console_repl_t *repl) Delete console REPL environment. - Param repl [in] REPL handle returned from esp_console_new_repl_xxx - Return ESP_OK on success ESP_FAIL on errors - - esp_err_t (*del)(esp_console_repl_t *repl) 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() Type Definitions - typedef struct linenoiseCompletions linenoiseCompletions - typedef int (*esp_console_cmd_func_t)(int argc, char **argv) Console command main function. - Param argc number of arguments - Param argv array with argc entries, each pointing to a zero-terminated string argument - Return console command return code, 0 indicates "success" - typedef struct esp_console_repl_s esp_console_repl_t Type defined for console REPL.
eFuse Manager 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 >
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 ESP-IDF. Each block is divided into 8 32-bits registers. eFuse Manager Component 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 checks with the common CSV file. CSV files: common (esp_efuse_table.csv) - contains eFuse fields which are used inside the ESP-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. Description CSV File The CSV file contains a description of the eFuse fields. In the simple case, one field has one line of description. Table header: # field_name, efuse_block(EFUSE_BLK0..EFUSE_BLK3), bit_start(0..255), bit_count(1..256), comment Individual params in CSV file the following meanings: field_name Name of field. The prefix ESP_EFUSE_ is added to the name, and this field name is available in the code. This name is used to access the fields. The name must be unique for all fields. If the line has an empty name, then this line is combined with the previous field. This allows you to set an arbitrary order of bits in the field, and expand the field as well (see MAC_FACTORYfield in the common table). The field_name supports structured format using . to show that the field belongs to another field (see WR_DISand RD_DISin the common table). efuse_block Block number. It determines where the eFuse bits are placed for this field.
The bit_start field can be omitted. In this case, it is set to bit_start + bit_count from the previous record, if it has the same efuse_block. Otherwise (if efuse_block is different, or this is the first entry), an error will be generated. bit_count The number of bits to use in this field (1..-). This parameter cannot be omitted. This field also may be MAX_BLK_LENin this case, the field length has the maximum block length, taking into account the coding scheme (applicable for ESP_EFUSE_SECURE_BOOT_KEYand ESP_EFUSE_ENCRYPT_FLASH_KEYfields). The value MAX_BLK_LENdepends on CONFIG_EFUSE_CODE_SCHEME_SELECTOR, which will be replaced with "None" - 256, "3/4" - 192, "REPEAT" - 128. comment This param is using for comment field, it also move to C-header file. The comment field can be omitted. If a non-sequential bit order is required to describe a field, then the field description in the following lines should be continued without specifying a name, indicating that it belongs to one field.
For example two fields MAC_FACTORY and MAC_FACTORY_CRC: # Factory MAC address # ####################### MAC_FACTORY, EFUSE_BLK0, 72, 8, Factory MAC addr [0] , EFUSE_BLK0, 64, 8, Factory MAC addr [1] , EFUSE_BLK0, 56, 8, Factory MAC addr [2] , EFUSE_BLK0, 48, 8, Factory MAC addr [3] , EFUSE_BLK0, 40, 8, Factory MAC addr [4] , EFUSE_BLK0, 32, 8, Factory MAC addr [5] MAC_FACTORY_CRC, EFUSE_BLK0, 80, 8, CRC8 for factory MAC address This field is available in code as ESP_EFUSE_MAC_FACTORY and ESP_EFUSE_MAC_FACTORY_CRC. Structured eFuse Fields WR_DIS, EFUSE_BLK0, 0, 32, Write protection WR_DIS.RD_DIS, EFUSE_BLK0, 0, 1, Write protection for RD_DIS WR_DIS.FIELD_1, EFUSE_BLK0, 1, 1, Write protection for FIELD_1 WR_DIS.FIELD_2, EFUSE_BLK0, 2, 4, Write protection for FIELD_2 (includes B1 and B2) WR_DIS.FIELD_2.B1, EFUSE_BLK0, 2, 2, Write protection for FIELD_2.B1 WR_DIS.FIELD_2.B2, EFUSE_BLK0, 4, 2, Write protection for FIELD_2.B2 WR_DIS.FIELD_3, EFUSE_BLK0, 5, 1, Write protection for FIELD_3 WR_DIS.FIELD_3.ALIAS, EFUSE_BLK0, 5, 1, Write protection for FIELD_3 (just a alias for WR_DIS.FIELD_3) WR_DIS.FIELD_4, EFUSE_BLK0, 7, 1, Write protection for FIELD_4 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 cannot 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 ESP-IDF names for structured eFuse fields should be unique. The efuse_table_gen tool generates the final names where the dot is replaced by _. The names for using in ESP-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: Field at USER_DATA, EFUSE_BLK3, 0, 256 intersected with SERIAL_NUMBER, EFUSE_BLK3, 0, 32 Solution: Describe SERIAL_NUMBER to be included in USER_DATA.
Field at FEILD, EFUSE_BLK3, 0, 50 out of range FEILD.MAJOR_NUMBER, EFUSE_BLK3, 60, 32 Solution: Change bit_start for FIELD.MAJOR_NUMBER from 60 to 0, so MAJOR_NUMBER is in the FEILD range. 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 After generation in the folder $IDF_PATH/components/efuse/esp32 create: esp_efuse_table.c file. In include folder esp_efuse_table.c file. To generate a custom files, use the following command idf.py efuse-custom-table or: 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 After generation in the folder PROJECT_PATH/main create: esp_efuse_custom_table.c file. In include folder esp_efuse_custom_table.c file. To use the generated fields, you need to include two files: #include "esp_efuse.h" #include "esp_efuse_table.h" // or "esp_efuse_custom_table.h" Supported Coding Scheme eFuse have three coding schemes: None(value 0).
3/4 192 bits. Repeat 128 bits. You can find out the coding scheme of your chip: run a espefuse.py -p PORT summarycommand. from esptoolutility logs (during flashing). calling the function in the code esp_efuse_get_coding_scheme()for the EFUSE_BLK3 block. eFuse tables must always comply with the coding scheme in the chip. There is an CONFIG_EFUSE_CODE_SCHEME_SELECTOR option to select the coding type for tables in a Kconfig. When generating source files, if your tables do not follow the coding scheme, an error message will be displayed. Adjust the length or offset fields. If your program was compiled with None encoding and 3/4 is used in the chip, then the ESP_ERR_CODING error may occur when calling the eFuse API (the field is outside the block boundaries). If the field matches the new block boundaries, then the API will work without errors. 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 cannot 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 writing 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_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). esp_efuse_key_block_unused()- Returns true if the key block is unused, false otherwise. For frequently used fields, special functions are made, like this esp_efuse_get_pkg_ver().
[3 ] read_regs: 03020100 07060504 0B0A0908 0F0E0D0C 13121111 17161514 1B1A1918 1F1E1D1C BLOCK4 (BLOCK4 ) [4 ] read_regs: 03020100 07060504 0B0A0908 0F0E0D0C 13121111 17161514 1B1A1918 1F1E1D1C where is the register representation: 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 where is the byte representation: 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). USER_DATA, EFUSE_BLK3, 0, 256, User data USER_DATA.FIELD1, EFUSE_BLK3, 16, 16, Field1 ID, EFUSE_BLK4, 8, 3, ID bit[0..2] , EFUSE_BLK4, 16, 2, ID bit[3..4] , EFUSE_BLK4, 32, 3, ID bit[5..7] 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 esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA, &field1, field1_size); // field1 = 0x0302 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 =
The json string has the following properties: { "MAC": { "bit_len": 48, "block": 0, "category": "identity", "description": "Factory MAC Address", "efuse_type": "bytes:6", "name": "MAC", "pos": 0, "readable": true, "value": "94: b9:7e:5a:6e:58 (CRC 0xe2 OK)", "word": 1, "writeable": true }, } These functions can be used from a top-level project CMakeLists.txt (get-started/hello_world/CMakeLists.txt): # ... project(hello_world) espefuse_get_json_summary(efuse_json) espefuse_get_efuse(ret_data ${efuse_json} "MAC" "value") message("MAC:" ${ret_data}) The format of the value property is the same as shown in espefuse.py summary. MAC:94:
b9:7e:5a:6e:58 (CRC 0xe2 OK) There is an example test system/efuse/CMakeLists.txt which adds a custom target efuse-summary. This allows you to run the idf.py efuse-summary command to read the required eFuses (specified in the efuse_names list) at any time, not just at project build time. Debug eFuse & Unit Tests Virtual eFuses The Kconfig option CONFIG_EFUSE_VIRTUAL virtualizes eFuse values inside the eFuse Manager, 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). Flash Encryption Testing Flash Encryption (FE) is a hardware feature that requires the physical burning of eFuses: key and FLASH_CRYPT_CNT. If FE is not actually enabled then enabling the CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH option just gives testing possibilities and does not encrypt anything in the flash, even though the logs say encryption happens. The bootloader_flash_write() is adapted for this purpose. But if FE is already enabled on the chip and you run an application or bootloader created with the CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH option then the flash encryption/decryption operations will work properly (data are encrypted as it is written into an encrypted flash partition and decrypted when they are read from an encrypted partition). espefuse.py esptool includes a useful tool for reading/writing ESP32 eFuse bits - espefuse.py. espefuse.py -p PORT summary espefuse.py v4.6-dev Connecting.... Detecting chip type... Unsupported detection protocol, switching and trying again... Connecting.....
[Meaningful Value] [Readable/Writeable] (Hex Value) ---------------------------------------------------------------------------------------- Calibration fuses: ADC_VREF (BLOCK0) True ADC reference voltage = 1121 R/W (0b00011) Config fuses: WR_DIS (BLOCK0) Efuse write disable mask = 0 R/W (0x0000) RD_DIS (BLOCK0) Disable reading from BlOCK1-3 = 0 R/W (0x0) DISABLE_APP_CPU (BLOCK0) Disables APP CPU = False R/W (0b0) DISABLE_BT (BLOCK0) Disables Bluetooth = False R/W (0b0) DIS_CACHE (BLOCK0) Disables cache = False R/W (0b0) CHIP_CPU_FREQ_LOW (BLOCK0) If set alongside EFUSE_RD_CHIP_CPU_FREQ_RATED; the = False R/W (0b0) ESP32's max CPU frequency is rated for 160MHz. 24 0MHz otherwise CHIP_CPU_FREQ_RATED (BLOCK0) If set; the ESP32's maximum CPU frequency has been = True R/W (0b1) rated BLK3_PART_RESERVE (BLOCK0) BLOCK3 partially served for ADC calibration data = False R/W (0b0) CLK8M_FREQ (BLOCK0) 8MHz clock freq override = 51 R/W (0x33) VOL_LEVEL_HP_INV (BLOCK0) This field stores the voltage level for CPU to run = 0 R/W (0b00) at 240 MHz; or for flash/PSRAM to run at 80 MHz.0 x0: level 7; 0x1: level 6; 0x2: level 5; 0x3:
(RO) CODING_SCHEME (BLOCK0) Efuse variable block length scheme = NONE (BLK1-3 len=256 bits) R/W (0b00) CONSOLE_DEBUG_DISABLE (BLOCK0) Disable ROM BASIC interpreter fallback = True R/W (0b1) DISABLE_SDIO_HOST (BLOCK0) = False R/W (0b0) DISABLE_DL_CACHE (BLOCK0) Disable flash cache in UART bootloader = False R/W (0b0) Flash fuses: FLASH_CRYPT_CNT (BLOCK0) Flash encryption is enabled if this field has an o = 0 R/W (0b0000000) dd number of bits set FLASH_CRYPT_CONFIG (BLOCK0) Flash encryption config (key tweak bits) = 0 R/W (0x0) Identity fuses: CHIP_PACKAGE_4BIT (BLOCK0) Chip package identifier #4bit = False R/W (0b0) CHIP_PACKAGE (BLOCK0) Chip package identifier = 1 R/W (0b001)
True R/W (0b1) CHIP_VER_REV2 (BLOCK0) = True R/W (0b1) WAFER_VERSION_MINOR (BLOCK0) = 0 R/W (0b00) WAFER_VERSION_MAJOR (BLOCK0) calc WAFER VERSION MAJOR from CHIP_VER_REV1 and CH = 3 R/W (0b011) IP_VER_REV2 and apb_ctl_date (read only) PKG_VERSION (BLOCK0) calc Chip package = CHIP_PACKAGE_4BIT << 3 + CHIP_ = 1 R/W (0x1) PACKAGE (read only) Jtag fuses: JTAG_DISABLE (BLOCK0) Disable JTAG = False R/W (0b0) Mac fuses: MAC (BLOCK0) MAC address = 94: b9:7e:5a:6e:58 (CRC 0xe2 OK) R/W MAC_CRC (BLOCK0) CRC8 for MAC address = 226 R/W (0xe2) MAC_VERSION (BLOCK3) Version of the MAC field = 0 R/W (0x00) Security fuses: UART_DOWNLOAD_DIS (BLOCK0) Disable UART download mode. Valid for ESP32 V3 and = False R/W (0b0) newer; only 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) 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) KEY_STATUS (BLOCK0) Usage of efuse block 3 (reserved) = False R/W (0b0) SECURE_VERSION (BLOCK3) Secure version for anti-rollback = 0 R/W (0x00000000)
R/W Spi Pad fuses: SPI_PAD_CONFIG_HD (BLOCK0) read for SPI_pad_config_hd = 0 R/W (0b00000) 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_CS0 (BLOCK0) Override SD_CMD pad (GPIO11/SPICS0) = 0 R/W (0b00000) Vdd fuses: XPD_SDIO_REG (BLOCK0) read for XPD_SDIO_REG = False R/W (0b0) XPD_SDIO_TIEH (BLOCK0) If XPD_SDIO_FORCE & XPD_SDIO_REG = 1.8V R/W (0b0) XPD_SDIO_FORCE (BLOCK0) Ignore MTDI pin (GPIO12) for VDD_SDIO on reset = False R/W (0b0) Flash voltage (VDD_SDIO) determined by GPIO12
efuse 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 - enumerator EFUSE_BLK0 - 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 - enumerator EFUSE_CODING_SCHEME_NONE - 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 - enumerator ESP_EFUSE_KEY_PURPOSE_USER Header File This header file can be included with: #include "esp_efuse.h" This header file is a part of the API provided by the efusecomponent.
efuse 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.
Error in the passed arguments. - - bool esp_efuse_read_field_bit(const esp_efuse_desc_t *field []) Read a single bit eFuse field as a boolean value. 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. - - esp_err_t esp_efuse_read_field_cnt(const esp_efuse_desc_t *field [], size_t *out_cnt) Reads bits from EFUSE field and returns number of bits programmed as "1". If the bits are set not sequentially, they will still be counted. 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.
Error in the passed arguments. - - esp_err_t esp_efuse_write_field_blob(const esp_efuse_desc_t *field [], const void *src, size_t src_size_bits) Writes array to EFUSE field. The number of write bits will be limited to the minimum value from the description of the bits in "field" structure or "src_size_bits" required size. Use "esp_efuse_get_field_size()" function to determine the length of the field. After the function is completed, the writing registers are cleared. - Parameters field -- [in] A pointer to the structure describing the fields of efuse. src -- [in] A pointer to array that contains the data for writing. src_size_bits -- [in] The number of bits required to write. - - Returns ESP_OK: The operation was successfully completed.
Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. - - esp_err_t esp_efuse_write_field_cnt(const esp_efuse_desc_t *field [], size_t cnt) Writes a required count of bits as "1" to EFUSE field. If there are no free bits in the field to set the required number of bits to "1", ESP_ERR_EFUSE_CNT_IS_FULL error is returned, the field will not be partially recorded. After the function is completed, the writing registers are cleared. - 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.
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.
Error repeated programming of programmed bits is strictly forbidden. - - esp_efuse_coding_scheme_t esp_efuse_get_coding_scheme(esp_efuse_block_t blk) Return efuse coding scheme for blocks. Note The coding scheme is applicable only to 1, 2 and 3 blocks. For 0 block, the coding scheme is always NONE. - Parameters blk -- [in] Block number of eFuse. - Returns Return efuse coding scheme for blocks - esp_err_t esp_efuse_read_block(esp_efuse_block_t blk, void *dst_key, size_t offset_in_bits, size_t size_bits) Read key to efuse block starting at the offset and the required size. 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.
Error range of data does not match the coding scheme. - - esp_err_t esp_efuse_write_block(esp_efuse_block_t blk, const void *src_key, size_t offset_in_bits, size_t size_bits) Write key to efuse block starting at the offset and the required size. - Parameters blk -- [in] Block number of eFuse. src_key -- [in] A pointer to array that contains the key for writing. offset_in_bits -- [in] Start bit in block. size_bits -- [in] The number of bits required to write. - - Returns ESP_OK: The operation was successfully completed.
Error repeated programming of programmed bits - - 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 - - esp_err_t esp_efuse_set_rom_log_scheme(esp_efuse_rom_log_scheme_t log_scheme) Set boot ROM log scheme via eFuse. 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. - Parameters log_scheme -- Supported ROM log scheme - Returns ESP_OK
This SoC is not capable of setting ROM log scheme ESP_ERR_INVALID_STATE This eFuse is write protected or has been burned already - - uint32_t esp_efuse_read_secure_version(void) Return secure_version from efuse field. - Returns Secure version from efuse field - bool esp_efuse_check_secure_version(uint32_t secure_version) Check secure_version from app and secure_version and from efuse field. - Parameters secure_version -- Secure version from app. - Returns True: If version of app is equal or more then secure_version from efuse. - - esp_err_t esp_efuse_update_secure_version(uint32_t secure_version) Write efuse field by secure_version value. Update the secure_version value is available if the coding scheme is None. Note: Do not use this function in your applications. This function is called as part of the other API. - Parameters secure_version -- [in] Secure version from app. - Returns ESP_OK: Successful. ESP_FAIL: secure version of app cannot be set to efuse field.
Anti rollback is not supported with the 3/4 and Repeat coding scheme. - - esp_err_t esp_efuse_batch_write_begin(void) Set the batch mode of writing fields. This mode allows you to write the fields in the batch mode when need to burn several efuses at one time. To enable batch mode call begin() then perform as usually the necessary operations read and write and at the end call commit() to actually burn all written efuses. The batch mode can be used nested. The commit will be done by the last commit() function. The number of begin() functions should be equal to the number of commit() functions. 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. // Example of using the batch writing mode. // set the batch writing mode esp_efuse_batch_write_begin(); // use any writing functions as usual esp_efuse_write_field_blob(ESP_EFUSE_...); esp_efuse_write_field_cnt(ESP_EFUSE_...); esp_efuse_set_write_protect(EFUSE_BLKx); esp_efuse_write_reg(EFUSE_BLKx, ...); esp_efuse_write_block(EFUSE_BLKx, ...); esp_efuse_write(ESP_EFUSE_1, 3); // ESP_EFUSE_1 == 1, here we write a new value = 3. The changes will be burn by the commit() function. esp_efuse_read_...(ESP_EFUSE_1); // this function returns ESP_EFUSE_1 == 1 because uncommitted changes are not readable, it will be available only after commit. ...
. - 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 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 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. Note For ESP32: no keypurpose, it returns always True. - Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX - Returns True: The key purpose is write protected. False: The key purpose is writeable. - esp_efuse_purpose_t esp_efuse_get_key_purpose(esp_efuse_block_t block) Returns the current purpose set for an efuse key block. - Parameters block -- [in] A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX - Returns Value: If Successful, it returns the value of the purpose related to the given key block. ESP_EFUSE_KEY_PURPOSE_MAX: Otherwise. - - esp_err_t esp_efuse_write_key(esp_efuse_block_t block, esp_efuse_purpose_t purpose, const void *key, size_t key_size_bytes) Program a block of key data to an efuse block. The burn of a key, protection bits, and a purpose happens in batch mode. Note This API also enables the read protection efuse bit for certain key blocks like XTS-AES, HMAC, ECDSA etc. This ensures that the key is only accessible to hardware peripheral.
Error repeated programming of programmed bits is strictly forbidden. ESP_ERR_CODING: Error range of data does not match the coding scheme. - - esp_err_t esp_efuse_write_keys(const esp_efuse_purpose_t purposes [], uint8_t keys[][32], unsigned number_of_keys) Program keys to unused efuse blocks. The burn of keys, protection bits, and purposes happens in batch mode. Note This API also enables the read protection efuse bit for certain key blocks like XTS-AES, HMAC, ECDSA etc. This ensures that the key is only accessible to hardware peripheral.
eFuse errors in BLOCK0. 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. Note Refers to ESP32-C3 only. - 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..-] - esp_efuse_block_t efuse_block 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 - enumerator ESP_EFUSE_ROM_LOG_ALWAYS_ON
Error Code and Helper Functions 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 Codes Reference. API Reference Header File This header file can be included with: #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.
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 This header file can be included with: #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 --
At most buflen bytes are written into the buf buffer (including 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 Operation has not fully completed - ESP_ERR_NOT_ALLOWED Operation is not allowed - 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.
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 intermediate ones from the certificate chain. The reason is 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_http_client_config_t::crt_bundle_attach member for verification by the ESP x509 Certificate Bundle feature, which covers most of the trusted root certificates. Partial Image Download over HTTPS To use the partial image download feature, enable partial_http_download configuration in esp_https_ota_config_t. When this configuration is enabled, firmware image will be downloaded in multiple HTTP requests of specified sizes. Maximum content length of each request can be specified by setting max_http_request_size to the required value. This option is useful while fetching image from a service like AWS S3, where mbedTLS Rx buffer size (CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN) can be set to a lower value which is not possible without enabling this configuration. Default value of mbedTLS Rx buffer size is set to 16 KB. By using partial_http_download with max_http_request_size of 4 KB, size of mbedTLS Rx buffer can be reduced to 4 KB. With this configuration, memory saving of around 12 KB is expected. Signature Verification For additional security, signature of OTA firmware images can be verified. For more information, please refer to 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. OTA Upgrades with Pre-Encrypted Firmware To perform OTA upgrades with pre-encrypted firmware, please enable CONFIG_ESP_HTTPS_OTA_DECRYPT_CB in component menuconfig. Example that performs OTA upgrade with pre-encrypted firmware: system/ota/pre_encrypted_ota. OTA System Events ESP HTTPS OTA has various events for which a handler can be triggered by the Event Loop Library when the particular event occurs. The handler has to be registered using esp_event_handler_register(). This helps the event handling for ESP HTTPS OTA. esp_https_ota_event_t has all the events which can happen when performing OTA upgrade using ESP HTTPS OTA.
event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) { if (event_base == ESP_HTTPS_OTA_EVENT) { switch (event_id) { case ESP_HTTPS_OTA_START: ESP_LOGI(TAG, "OTA started"); break; case ESP_HTTPS_OTA_CONNECTED: ESP_LOGI(TAG, "Connected to server"); break; case ESP_HTTPS_OTA_GET_IMG_DESC: ESP_LOGI(TAG, "Reading Image Description"); break; case ESP_HTTPS_OTA_VERIFY_CHIP_ID: ESP_LOGI(TAG, "Verifying chip id of new image: %d", *(esp_chip_id_t *)event_data); break; case ESP_HTTPS_OTA_DECRYPT_CB: ESP_LOGI(TAG, "Callback to decrypt function"); break; case ESP_HTTPS_OTA_WRITE_FLASH: ESP_LOGD(TAG, "Writing to flash: %d written", *(int *)event_data); break; case ESP_HTTPS_OTA_UPDATE_BOOT_PARTITION:
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_pemmember 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_otacomponent should be called. If more information and control is needed during the HTTPS OTA process, then one can use esp_https_ota_beginand subsequent APIs. If this API returns successfully, esp_restart() must be called to boot from the new firmware image. - Parameters ota_config -- [in] pointer to esp_https_ota_config_t structure. - Returns ESP_OK: OTA data updated, next reboot will use specified partition.
Flash write failed. For other return codes, refer OTA documentation in esp-idf's app_update component. - - esp_err_t esp_https_ota_begin(const esp_https_ota_config_t *ota_config, esp_https_ota_handle_t *handle) Start HTTPS OTA Firmware upgrade. This function initializes ESP HTTPS OTA context and establishes HTTPS connection. This function must be invoked first. If this function returns successfully, then esp_https_ota_performshould be called to continue with the OTA process and there should be a call to esp_https_ota_finishon completion of OTA operation or on failure in subsequent operations. This API supports URL redirection, but if CA cert of URLs differ then it should be appended to cert_pemmember of http_config, which is a part of ota_config. In case of error, this API explicitly sets handleto NULL. Note This API is blocking, so setting is_asyncmember of http_configstructure 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_twhich will be initialised in this function - - Returns ESP_OK: HTTPS OTA Firmware upgrade context initialised and HTTPS connection established ESP_FAIL: For generic failure.
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. - - esp_err_t esp_https_ota_perform(esp_https_ota_handle_t https_ota_handle) Read image data from HTTP stream and write it to OTA partition. This function reads image data from HTTP stream and writes it to OTA partition. This function must be called only if esp_https_ota_begin() returns successfully. This function must be called in a loop since it returns after every HTTP read operation thus giving you the flexibility to stop OTA operation midway. - Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure - Returns ESP_ERR_HTTPS_OTA_IN_PROGRESS: OTA update is in progress, call this API again to continue. ESP_OK: OTA update was successful ESP_FAIL: OTA update failed ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_INVALID_VERSION: Invalid chip revision in image header ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation. ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL:
Flash write failed. For other return codes, refer OTA documentation in esp-idf's app_update component. - - bool esp_https_ota_is_complete_data_received(esp_https_ota_handle_t https_ota_handle) Checks if complete data was received or not. Note This API can be called just before esp_https_ota_finish() to validate if the complete image was indeed received. - Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure - Returns false true - - esp_err_t esp_https_ota_finish(esp_https_ota_handle_t https_ota_handle) Clean-up HTTPS OTA Firmware upgrade and close HTTPS connection. This function closes the HTTP connection and frees the ESP HTTPS OTA context. This function switches the boot partition to the OTA partition containing the new firmware image. 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 - Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure - Returns ESP_OK: Clean-up successful ESP_ERR_INVALID_STATE ESP_ERR_INVALID_ARG: Invalid argument ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image - - esp_err_t esp_https_ota_abort(esp_https_ota_handle_t https_ota_handle) Clean-up HTTPS OTA Firmware upgrade and close HTTPS connection. This function closes the HTTP connection and frees the ESP HTTPS OTA context. Note esp_https_ota_abort should not be called after calling esp_https_ota_finish - Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure - Returns ESP_OK: Clean-up successful ESP_ERR_INVALID_STATE: Invalid ESP HTTPS OTA state ESP_FAIL: OTA not started ESP_ERR_NOT_FOUND: OTA handle not found ESP_ERR_INVALID_ARG:
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 - - int esp_https_ota_get_image_len_read(esp_https_ota_handle_t https_ota_handle) This function returns OTA image data read so far. Note This API should be called only if esp_https_ota_perform()has been called atleast once or if esp_https_ota_get_img_deschas been called before. - Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure - Returns -1 On failure total bytes read so far - - int esp_https_ota_get_image_size(esp_https_ota_handle_t https_ota_handle) This function returns OTA image total size. 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()) - Parameters https_ota_handle -- [in] pointer to esp_https_ota_handle_t structure - Returns -1 On failure or chunked encoding total bytes of image - Structures - struct esp_https_ota_config_t ESP HTTPS OTA configuration. Public Members - const esp_http_client_config_t *http_config ESP HTTP client configuration - 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 - const esp_http_client_config_t *http_config Macros - ESP_ERR_HTTPS_OTA_BASE - ESP_ERR_HTTPS_OTA_IN_PROGRESS Type Definitions - typedef void *esp_https_ota_handle_t - typedef esp_err_t (*http_client_init_cb_t)(esp_http_client_handle_t) Enumerations - enum esp_https_ota_event_t
Events generated by OTA process. Values: - enumerator ESP_HTTPS_OTA_START OTA started - enumerator ESP_HTTPS_OTA_CONNECTED Connected to server - enumerator ESP_HTTPS_OTA_GET_IMG_DESC Read app description from image header - enumerator ESP_HTTPS_OTA_VERIFY_CHIP_ID Verify chip id of new image - enumerator ESP_HTTPS_OTA_DECRYPT_CB Callback to decrypt function - enumerator ESP_HTTPS_OTA_WRITE_FLASH Flash write operation - enumerator ESP_HTTPS_OTA_UPDATE_BOOT_PARTITION Boot partition update after successful ota update - enumerator ESP_HTTPS_OTA_FINISH OTA finished - enumerator ESP_HTTPS_OTA_ABORT OTA aborted - enumerator ESP_HTTPS_OTA_START
Event Loop Library Overview The event loop library allows components to declare events so that other components can register handlers -- codes that executes when those events occur. This allows loosely-coupled components to attach desired behavior to state changes of other components without application involvement. This also simplifies event processing by serializing and deferring code execution to another context. One common case is, if a high-level library is using the Wi-Fi library: it may subscribe to ESP32 Wi-Fi Programming Model directly and act on those events. Note Various modules of the Bluetooth stack deliver events to applications via dedicated callback functions instead of via the Event Loop Library. Using esp_event APIs There are two objects of concern for users of this library: events and event loops. An event indicates an important occurrence, such as a successful Wi-Fi connection to an access point. A two-part identifier should be used when referencing events, see declaring and defining events for details. The event loop is the bridge between events and event handlers. The event source publishes events to the event loop using the APIs provided by the event loop library, and event handlers registered to the event loop respond to specific types of events. Using this library roughly entails the following flow: The user defines a function that should run when an event is posted to a loop. This function is referred to as the event handler, and should have the same signature as esp_event_handler_t. 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 is discussed in default event loop. Components register event handlers to the loop using esp_event_handler_register_with(). Handlers can be registered with multiple loops, see notes on handler registration. Event sources post an event to the loop using esp_event_post_to(). Components wanting to remove their handlers from being called can do so by unregistering from the loop using esp_event_handler_unregister_with(). Event loops that are no longer needed can be deleted using esp_event_loop_delete(). In code, the flow above may look like as follows: // 1. Define the event handler void
post-event MY_EVENT_BASE, MY_EVENT_ID and run loop at some point } 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 get 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 also gets its handlers registered first. Handlers registered one after the other by a single task are still dispatched in the order relative to each other, but if that task gets pre-empted in between registration by another task that also registers handlers; then during dispatch those handlers also get executed in between. Event Loop Profiling A configuration option CONFIG_ESP_EVENT_LOOP_PROFILING can be enabled in order to activate statistics collection for all event loops created. The function esp_event_dump() can be used to output the collected statistics to a file stream. More details on the information included in the dump can be found in the esp_event_dump() API Reference. Application Example Examples of using the esp_event library can be found in system/esp_event. The examples cover event declaration, loop creation, handler registration and deregistration, and event posting. Other examples which also adopt esp_event library: - NMEA Parser , which decodes the statements received from GPS. API Reference Header File This header file can be included with: #include "esp_event.h" This header file is a part of the API provided by the esp_eventcomponent. To declare that your component depends on esp_event, add the following to your CMakeLists.txt: REQUIRES esp_event or PRIV_REQUIRES
esp_event 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_ERR_INVALID_STATE: Default event loop has already been created 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 --
event_base, int32_t event_id, esp_event_handler_t event_handler, void *event_handler_arg) Register an event handler to the system event loop (legacy). 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. specific events: specify exact event_base and event_id all events of a certain base: specify exact event_base and use ESP_EVENT_ANY_ID as the event_id all events known by the loop: use ESP_EVENT_ANY_BASE for event_base and ESP_EVENT_ANY_ID as the event_id Registering multiple handlers to events is possible. Registering a single handler to multiple events is also possible. However, registering the same handler to the same event multiple times would cause the previous registrations to be overwritten. 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 dispatched 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 - - - esp_err_t esp_event_handler_register_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler,
void *event_handler_arg) Register an event handler to a specific loop (legacy). 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 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 dispatched 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 - - esp_err_t esp_event_handler_instance_register_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler, void *event_handler_arg, esp_event_handler_instance_t *instance)
Register an instance of event handler to a specific loop. 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. specific events: specify exact event_base and event_id all events of a certain base: specify exact event_base and use ESP_EVENT_ANY_ID as the event_id all events known by the loop: use ESP_EVENT_ANY_BASE for event_base and ESP_EVENT_ANY_ID as the event_id Besides the error, the function returns an instance object as output parameter to identify each registration. This is necessary to remove (unregister) the registration before the event loop is deleted. Registering multiple handlers to events, registering a single handler to multiple events as well as registering the same handler to the same event multiple times is possible. Each registration yields a distinct instance object which identifies it over the registration lifetime. 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 dispatched 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 - - - esp_err_t esp_event_handler_instance_register(esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler, void *event_handler_arg, esp_event_handler_instance_t *instance)
Register an instance of event handler to the default loop. This function does the same as esp_event_handler_instance_register_with, except that it registers the handler to the default event loop. 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 dispatched 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 - - esp_err_t esp_event_handler_unregister(esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler) Unregister a handler with the system event loop (legacy).
Unregisters a handler, so it will no longer be called during dispatch. Handlers can be unregistered for any combination 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 unregister handlers that were registered with the same wildcard arguments. 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 - esp_err_t esp_event_handler_unregister_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler) Unregister a handler from a specific event loop (legacy). 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. - 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 - - esp_err_t esp_event_handler_instance_unregister_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id, esp_event_handler_instance_t instance) Unregister a handler instance from a specific event loop.
| Task Name | Description | Stack Size | Affinity | Priority | Idle Tasks ( | An idle task ( | Core x | | FreeRTOS Timer Task ( | FreeRTOS will create the Timer Service/Daemon Task if any FreeRTOS Timer APIs are called by the application | Core 0 | Main Task ( | Task that simply calls | | IPC Tasks ( | When CONFIG_FREERTOS_UNICORE is false, an IPC task ( | Core x | | ESP Timer Task ( | ESP-IDF creates the ESP Timer Task used to process ESP Timer callbacks | Core 0 | Note Note that if an application uses other ESP-IDF features (e.g., Wi-Fi or Bluetooth), those features may create their own background tasks in addition to the tasks listed in the table above. FreeRTOS Additions ESP-IDF provides some supplemental features to FreeRTOS such as Ring Buffers, ESP-IDF style Tick and Idle Hooks, and TLSP deletion callbacks. See FreeRTOS (Supplemental Features) for more details. FreeRTOS Heap Vanilla FreeRTOS provides its own selection of heap implementations. However, ESP-IDF already implements its own heap (see Heap Memory Allocation), thus ESP-IDF does not make use of the heap implementations provided by Vanilla FreeRTOS. All FreeRTOS ports in ESP-IDF map FreeRTOS memory allocation or free calls (e.g., pvPortMalloc() and pvPortFree()) to ESP-IDF heap API (i.e., heap_caps_malloc() and heap_caps_free()). However, the FreeRTOS ports ensure that all dynamic memory allocated by FreeRTOS is placed in internal memory. Note If users wish to place FreeRTOS tasks/objects in external memory, users can use the following methods: Allocate the task or object using one of the ...CreateWithCaps()API, such as xTaskCreateWithCaps()and xQueueCreateWithCaps()(see
This document provides information regarding the dual-core SMP implementation of FreeRTOS inside ESP-IDF. This document is split into the following sections: Sections Overview The original FreeRTOS (hereinafter referred to as Vanilla FreeRTOS) is a compact and efficient real-time operating system supported on numerous single-core MCUs and SoCs. However, to support dual-core ESP targets, such as ESP32, ESP32-S3, and ESP32-P4, ESP-IDF provides a unique implementation of FreeRTOS with dual-core symmetric multiprocessing (SMP) capabilities (hereinafter referred to as IDF FreeRTOS). IDF FreeRTOS source code is based on Vanilla FreeRTOS v10.5.1 but contains significant modifications to both kernel behavior and API in order to support dual-core SMP. However, IDF FreeRTOS can also be configured for single-core by enabling the CONFIG_FREERTOS_UNICORE option (see Single-Core Mode for more details). Note This document assumes that the reader has a requisite understanding of Vanilla FreeRTOS, i.e., its features, behavior, and API usage. Refer to the Vanilla FreeRTOS documentation for more details. Symmetric Multiprocessing Basic Concepts Symmetric multiprocessing is a computing architecture where two or more identical CPU cores are connected to a single shared main memory and controlled by a single operating system. In general, an SMP system: has multiple cores running independently. Each core has its own register file, interrupts, and interrupt handling. presents an identical view of memory to each core. Thus, a piece of code that accesses a particular memory address has the same effect regardless of which core it runs on. The main advantages of an SMP system compared to single-core or asymmetric multiprocessing systems are that: the presence of multiple cores allows for multiple hardware threads, thus increasing overall processing throughput. having symmetric memory means that threads can switch cores during execution. This, in general, can lead to better CPU utilization. Although an SMP system allows threads to switch cores, there are scenarios where a thread must/should only run on a particular core. Therefore, threads in an SMP system also have a core affinity that specifies which particular core the thread is allowed to run on. A thread that is pinned to a particular core is only able to run on that core. A thread that is unpinned will be allowed to switch between cores during execution instead of being pinned to a particular core. SMP on an ESP Target ESP targets such as ESP32, ESP32-S3, and ESP32-P4 are dual-core SMP SoCs. These targets have the following hardware features that make them SMP-capable: Two identical cores are known as Core 0 and Core 1. This means that the execution of a piece of code is identical regardless of which core it runs on.
If multiple cores access the same memory address simultaneously, their access will be serialized by the memory bus. True atomic access to the same memory address is achieved via an atomic compare-and-swap instruction provided by the ISA. - Cross-core interrupts that allow one core to trigger an interrupt on the other core. This allows cores to signal events to each other (such as requesting a context switch on the other core). Note Within ESP-IDF, Core 0 and Core 1 are sometimes referred to as PRO_CPU and APP_CPU respectively. The aliases exist in ESP-IDF as they reflect how typical ESP-IDF applications utilize the two cores. Typically, the tasks responsible for handling protocol related processing such as Wi-Fi or Bluetooth are pinned to Core 0 (thus the name PRO_CPU), where as the tasks handling the remainder of the application are pinned to Core 1, (thus the name APP_CPU). Tasks Creation Vanilla FreeRTOS provides the following functions to create a task: xTaskCreate()creates a task. The task's memory is dynamically allocated. xTaskCreateStatic()creates a task. The task's memory is statically allocated, i.e., provided by the user. However, in an SMP system, tasks need to be assigned a particular affinity. Therefore, ESP-IDF provides a ...PinnedToCore() version of Vanilla FreeRTOS's task creation functions: xTaskCreatePinnedToCore()creates a task with a particular core affinity. The task's memory is dynamically allocated. xTaskCreateStaticPinnedToCore()creates a task with a particular core affinity. The task's memory is statically allocated, i.e., provided by the user. The ...PinnedToCore() versions of the task creation function API differ from their vanilla counterparts by having an extra xCoreID parameter that is used to specify the created task's core affinity. The valid values for core affinity are: 0, which pins the created task to Core 0 1, which pins the created task to Core 1 tskNO_AFFINITY, which allows the task to be run on both cores Note that IDF FreeRTOS still supports the vanilla versions of the task creation functions. However, these standard functions have been modified to essentially invoke their respective ...PinnedToCore() counterparts while setting the core affinity to tskNO_AFFINITY. Note IDF FreeRTOS also changes the units of ulStackDepth in the task creation functions. Task stack sizes in Vanilla FreeRTOS are specified in a number of words, whereas in IDF FreeRTOS, the task stack sizes are specified in bytes. Execution The anatomy of a task in IDF FreeRTOS is the same as in Vanilla FreeRTOS. More specifically, IDF FreeRTOS tasks: Can only be in one of the following states: Running, Ready, Blocked, or Suspended. Task functions are typically implemented as an infinite loop. Task functions should never return.
IDF FreeRTOS provides the same vTaskDelete() function. However, due to the dual-core nature, there are some behavioral differences when calling vTaskDelete() in IDF FreeRTOS: When deleting a task that is currently running on the other core, a yield is triggered on the other core, and the task's memory is freed by one of the idle tasks. A deleted task's memory is freed immediately if it is not running on either core. Please avoid deleting a task that is running on another core as it is difficult to determine what the task is performing, which may lead to unpredictable behavior such as: Deleting a task that is holding a mutex. Deleting a task that has yet to free memory it previously allocated. Where possible, please design your own application so that when calling vTaskDelete(), the deleted task is in a known state. For example: Tasks self-deleting via vTaskDelete(NULL)when their execution is complete and have also cleaned up all resources used within the task. Tasks placing themselves in the suspend state via vTaskSuspend()before being deleted by another task. SMP Scheduler The Vanilla FreeRTOS scheduler is best described as a fixed priority preemptive scheduler with time slicing meaning that: Each task is given a constant priority upon creation. The scheduler executes the highest priority ready-state task. The scheduler can switch execution to another task without the cooperation of the currently running task. The scheduler periodically switches execution between ready-state tasks of the same priority in a round-robin fashion. Time slicing is governed by a tick interrupt. The IDF FreeRTOS scheduler supports the same scheduling features, i.e., Fixed Priority, Preemption, and Time Slicing, albeit with some small behavioral differences. Fixed Priority In Vanilla FreeRTOS, when the scheduler selects a new task to run, it always selects the current highest priority ready-state task. In IDF FreeRTOS, each core independently schedules tasks to run. When a particular core selects a task, the core will select the highest priority ready-state task that can be run by the core. A task can be run by the core if: The task has a compatible affinity, i.e., is either pinned to that core or is unpinned. The task is not currently being run by another core. However, please do not assume that the two highest priority ready-state tasks are always run by the scheduler, as a task's core affinity must also be accounted for.
Task B is not run even though it is the second-highest priority task. Preemption In Vanilla FreeRTOS, the scheduler can preempt the currently running task if a higher priority task becomes ready to execute. Likewise in IDF FreeRTOS, each core can be individually preempted by the scheduler if the scheduler determines that a higher-priority task can run on that core. However, there are some instances where a higher-priority task that becomes ready can be run on multiple cores. In this case, the scheduler only preempts one core. The scheduler always gives preference to the current core when multiple cores can be preempted. In other words, if the higher priority ready task is unpinned and has a higher priority than the current priority of both cores, the scheduler will always choose to preempt the current core. For example, given the following tasks: Task A of priority 8 currently running on Core 0 Task B of priority 9 currently running on Core 1 Task C of priority 10 that is unpinned and was unblocked by Task B The resulting schedule will have Task A running on Core 0 and Task C preempting Task B given that the scheduler always gives preference to the current core. Time Slicing The Vanilla FreeRTOS scheduler implements time slicing, which means that if the current highest ready priority contains multiple ready tasks, the scheduler will switch between those tasks periodically in a round-robin fashion. However, in IDF FreeRTOS, it is not possible to implement perfect Round Robin time slicing due to the fact that a particular task may not be able to run on a particular core due to the following reasons: The task is pinned to another core. For unpinned tasks, the task is already being run by another core. Therefore, when a core searches the ready-state task list for a task to run, the core may need to skip over a few tasks in the same priority list or drop to a lower priority in order to find a ready-state task that the core can run. The IDF FreeRTOS scheduler implements a Best Effort Round Robin time slicing for ready-state tasks of the same priority by ensuring that tasks that have been selected to run are placed at the back of the list, thus giving unselected tasks a higher priority on the next scheduling iteration (i.e., the next tick interrupt or yield). The following example demonstrates the Best Effort Round Robin time slicing in action. Assume that: There are four ready-state tasks of the same priority AX, B0, C1, and D1where: The priority is the current highest priority with ready-state . The first character represents the task's name, i.e., A, B, C, D. The second character represents the task's core pinning, and Xmeans unpinned. - The task list is always searched from the head. Starting state. None of the ready-state tasks have been selected to run.
Tail The implications to users regarding the Best Effort Round Robin time slicing: Users cannot expect multiple ready-state tasks of the same priority to run sequentially as is the case in Vanilla FreeRTOS. As demonstrated in the example above, a core may need to skip over tasks. However, given enough ticks, a task will eventually be given some processing time. If a core cannot find a task runnable task at the highest ready-state priority, it will drop to a lower priority to search for tasks. To achieve ideal round-robin time slicing, users should ensure that all tasks of a particular priority are pinned to the same core. Tick Interrupts Vanilla FreeRTOS requires that a periodic tick interrupt occurs. The tick interrupt is responsible for: Incrementing the scheduler's tick count Unblocking any blocked tasks that have timed out Checking if time slicing is required, i.e., triggering a context switch Executing the application tick hook In IDF FreeRTOS, each core receives a periodic interrupt and independently runs the tick interrupt. The tick interrupts on each core are of the same period but can be out of phase. However, the tick responsibilities listed above are not run by all cores: Core 0 executes all of the tick interrupt responsibilities listed above Core 1 only checks for time slicing and executes the application tick hook Note Core 0 is solely responsible for keeping time in IDF FreeRTOS. Therefore, anything that prevents Core 0 from incrementing the tick count, such as suspending the scheduler on Core 0, will cause the entire scheduler's timekeeping to lag behind. Idle Tasks Vanilla FreeRTOS will implicitly create an idle task of priority 0
Single-Core Mode Although IDF FreeRTOS is modified for dual-core SMP, IDF FreeRTOS can also be built for single-core by enabling the CONFIG_FREERTOS_UNICORE option. For single-core targets (such as ESP32-S2 and ESP32-C3), the CONFIG_FREERTOS_UNICORE option is always enabled. For multi-core targets (such as ESP32 and ESP32-S3), CONFIG_FREERTOS_UNICORE can also be set, but will result in the application only running Core 0. When building in single-core mode, IDF FreeRTOS is designed to be identical to Vanilla FreeRTOS, thus all aforementioned SMP changes to kernel behavior are removed. As a result, building IDF FreeRTOS in single-core mode has the following characteristics: All operations performed by the kernel inside critical sections are now deterministic (i.e., no walking of linked lists inside critical sections). Vanilla FreeRTOS scheduling algorithm is restored (including perfect Round Robin time slicing). All SMP specific data is removed from single-core builds. SMP APIs can still be called in single-core mode. These APIs remain exposed to allow source code to be built for single-core and multi-core, without needing to call a different set of APIs. However, SMP APIs will not exhibit any SMP behavior in single-core mode, thus becoming equivalent to their single-core counterparts.
API will only accept 0as a valid value for xCoreID. ... PinnedToCore()task creation APIs will simply ignore the xCoreIDcore affinity argument. Critical section APIs will still require a spinlock argument, but no spinlock will be taken and critical sections revert to simply disabling/enabling interrupts. API Reference This section introduces FreeRTOS types, functions, and macros. It is automatically generated from FreeRTOS header files. Task API Header File This header file can be included with: #include "freertos/task.h" Functions - static inline BaseType_t xTaskCreate(TaskFunction_t pxTaskCode, const char *const pcName, const configSTACK_DEPTH_TYPE 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.
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().
void vTaskCode( void * pvParameters ) { for( ;; ) { // Task code goes here. } } // Function that creates a task. void vOtherFunction( void ) { static uint8_t ucParameterToPass ; TaskHandle_t xHandle = NULL; // 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 // the new task attempts to access it.
xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle ); configASSERT( xHandle ); // Use the handle to delete the task. if( xHandle != NULL ) { vTaskDelete( xHandle ); } } Note If configNUMBER_OF_CORES > 1, this function will create an unpinned task (see tskNO_AFFINITY for more details). 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 pxTaskCode -- Pointer to the task entry function. Tasks must be implemented to never return (i.e. continuous loop).
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 portPRIVILEGE_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 referenced. - - 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 TaskHandle_t xTaskCreateStatic(TaskFunction_t pxTaskCode, const char *const pcName, const uint32_t ulStackDepth, void *const pvParameters, UBaseType_t uxPriority, StackType_t *const puxStackBuffer, StaticTask_t *const pxTaskBuffer) 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. Example usage: // Dimensions of the buffer that the task being created will use as its stack. //
This is the number of words the stack will hold, not the number of // bytes. For example, if each stack item is 32-bits, and this is set to 100, // then 400 bytes (100 * 32-bits) will be allocated. #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 ]; // Function that implements the task being created. void vTaskCode( void * pvParameters ) { //
Parameter passed into the task. tskIDLE_PRIORITY,// Priority at which the task is created. xStack, // Array to use as the task's stack. &xTaskBuffer ); // Variable to hold the task's data structure. // 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 configNUMBER_OF_CORES > 1, this function will create an unpinned task (see tskNO_AFFINITY for more details). 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 pxTaskCode -- Pointer to the task entry function. Tasks must be implemented to never return (i.e. continuous loop).
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 puxStackBuffer nor pxTaskBuffer are NULL, then the task will be created and a handle to the created task is returned. If either puxStackBuffer or pxTaskBuffer are NULL then the task will not be created and NULL is returned. - void vTaskAllocateMPURegions(TaskHandle_t xTask, const MemoryRegion_t *const pxRegions) 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: // Define an array of MemoryRegion_t structures that configures an MPU region // allowing read/write access for 1024 bytes starting at the beginning of the // ucOneKByte array. The other two of the maximum 3 definable regions are // unused so set to zero. static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] = { // Base address Length Parameters { ucOneKByte, 1024, portMPU_REGION_READ_WRITE }, { 0, 0, 0 }, { 0, 0, 0 } }; void vATask( void *pvParameters ) { // This task was created such that it has access to certain regions of // memory as defined by the MPU configuration. At some point it is // desired that these MPU regions are replaced with that defined in the // xAltRegions const struct above. Use a call to vTaskAllocateMPURegions() // for this purpose. NULL is used as the task handle to indicate that this // function should modify the MPU regions of the calling task. vTaskAllocateMPURegions( NULL, xAltRegions ); // 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 xTask -- The handle of the task being updated. pxRegions -- A pointer to a MemoryRegion_t structure that contains the new memory region definitions. - - void vTaskDelete(TaskHandle_t xTaskToDelete) INCLUDE_vTaskDelete must be defined as 1 for this function to be available. See the configuration section for more information. Remove a task from the RTOS real time kernel's management. The task being deleted will be removed from all ready, blocked, suspended and event lists.
The idle task is responsible for freeing the kernel allocated memory from tasks that have been deleted. It is therefore important that the idle task is not starved of microcontroller processing time if your application makes any calls to vTaskDelete (). Memory allocated by the task code is not automatically freed, and should be freed before the task is deleted. See the demo application file death.c for sample code that utilises vTaskDelete (). Example usage: void vOtherFunction( void ) { TaskHandle_t xHandle; // Create the task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // Use the handle to delete the task. vTaskDelete( xHandle ); } - Parameters xTaskToDelete --
The handle of the task to be deleted. Passing NULL will cause the calling task to be deleted. - void vTaskDelay(const TickType_t xTicksToDelay) Delay a task for a given number of ticks. The actual time that the task remains blocked depends on the tick rate. The constant portTICK_PERIOD_MS can be used to calculate real time from the tick rate - with the resolution of one tick period. INCLUDE_vTaskDelay must be defined as 1 for this function to be available. See the configuration section for more information. vTaskDelay() specifies a time at which the task wishes to unblock relative to the time at which vTaskDelay() is called. For example, specifying a block period of 100 ticks will cause the task to unblock 100 ticks after vTaskDelay() is called. vTaskDelay() does not therefore provide a good method of controlling the frequency of a periodic task as the path taken through the code, as well as other task and interrupt activity, will affect the frequency at which vTaskDelay() gets called and therefore the time at which the task next executes. See xTaskDelayUntil() for an alternative API function designed to facilitate fixed frequency execution. It does this by specifying an absolute time (rather than a relative time) at which the calling task should unblock.
Example usage: void vTaskFunction( void * pvParameters ) { // Block for 500ms. const TickType_t xDelay = 500 / portTICK_PERIOD_MS; 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. - BaseType_t xTaskDelayUntil(TickType_t *const pxPreviousWakeTime, const TickType_t xTimeIncrement) INCLUDE_xTaskDelayUntil must be defined as 1 for this function to be available. See the configuration section for more information. Delay a task until a specified time. This function can be used by periodic tasks to ensure a constant execution frequency. This function differs from vTaskDelay () in one important aspect: vTaskDelay () will cause a task to block for the specified number of ticks from the time vTaskDelay () is called. It is therefore difficult to use vTaskDelay () by itself to generate a fixed execution frequency as the time between a task starting to execute and that task calling vTaskDelay () may not be fixed [the task may take a different path though the code between calls, or may get interrupted or preempted a different number of times each time it executes]. Whereas vTaskDelay () specifies a wake time relative to the time at which the function is called, xTaskDelayUntil () specifies the absolute (exact) time at which it wishes to unblock. The macro pdMS_TO_TICKS() can be used to calculate the number of ticks from a time specified in milliseconds with a resolution of one tick period. Example usage: // Perform an action every 10 ticks. void vTaskFunction( void * pvParameters ) { TickType_t xLastWakeTime; const TickType_t xFrequency = 10; BaseType_t xWasDelayed; // Initialise the xLastWakeTime variable with the current time. xLastWakeTime = xTaskGetTickCount (); for( ;; ) { // Wait for the next cycle. xWasDelayed = xTaskDelayUntil( &xLastWakeTime, xFrequency ); // Perform action here.
The cycle time period. The task will be unblocked at time *pxPreviousWakeTime + xTimeIncrement. Calling xTaskDelayUntil with the same xTimeIncrement 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 . - BaseType_t xTaskAbortDelay(TaskHandle_t xTask) INCLUDE_xTaskAbortDelay must be defined as 1 in FreeRTOSConfig.h for this function to be available. A task will enter the Blocked state when it is waiting for an event. The event it is waiting for can be a temporal event (waiting for a time), such as when vTaskDelay() is called, or an event on an object, such as when xQueueReceive() or ulTaskNotifyTake() is called. If the handle of a task that is in the Blocked state is used in a call to xTaskAbortDelay() then the task will leave the Blocked state, and return from whichever function call placed the task into the Blocked state. There is no 'FromISR' version of this function as an interrupt would need to know which object a task was blocked on in order to know which actions to take. For example, if the task was blocked on a queue the interrupt handler would then need to know if the queue was locked. - Parameters xTask -- The handle of the task to remove from the Blocked state. - Returns If the task referenced by xTask was not in the Blocked state then pdFAIL is returned. Otherwise pdPASS is returned. - UBaseType_t uxTaskPriorityGet(const TaskHandle_t xTask) INCLUDE_uxTaskPriorityGet must be defined as 1 for this function to be available. See the configuration section for more information. Obtain the priority of any task. Example usage: void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... // Use the handle to obtain the priority of the created task. // It was created with tskIDLE_PRIORITY, but may have changed // it itself. if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY ) { // The task has changed it's priority. } // ... //
if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) ) { // Our priority (obtained using NULL handle) is higher. } } - 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. - UBaseType_t uxTaskPriorityGetFromISR(const TaskHandle_t xTask) A version of uxTaskPriorityGet() that can be used from an ISR. - eTaskState eTaskGetState(TaskHandle_t xTask) INCLUDE_eTaskGetState must be defined as 1 for this function to be available. See the configuration section for more information. Obtain the state of any task. States are encoded by the eTaskState enumerated type. - Parameters xTask -- Handle of the task to be queried. - Returns The state of xTask at the time the function was called. Note the state of the task might change between the function being called, and the functions return value being tested by the calling task. - void vTaskGetInfo(TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState)
configUSE_TRACE_FACILITY must be defined as 1 for this function to be available. See the configuration section for more information. Populates a TaskStatus_t structure with information about a task. Example usage: void vAFunction( void ) { TaskHandle_t xHandle; TaskStatus_t xTaskDetails; // Obtain the handle of a task from its name. xHandle = xTaskGetHandle( "Task_Name" ); // Check the handle is not NULL. configASSERT( xHandle ); // Use the handle to obtain further information about the task. vTaskGetInfo( xHandle, &xTaskDetails, pdTRUE, // Include the high water mark in xTaskDetails. eInvalid )
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. - - void vTaskPrioritySet(TaskHandle_t xTask, UBaseType_t uxNewPriority) INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available. See the configuration section for more information. Set the priority of any task. A context switch will occur before the function returns if the priority being set is higher than the currently executing task. Example usage: void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... //
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. - - void vTaskSuspend(TaskHandle_t xTaskToSuspend) INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. See the configuration section for more information. Suspend any task. When suspended a task will never get any microcontroller processing time, no matter what its priority. Calls to vTaskSuspend are not accumulative - i.e. calling vTaskSuspend () twice on the same task still only requires one call to vTaskResume () to ready the suspended task. Example usage: void vAFunction( void ) { TaskHandle_t xHandle; // Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); // ... //
vTaskSuspend( xHandle ); // ... // The created task will not run during this period, unless // another task calls vTaskResume( xHandle ). //... // Resume the suspended task ourselves. vTaskResume( xHandle ); // The created task will once again get microcontroller processing // time in accordance with its priority within the system. } - Parameters xTaskToResume -- Handle to the task being readied. - BaseType_t xTaskResumeFromISR(TaskHandle_t xTaskToResume) INCLUDE_xTaskResumeFromISR must be defined as 1 for this function to be available. See the configuration section for more information. An implementation of vTaskResume() that can be called from within an ISR. A task that has been suspended by one or more calls to vTaskSuspend () will be made available for running again by a single call to xTaskResumeFromISR (). xTaskResumeFromISR() should not be used to synchronise a task with an interrupt if there is a chance that the interrupt could arrive prior to the task being suspended - as this can lead to interrupts being missed. Use of a semaphore as a synchronisation mechanism would avoid this eventuality. - Parameters xTaskToResume -- Handle to the task being readied. - Returns pdTRUE if resuming the task should result in a context switch, otherwise pdFALSE. This is used by the ISR to determine if a context switch may be required following the ISR. - 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, xTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler is suspended. Example usage: void vTask1( void * pvParameters ) { for( ;; ) { // Task code goes here. // ... //
At some point the task wants to perform a long operation during // which it does not want to get swapped out. It cannot use // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the // operation may cause interrupts to be missed - including the // ticks. // Prevent the real time kernel swapping out the task. vTaskSuspendAll (); // Perform the operation here. There is no need to use critical // sections as we have all the microcontroller processing time. // During this time interrupts will still operate and the kernel // tick count will be maintained. // ... //
At some point the task wants to perform a long operation during // which it does not want to get swapped out. It cannot use // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the // operation may cause interrupts to be missed - including the // ticks. // Prevent the real time kernel swapping out the task. vTaskSuspendAll (); // Perform the operation here. There is no need to use critical // sections as we have all the microcontroller processing time. // During this time interrupts will still operate and the real // time kernel tick count will be maintained. // ... //
if( !xTaskResumeAll () ) { taskYIELD (); } } } - Returns If resuming the scheduler caused a context switch then pdTRUE is returned, otherwise pdFALSE is returned. - TickType_t xTaskGetTickCount(void) - Returns The count of ticks since vTaskStartScheduler was called. - TickType_t xTaskGetTickCountFromISR(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. - BaseType_t xTaskGetStaticBuffers(TaskHandle_t xTask, StackType_t **ppuxStackBuffer, StaticTask_t **ppxTaskBuffer) Retrieve pointers to a statically created task's data structure buffer and stack buffer. These are the same buffers that are supplied at the time of creation. - Parameters xTask -- The task for which to retrieve the buffers. ppuxStackBuffer -- Used to return a pointer to the task's stack buffer. ppxTaskBuffer -- Used to return a pointer to the task's data structure buffer. - - Returns pdTRUE if buffers were retrieved, pdFALSE otherwise. - UBaseType_t uxTaskGetStackHighWaterMark(TaskHandle_t 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 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.
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. - configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2(TaskHandle_t 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.
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. - void vTaskSetApplicationTaskTag(TaskHandle_t xTask, TaskHookFunction_t pxHookFunction) Sets pxHookFunction to be the task hook function used by the task xTask. Passing xTask as NULL has the effect of setting the calling tasks hook function. - TaskHookFunction_t xTaskGetApplicationTaskTag(TaskHandle_t xTask) Returns the pxHookFunction value assigned to the task 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) Each task contains an array of pointers that is dimensioned by the configNUM_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. The following two functions are used to set and query a pointer respectively. - void *pvTaskGetThreadLocalStoragePointer(TaskHandle_t xTaskToQuery, BaseType_t xIndex) - void vApplicationGetIdleTaskMemory(StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize) This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Idle 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 ppxIdleTaskTCBBuffer -- A handle to a statically allocated TCB buffer ppxIdleTaskStackBuffer -- A handle to a statically allocated Stack buffer for the idle task pulIdleTaskStackSize -- A pointer to the number of elements that will fit in the allocated stack buffer - - BaseType_t xTaskCallApplicationTaskHook(TaskHandle_t xTask, void *pvParameter) Calls the hook function associated with xTask. Passing xTask as NULL has the effect of calling the Running tasks (the calling task) hook function. pvParameter is passed to the hook function for the task to interpret as it wants. The return value is the value returned by the task hook function registered by the user. - TaskHandle_t xTaskGetIdleTaskHandle(void) xTaskGetIdleTaskHandle() is only available if INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h. Simply returns the handle of the idle task of the current core. It is not valid to call xTaskGetIdleTaskHandle() before the scheduler has been started. - UBaseType_t uxTaskGetSystemState(TaskStatus_t *const pxTaskStatusArray, const UBaseType_t uxArraySize, configRUN_TIME_COUNTER_TYPE *const pulTotalRunTime) configUSE_TRACE_FACILITY must be defined as 1 in FreeRTOSConfig.h for uxTaskGetSystemState() to be available. uxTaskGetSystemState() populates an TaskStatus_t structure for each task in the system. TaskStatus_t structures contain, among other things, members for the task handle, task name, task priority, task state, and total amount of run time consumed by the task. See the TaskStatus_t structure definition in this file for the full member list.
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; configRUN_TIME_COUNTER_TYPE ulTotalRunTime, ulStatsAsPercentage; // Make sure the write buffer does not contain a string. pcWriteBuffer = 0x00; // Take a snapshot of the number of tasks in case it changes while this // function is executing. uxArraySize = uxTaskGetNumberOfTasks(); // Allocate a TaskStatus_t structure for each task. An array could be // allocated statically at compile time.