Table of Contents

Advertisement

Quick Links

ESP32-S2
ESP-IDF Programming Guide
Release v4.4
Espressif Systems
Jan 24, 2022

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the ESP32-S2 and is the answer not in the manual?

Questions and answers

Summary of Contents for Espressif ESP32-S2

  • Page 1 ESP32-S2 ESP-IDF Programming Guide Release v4.4 Espressif Systems Jan 24, 2022...
  • Page 2: Table Of Contents

    ......... . 69 1.16.1 Establish Serial Connection with ESP32-S2 .
  • Page 3 1.16.5 Customized Setup of Toolchain ....... 80 2 API Reference Networking APIs .
  • Page 4 ........1242 3 ESP32-S2 Hardware Reference...
  • Page 5 4.1.3 Configuration Options and Dependencies ......1254 4.1.4 How to use this library ........1255 Application Startup Flow .
  • Page 6 ........1351 4.13.6 ESP32-S2 Flash Encryption Status .
  • Page 7 ........1372 4.17.5 Configuring ESP32-S2 Target .
  • Page 8 ........1476 4.28.1 ESP32-S2 ULP coprocessor instruction set .
  • Page 9 ..... . . 1528 4.33.11 ESP32-S2 Wi-Fi Station Connecting When Multiple APs Are Found ... 1532 4.33.12 Wi-Fi Reconnect...
  • Page 10 ......... . 1568 6.5.1 Espressif IoT Development Framework Style Guide ....1568 6.5.2...
  • Page 11 10 About 1599 11 Switch Between Languages 1601 Index 1603 Index 1603...
  • Page 12 Table of contents This is the documentation for Espressif IoT Development Framework (esp-idf). ESP-IDF is the official development framework for the ESP32, ESP32-S and ESP32-C Series SoCs. This document describes using ESP-IDF with the ESP32-S2 SoC. Get Started API Reference...
  • Page 13 Table of contents Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 14: Get Started

    This document is intended to help you set up the software development environment for the hardware based on the ESP32-S2 chip by Espressif. After that, a simple example will show you how to use ESP-IDF (Espressif IoT Development Framework) for menu configuration, then for building and flashing firmware onto an ESP32-S2 board.
  • Page 15: Development Board Overviews

    (setup) Fig. 1: Development of applications for ESP32-S2 1.3 Development Board Overviews If you have one of ESP32-S2 development boards listed below, you can click on the link to learn more about its hardware. 1.3.1 ESP32-S2-Saola-1 This user guide provides information on ESP32-S2-Saola-1, a small-sized...
  • Page 16 Chapter 1. Get Started Fig. 2: ESP32-S2-Saola-1 Getting Started This section describes how to get started with ESP32-S2-Saola-1. It begins with a few introductory sections about the ESP32-S2-Saola-1, then Section Start Application Development provides instructions on how to get the ESP32- S2-Saola-1 ready and flash firmware into it.
  • Page 17 Description ESP32-S2-WROVER ESP32-S2-WROVER is a powerful, generic Wi-Fi MCU module that inte- grates ESP32-S2. It has a PCB antenna, a 4 MB external SPI flash and an additional 2 MB PSRAM. Pin Headers All available GPIO pins (except for the SPI bus for flash and PSRAM) are broken out to the pin headers on the board.
  • Page 18 Chapter 1. Get Started Note: ESP32-S2 series of chips only supports ESP-IDF master or version v4.2 and higher. Hardware Reference Block Diagram A block diagram below shows the components of ESP32-S2-Saola-1 and their interconnections. Fig. 4: ESP32-S2-Saola-1 (click to enlarge)
  • Page 19 GPIO19, ADC2_CH8, USB_D- IO18 GPIO18, ADC2_CH7, DAC_2, RGB LED Pin Layout Hardware Revision Details This is the first revision of this board released. P: Power supply; I: Input; O: Output; T: High impedance. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 20: Esp32-S2-Devkitm-1(U)

    ESP32-S2-DevKitM-1(U) is a general-purpose development board based on ESP32-S2FH4 chip, which falls into ESP32-S2 chip series. With a rich peripheral set and optimized pinout, this board allows rapid prototyping. ESP32-S2-DevKitM-1 is embedded with ESP32-S2-MINI-1 module (on-board PCB antenna), while ESP32-S2-...
  • Page 21 ESP32-S2-DevKitM-1(U) is entry-level development board equipped with either ESP32-S2-MINI-1 or ESP32-S2-MINI-1U module. Most of the I/O pins on the module are broken out to the pin headers on both sides for easy interfacing. Developers can either connect peripherals with jumper wires or mount ESP32-S2-DevKitM-1(U) on a breadboard.
  • Page 22 Chapter 1. Get Started Fig. 6: ESP32-S2-DevKitM-1 - front Fig. 7: ESP32-S2-DevKitM-1U - front Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 23 Installation Step by Step will quickly help you set up the development environment and then flash an application example into your ESP32-S2-DevKitM-1(U). Note: ESP32-S2 series of chips only is only supported in ESP-IDF master or version v4.2 and higher. Hardware Reference Block Diagram A block diagram below shows the components of ESP32-S2-DevKitM-1 and their interconnec- tions.
  • Page 24 Chapter 1. Get Started Fig. 8: ESP32-S2-DevKitM-1(U) (click to enlarge) Header Block The two tables below provide the Name and Function of the pin headers on both sides of the board (J1 and J3). The pin header names are shown in ESP32-S2-DevKitM-1 - front.
  • Page 25 I/O/T RTC_GPIO20, GPIO20, U1CTS, ADC2_CH9, CLK_OUT1, USB_D+ I/O/T RTC_GPIO19, GPIO19, U1RTS, ADC2_CH8, CLK_OUT2, USB_D- I/O/T RTC_GPIO18, GPIO18, U1RXD, ADC2_CH7, DAC_2, CLK_OUT3, RGB LED Fig. 9: ESP32-S2-DevKitM-1(U) Pin Layout (click to enlarge) Pin Layout Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 26: Esp32-S2-Devkitc-1

    For other design documentation for the board, please contact us at sales@espressif.com. 1.3.3 ESP32-S2-DevKitC-1 This user guide will help you get started with ESP32-S2-DevKitC-1 and will also provide more in-depth information. ESP32-S2-DevKitC-1 is an entry-level development board based on ESP32-S2-SOLO (on-board PCB antenna) or ESP32-S2-SOLO-U (external antenna connector), which are two general-purpose modules with a 4 MB SPI flash.
  • Page 27 Chapter 1. Get Started Getting Started This section provides a brief introduction of ESP32-S2-DevKitC-1, instructions on how to do the initial hardware setup and how to flash firmware onto it. Fig. 11: ESP32-S2-DevKitC-1 - front Description of Components The key components of the board are described in a clockwise direction.
  • Page 28 Started, where Section Installation Step by Step will quickly help you set up the development environment and then flash an application example into your ESP32-S2-DevKitC-1. Contents and Packaging Retail orders If you order a few samples, each ESP32-S2-DevKitC-1 comes in an individual package in either antistatic bag or any packaging depending on your retailer.
  • Page 29 Power Supply Options There are three mutually exclusive ways to provide power to the board: • USB-to-UART Port and ESP32-S2 USB Port (either one or both), default power supply (recommended) • 5V and G (GND) pins • 3V3 and G (GND) pins...
  • Page 30 I/O/T SPIIO4, GPIO33, FSPIHD I/O/T RTC_GPIO21, GPIO21 I/O/T RTC_GPIO20, GPIO20, U1CTS, ADC2_CH9, CLK_OUT1, USB_D+ I/O/T RTC_GPIO19, GPIO19, U1RTS, ADC2_CH8, CLK_OUT2, USB_D- Ground Ground Fig. 13: ESP32-S2-DevKitC-1 Pin Layout (click to enlarge) Pin Layout Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 31: Esp32-S2-Kaluga-1 Kit V1.3

    • Provide the users with the tools for development of human-computer interaction applications based on the ESP32-S2 There are many ways of how the ESP32-S2’s abundant functionalities can be used. For starters, the possible use cases may include: • Smart home: From simplest smart lighting, smart door locks, smart sockets, to video streaming devices, security cameras, OTT devices, and home appliances •...
  • Page 32 Related Documents: Gives links to related documentation. Getting Started This section describes how to get started with the ESP32-S2-Kaluga-1. It begins with a few introductory sections about the ESP32-S2-Kaluga-1, then Section Start Application Development provides instructions on how to do the initial hardware setup and then how to flash firmware onto the ESP32-S2-Kaluga-1.
  • Page 33 Chapter 1. Get Started Fig. 15: ESP32-S2-Kaluga-1 (click to enlarge) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 34 Chapter 1. Get Started Fig. 16: ESP32-S2-Kaluga-1 - front (click to enlarge) Fig. 17: ESP32-S2-Kaluga-1 - back (click to enlarge) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 35 Chapter 1. Get Started Description of Components The description of components starts from the ESP32-S2 module on the left side and then goes clockwise. Reserved means that the functionality is available, but the current version of the kit does not use it.
  • Page 36 GitHub. Contents and Packaging Retail orders If you order one or several samples of the kit, each ESP32-S2-Kaluga-1 development kit comes in an individual package. Fig. 18: ESP32-S2-Kaluga-1 - package The contents are as follows: • Main Board –...
  • Page 37 If you order in bulk, the boards come in large cardboard boxes. For wholesale orders, please go to https://www.espressif.com/en/contact-us/sales-questions. Hardware Reference Block Diagram A block diagram below shows the components of the ESP32-S2-Kaluga-1 and their interconnec- tions. Fig. 19: ESP32-S2-Kaluga-1 block diagram Power Supply Options There are four ways to provide power to the board: •...
  • Page 38 Boards Used HW Conflict Limitations Solution 8311A v1.3 + CAM I2S Controller ESP32-S2 has only one I2S inter- Utilize time division multiple ac- v1.1 face. But both extension boards cess, or use a different audio mod- require connection via the ESP32- ule that can be connected via other S2’s I2S interface (LyraT-8311A...
  • Page 39 • Provide the users with the tools for development of human-computer interaction applications based on the ESP32-S2 There are many ways of how the ESP32-S2’s abundant functionalities can be used. For starters, the possible use cases may include: • Smart home: From simplest smart lighting, smart door locks, smart sockets, to video streaming devices, security cameras, OTT devices, and home appliances •...
  • Page 40 ESP32-S2-Kaluga-1, then Section Start Application Development provides instructions on how to do the initial hardware setup and then how to flash firmware onto the ESP32-S2-Kaluga-1. Overview The ESP32-S2-Kaluga-1 main board is the heart of the kit. It integrates the ESP32-S2-WROVER module and all the connectors for extension boards.
  • Page 41 – LCD interface (8-bit parallel RGB, 8080, and 6800 interface) • Camera image acquisition – Supports OV2640 and OV3660 camera modules – 8-bit DVP image sensor interface (ESP32-S2 also supports 16-bit DVP image sensors, you can design it yourself) – Clock frequency up to 40 MHz –...
  • Page 42 3.2”LCD FPC connector Connect a 3.2” LCD extension board (e.g., ESP-LyraP-LCD32) using the FPC cable. Start Application Development Before powering up your ESP32-S2-Kaluga-1, please make sure that it is in good condition with no obvious signs of damage. Required Hardware • ESP32-S2-Kaluga-1 •...
  • Page 43 The programming guide and application examples for your ESP32-S2-Kaluga-1 kit can be found in esp-dev-kits repository on GitHub. Contents and Packaging Retail orders If you order one or several samples of the kit, each ESP32-S2-Kaluga-1 development kit comes in an individual package containing: • Main Board – ESP32-S2-Kaluga-1 • Extension Boards: –...
  • Page 44 Chapter 1. Get Started Fig. 23: ESP32-S2-Kaluga-1 block diagram Boards Used Limitations Solution Conflict 8311A v1.2 + CAM ESP32-S2 has only one I2S No ready solution for now. v1.0 Con- interface. But both exten- troller, sion boards require connection IO46 via the ESP32-S2’s I2S in-...
  • Page 45 ESP-LyraP-CAM v1.0 This user guide provides information on the ESP-LyraP-CAM extension board. This extension board cannot be bought separately and is usually sold together with other Espressif development boards (e.g., ESP32-S2-Kaluga-1), which will be referred to as main boards below.
  • Page 46 Chapter 1. Get Started Fig. 24: ESP-LyraP-CAM Fig. 25: ESP-LyraP-CAM - front and back Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 47 Fig. 26: ESP-LyraP-CAM block diagram Hardware Revision Details No previous versions available. Related Documents • ESP-LyraP-CAM Schematic (PDF) • ESP-LyraP-CAM PCB Layout (PDF) For other design documentation for the board, please contact us at sales@espressif.com. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 48 ESP-LyraP-LCD32 v1.1 This user guide provides information on the ESP-LyraP-LCD32 extension board. This extension board cannot be bought separately and is usually sold together with other Espressif development boards (e.g., ESP32-S2-Kaluga-1), which will be referred to as main boards below.
  • Page 49 Before powering up your ESP-LyraP-LCD32, please make sure that it is in good condition with no obvious signs of damage. Required Hardware • Board with a female Extension Header (e.g., ESP32-S2-Kaluga-1, ESP-LyraT-8311A) • ESP-LyraP-LCD32 extension board • Four mounting bolts (for stable mounting) •...
  • Page 50 ESP-LyraP-TouchA v1.1 This user guide provides information on the ESP-LyraP-TouchA extension board. This board cannot be bought separately and is usually sold together with other Espressif development boards (e.g., ESP32-S2-Kaluga-1), which will be referred to as main boards below. Currently, ESP-LyraP-TouchA v1.1 is sold as part of the following kits: •...
  • Page 51 Chapter 1. Get Started Fig. 30: ESP-LyraP-TouchA Fig. 31: ESP-LyraP-TouchA Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 52 Before powering up your ESP-LyraP-TouchA, please make sure that it is in good condition with no obvious signs of damage. Required Hardware • Board with a Touch FPC connector (e.g., ESP32-S2-Kaluga-1) • ESP-LyraP-TouchA extension board • FPC cable • Computer running Windows, Linux, or macOS Hardware Setup Connect the two FPC connectors with the FPC cable.
  • Page 53 ESP-LyraT-8311A v1.2 This user guide provides information on the ESP-LyraT-8311A extension board. This board cannot be bought separately and is usually sold together with other Espressif development boards (e.g., ESP32-S2-Kaluga-1), which will be referred to as main boards below. Currently, ESP-LyraT-8311A v1.2 is sold as part of the ESP32-S2-Kaluga-1 Kit v1.2.
  • Page 54 Start Application Development Before powering up your ESP-LyraT-8311A, please make sure that it is in good condition with no obvious signs of damage. Required Hardware Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 55 ESP-ADF Getting Started Guide if you develop with ESP-ADF (Espressif Audio Development Framework). • Section Software Setup of the ESP32-S2-Kaluga-1 kit user guide if you develop directly with ESP-IDF (Espres- sif IOT Development Framework). Hardware Reference Block Diagram A block diagram below shows the components of ESP-LyraT-8311A and their interconnections.
  • Page 56 ESP-LyraP-CAM v1.1 This user guide provides information on the ESP-LyraP-CAM extension board. This extension board cannot be bought separately and is usually sold together with other Espressif development boards (e.g., ESP32-S2-Kaluga-1), which will be referred to as main boards below.
  • Page 57 Before powering up your ESP-LyraP-CAM, please make sure that it is in good condition with no obvious signs of damage. Required Hardware • Board with a female Camera Header (e.g., ESP32-S2-Kaluga-1) • ESP-LyraP-CAM extension board • Computer running Windows, Linux, or macOS Hardware Setup Insert the ESP-LyraP-CAM extension board into your board’s female Camera Header.
  • Page 58 ESP-LyraP-LCD32 v1.2 This user guide provides information on the ESP-LyraP-LCD32 extension board. This extension board cannot be bought separately and is usually sold together with other Espressif development boards (e.g., ESP32-S2-Kaluga-1), which will be referred to as main boards below.
  • Page 59 Chapter 1. Get Started Fig. 39: ESP-LyraP-LCD32 (click to enlarge) Fig. 40: ESP-LyraP-LCD32 - front (click to enlarge) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 60 Before powering up your ESP-LyraP-LCD32, please make sure that it is in good condition with no obvious signs of damage. Required Hardware • Board with a female Extension Header (e.g., ESP32-S2-Kaluga-1, ESP-LyraT-8311A) • ESP-LyraP-LCD32 extension board • Four mounting bolts (for stable mounting) •...
  • Page 61 ESP-LyraT-8311A v1.3 This user guide provides information on the ESP-LyraT-8311A extension board. This board cannot be bought separately and is usually sold together with other Espressif development boards (e.g., ESP32-S2-Kaluga-1), which will be referred to as main boards below. Currently, ESP-LyraT-8311A v1.3 is sold as part of the ESP32-S2-Kaluga-1 Kit v1.3.
  • Page 62 Chapter 1. Get Started Fig. 43: ESP-LyraT-8311A (click to enlarge) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 63 (AEC) function Mono Audio Codec ES8311 audio ADC and DAC; it can convert the analog signal picked up by the microphone or convert digital signal to play it back through a speaker or headphones Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 64 ESP-ADF Getting Started Guide if you develop with ESP-ADF (Espressif Audio Development Framework). • Section Software Setup of the ESP32-S2-Kaluga-1 kit user guide if you develop directly with ESP-IDF (Espres- sif IOT Development Framework). Hardware Reference Block Diagram A block diagram below shows the components of ESP-LyraT-8311A and their interconnections.
  • Page 65: Installation Step By Step

    Chapter 1. Get Started Related Documents • ESP-LyraT-8311A Schematic (PDF) • ESP-LyraT-8311A PCB Layout (PDF) For other design documentation for the board, please contact us at sales@espressif.com. • ESP32-S2-WROVER Datasheet (PDF) • ESP Product Selector • JTAG Debugging • ESP32-S2-Kaluga-1 Schematic (PDF) •...
  • Page 66 Note that unlike the previous option, this way requires Python and Git to be present in PATH. If you get errors related to Python or Git not being found, use the first option. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 67 Chapter 1. Get Started Fig. 46: Completing the ESP-IDF Tools Setup Wizard with Run ESP-IDF PowerShell Environment Fig. 47: ESP-IDF PowerShell Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 68 Chapter 1. Get Started Fig. 48: Completing the ESP-IDF Tools Setup Wizard with Run ESP-IDF Command Prompt (cmd.exe) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 69 Chapter 1. Get Started Fig. 49: ESP-IDF Command Prompt Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 70: Standard Setup Of Toolchain For Linux

    This will download and install the tools necessary to use ESP-IDF. If the specific version of the tool is already installed, no action will be taken. The tools are downloaded and installed into a directory specified during ESP-IDF Tools Installer process. By default, this is C:\Users\username\.espressif. Add ESP-IDF tools to PATH using an export script ESP-IDF tools installer creates a Start menu shortcut for “ESP-IDF Command Prompt”.
  • Page 71: Standard Setup Of Toolchain For Mac Os

    Additional Tips Permission issues /dev/ttyUSB0 With some Linux distributions you may get the Failed to open port /dev/ttyUSB0 error message when flashing the ESP32-S2. This can be solved by adding the current user to the dialout group.
  • Page 72 Note: This guide uses the directory ~/esp on Linux and macOS or %userprofile%\esp on Windows as an installation folder for ESP-IDF. You can use any directory, but you will need to adjust paths for the commands respectively. Keep in mind that ESP-IDF does not support spaces in paths. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 73: Step 2. Get Esp-Idf

    Chapter 1. Get Started 1.6 Step 2. Get ESP-IDF To build applications for the ESP32-S2, you need the software libraries provided by Espressif in ESP-IDF repository. To get ESP-IDF, navigate to your installation directory and clone the repository with git clone, following in- structions below specific to your operating system.
  • Page 74: Alternative File Downloads

    Note: This setting only controls individual tools downloaded from GitHub releases, it doesn’t change the URLs used to access any Git repositories. Windows To prefer the Espressif download server when running the ESP-IDF Tools Installer, mark the Use Espressif down- load mirror instead of GitHub in the screen Select Components section Optimization. Linux and macOS To prefer the Espressif download server when installing tools, use the following sequence of commands when running install.sh:...
  • Page 75: Windows

    IDF virtual environment in every terminal session (including those where IDF is not needed), defeating the purpose of the virtual environment and likely affecting other software. 1.9 Step 5. Start a Project Now you are ready to prepare your application for ESP32-S2. You can start with get-started/hello_world project...
  • Page 76: Step 6. Connect Your Device

    Important: The ESP-IDF build system does not support spaces in the paths to either ESP-IDF or to projects. 1.10 Step 6. Connect Your Device Now connect your ESP32-S2 board to the computer and check under what serial port the board is visible. Serial ports have the following patterns in their names: •...
  • Page 77: Step 8. Build The Project

    If there are no errors, the build will finish by generating the firmware binary .bin files. 1.13 Step 9. Flash onto the Device Flash the binaries that you just built (bootloader.bin, partition-table.bin and hello_world.bin) onto your ESP32-S2 board by running: Espressif Systems Release v4.4...
  • Page 78: Encountered Issues While Flashing

    ESP32-S2). The DTR and RTS control lines are in turn connected to GPIO0 and CHIP_PU (EN) pins of ESP32-S2, thus changes in the voltage levels of DTR and RTS will boot ESP32-S2 into Firmware Download mode. As an example, check the schematic for the ESP32 DevKitC development board.
  • Page 79: Step 10. Monitor

    After startup and diagnostic logs scroll up, you should see “Hello world!”printed out by the application. Hello world! Restarting in 10 seconds... This is esp32s2 chip with 1 CPU core(s), WiFi, silicon revision 0, 2MB external␣ flash → Minimum free heap size: 253900 bytes (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 80: Updating Esp-Idf

    USB to serial converter chip on your ESP32-S2 board (or external converter dongle), search for drivers in internet and install them. Below is the list of USB to serial converter chips installed on most of the ESP32-S2 boards produced by Espressif together with links to the drivers: Espressif Systems Release v4.4...
  • Page 81 Check port on Linux and macOS To check the device name for the serial port of your ESP32-S2 board (or external converter dongle), run this command two times, first with the board / dongle unplugged, then with plugged in. The port which appears the second time is...
  • Page 82 Chapter 1. Get Started Fig. 52: Two USB Serial Ports of ESP-WROVER-KIT in Windows Device Manager Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 83 Windows and Linux. Remember to select exactly the same serial port you have identified in steps above. Then open serial port in terminal and check, if you see any log printed out by ESP32-S2. The log contents will depend on application loaded to ESP32-S2, see Example Output.
  • Page 84 Chapter 1. Get Started Fig. 53: Setting Serial Communication in PuTTY on Windows Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 85 Chapter 1. Get Started Fig. 54: Setting Serial Communication in PuTTY on Linux Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 86: Build And Flash With Eclipse Ide

    ESP32-S2 will boot and produce serial output. This depends on the hardware itself, most devel- opment boards (including all Espressif boards) do not have this issue. The issue is present if RTS & DTR are wired directly to the EN & GPIO0 pins. See the esptool documentation for more details.
  • Page 87: Idf Monitor

    Quick Installation Guide. Review the tutorials <https://github.com/espressif/vscode-esp-idf-extension/blob/master/docs/tutorial/toc.md> for ESP-IDF Visual Studio Code Extension to learn how to use all features. Supported Features • Setup, will help you to quickly install ESP-IDF and its relevant toolchain with just few clicks.
  • Page 88 If an ESP-IDF app crashes and panics, a register dump and backtrace is produced, such as the following: Guru Meditation Error of type StoreProhibited occurred on core 0. Exception was␣ unhandled. → Register dump: (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 89 To decode each address, IDF Monitor runs the following command in the background: xtensa-esp32s2-elf-addr2line -pfiaC -e build/PROJECT.elf ADDRESS Note: Set environment variable ESP_MONITOR_DECODE to 0 or call idf_monitor.py with specific command line option: idf_monitor.py --disable-address-decoding to disable address decoding. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 90 • Rule "tag1:I tag2:W" only prints tag1 at the Info verbosity level or lower and tag2 at the Warning verbosity level or lower. • Rule "tag1:I tag2:W tag3:N" is essentially equivalent to the previous one because tag3:N specifies that tag3 should not be printed. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 91: Customized Setup Of Toolchain

    • When “gdb”is run, it might stall for a short time before it begins communicating with the GDBStub. 1.16.5 Customized Setup of Toolchain Instead of downloading binary toolchain from Espressif website (see Step 3. Set up the tools) you may build the toolchain yourself.
  • Page 92 Open Command Prompt and run the following commands: mkdir %userprofile%\esp %userprofile%\esp git clone -b v4.4 --recursive https://github.com/espressif/esp-idf.git ESP-IDF will be downloaded into %userprofile%\esp\esp-idf. Consult ESP-IDF Versions for information about which ESP-IDF version to use in a given situation.
  • Page 93 Step 3. Set up the tools. Setup Linux Toolchain from Scratch The following instructions are alternative to downloading binary toolchain from Espressif website. To quickly setup the binary toolchain, instead of compiling it yourself, backup and proceed to section Standard Setup of Toolchain for Linux.
  • Page 94 – Arch: sudo pacman -Sy --needed python-pip Create the working directory and go into it: mkdir -p ~/esp cd ~/esp Download crosstool-NG and build it: git clone https://github.com/espressif/crosstool-NG.git cd crosstool-NG git checkout esp-2021r2 (continues on next page) Espressif Systems Release v4.4...
  • Page 95 MacPorts needs a full XCode installation, while Homebrew only needs XCode command line tools. Customized Setup of Toolchain section for some of the reasons why installing the toolchain from scratch may be necessary. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 96 Create a symlink to your work directory: mkdir -p ~/esp ln -s /Volumes/ctng ~/esp/ctng-volume Go into the newly created directory: cd ~/esp/ctng-volume Download crosstool-NG and build it: git clone https://github.com/espressif/crosstool-NG.git cd crosstool-NG git checkout esp-2021r2 git submodule update --init ./bootstrap &&...
  • Page 97 Toolchain will be built in ~/esp/ctng-volume/crosstool-NG/builds/xtensa-esp32s2-elf. To use it, you need to add ~/esp/ctng-volume/crosstool-NG/builds/xtensa-esp32s2-elf/bin to PATH environment variable. Next Steps To carry on with development environment setup, proceed to Step 2. Get ESP-IDF. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 98: Api Reference

    • Station mode (aka STA mode or Wi-Fi client mode). ESP32-S2 connects to an access point. • AP mode (aka Soft-AP mode or Access Point mode). Stations connect to the ESP32-S2. • Combined AP-STA mode (ESP32-S2 is concurrently an access point and a station connected to another access point).
  • Page 99 • ESP_OK: succeed • ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init esp_err_t esp_wifi_restore(void) Restore WiFi stack persistent settings to default values. This function will reset settings made using the following APIs: • esp_wifi_set_bandwidth, Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 100 Attention The values of maximum active scan time and passive scan time per channel are limited to 1500 milliseconds. Values above 1500ms may cause station to disconnect from AP and are not recommended. Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 101 For example, phy_11b = 1 imply that ap support 802.11b mode esp_err_t esp_wifi_set_ps(wifi_ps_type_t type) Set current WiFi power save type. Attention Default power save type is WIFI_PS_MIN_MODEM. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 102 Attention 1. API return false if try to get a interface that is not enable Return • ESP_OK: succeed • ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init • ESP_ERR_WIFI_IF: invalid interface • ESP_ERR_INVALID_ARG: invalid argument Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 103 Attention 7. When this API is called, the PHY init data will switch to the PHY init data type corresponding to the country info. Return • ESP_OK: succeed • ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init • ESP_ERR_INVALID_ARG: invalid argument Parameters • country: the configured country info Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 104: Esp_Ok: Succeed

    Enable the promiscuous mode. Return • ESP_OK: succeed • ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init Parameters • en: false - disable, true - enable esp_err_t esp_wifi_get_promiscuous(bool *en) Get the promiscuous mode. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 105 ESP32 station. Return • ESP_OK: succeed • ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init • ESP_ERR_INVALID_ARG: invalid argument • ESP_ERR_WIFI_IF: invalid interface • ESP_ERR_WIFI_MODE: invalid mode • ESP_ERR_WIFI_PASSWORD: invalid password Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 106 • ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init • ESP_ERR_INVALID_ARG: invalid argument Parameters • storage: : storage type esp_err_t esp_wifi_set_vendor_ie(bool enable, wifi_vendor_ie_type_t type, wifi_vendor_ie_id_t idx, const void *vnd_ie) Set 802.11 Vendor-Specific Information Element. Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 107: Esp_Err_Wifi_Not_Init: Wifi Is Not Initialized By Esp_Wifi_Init

    Attention 2. Default WiFi event mask is WIFI_EVENT_MASK_AP_PROBEREQRECVED. Attention 3. There may be lots of stations sending probe request data around. Don’t unmask this event unless you need to receive probe request data. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 108 • ESP_OK: succeed • ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init • ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start or promiscuous mode is not en- abled • ESP_ERR_INVALID_ARG: invalid argument Parameters • config: configuration Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 109 0. Attention Enabling power save may cause the return value inaccurate, except WiFi modem sleep Return 0 or the TSF time Parameters • interface: The interface whose tsf_time is to be retrieved. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 110: Esp_Err_Wifi_Not_Started: Wifi Is Not Started By Esp_Wifi_Start

    FTM procedure. Attention Use this API only in Station mode Return • ESP_OK: succeed • others: failed Parameters • cfg: FTM Initiator session configuration esp_err_t esp_wifi_ftm_end_session(void) End the ongoing FTM Initiator session. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 111 Attention 4. The country configuration is stored into flash. Attention 5. When this API is called, the PHY init data will switch to the PHY init data type corresponding to the country info. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 112: Esp_Err_Invalid_Arg: Invalid Argument

    WiFi station crypto functions when connect int static_rx_buf_num WiFi static RX buffer number int dynamic_rx_buf_num WiFi dynamic RX buffer number int tx_buf_type WiFi TX buffer type int static_tx_buf_num WiFi static TX buffer number Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 113 WiFi driver was not started by esp_wifi_start ESP_ERR_WIFI_NOT_STOPPED WiFi driver was not stopped by esp_wifi_stop ESP_ERR_WIFI_IF WiFi interface error ESP_ERR_WIFI_MODE WiFi mode error ESP_ERR_WIFI_STATE WiFi internal state error ESP_ERR_WIFI_CONN WiFi internal control block of station or soft-AP error Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 114 Returned when WiFi is stopping ESP_ERR_WIFI_NOT_ASSOC The WiFi connection is not associated ESP_ERR_WIFI_TX_DISALLOW The WiFi TX is disallowed WIFI_STATIC_TX_BUFFER_NUM WIFI_CACHE_TX_BUFFER_NUM WIFI_DYNAMIC_TX_BUFFER_NUM WIFI_CSI_ENABLED WIFI_AMPDU_RX_ENABLED WIFI_AMPDU_TX_ENABLED WIFI_AMSDU_TX_ENABLED WIFI_NVS_ENABLED WIFI_NANO_FORMAT_ENABLED WIFI_INIT_CONFIG_MAGIC WIFI_DEFAULT_RX_BA_WIN WIFI_TASK_CORE_ID WIFI_SOFTAP_BEACON_MAX_LEN WIFI_MGMT_SBUF_NUM WIFI_STA_DISCONNECTED_PM_ENABLED CONFIG_FEATURE_WPA3_SAE_BIT CONFIG_FEATURE_CACHE_TX_BUF_BIT Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 115 The usage of this union (for ap or sta configuration) is determined by the accompanying interface argument passed to esp_wifi_set_config() or esp_wifi_get_config() Public Members wifi_ap_config_t configuration of AP wifi_sta_config_t configuration of STA Structures struct wifi_country_t Structure describing WiFi country-based regional restrictions. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 116 SSID of AP uint8_t *bssid MAC address of AP uint8_t channel channel, scan the specific channel bool show_hidden enable to scan AP whose SSID is hidden wifi_scan_type_t scan_type scan type, active or passive Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 117 6 flag to identify if FTM is supported in initiator mode uint32_t reserved : 25 bit: 7..31 reserved wifi_country_t country country information of AP struct wifi_scan_threshold_t Structure describing parameters for a WiFi fast scan. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 118 WIFI_CIPHER_TYPE_TKIP, enum values before that will be consid- ered as invalid and default cipher suites(TKIP+CCMP) will be used. Valid cipher suites softAP mode WIFI_CIPHER_TYPE_TKIP, WIFI_CIPHER_TYPE_CCMP WIFI_CIPHER_TYPE_TKIP_CCMP. bool ftm_responder Enable FTM Responder mode struct wifi_sta_config_t STA configuration settings for the ESP32. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 119 : 1 bit: 0 flag to identify if 11b mode is enabled or not uint32_t phy_11g : 1 bit: 1 flag to identify if 11g mode is enabled or not Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 120 : 5 PHY rate encoding of the packet. Only valid for non HT(11bg) packet unsigned __pad0__ : 1 reserved unsigned sig_mode : 2 0: non HT(11bg) packet; 1: HT(11n) packet; 3: VHT(11ac) packet Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 121 : 1 antenna number from which this packet is received. 0: WiFi antenna 0; 1: WiFi antenna 1 signed noise_floor : 8 noise floor of Radio Frequency Module(RF). unit: 0.25dBm Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 122 Default false uint8_t shift manually left shift bits of the scale of the CSI data. The range of the left shift bits is 0~15 struct wifi_csi_info_t CSI data type. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 123 WIFI_ANT_MODE_AUTO uint8_t enabled_ant0 : 4 Index (in antenna GPIO configuration) of enabled WIFI_ANT_MODE_ANT0 uint8_t enabled_ant1 : 4 Index (in antenna GPIO configuration) of enabled WIFI_ANT_MODE_ANT1 struct wifi_action_tx_req_t Action Frame Tx Request. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 124 Argument structure for WIFI_EVENT_STA_CONNECTED event Public Members uint8_t ssid[32] SSID of connected AP uint8_t ssid_len SSID length of connected AP Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 125 Argument structure for WIFI_EVENT_STA_WPS_ER_SUCCESS event Public Members uint8_t ap_cred_cnt Number of AP credentials received uint8_t ssid[MAX_SSID_LEN] SSID of AP uint8_t passphrase[MAX_PASSPHRASE_LEN] Passphrase for the AP struct wifi_event_sta_wps_er_success_t::[anonymous] ap_cred[MAX_WPS_AP_CRED] All AP credentials received from WPS handshake Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 126 Argument structure for Public Members uint8_t dlog_token Dialog Token of the FTM frame int8_t rssi RSSI of the FTM frame received uint32_t rtt Round Trip Time in pSec with a peer Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 127 Context to identify the request uint8_t da[6] Destination MAC address uint8_t status Status of the operation struct wifi_event_roc_done_t Argument structure for WIFI_EVENT_ROC_DONE event Public Members uint32_t context Context to identify the request Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 128 filter the control packets with subtype of RTS WIFI_PROMIS_CTRL_FILTER_MASK_CTS filter the control packets with subtype of CTS WIFI_PROMIS_CTRL_FILTER_MASK_ACK filter the control packets with subtype of ACK WIFI_PROMIS_CTRL_FILTER_MASK_CFEND filter the control packets with subtype of CF-END Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 129 Values: WIFI_MODE_NULL = 0 null mode WIFI_MODE_STA WiFi station mode WIFI_MODE_AP WiFi soft-AP mode WIFI_MODE_APSTA WiFi station + soft-AP mode WIFI_MODE_MAX enum wifi_interface_t Values: WIFI_IF_STA = ESP_IF_WIFI_STA WIFI_IF_AP = ESP_IF_WIFI_AP enum wifi_country_policy_t Values: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 130 WIFI_REASON_NOT_AUTHED = 6 WIFI_REASON_NOT_ASSOCED = 7 WIFI_REASON_ASSOC_LEAVE = 8 WIFI_REASON_ASSOC_NOT_AUTHED = 9 WIFI_REASON_DISASSOC_PWRCAP_BAD = 10 WIFI_REASON_DISASSOC_SUPCHAN_BAD = 11 WIFI_REASON_BSS_TRANSITION_DISASSOC = 12 WIFI_REASON_IE_INVALID = 13 WIFI_REASON_MIC_FAILURE = 14 WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT = 15 WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT = 16 Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 131 Values: WIFI_CIPHER_TYPE_NONE = 0 the cipher type is none WIFI_CIPHER_TYPE_WEP40 the cipher type is WEP40 WIFI_CIPHER_TYPE_WEP104 the cipher type is WEP104 WIFI_CIPHER_TYPE_TKIP the cipher type is TKIP WIFI_CIPHER_TYPE_CCMP the cipher type is CCMP Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 132 Minimum modem power saving. In this mode, station wakes up to receive beacon every DTIM period WIFI_PS_MAX_MODEM Maximum modem power saving. In this mode, interval to receive beacons is determined by the lis- ten_interval parameter in wifi_sta_config_t Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 133 Other type, such as MIMO etc.‘buf’ argument is wifi_promiscuous_pkt_t but the payload is zero length. enum wifi_ant_mode_t WiFi antenna mode. Values: WIFI_ANT_MODE_ANT0 Enable WiFi antenna 0 only WIFI_ANT_MODE_ANT1 Enable WiFi antenna 1 only Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 134 MCS2 with long GI, 19.5 Mbps for 20MHz, 40.5 Mbps for 40MHz WIFI_PHY_RATE_MCS3_LGI = 0x13 MCS3 with long GI, 26 Mbps for 20MHz, 54 Mbps for 40MHz WIFI_PHY_RATE_MCS4_LGI = 0x14 MCS4 with long GI, 39 Mbps for 20MHz, 81 Mbps for 40MHz Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 135 ESP32 station stop WIFI_EVENT_STA_CONNECTED ESP32 station connected to AP WIFI_EVENT_STA_DISCONNECTED ESP32 station disconnected from AP WIFI_EVENT_STA_AUTHMODE_CHANGE the auth mode of AP connected by ESP32 station changed WIFI_EVENT_STA_WPS_ER_SUCCESS ESP32 station wps succeeds in enrollee mode Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 136 WPS_FAIL_REASON_NORMAL = 0 ESP32 WPS normal fail reason WPS_FAIL_REASON_RECV_M2D ESP32 WPS receive M2D frame WPS_FAIL_REASON_MAX enum wifi_ftm_status_t FTM operation status types. Values: FTM_STATUS_SUCCESS = 0 FTM exchange is successful FTM_STATUS_UNSUPPORTED Peer does not support FTM Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 137 Point (AP). This information is provided using the smartphone. This is particularly important to headless device and systems, due to their lack of a user interface. If you are looking for other options to provision your ESP32-S2 devices, check Provisioning API.
  • Page 138 MAC address of target AP or not. uint8_t bssid[6] MAC address of target AP. smartconfig_type_t type Type of smartconfig(ESPTouch or AirKiss). uint8_t token Token from cellphone which is used to send ACK to cellphone. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 139 ESP-NOW Overview ESP-NOW is a kind of connectionless Wi-Fi communication protocol that is defined by Espressif. In ESP-NOW, application data is encapsulated in a vendor-specific action frame and then transmitted from one Wi-Fi device to another without connection. CTR with CBC-MAC Protocol(CCMP) is used to protect the action frame for security.
  • Page 140 • Category Code: The Category Code field is set to the value(127) indicating the vendor-specific category. • Organization Identifier: The Organization Identifier contains a unique identifier (0x18fe34), which is the first three bytes of MAC address applied by Espressif. • Random Value: The Random Value filed is used to prevents relay attacks.
  • Page 141 Register callback function of receiving ESPNOW data. Return • ESP_OK : succeed • ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized • ESP_ERR_ESPNOW_INTERNAL : internal error Parameters • cb: callback function of receiving ESPNOW data Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 142 • ESP_ERR_ESPNOW_EXIST : peer has existed Parameters • peer: peer information esp_err_t esp_now_del_peer(const uint8_t *peer_addr) Delete a peer from peer list. Return • ESP_OK : succeed • ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized • ESP_ERR_ESPNOW_ARG : invalid argument Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 143 • ESP_ERR_ESPNOW_ARG : invalid argument Parameters • num: number of peers esp_err_t esp_now_set_pmk(const uint8_t *pmk) Set the primary master key. Attention 1. primary master key is used to encrypt local master key Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 144 Number of ESPNOW peers which exist currently. Public Members int total_num Total number of ESPNOW peers, maximum value is ESP_NOW_MAX_TOTAL_PEER_NUM int encrypt_num Number of encrypted ESPNOW peers, maximum value is ESP_NOW_MAX_ENCRYPT_PEER_NUM Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 145 • data_len: length of received data typedef void (*esp_now_send_cb_t)(const uint8_t *mac_addr, esp_now_send_status_t status) Callback function of sending ESPNOW data. Parameters • mac_addr: peer MAC address • status: status of sending ESPNOW data (succeed or fail) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 146 Before ESP-WIFI-MESH events can be used, the application must register a Mesh Events handler via esp_event_handler_register() to the default event task. The Mesh Events handler that is registered contain handlers for each ESP-WIFI-MESH event relevant to the application. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 147 DHCP client service and immediately obtain an IP address. Doing so will allow other nodes to begin transmitting/receiving packets to/from the external IP network. However, this step is unnecessary if static IP settings are used. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 148 /* Enable the Mesh IE encryption by default */ mesh_cfg_t cfg MESH_INIT_CONFIG_DEFAULT(); /* mesh ID */ memcpy((uint8_t *) &cfg.mesh_id, MESH_ID, 6); /* channel (must match the router's channel) */ (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 149 • If the node was previously disconnected and was scanning for a parent node or router, it will stop scanning. • If the node was previously attempting to reconnect to a parent node or router, it will stop reconnecting. Espressif Systems Release v4.4...
  • Page 150 Wi-Fi APIs. This will prevent the ESP-WIFI-MESH stack from attempting to call any Wi-Fi APIs and potentially interfering with the application’s calls. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 151 • Check whether Wi-Fi is started. • Initialize mesh global variables with default values. Attention This API shall be called after Wi-Fi is started. Return • ESP_OK • ESP_FAIL esp_err_t esp_mesh_deinit(void) Mesh de-initialization. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 152 • ESP_ERR_MESH_TIMEOUT • ESP_ERR_MESH_QUEUE_FULL • ESP_ERR_MESH_NO_ROUTE_FOUND • ESP_ERR_MESH_DISCARD Parameters • [in] to: the address of the final destination of the packet – If the packet is to the root, set this parameter to NULL. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 153 • Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting to be received by applications. Return • ESP_OK • ESP_ERR_MESH_ARGUMENT • ESP_ERR_MESH_NOT_START • ESP_ERR_MESH_TIMEOUT • ESP_ERR_MESH_DISCARD Parameters • [out] from: the address of the original source of the packet Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 154 Set mesh stack configuration. • Use MESH_INIT_CONFIG_DEFAULT() to initialize the default values, mesh IE is encrypted by de- fault. • Mesh network is established on a fixed channel (1-14). • Mesh event callback is mandatory. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 155 Attention This API is used to dynamically modify the mesh network ID. Return • ESP_OK • ESP_ERR_MESH_ARGUMENT: invalid argument Parameters • [in] id: pointer to mesh network ID esp_err_t esp_mesh_get_id(mesh_addr_t *id) Get mesh network ID. Return • ESP_OK Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 156 • [in] pwd: pointer to the password • [in] len: password length esp_err_t esp_mesh_set_ap_authmode(wifi_auth_mode_t authmode) Set mesh softAP authentication mode. Attention This API shall be called before mesh is started. Return • ESP_OK • ESP_ERR_MESH_ARGUMENT • ESP_ERR_MESH_NOT_ALLOWED Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 157 • If self-organized is disabled, users should set a parent for the device via esp_mesh_set_parent(). Attention This API is used to dynamically modify whether to enable the self organizing. Return • ESP_OK • ESP_FAIL Parameters • [in] enable: enable or disable self-organized networking Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 158 • If mesh softAP hasn’t received any data from an associated child within this time, mesh softAP will take this child inactive and disassociate it. • If mesh softAP is encrypted, this value should be set a greater value, such as 30 seconds. Return • ESP_OK Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 159 Return the number of upQ for a certain address Parameters • [in] addr: self address or an associate children address • [out] xseqno_in: sequence number of the last received packet from the specified address Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 160 Return the number of group ID addresses esp_err_t esp_mesh_get_group_list(mesh_addr_t *addr, int num) Get group ID addresses. Return • ESP_OK • ESP_MESH_ERR_ARGUMENT Parameters • [out] addr: pointer to group ID addresses • [in] num: the number of group ID addresses Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 161 Set delay time before starting root healing. Return • ESP_OK Parameters • [in] delay_ms: delay time in milliseconds int esp_mesh_get_root_healing_delay(void) Get delay time before network starts root healing. Return delay time in milliseconds Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 162 • [out] len: mesh networking IE length esp_err_t esp_mesh_scan_get_ap_record(wifi_ap_record_t *ap_record, void *buffer) Get AP record. Attention Different from esp_wifi_scan_get_ap_records(), this API only gets one of APs scanned each time. See “manual_networking”example. Return • ESP_OK • ESP_ERR_WIFI_NOT_INIT Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 163 • Set how many beacons with CSA IE will be sent before changing a new channel • Enable the channel switch function Attention This API is only called by the root. Return • ESP_OK Parameters • [in] new_bssid: the new router BSSID if the router changes Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 164 Check whether the mesh Power Save function is enabled. Return true/false bool esp_mesh_is_device_active(void) Check whether the device is in active state. • If the device is not in active state, it will neither transmit nor receive frames. Return true/false Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 165 • If the root is specified (FIXED-ROOT), call this API in the root to provide a default nwk_duty for the entire network. • After joins the network, any device can call this API to change the nwk_duty, duration_mins or applied_rule. Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 166 • [in] fwd_times: the times of forwarding duty signaling packets Unions union mesh_addr_t #include <esp_mesh.h> Mesh address. Public Members uint8_t addr[6] mac address mip_t mip address union mesh_event_info_t #include <esp_mesh.h> Mesh event information. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 167 PS duty information union mesh_rc_config_t #include <esp_mesh.h> Vote address configuration. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 168 Wi-Fi event SYSTEM_EVENT_STA_CONNECTED does uint16_t self_layer layer uint8_t duty parent duty struct mesh_event_no_parent_found_t No parent found information. Public Members int scan_times scan times being through struct mesh_event_layer_change_t Layer change information. Public Members uint16_t new_layer new layer Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 169 Routing table change. Public Members uint16_t rt_size_new the new value uint16_t rt_size_change the changed value Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 170 Mesh option. Public Members uint8_t type option type uint16_t len option length uint8_t *val option value struct mesh_data_t Mesh data for esp_mesh_send() and esp_mesh_recv() Public Members uint8_t *data data Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 171 “fail”(mesh_attempts_t) times is reached, device will change to a full channel scan for a network that could join. The default value is false. mesh_addr_t mesh_id mesh network identification Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 172 The number of packets available in the queue waiting to be received by applications. Public Members int toDS to external DS int toSelf to self Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 173 ESP_ERR_MESH_NO_ROUTE_FOUND no route found to forward the packet ESP_ERR_MESH_OPTION_NULL no option found ESP_ERR_MESH_OPTION_UNKNOWN unknown option ESP_ERR_MESH_XON_NO_WINDOW no window for software flow control on upstream ESP_ERR_MESH_INTERFACE low-level Wi-Fi interface error Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 174 IP address; used with esp_mesh_send() and esp_mesh_recv() MESH_ASSOC_FLAG_VOTE_IN_PROGRESS Flag of mesh networking IE. vote in progress MESH_ASSOC_FLAG_NETWORK_FREE no root in current network MESH_ASSOC_FLAG_ROOTS_FOUND root conflict is found MESH_ASSOC_FLAG_ROOT_FIXED fixed root MESH_PS_DEVICE_DUTY_REQUEST Mesh PS (Power Save) duty cycle type. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 175 MESH_EVENT_ROUTING_TABLE_REMOVE routing table is changed by removing leave children MESH_EVENT_PARENT_CONNECTED parent is connected on station interface MESH_EVENT_PARENT_DISCONNECTED parent is disconnected on station interface MESH_EVENT_NO_PARENT_FOUND no parent found Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 176 SSID, this event will be posted and the new router information is attached. MESH_EVENT_PS_PARENT_DUTY parent duty MESH_EVENT_PS_CHILD_DUTY child duty MESH_EVENT_PS_DEVICE_DUTY device duty MESH_EVENT_MAX enum mesh_type_t Device type. Values: MESH_IDLE hasn’t joined the mesh network yet Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 177 Values: MESH_VOTE_REASON_ROOT_INITIATED = 1 vote is initiated by the root MESH_VOTE_REASON_CHILD_INITIATED vote is initiated by children enum mesh_disconnect_reason_t Mesh disconnect reason code. Values: MESH_REASON_CYCLIC = 100 cyclic is detected MESH_REASON_PARENT_IDLE parent is idle Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 178 • Simple and intuitive to use; no lengthy instructions to follow for new device setup • No need to remember and enter passwords into the device being provisioned • Works with electronic or printed QR codes, or human-readable strings • Supports both WPA2 and WPA3 networks Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 179 ESP32-S2 supports Enrollee mode of Easy Connect with QR Code as the provisioning method. A display is required to display this QR Code. Users can scan this QR Code using their capable device and provision the ESP32-S2 to their Wi-Fi network. The provisioning device needs to be connected to the AP which need not support Wi-Fi Easy Connect™.
  • Page 180: Ethernet

    DPP Authentication failure Code examples for the Wi-Fi API are provided in the wifi directory of ESP-IDF examples. Code examples for ESP-WIFI-MESH are provided in the mesh directory of ESP-IDF examples. 2.1.2 Ethernet Ethernet Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 181 10101011 (as seen on the physical medium). It is sometimes considered to be part of the preamble. When transmitting and receiving data, the preamble and SFD bytes will automatically be generated or stripped from the packets. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 182 CRC fields will be written into the receive buffer when packets arrive, so they may be evaluated by the host controller if needed. Note: Besides the basic data frame described above, there’re two other common frame types in 10/100 Mbps Ethernet: control frames and VLAN tagged frames. They’re not supported in ESP-IDF. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 183 // SPI bus configuration spi_device_handle_t spi_handle NULL; spi_bus_config_t buscfg .miso_io_num CONFIG_EXAMPLE_ETH_SPI_MISO_GPIO, .mosi_io_num CONFIG_EXAMPLE_ETH_SPI_MOSI_GPIO, .sclk_io_num CONFIG_EXAMPLE_ETH_SPI_SCLK_GPIO, .quadwp_io_num .quadhd_io_num ESP_ERROR_CHECK(spi_bus_initialize(CONFIG_EXAMPLE_ETH_SPI_HOST, &buscfg, 1)); // Allocate SPI device from the bus spi_device_interface_config_t devcfg .command_bits .address_bits (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 184 *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) uint8_t mac_addr[6] {0}; /* we can get the ethernet driver handle from event data */ esp_eth_handle_t eth_handle *(esp_eth_handle_t *)event_data; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 185 *event (ip_event_got_ip_t *) event_data; const esp_netif_ip_info_t *ip_info &event->ip_info; ESP_LOGI(TAG, "Ethernet Got IP Address"); ESP_LOGI(TAG, "~~~~~~~~~~~"); ESP_LOGI(TAG, "ETHIP:" IPSTR, IP2STR(&ip_info->ip)); ESP_LOGI(TAG, "ETHMASK:" IPSTR, IP2STR(&ip_info->netmask)); ESP_LOGI(TAG, "ETHGW:" IPSTR, IP2STR(&ip_info->gw)); ESP_LOGI(TAG, "~~~~~~~~~~~"); (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 186 ETH_CMD_S_FLOW_CTRL, true);. One thing should be kept in mind, is that the pause frame ability will be advertised to peer end by PHY during auto negotiation. Ethernet driver sends pause frame only when both sides of the link support it. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 187 Note This function does the oppsite operation of esp_eth_start. Return • ESP_OK: stop esp_eth driver successfully • ESP_ERR_INVALID_ARG: stop esp_eth driver failed because of some invalid argument • ESP_ERR_INVALID_STATE: stop esp_eth driver failed because driver has not started yet Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 188 MAC address is to be copied. The buffer size must be at least 6 bytes. • ETH_CMD_S_PHY_ADDR sets PHY address in range of <0-31>. data argument is pointer to memory of uint32_t datatype from where the configuration option is read. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 189 • [in] hdl: handle of Ethernet driver Structures struct esp_eth_config_t Configuration of Ethernet driver. Public Members esp_eth_mac_t *mac Ethernet MAC object. esp_eth_phy_t *phy Ethernet PHY object. uint32_t check_link_period_ms Period time of checking Ethernet link status. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 190 • ESP_ERR_TIMEOUT: write PHY register failed because of timeout • ESP_FAIL: write PHY register failed because some other error occurred Parameters • [in] eth_handle: handle of Ethernet driver • [in] phy_addr: PHY chip address (0~31) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 191 Write PHY register. Return • ESP_OK: write PHY register successfully • ESP_FAIL: write PHY register failed because some error occurred Parameters • [in] eth: mediator of Ethernet driver • [in] phy_addr: PHY Chip address (0~31) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 192 Maximum frame size (1522 Bytes) ETH_MIN_PACKET_SIZE Minimum frame size (64 Bytes) Type Definitions typedef struct esp_eth_mediator_s esp_eth_mediator_t Ethernet mediator. Enumerations enum esp_eth_state_t Ethernet driver state. Values: ETH_STATE_LLINIT Lowlevel init done ETH_STATE_DEINIT Deinit done Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 193 ETHERNET_EVENT_START Ethernet driver start ETHERNET_EVENT_STOP Ethernet driver stop ETHERNET_EVENT_CONNECTED Ethernet got a valid link ETHERNET_EVENT_DISCONNECTED Ethernet lost a valid link Header File • components/esp_eth/include/esp_eth_mac.h Unions union eth_mac_clock_config_t #include <esp_eth_mac.h> Ethernet MAC Clock Configuration. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 194 Start Ethernet MAC. Return • ESP_OK: start Ethernet MAC successfully • ESP_FAIL: start Ethernet MAC failed because some other error occurred Parameters • [in] mac: Ethernet MAC instance esp_err_t (*stop)(esp_eth_mac_t *mac) Stop Ethernet MAC. Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 195 • ESP_ERR_INVALID_STATE: write PHY register failed because of wrong state of MAC • ESP_ERR_TIMEOUT: write PHY register failed because of timeout • ESP_FAIL: write PHY register failed because some other error occurred Parameters • [in] mac: Ethernet MAC instance Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 196 • ESP_FAIL: set link status failed because some other error occurred Parameters • [in] mac: Ethernet MAC instance • [in] link: Link status esp_err_t (*set_promiscuous)(esp_eth_mac_t *mac, bool enable) Set promiscuous of MAC. Return • ESP_OK: set promiscuous mode successfully Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 197 SMI MDIO GPIO number, set to -1 could bypass the SMI GPIO configuration uint32_t flags Flags that specify extra capability for mac driver eth_data_interface_t interface EMAC Data interface to PHY (MII/RMII) eth_mac_clock_config_t clock_config EMAC Interface clock configuration Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 198 EMAC_CLK_OUT_GPIO = 16 Output RMII Clock from internal APLL Clock available at GPIO16. EMAC_CLK_OUT_180_GPIO = 17 Inverted Output RMII Clock from internal APLL Clock available at GPIO17. Header File • components/esp_eth/include/esp_eth_phy.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 199 *esp_eth_phy_new_ksz8081(const eth_phy_config_t *config) Create a PHY instance of KSZ8081. Return • instance: create PHY instance successfully • NULL: create PHY instance failed because some error occurred Parameters • [in] config: configuration of PHY Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 200 • [in] phyL: Ethernet PHY instance esp_err_t (*negotiate)(esp_eth_phy_t *phy) Start auto negotiation. Return • ESP_OK: restart auto negotiation successfully • ESP_FAIL: restart auto negotiation failed because some error occurred Parameters • [in] phy: Ethernet PHY instance Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 201 • [in] enable: enables or disables PHY loopback esp_err_t (*del)(esp_eth_phy_t *phy) Free memory of Ethernet PHY instance. Return • ESP_OK: free PHY instance successfully • ESP_FAIL: free PHY instance failed because some error occurred Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 202 IP layer handlers for Ethernet is now handled automatically. Do not call this function if you want to use multiple Ethernet instances at a time. Return • ESP_ERR_INVALID_ARG: invalid parameter (esp_netif is NULL) • ESP_OK: set default IP layer handlers successfully • others: other failure occurred during register esp_event handler Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 203: Thread

    • ESP_ERR_NO_MEM if allocation has failed • ESP_ERR_INVALID_ARG if radio or host connection mode not supported • ESP_ERR_INVALID_STATE if already initialized Parameters • [in] init_config: The initialization configuration. esp_err_t esp_openthread_launch_mainloop(void) Launches the OpenThread main loop. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 204 The uart port config for OpenThread. Public Members uart_port_t port UART port number uart_config_t uart_config UART configuration, see uart_config_t docs int rx_pin UART RX pin int tx_pin UART TX pin struct esp_openthread_radio_config_t The OpenThread radio configuration. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 205 The radio configuration esp_openthread_host_connection_config_t host_config The host connection configuration esp_openthread_port_config_t port_config The port configuration Enumerations enum esp_openthread_event_t OpenThread event declarations. Values: OPENTHREAD_EVENT_START OpenThread stack start OPENTHREAD_EVENT_STOP OpenThread stack stop OPENTHREAD_EVENT_IF_UP OpenThread network interface up Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 206 Note Every OT APIs that takes an otInstance argument MUST be protected with this API lock except that the call site is in OT callbacks. Return • True on lock acquired • False on failing to acquire the lock with the timeout. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 207 Return The backbone interface or NULL if border router not initialized. Thread is an IPv6-based mesh networking technology for IoT. Code examples for the Thread API are provided in openthread directory of ESP-IDF examples. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 208: Ip Network Layer

    • --<--->-- Data packets going from communication media to TCP/IP stack and back • ******** Events aggregated in ESP-NETIF propagates to driver, user code and network stack • | User settings and runtime configuration ESP-NETIF interaction Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 209 • DHCP server and client API • DNS API 6) Driver conversion utilities D) Network stack Network stack has no public interaction with application code with regard to public interfaces and shall be fully abstracted by ESP-NETIF API. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 210 • pointer to esp-netif object on success • NULL otherwise Parameters • [in] esp_netif_config: pointer esp-netif configuration void esp_netif_destroy(esp_netif_t *esp_netif) Destroys the esp_netif object. Parameters • [in] esp_netif: pointer to the object to be deleted Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 211 • data: void esp_netif_action_connected(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IO driver connected event. Note This API can be directly used as event handler Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 212 • [in] esp_netif: Handle to esp-netif instance • base: • event_id: • data: void esp_netif_action_remove_ip6_address(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data) Default building block for network interface action upon IPv6 address removed by the underlying stack. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 213 (and string may change if the hostname changes). bool esp_netif_is_netif_up(esp_netif_t *esp_netif) Test if supplied interface is up or down. Return • true - Interface is up • false - Interface is down Parameters • [in] esp_netif: Handle to esp-netif instance Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 214 If the interface is disconnected or down for too long, the “IP lost timer”will expire (after the configured interval) and set the old IP information to zero. Return • ESP_OK • ESP_ERR_ESP_NETIF_INVALID_PARAMS Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 215 • [in] opt_id: Option index to get or set, must be one of the supported enum values. • [inout] opt_val: Pointer to the option parameter. • [in] opt_len: Length of the option parameter. esp_err_t esp_netif_dhcpc_start(esp_netif_t *esp_netif) Start DHCP client (only if enabled in interface object) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 216 Stop DHCP server (only if enabled in interface object) Return • ESP_OK • ESP_ERR_ESP_NETIF_INVALID_PARAMS • ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED • ESP_ERR_ESP_NETIF_IF_NOT_READY Parameters • [in] esp_netif: Handle to esp-netif instance esp_err_t esp_netif_set_dns_info(esp_netif_t *esp_netif, esp_netif_dns_type_t type, esp_netif_dns_info_t *dns) Set DNS Server information. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 217 • ESP_OK • ESP_FAIL If interface is down, does not have a link-local IPv6 address, or the link-local IPv6 address is not a preferred address. Parameters • [in] esp_netif: Handle to esp-netif instance Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 218 • [out] dst: Address of the target esp_ip4_addr_t structure to receive converted address esp_err_t esp_netif_str_to_ip6(const char *src, esp_ip6_addr_t *dst) Converts Ascii internet IPv6 address into esp_ip4_addr_t Zeros in the IP address can be stripped or completely ommited: “2001:db8:85a3:0:0:0:2:1”or “2001:db8::2:1”) Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 219 Iterates over list of interfaces. Returns first netif if NULL given as parameter. Return First netif from the list if supplied parameter is NULL, next one otherwise Parameters • [in] esp_netif: Handle to esp-netif instance Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 220 • ESP_OK on success, error returned from esp_event_handler_register if failed esp_err_t esp_wifi_clear_default_wifi_driver_and_handlers(void *esp_netif) Clears default wifi event handlers for supplied network interface. Return • ESP_OK on success, error returned from esp_event_handler_register if failed Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 221 Network stack initialization Simply replace tcpip_adapter_init() with esp_netif_init(). Please note that the ESP-NETIF initialization API returns standard error code and the esp_netif_deinit() for un- initialization is available. Also replace #include "tcpip_adapter.h" with #include "esp_netif.h". Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 222 Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 223 I/O drivers also typically provide default definitions of lifecycle behaviour of related network interfaces based on state transitions of I/O drivers. For example driver start -> network start, etc. An example of such a default handler is provided below: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 224 • [in] data: Data to be transmitted • [in] len: Length of the data frame • [in] netstack_buf: net stack buffer void esp_netif_free_rx_buffer(void *esp_netif, void *buffer) Free the rx buffer allocated by the media driver. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 225: Application Layer

    An ADC conversion is to convert the input analog voltage to a digital value. The ADC conversion results provided by the ADC driver APIs are raw data. Resolution of ESP32-S2 ADC raw results under Single Read mode is 12-bit. •...
  • Page 226 GPIO pin. It comes handy to calibrate ADC reading and this is discussed in section Calibration. Note: See ADC Limitations for the limitation of using ADC single read mode. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 227 Minimizing Noise The ESP32-S2 ADC can be sensitive to noise leading to large discrepancies in ADC readings. Depending on the usage scenario, users may connect a bypass capacitor (e.g. a 100 nF ceramic capacitor) to the ADC input pad in use, to minimize noise.
  • Page 228 1. ADC1_CHANNEL_0_GPIO_NUM is the GPIO number of ADC1 channel 0. 2. ADC1_GPIOn_CHANNEL is the ADC1 channel number of GPIO n. API Reference This reference covers three components: • ADC driver • ADC Calibration • GPIO Lookup Macros Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 229 +-------------+-----------------+ 150 ~ 1750 +-------------+-----------------+ 150 ~ 2450 +----------+-------------+-----------------+ +-------------+-----------------+ 0 ~ 1050 | ESP32-S2 +-------------+-----------------+ 0 ~ 1300 +-------------+-----------------+ 0 ~ 2500 +----------+-------------+-----------------+ For maximum accuracy, use the ADC calibration APIs and measure voltages within these recommended ranges. Espressif Systems Release v4.4...
  • Page 230 Set ADC source clock. Return • ESP_OK success Parameters • clk_div: ADC clock divider, ADC clock is divided from APB clock esp_err_t adc_set_data_width(adc_unit_t adc_unit, adc_bits_width_t width_bit) Configure ADC capture width. Return • ESP_OK success Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 231 +-------------+-----------------+ 150 ~ 1750 +-------------+-----------------+ 150 ~ 2450 +----------+-------------+-----------------+ +-------------+-----------------+ 0 ~ 1050 | ESP32-S2 +-------------+-----------------+ 0 ~ 1300 +-------------+-----------------+ 0 ~ 2500 +----------+-------------+-----------------+ For maximum accuracy, use the ADC calibration APIs and measure voltages within these recommended ranges. Note This function also configures the input GPIO pin mux to connect it to the ADC2 channel. It must be called before calling adc2_get_raw() for this channel.
  • Page 232 If Wi-Fi is started via esp_wifi_start(), this function will always fail with ESP_ERR_TIMEOUT. Note ESP32-S2: ADC2 support hardware arbiter. The arbiter is to improve the use efficiency of ADC2. After the control right is robbed by the high priority, the low priority controller will read the invalid ADC2 data.
  • Page 233 *config) Set adc digital controller filter configuration. Note For ESP32S2, Filter IDX0/IDX1 can only be used to filter all enabled channels of ADC1/ADC2 unit at the same time. Return • ESP_OK Success Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 234 ADC DMA driver configuration. Public Members uint32_t max_store_buf_size Max length of the converted data that driver can store before they are processed. uint32_t conv_num_each_intr Bytes of data that can be converted in 1 interrupt. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 235 ADC_WIDTH_9Bit ADC_WIDTH_10Bit ADC_WIDTH_11Bit ADC_WIDTH_12Bit ADC_MAX_DELAY Digital ADC DMA read max timeout value, it may make the adc_digi_read_bytes block forever if the OS supports. Type Definitions typedef struct adc_digi_init_config_s adc_digi_init_config_t ADC DMA driver configuration. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 236 ADC1_CHANNEL_9 ADC1 channel 9 is GPIO10 ADC1_CHANNEL_MAX enum adc2_channel_t Values: ADC2_CHANNEL_0 = 0 ADC2 channel 0 is GPIO4 (ESP32), GPIO11 (ESP32-S2) ADC2_CHANNEL_1 ADC2 channel 1 is GPIO0 (ESP32), GPIO12 (ESP32-S2) ADC2_CHANNEL_2 ADC2 channel 2 is GPIO2 (ESP32), GPIO13 (ESP32-S2) ADC2_CHANNEL_3...
  • Page 237 ADC digital controller (DMA mode) output data format. Used to analyze the acquired ADC (DMA) data. Note ESP32: Only type1 is valid. ADC2 does not support DMA mode. Note ESP32-S2: Member channel can be used to judge the validity of the ADC data, because the role of the arbiter may get invalid ADC data.
  • Page 238 Note For ESP32-S2, The filter object is always all enabled channels. Public Members adc_unit_t adc_unit Set adc unit number for filter. For ESP32-S2, Filter IDX0/IDX1 can only be used to filter all enabled channels of ADC1/ADC2 unit at the same time. adc_channel_t channel Set adc channel number for filter.
  • Page 239 ADC channels handle. See adc1_channel_t, adc2_channel_t. Note For ESP32 ADC1, don’t use ADC_CHANNEL_8, ADC_CHANNEL_9. See adc1_channel_t. Values: ADC_CHANNEL_0 = 0 ADC channel ADC_CHANNEL_1 ADC channel ADC_CHANNEL_2 ADC channel ADC_CHANNEL_3 ADC channel ADC_CHANNEL_4 ADC channel Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 240 ADC_CONV_BOTH_UNIT = 3 Use Both ADC1 and ADC2 for conversion simultaneously. ADC_CONV_ALTER_UNIT = 7 Use both ADC1 and ADC2 for conversion by turn. e.g. ADC1 -> ADC2 -> ADC1 -> ADC2 ….. ADC_CONV_UNIT_MAX Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 241 Note For ESP32-S2, The filter object of the ADC is fixed. Values: ADC_DIGI_FILTER_IDX0 = 0 The filter index 0. For ESP32-S2, It can only be used to filter all enabled channels of ADC1 unit at the same time. ADC_DIGI_FILTER_IDX1 The filter index 1. For ESP32-S2, It can only be used to filter all enabled channels of ADC2 unit at the same time.
  • Page 242 Note For ESP32-S2, The monitor object of the ADC is fixed. Values: ADC_DIGI_MONITOR_IDX0 = 0 The monitor index 0. For ESP32-S2, It can only be used to monitor all enabled channels of ADC1 unit at the same time. ADC_DIGI_MONITOR_IDX1 The monitor index 1. For ESP32-S2, It can only be used to monitor all enabled channels of ADC2 unit at the same time.
  • Page 243 • ESP_OK: ADC read and converted to mV • ESP_ERR_INVALID_ARG: Error due to invalid arguments • ESP_ERR_INVALID_STATE: Reading result is invalid. Try to read again. Parameters • [in] channel: ADC Channel to read Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 244 Characterization based on Two Point values stored in eFuse ESP_ADC_CAL_VAL_DEFAULT_VREF = 2 Characterization based on default reference voltage ESP_ADC_CAL_VAL_EFUSE_TP_FIT = 3 Characterization based on Two Point values and fitting curve coefficients stored in eFuse ESP_ADC_CAL_VAL_MAX ESP_ADC_CAL_VAL_NOT_SUPPORTED = ESP_ADC_CAL_VAL_MAX GPIO Lookup Macros Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 245 ADC1_CHANNEL_1_GPIO_NUM ADC1_GPIO3_CHANNEL ADC1_CHANNEL_2_GPIO_NUM ADC1_GPIO4_CHANNEL ADC1_CHANNEL_3_GPIO_NUM ADC1_GPIO5_CHANNEL ADC1_CHANNEL_4_GPIO_NUM ADC1_GPIO6_CHANNEL ADC1_CHANNEL_5_GPIO_NUM ADC1_GPIO7_CHANNEL ADC1_CHANNEL_6_GPIO_NUM ADC1_GPIO8_CHANNEL ADC1_CHANNEL_7_GPIO_NUM ADC1_GPIO9_CHANNEL ADC1_CHANNEL_8_GPIO_NUM ADC1_GPIO10_CHANNEL ADC1_CHANNEL_9_GPIO_NUM ADC2_GPIO11_CHANNEL ADC2_CHANNEL_0_GPIO_NUM ADC2_GPIO12_CHANNEL ADC2_CHANNEL_1_GPIO_NUM ADC2_GPIO13_CHANNEL ADC2_CHANNEL_2_GPIO_NUM ADC2_GPIO14_CHANNEL ADC2_CHANNEL_3_GPIO_NUM ADC2_GPIO15_CHANNEL ADC2_CHANNEL_4_GPIO_NUM ADC2_GPIO16_CHANNEL ADC2_CHANNEL_5_GPIO_NUM ADC2_GPIO17_CHANNEL ADC2_CHANNEL_6_GPIO_NUM ADC2_GPIO18_CHANNEL ADC2_CHANNEL_7_GPIO_NUM Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 246: Digital To Analog Converter (Dac)

    ADC2_CHANNEL_9_GPIO_NUM 2.2.2 Digital To Analog Converter (DAC) Overview ESP32-S2 has two 8-bit DAC (digital to analog converter) channels, connected to GPIO17 (Channel 1) and GPIO18 (Channel 2). The DAC driver allows these channels to be set to arbitrary voltages. The DAC channels can also be driven with DMA-style written sample data by the digital controller, however the driver does not supported this yet.
  • Page 247 DAC channel 2 I2S right channel will be mapped to DAC channel 1 Parameters • channel: DAC channel esp_err_t dac_output_disable(dac_channel_t channel) DAC pad output disable. Note DAC channel 1 is attached to GPIO25, DAC channel 2 is attached to GPIO26 Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 248 Config the cosine wave generator function in DAC module. Public Members dac_channel_t en_ch Enable the cosine wave generator of DAC channel. dac_cw_scale_t scale Set the amplitude of the cosine wave generator output. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 249 1/2. DAC_CW_SCALE_4 = 0x2 1/4. DAC_CW_SCALE_8 = 0x3 1/8. enum dac_cw_phase_t Set the phase of the cosine wave generator output. Values: DAC_CW_PHASE_0 = 0x2 Phase shift +0° DAC_CW_PHASE_180 = 0x3 Phase shift +180° Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 250: General Purpose Timer

    Timer Initialization The two ESP32-S2 timer groups, with two timer(s) in each, provide the total of four individual timers for use. An ESP32-S2 timer group should be identified using timer_group_t. An individual timer in a group should be identified with timer_idx_t.
  • Page 251 For more information on how to use interrupts, please see the application example below. Application Example The 64-bit hardware timer example: peripherals/timer_group. API Reference Header File • components/driver/include/driver/timer.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 252 • timer_num: Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] esp_err_t timer_set_counter_mode(timer_group_t group_num, timer_idx_t timer_num, timer_count_dir_t counter_dir) Set counting mode for hardware timer. Return • ESP_OK Success • ESP_ERR_INVALID_ARG Parameter error Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 253 • ESP_ERR_INVALID_ARG Parameter error Parameters • group_num: Timer group, 0 for TIMERG0 or 1 for TIMERG1 • timer_num: Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] • alarm_en: To enable or disable timer alarm function. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 254 • handle: Pointer to return handle. If non-NULL, a handle for the interrupt will be returned here. Return • ESP_OK Success • ESP_ERR_INVALID_ARG Parameter error esp_err_t timer_init(timer_group_t group_num, timer_idx_t timer_num, const timer_config_t *config) Initializes and configure the timer. Return • ESP_OK Success • ESP_ERR_INVALID_ARG Parameter error Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 255 Return • ESP_OK Success • ESP_ERR_INVALID_ARG Parameter error Parameters • group_num: Timer group number, 0 for TIMERG0 or 1 for TIMERG1 • timer_num: Timer index. esp_err_t timer_disable_intr(timer_group_t group_num, timer_idx_t timer_num) Disable timer interrupt. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 256 Get the masked interrupt status, just used in ISR. Return • Interrupt status Parameters • group_num: Timer group number, 0 for TIMERG0 or 1 for TIMERG1 uint32_t timer_group_get_intr_status_in_isr(timer_group_t group_num) Get interrupt status, just used in ISR. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 257 FreeRTOS calls is pdTRUE, return true; otherwise return false. typedef intr_handle_t timer_isr_handle_t Interrupt handle, used in order to free the isr after use. Aliases to an int handle for now. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 258 Select a hardware timer from timer groups. Values: TIMER_0 = 0 Select timer0 of GROUPx TIMER_1 = 1 Select timer1 of GROUPx TIMER_MAX enum timer_count_dir_t Decides the direction of counter. Values: TIMER_COUNT_DOWN = 0 Descending Count from cnt.high|cnt.low Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 259 Disable auto-reload: hardware will not load counter value after an alarm event TIMER_AUTORELOAD_EN = 1 Enable auto-reload: hardware will load counter value after an alarm event TIMER_AUTORELOAD_MAX enum timer_src_clk_t Select timer source clock. Values: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 260: Gpio & Rtc Gpio

    Overview The ESP32-S2 chip features 43 physical GPIO pads. Some GPIO pads cannot be used or do not have the corre- sponding pin on the chip package. For more details, see ESP32-S2 Technical Reference Manual > IO MUX and GPIO Matrix (GPIO, IO_MUX) [PDF].
  • Page 261 Note This function also configures the IOMUX for this pin to the GPIO function, and disconnects any other peripheral output configured via GPIO Matrix. Return Always return ESP_OK. Parameters • gpio_num: GPIO number. esp_err_t gpio_set_intr_type(gpio_num_t gpio_num, gpio_int_type_t intr_type) GPIO set interrupt trigger type. Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 262 • gpio_num: GPIO number. If you want to get the logic level of e.g. pin GPIO16, gpio_num should be GPIO_NUM_16 (16); esp_err_t gpio_set_direction(gpio_num_t gpio_num, gpio_mode_t mode) GPIO set direction. Configure GPIO direction,such as output_only,input_only,output_and_input Return • ESP_OK Success • ESP_ERR_INVALID_ARG GPIO error Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 263 • ESP_OK Success ; • ESP_ERR_INVALID_ARG GPIO error • ESP_ERR_NOT_FOUND No free interrupt found with the specified flags esp_err_t gpio_pullup_en(gpio_num_t gpio_num) Enable pull-up on GPIO. Return • ESP_OK Success • ESP_ERR_INVALID_ARG Parameter error Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 264 This limit is smaller compared to a global GPIO interrupt handler due to the additional level of indirection. Return • ESP_OK Success • ESP_ERR_INVALID_STATE Wrong state, the ISR service has not been initialized. • ESP_ERR_INVALID_ARG Parameter error Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 265 If you don’t want this behavior, you should configure gpio18 as output mode and set it to hight level before calling gpio_hold_dis. Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 266 Disable SLP_SEL to change GPIO status automantically in lightsleep. Return • ESP_OK Success Parameters • gpio_num: GPIO number of the pad. esp_err_t gpio_sleep_set_direction(gpio_num_t gpio_num, gpio_mode_t mode) GPIO set direction at sleep. Configure GPIO direction,such as output_only,input_only,output_and_input Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 267 GPIO pin: set with bit mask, each bit maps to a GPIO gpio_mode_t mode GPIO mode: set input/output mode gpio_pullup_t pull_up_en GPIO pull-up gpio_pulldown_t pull_down_en GPIO pull-down gpio_int_type_t intr_type GPIO interrupt type Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 268 Pin 14 selected GPIO_SEL_15 Pin 15 selected GPIO_SEL_16 Pin 16 selected GPIO_SEL_17 Pin 17 selected GPIO_SEL_18 Pin 18 selected GPIO_SEL_19 Pin 19 selected GPIO_SEL_20 Pin 20 selected GPIO_SEL_21 Pin 21 selected GPIO_SEL_26 Pin 26 selected Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 269 Pin 40 selected GPIO_SEL_41 Pin 41 selected GPIO_SEL_42 Pin 42 selected GPIO_SEL_43 Pin 43 selected GPIO_SEL_44 Pin 44 selected GPIO_SEL_45 Pin 45 selected GPIO_SEL_46 Pin 46 selected GPIO_PIN_REG_0 GPIO_PIN_REG_1 GPIO_PIN_REG_2 GPIO_PIN_REG_3 GPIO_PIN_REG_4 GPIO_PIN_REG_5 Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 270 GPIO_PIN_REG_12 GPIO_PIN_REG_13 GPIO_PIN_REG_14 GPIO_PIN_REG_15 GPIO_PIN_REG_16 GPIO_PIN_REG_17 GPIO_PIN_REG_18 GPIO_PIN_REG_19 GPIO_PIN_REG_20 GPIO_PIN_REG_21 GPIO_PIN_REG_22 GPIO_PIN_REG_23 GPIO_PIN_REG_24 GPIO_PIN_REG_25 GPIO_PIN_REG_26 GPIO_PIN_REG_27 GPIO_PIN_REG_28 GPIO_PIN_REG_29 GPIO_PIN_REG_30 GPIO_PIN_REG_31 GPIO_PIN_REG_32 GPIO_PIN_REG_33 GPIO_PIN_REG_34 GPIO_PIN_REG_35 GPIO_PIN_REG_36 GPIO_PIN_REG_37 GPIO_PIN_REG_38 GPIO_PIN_REG_39 GPIO_PIN_REG_40 GPIO_PIN_REG_41 GPIO_PIN_REG_42 GPIO_PIN_REG_43 GPIO_PIN_REG_44 Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 271 GPIO_NUM_9 = 9 GPIO9, input and output GPIO_NUM_10 = 10 GPIO10, input and output GPIO_NUM_11 = 11 GPIO11, input and output GPIO_NUM_12 = 12 GPIO12, input and output GPIO_NUM_13 = 13 GPIO13, input and output Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 272 GPIO_NUM_36 = 36 GPIO36, input and output GPIO_NUM_37 = 37 GPIO37, input and output GPIO_NUM_38 = 38 GPIO38, input and output GPIO_NUM_39 = 39 GPIO39, input and output GPIO_NUM_40 = 40 GPIO40, input and output Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 273 GPIO_MODE_INPUT_OUTPUT_OD = ((GPIO_MODE_DEF_INPUT) | (GPIO_MODE_DEF_OUTPUT) | (GPIO_MODE_D GPIO mode : output and input with open-drain mode GPIO_MODE_INPUT_OUTPUT = ((GPIO_MODE_DEF_INPUT) | (GPIO_MODE_DEF_OUTPUT)) GPIO mode : output and input mode enum gpio_pullup_t Values: GPIO_PULLUP_DISABLE = 0x0 Disable GPIO pull-up resistor Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 274 • gpio_num: GPIO number static int rtc_io_number_get(gpio_num_t gpio_num) Get RTC IO index number by gpio number. Return >=0: Index of rtcio. -1 : The gpio is not rtcio. Parameters • gpio_num: GPIO number Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 275 NOTE: ESP32 support INPUT_ONLY mode. ESP32S2 support INPUT_ONLY, OUTPUT_ONLY, IN- PUT_OUTPUT mode. Return • ESP_OK Success • ESP_ERR_INVALID_ARG GPIO is not an RTC IO Parameters • gpio_num: GPIO number (e.g. GPIO_NUM_12) • mode: GPIO direction Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 276 • strength: Drive capability of the pad esp_err_t rtc_gpio_get_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t *strength) Get RTC GPIO pad drive capability. Return • ESP_OK Success • ESP_ERR_INVALID_ARG Parameter error Parameters • gpio_num: GPIO number, only support output GPIOs Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 277 • ESP_ERR_INVALID_ARG if gpio_num is not an RTC IO, or intr_type is not one of GPIO_INTR_HIGH_LEVEL, GPIO_INTR_LOW_LEVEL. Parameters • gpio_num: GPIO number • intr_type: Wakeup on high level (GPIO_INTR_HIGH_LEVEL) or low level (GPIO_INTR_LOW_LEVEL) esp_err_t rtc_gpio_wakeup_disable(gpio_num_t gpio_num) Disable wakeup from sleep mode using specific GPIO. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 278: Dedicated Gpio

    GPIO bundle in a pin-to-core task. For example, if GPIOA is connected to CPU0, and the dedicated GPIO instruction is issued from CPU1, then it’s impossible to control GPIOA. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 279 Read the value that output from bundle dedic_gpio_bundle_read_in() Note: The functions above just wrap the customized instructions defined for ESP32-S2, for the details of those instructions, please refer to ESP32-S2 Technical Reference Manual > IO MUX and GPIO Matrix (GPIO, IO_MUX) [PDF].
  • Page 280 4 GPIO channels imm[4:0] imm[4:0] For details of supported dedicated GPIO instructions, please refer to ESP32-S2 Technical Reference Manual > IO MUX and GPIO Matrix (GPIO, IO_MUX) [PDF]. The supported dedicated CPU instructions are also wrapped inside soc/cpu_ll.h as helper inline functions.
  • Page 281 Return Value that output from the GPIO bundle, low bit represents low member in the bundle Note For performance reasons, this function doesn’t check the validity of any parameters, and is placed in IRAM. Parameters • [in] bundle: Handle of GPIO bundle that returned from “dedic_gpio_new_bundle” Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 282 : 1 Invert input signal unsigned int out_en : 1 Enable output unsigned int out_invert : 1 Invert output signal struct dedic_gpio_bundle_config_t::[anonymous] flags Flags to control specific behaviour of GPIO bundle Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 283: Hash-Based Message Authentication Code (Hmac)

    HMAC generation using a key burned into an eFuse block. HMACs work with pre-shared secret keys and provide authenticity and integrity to a message. For more detailed information on the application workflow and the HMAC calculation process, see ESP32-S2 Tech- nical Reference Manual > HMAC Accelerator (HMAC) [PDF].
  • Page 284 Chapter 2. API Reference HMAC on the ESP32-S2 On the ESP32-S2, the HMAC module works with a secret key burnt into the eFuses. This eFuse key can be made completely inaccessible for any resources outside the cryptographic modules, thus avoiding key leakage.
  • Page 285 firmware. 3. To re-disable JTAG in the firmware, reset the system or call esp_hmac_jtag_disable(). For more details, see ESP32-S2 Technical Reference Manual > HMAC Accelerator (HMAC) [PDF]. Application Outline Following code is an outline of how to set an eFuse key and then use it to calculate an HMAC for software usage.
  • Page 286 JTAG key by calling esp_hmac_jtag_enable() API. Return • ESP_OK return ESP_OK after writing the HMAC_SET_INVALIDATE_JTAG_REG with value Enumerations enum hmac_key_id_t The possible efuse keys for the HMAC peripheral Values: HMAC_KEY0 = 0 HMAC_KEY1 HMAC_KEY2 HMAC_KEY3 HMAC_KEY4 HMAC_KEY5 HMAC_KEY_MAX Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 287: Digital Signature (Ds)

    Both the HMAC key and the RSA private key have to be created and stored before the DS peripheral can be used. This needs to be done in software on the ESP32-S2 or alternatively on a host. For this context, the IDF provides...
  • Page 288 NVS partition for the encrypted private key parameters. Then the script flashes this par- tition onto the ESP32-S2. The application then needs to read the DS data from NVS, which can be done with the function esp_read_ds_data_from_nvs in file ssl_mutual_auth/main/app_main.c...
  • Page 289 • iv: Pointer to 16 byte IV buffer, will be copied into ‘data’. Should be randomly generated bytes each time. • p_data: Pointer to input plaintext key data. The expectation is this data will be deleted after this process is done and ‘data’is stored. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 290 RSA r inverse operand. uint32_t M_prime RSA M prime operand. esp_digital_signature_length_t length RSA length. Macros ESP_ERR_HW_CRYPTO_DS_HMAC_FAIL HMAC peripheral problem ESP_ERR_HW_CRYPTO_DS_INVALID_KEY given HMAC key isn’t correct, HMAC peripheral problem ESP_ERR_HW_CRYPTO_DS_INVALID_DIGEST message digest check failed, result is invalid Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 291: Inter-Integrated Circuit (I2C)

    (within one foot). ESP32-S2 has two I2C controllers (also referred to as ports) which are responsible for handling communications on the I2C bus. Each I2C controller can operate as master or slave. As an example, one controller can act as a master and the other as a slave at the same time.
  • Page 292 • Configure communication pins – Assign GPIO pins for SDA and SCL signals – Set whether to enable ESP32-S2’s internal pull-ups • (Master only) Set I2C clock speed • (Slave only) Configure the following – Whether to enable 10 bit address mode –...
  • Page 293 2. I2C_SCLK_SRC_FLAG_LIGHT_SLEEP: It supports Light-sleep mode, which APB clock cannot do. 3. Some flags may not be supported on ESP32-S2, reading technical reference manual before using it. Note: The clock frequency of SCL in master mode should not be lager than max frequency for SCL mentioned in the table above.
  • Page 294 Compared to writing data, the command link is populated in Step 4 not with i2c_master_write... func- tions but with i2c_master_read_byte() and / or i2c_master_read(). Also, the last read in Step 5 is configured so that the master does not provide the ACK bit. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 295 When implementing your own interrupt handler, refer to ESP32-S2 Technical Reference Manual > I2C Controller (I2C) > Interrupts [PDF] for the description of interrupts triggered by the I2C controller.
  • Page 296 If you want to modify already entered values, use the function i2c_param_config(). Note: ESP32-S2’s internal pull-ups are in the range of tens of kOhm, which is, in most cases, insufficient for use as I2C pull-ups. Users are advised to use external pull-ups with values described in the specification.
  • Page 297 I2C rx fifo Return • ESP_OK Success • ESP_ERR_INVALID_ARG Parameter error Parameters • i2c_num: I2C port number esp_err_t i2c_isr_register(i2c_port_t i2c_num, void (*fn))void * , void *arg, int intr_alloc_flags, intr_handle_t *handleRegister an I2C ISR handler. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 298 Perform a read to a device connected to a particular I2C port. This function is a wrapper to i2c_master_start(), i2c_master_write(), i2c_master_read(), etc …It shall only be called in I2C master mode. Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 299 The required bytes will be dynamically allocated. Return Handle to the I2C command link void i2c_cmd_link_delete_static(i2c_cmd_handle_t cmd_handle) Free the I2C commands list allocated statically with i2c_cmd_link_create_static. Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 300 I2C master mode. Call i2c_master_cmd_begin() to send all queued commands. Return • ESP_OK Success • ESP_ERR_INVALID_ARG Parameter error • ESP_ERR_NO_MEM The static buffer used to create cmd_handler is too small • ESP_FAIL No more memory left on the heap Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 301 FIFO with the internal ringbuffer’s data. Note This function shall only be called in I2C slave mode. Return • ESP_FAIL (-1) Parameter error • Other (>=0) The number of data bytes pushed to the I2C slave buffer. Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 302 • cyc_num: the APB cycles need to be filtered (0<= cyc_num <=7). When the period of a pulse is less than cyc_num * APB_cycle, the I2C controller will ignore this pulse. esp_err_t i2c_filter_disable(i2c_port_t i2c_num) Disable filter on I2C bus. Return • ESP_OK Success • ESP_ERR_INVALID_ARG Parameter error Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 303 • sample_time: clock number I2C used to sample data on SDA after the rising-edge of SCL, it’ s a 10-bit value • hold_time: clock number I2C used to hold the data after the falling-edge of SCL, it’s a 10-bit value Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 304 • ESP_ERR_INVALID_ARG Parameter error Parameters • i2c_num: I2C port number • tx_trans_mode: pointer to get I2C sending data mode • rx_trans_mode: pointer to get I2C receiving data mode Structures struct i2c_config_t I2C initialization parameters. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 305 The following macro is used to determine the recommended size of the buffer to pass to i2c_cmd_link_create_static() function. It requires one parameter, TRANSACTIONS, de- scribing the number of transactions intended to be performed on the I2C port. For example, if one wants Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 306 I2C read data enum i2c_trans_mode_t Values: I2C_DATA_MODE_MSB_FIRST = 0 I2C data msb first I2C_DATA_MODE_LSB_FIRST = 1 I2C data lsb first I2C_DATA_MODE_MAX enum i2c_addr_mode_t Values: I2C_ADDR_BIT_7 = 0 I2C 7bit address for slave mode Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 307: Inter-Ic Sound (I2S)

    I2S (Inter-IC Sound) is a serial, synchronous communication protocol that is usually used for transmitting audio data between two digital audio devices. ESP32-S2 contains one I2S peripheral(s). These peripherals can be configured to input and output sample data via the I2S driver.
  • Page 308 Chapter 2. API Reference For more information, see ESP32-S2 Technical Reference Manual > I2S Controller (I2S) > LCD Mode [PDF]. Note: For high accuracy clock applications, use the APLL_CLK clock source, which has the frequency range of 16 ~ 128 MHz. You can enable the APLL_CLK clock source by setting i2s_config_t::use_apll to TRUE.
  • Page 309 I2S_MODE_MASTER I2S_MODE_TX, .sample_rate 44100, .bits_per_sample I2S_BITS_PER_SAMPLE_16BIT, .channel_format I2S_CHANNEL_FMT_RIGHT_LEFT, .communication_format I2S_COMM_FORMAT_STAND_I2S .tx_desc_auto_clear false, .dma_buf_count .dma_buf_len .use_apll false, .intr_alloc_flags ESP_INTR_FLAG_LEVEL1 // Interrupt level 1, default 0 static const i2s_pin_config_t pin_config .bck_io_num (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 310 • i2s_num: I2S port number • i2s_config: I2S configurations - see i2s_config_t struct • queue_size: I2S event queue size/depth. • i2s_queue: I2S event queue handle, if set NULL, driver will not use an event queue. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 311 Read data from I2S DMA receive buffer. Note If the built-in ADC mode is enabled, we should call i2s_adc_enable and i2s_adc_disable around the whole reading process, to prevent the data getting corrupted. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 312 Zero the contents of the TX DMA buffer. Pushes zero-byte samples into the TX DMA buffer, until it is full. Return • ESP_OK Success • ESP_ERR_INVALID_ARG Parameter error Parameters • i2s_num: I2S port number Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 313 WS in out pin int data_out_num DATA out pin int data_in_num DATA in pin struct i2s_driver_config_t I2S driver configuration parameters. Public Members i2s_mode_t mode I2S work mode uint32_t sample_rate I2S sample rate Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 314 I2S_PIN_NO_CHANGE Use in i2s_pin_config_t for pins which should not be changed Type Definitions typedef i2s_driver_config_t i2s_config_t typedef intr_handle_t i2s_isr_handle_t Enumerations enum i2s_port_t I2S port number, the max port number is (I2S_NUM_MAX -1). Values: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 315 I2S_BITS_PER_CHAN_DEFAULT = (0) channel bit-width equals to data bit-width I2S_BITS_PER_CHAN_8BIT = (8) channel bit-width: 8 I2S_BITS_PER_CHAN_16BIT = (16) channel bit-width: 16 I2S_BITS_PER_CHAN_24BIT = (24) channel bit-width: 24 I2S_BITS_PER_CHAN_32BIT = (32) channel bit-width: 32 Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 316 PCM Long, (I2S_COMM_FORMAT_PCM | I2S_COMM_FORMAT_PCM_LONG) correspond to I2S_COMM_FORMAT_STAND_PCM_LONG enum i2s_channel_fmt_t I2S channel format type. Values: I2S_CHANNEL_FMT_RIGHT_LEFT Separated left and right channel I2S_CHANNEL_FMT_ALL_RIGHT Load right channel data in both two channels I2S_CHANNEL_FMT_ALL_LEFT Load left channel data in both two channels Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 317: Lcd

    ESP chips can generate various kinds of timings that needed by common LCDs on the market, like SPI LCD, I80 LCD (a.k.a Intel 8080 parallel LCD), RGB LCD, I2C LCD, etc. The esp_lcd component is officially to support those LCDs with a group of universal APIs across chips. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 318 Select APLL as the source clock LCD_CLK_SRC_XTAL Select XTAL as the source clock Header File • components/esp_lcd/include/esp_lcd_types.h Type Definitions typedef struct esp_lcd_panel_io_t *esp_lcd_panel_io_handle_t Type of LCD panel IO handle typedef struct esp_lcd_panel_t *esp_lcd_panel_handle_t Type of LCD panel handle Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 319 • [in] color: Buffer that holds the RGB color data • [in] color_size: Size of color in memory, in bytes esp_err_t esp_lcd_panel_io_del(esp_lcd_panel_io_handle_t Destory LCD panel IO handle (deinitialize panel and free all corresponding resource) Return • ESP_ERR_INVALID_ARG if parameter is invalid Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 320 • [in] bus: Intel 8080 bus handle, created by esp_lcd_new_i80_bus() esp_err_t esp_lcd_new_panel_io_i80(esp_lcd_i80_bus_handle_t bus, const esp_lcd_panel_io_i80_config_t *io_config, esp_lcd_panel_io_handle_t *ret_io) Create LCD panel IO, for Intel 8080 interface. Return • ESP_ERR_INVALID_ARG if parameter is invalid Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 321 If this flag is enabled, DC line = 0 means transfer data, DC line = 1 means transfer command; vice versa unsigned int octal_mode : 1 transmit with octal mode (8 data lines), this mode is used to simulate Intel 8080 timing struct esp_lcd_panel_io_i2c_config_t Public Members uint32_t dev_addr I2C device address Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 322 Transaction queue size, larger queue, higher throughput esp_lcd_panel_io_color_trans_done_cb_t on_color_trans_done Callback invoked when color data was tranferred done void *user_ctx User private data, passed directly to on_color_trans_done’s user_ctx int lcd_cmd_bits Bit-width of LCD command Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 323 • [in] user_ctx: User data, passed from esp_lcd_panel_io_xxx_config_t Header File • components/esp_lcd/include/esp_lcd_panel_ops.h Functions esp_err_t esp_lcd_panel_reset(esp_lcd_panel_handle_t panel) Reset LCD panel. Note Panel reset must be called before attempting to initialize the panel using esp_lcd_panel_init(). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 324 Note Combined with esp_lcd_panel_mirror(), one can realize screen rotation Return • ESP_OK on success • ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel Parameters • [in] panel: LCD panel handle, which is created by other factory API like esp_lcd_new_panel_st7789() Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 325 • ESP_ERR_INVALID_ARG if parameter is invalid • ESP_ERR_NO_MEM if out of memory • ESP_OK on success Parameters • [in] io: LCD panel IO handle • [in] panel_dev_config: general panel device configuration • [out] ret_panel: Returned LCD panel handle Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 326: Led Control (Ledc)

    PWM signals for other purposes. It has 8 channels which can generate independent waveforms that can be used, for example, to drive RGB LED devices. The PWM controller can automatically increase or decrease the duty cycle gradually, allowing for fades without any processor interference. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 327 Chapter 2. API Reference Functionality Overview Setting up a channel of the LEDC is done in three steps. Note that unlike ESP32, ESP32-S2 only supports configuring channels in “low speed”mode. Timer Configuration by specifying the PWM signal’s frequency and duty cycle resolution.
  • Page 328 Section Change PWM Frequency. Note: All the timers and channels in the ESP32-S2’s LED PWM Controller only support low speed mode. Any change of PWM settings must be explicitly triggered by software (see below). Change PWM Duty Cycle Using Software To set the duty cycle, use the dedicated function ledc_set_duty().
  • Page 329 (see timer configuration and the ESP32-S2 Technical Reference Manual > LED PWM Controller (LEDC) [PDF]). The LEDC can be used for generating signals at much higher frequencies that are sufficient enough to clock other devices, e.g., a digital camera module.
  • Page 330 • speed_mode: Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. • timer_num: LEDC timer index (0-3), select from ledc_timer_t • freq_hz: Set the LEDC frequency uint32_t ledc_get_freq(ledc_mode_t speed_mode, ledc_timer_t timer_num) LEDC get channel frequency (Hz) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 331 • duty: Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution) - 1] uint32_t ledc_get_duty(ledc_mode_t speed_mode, ledc_channel_t channel) LEDC get duty. Return • LEDC_ERR_DUTY if parameter error • Others Current LEDC duty Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 332 • duty_resolution: Resolution of duty setting in number of bits. The range of duty values is [0, (2**duty_resolution)] • clk_src: Select LEDC source clock. esp_err_t ledc_timer_rst(ledc_mode_t speed_mode, ledc_timer_t timer_sel) Reset LEDC timer. Return • ESP_ERR_INVALID_ARG Parameter error Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 333 • speed_mode: Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. , • channel: LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t • target_duty: Target duty of fading [0, (2**duty_resolution) - 1] Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 334 Note If a fade operation is running in progress on that channel, the driver would not allow it to be stopped. Other duty operations will have to wait until the fade operation has finished. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 335 Note The callback is called from an ISR, it must never attempt to block, and any FreeRTOS API called must be ISR capable. Return • ESP_ERR_INVALID_ARG Parameter error • ESP_OK Success • ESP_ERR_INVALID_STATE Fade function not installed. • ESP_FAIL Fade function init error Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 336 *param, void *user_arg) Type of LEDC event callback. Parameters • param: LEDC callback parameter • user_arg: User registered data Enumerations enum ledc_cb_event_t LEDC callback event type. Values: LEDC_FADE_END_EVT LEDC fade end event Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 337 Configure LEDC source clock. For low speed channels and high speed channels, you can specify the source clock using LEDC_USE_REF_TICK, LEDC_USE_APB_CLK or LEDC_AUTO_CLK. For low speed channels, you can also specify the source clock using LEDC_USE_RTC8M_CLK, in this case, all low speed channel’s source clock must be RTC8M_CLK Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 338 LEDC timer select RTC8M_CLK as source clock. Only for low speed channels and this parameter must be the same for all low speed channels LEDC_USE_XTAL_CLK LEDC timer select XTAL clock as source clock enum ledc_clk_src_t Values: LEDC_REF_TICK = LEDC_USE_REF_TICK LEDC timer clock divided from reference tick (1Mhz) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 339 LEDC PWM duty resolution of 2 bits LEDC_TIMER_3_BIT LEDC PWM duty resolution of 3 bits LEDC_TIMER_4_BIT LEDC PWM duty resolution of 4 bits LEDC_TIMER_5_BIT LEDC PWM duty resolution of 5 bits LEDC_TIMER_6_BIT LEDC PWM duty resolution of 6 bits Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 340: Pulse Counter (Pcnt)

    The PCNT module has 4 independent counting “units”numbered from 0 to 3. In the API they are referred to using pcnt_unit_t. Each unit has two independent channels numbered as 0 and 1 and specified with pcnt_channel_t. The configuration is provided separately per unit’s channel using pcnt_config_t and covers: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 341 To enable or disable events on reaching threshold values, you will also need to call functions pcnt_event_enable() and pcnt_event_disable(). In order to check what are the threshold values currently set, use function pcnt_get_event_value(). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 342 • pcnt_unit: PCNT unit number, select from pcnt_unit_t esp_err_t pcnt_counter_clear(pcnt_unit_t pcnt_unit) Clear and reset PCNT counter value to zero. Return • ESP_OK Success • ESP_ERR_INVALID_STATE pcnt driver has not been initialized • ESP_ERR_INVALID_ARG Parameter error Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 343 • evt_type: Watch point event type. All enabled events share the same interrupt (one interrupt per pulse counter unit). • value: Counter value for PCNT event esp_err_t pcnt_get_event_value(pcnt_unit_t unit, pcnt_evt_type_t evt_type, int16_t *value) Get PCNT event value of PCNT unit. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 344 Note Set the signal input to PCNT_PIN_NOT_USED if unused. Return • ESP_OK Success • ESP_ERR_INVALID_STATE pcnt driver has not been initialized • ESP_ERR_INVALID_ARG Parameter error Parameters • unit: PCNT unit number • channel: PCNT channel number Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 345 • pos_mode: Counter mode when detecting positive edge • neg_mode: Counter mode when detecting negative edge • hctrl_mode: Counter mode when control signal is high level • lctrl_mode: Counter mode when control signal is low level Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 346 Pulse input GPIO number, if you want to use GPIO16, enter pulse_gpio_num = 16, a negative value will be ignored int ctrl_gpio_num Control signal input GPIO number, a negative value will be ignored Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 347 Selection of available modes that determine the counter’ s action on the edge of the pulse signal’ s input GPIO. Note Configuration covers two actions, one for positive, and one for negative edge on the pulse input Espressif Systems Release v4.4...
  • Page 348 PCNT watch point event: Minimum counter value PCNT_EVT_H_LIM = 1 << 5 PCNT watch point event: Maximum counter value PCNT_EVT_ZERO = 1 << 6 PCNT watch point event: counter value zero event PCNT_EVT_MAX Header File • components/hal/include/hal/pcnt_types.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 349: Remote Control (Rmt)

    Change Operation Parameters Use Interrupts The RMT has four channels numbered from zero to three. Each channel is able to independently transmit or receive data. They are referred to using indexes defined in structure rmt_channel_t. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 350 Chapter 2. API Reference Fig. 8: RMT Transmitter Overview Fig. 9: RMT Receiver Overview Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 351 • Frequency of the carrier in Hz - carrier_freq_hz • Duty cycle of the carrier signal in percent (%) - carrier_duty_percent • Level of the RMT input, where the carrier is modulated to - carrier_level Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 352 In typical scenarios it is not enough as an ultimate storage for all incoming (and outgoing) items. Therefore this API supports retrieval of incoming items on the fly to save them in a ring buffer of a size defined by the user. The Espressif Systems Release v4.4...
  • Page 353 The RMT controller triggers interrupts on four specific events describes below. To enable interrupts on these events, the following functions are provided: • The RMT receiver has finished receiving a signal - rmt_set_rx_intr_en() Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 354 *div_cnt) Get RMT clock divider, channel clock is divided from source clock. Return • ESP_ERR_INVALID_ARG Parameter error • ESP_OK Success Parameters • channel: RMT channel • div_cnt: pointer to accept RMT counter divider Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 355 Configure RMT carrier for TX signal. Set different values for carrier_high and carrier_low to set different frequency of carrier. The unit of car- rier_high/low is the source clock tick, not the divided channel counter clock. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 356 • ESP_ERR_INVALID_ARG Parameter error • ESP_OK Success Parameters • channel: RMT channel • rx_idx_rst: Set true to reset memory index for receiver. Otherwise, receiver will continue receiving data to the last index in memory. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 357 first data to the last data in channel over and over again in a loop. esp_err_t rmt_get_tx_loop_mode(rmt_channel_t channel, bool *loop_en) Get RMT tx loop mode. Return • ESP_ERR_INVALID_ARG Parameter error • ESP_OK Success Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 358 • level: To set the output signal’s level for channel in idle state. esp_err_t rmt_get_idle_level(rmt_channel_t channel, bool *idle_out_en, rmt_idle_level_t *level) Get RMT idle output level for transmitter. Return • ESP_ERR_INVALID_ARG Parameter error • ESP_OK Success Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 359 Configure the GPIO used by RMT channel. Return • ESP_ERR_INVALID_ARG Configure RMT GPIO failed because of wrong parameter • ESP_OK Configure RMT GPIO successfully Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 360 • mem_offset: Index offset of memory. esp_err_t rmt_driver_install(rmt_channel_t channel, size_t rx_buf_size, int intr_alloc_flags) Initialize RMT driver. Return • ESP_ERR_INVALID_STATE Driver is already installed, call rmt_driver_uninstall first. • ESP_ERR_NO_MEM Memory allocation failure • ESP_ERR_INVALID_ARG Parameter error • ESP_OK Success Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 361 – If set 1, it will block the task and wait for sending done. – If set 0, it will not wait and return immediately. esp_err_t rmt_wait_tx_done(rmt_channel_t channel, TickType_t wait_time) Wait RMT TX finished. Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 362 *src, size_t src_size, bool wait_tx_done) Translate uint8_t type of data into rmt format and send it out. Requires rmt_translator_init to init the translator first. Return • ESP_FAIL Send fail • ESP_OK Send success Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 363 • When the loop auto-stop feature is enabled will halt RMT transmission after the loop count reaches a certain threshold • When disabled, the RMT transmission continue indefinitely until halted by the users Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 364 RMT carrier frequency rmt_carrier_level_t carrier_level Level of the RMT output, when the carrier is applied rmt_idle_level_t idle_level RMT idle level uint8_t carrier_duty_percent RMT carrier duty (%) uint32_t loop_count Maximum loop count Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 365 RMT memory block number uint32_t flags RMT channel extra configurations, OR’d with RMT_CHANNEL_FLAGS_[*] rmt_tx_config_t tx_config RMT TX parameter rmt_rx_config_t rx_config RMT RX parameter struct rmt_tx_end_callback_t Structure encapsulating a RMT TX end callback. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 366 0 if no data was converted. Header File • components/hal/include/hal/rmt_types.h Structures struct rmt_channel_status_result_t Data struct of RMT channel status. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 367 Note We highly recommended to use MEM mode not FIFO mode since there will be some gotcha in FIFO mode. Values: RMT_DATA_MODE_FIFO RMT_DATA_MODE_MEM RMT_DATA_MODE_MAX enum rmt_mode_t RMT Channel Working Mode (TX or RX) Values: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 368: Sd Spi Host Driver

    SPI bus can be shared among SD cards and other SPI devices. The SPI Master driver will handle exclusive access from different tasks. The SD SPI driver uses software-controlled CS signal. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 369 • ESP_ERR_INVALID_ARG if sdspi_host_init_device has invalid arguments • ESP_ERR_NO_MEM if memory can not be allocated • other errors from the underlying spi_master and gpio drivers Parameters • dev_config: pointer to device configuration structure Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 370 • handle: Handle of the sdspi device esp_err_t sdspi_host_io_int_wait(sdspi_dev_handle_t handle, TickType_t timeout_ticks) Wait for SDIO interrupt until timeout. Return • ESP_OK on success Parameters • handle: Handle of the sdspi device • timeout_ticks: Ticks to wait before timeout. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 371 GPIO number of write protect signal. gpio_num_t gpio_int GPIO number of interrupt line (input) for SDIO card. gpio_num_t gpio_miso GPIO number of MISO signal. gpio_num_t gpio_mosi GPIO number of MOSI signal. gpio_num_t gpio_sck GPIO number of SCK signal. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 372: Sigma-Delta Modulation

    Handle representing an SD SPI device. 2.2.15 Sigma-delta Modulation Introduction ESP32-S2 has a second-order sigma-delta modulation module. This driver configures the channels of the sigma-delta module. Functionality Overview There are 8 independent sigma-delta modulation channels identified with sigmadelta_channel_t. Each chan- nel is capable to output the binary, hardware generated signal with the sigma-delta modulation.
  • Page 373 Configure Sigma-delta channel. Return • ESP_OK Success • ESP_ERR_INVALID_STATE sigmadelta driver already initialized • ESP_ERR_INVALID_ARG Parameter error Parameters • config: Pointer of Sigma-delta channel configuration struct esp_err_t sigmadelta_set_duty(sigmadelta_channel_t channel, int8_t duty) Set Sigma-delta channel duty. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 374 Sigma-delta channel number int8_t sigmadelta_duty Sigma-delta duty, duty ranges from -128 to 127. uint8_t sigmadelta_prescale Sigma-delta prescale, prescale ranges from 0 to 255. uint8_t sigmadelta_gpio Sigma-delta output io number, refer to gpio.h for more details. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 375: Spi Master Driver

    Overview of ESP32-S2’s SPI peripherals ESP32-S2 integrates 4 SPI peripherals. • SPI0 and SPI1 are used internally to access the ESP32-S2’s attached flash memory. Both controllers share the same SPI bus signals, and there is an arbiter to determine which can access the bus.
  • Page 376 The SPI master driver has the concept of multiple Devices connected to a single bus (sharing a single ESP32-S2 SPI peripheral). As long as each Device is accessed by only one task, the driver is thread safe. However, if multiple tasks try to access the same SPI Device, the driver is not thread-safe. In this case, it is recommended to either: •...
  • Page 377 The read and write phases can also be optional, as not every transaction requires both writing and reading data. If rx_buffer is NULL and SPI_TRANS_USE_RXDATA is not set, the read phase is skipped. If tx_buffer is NULL and SPI_TRANS_USE_TXDATA is not set, the write phase is skipped. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 378 For more in- formation, see Acquiring. Transaction Line Mode Supported line modes for ESP32-S2 are listed as follows, to make use of these modes, set the member flags in the struct spi_transaction_t as shown in the Transaction Flag column. If you want to check if corresponding IO pins are set or not, set the member flags in the...
  • Page 379 • (Optional) To remove the driver for a bus, make sure no more drivers are attached and call spi_bus_free(). The example code for the SPI master driver can be found in the peripherals/spi_master directory of ESP-IDF exam- ples. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 380 On top of that, ESP32-S2 is a little-endian chip, which means that the least significant byte of uint16_t and uint32_t variables is stored at the smallest address. Hence, if uint16_t is stored in memory, bits [7:0] are sent first, followed by bits [15:8].
  • Page 381 The code example for using the SPI master half duplex mode to read/write a AT93C46D EEPROM (8-bit mode) can be found in the peripherals/spi_master/hd_eeprom directory of ESP-IDF examples. API Reference - SPI Common Header File • components/hal/include/hal/spi_types.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 382 Slave has received certain number of data from master, the number is determined by Master. SPI_EV_CMD9 = BIT(6) Received CMD9 from master. SPI_EV_CMDA = BIT(7) Received CMDA from master. SPI_EV_TRANS = BIT(8) A transaction has done. Header File • components/driver/include/driver/spi_common.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 383 GPIO pin for spi data0 signal in quad/octal mode, or -1 if not used. int miso_io_num GPIO pin for Master In Slave Out (=spi_q) signal, or -1 if not used. int data1_io_num GPIO pin for spi data1 signal in quad/octal mode, or -1 if not used. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 384 Transform received data of length <= 32 bits to the format of an unsigned integer. E.g. to transform the data of 15 bits placed in a 4-byte array to integer: uint16_t data SPI_SWAP_DATA_RX(*(uint32_t*)t->rx_data, 15); Parameters • DATA: Data to be rearranged, can be uint8_t, uint16_t or uint32_t. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 385 SPI DMA channels. Values: SPI_DMA_DISABLED = 0 Do not enable DMA for SPI. SPI_DMA_CH_AUTO = 3 Enable DMA, channel is automatically selected by driver. API Reference - SPI Master Header File • components/driver/include/driver/spi_master.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 386 Return • ESP_ERR_INVALID_ARG if parameter is invalid • ESP_ERR_TIMEOUT if there was no completed transaction before ticks_to_wait expired • ESP_OK on success Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 387 • ticks_to_wait: Ticks to wait until there’s a returned item; use portMAX_DELAY to never time out. esp_err_t spi_device_polling_transmit(spi_device_handle_t handle, spi_transaction_t *trans_desc) Send a polling transaction, wait for it to complete, and return the result. This function is the equivalent of calling spi_device_polling_start() followed by spi_device_polling_end(). Do Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 388 • cycles_remain_o: Address of cycles remaining (after dummy bits are used) output. – -1 If too many cycles remaining, suggest to compensate half a clock. – 0 If no remaining cycles or dummy bits are not used. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 389 MISO is ready on the line. Leave at 0 unless you know you need a delay. For better timing performance at high frequency (over 8MHz), it’s suggest to have the right value. int spics_io_num CS GPIO pin for this device, or -1 if not used. uint32_t flags Bitwise OR of SPI_DEVICE_* flags. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 390 *rx_buffer Pointer to receive buffer, or NULL for no MISO phase. Written by 4 bytes-unit if DMA is used. uint8_t rx_data[4] If SPI_TRANS_USE_RXDATA is set, data is received directly to this variable. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 391 Receive data LSB first instead of the default MSB first. SPI_DEVICE_BIT_LSBFIRST Transmit and receive LSB first. SPI_DEVICE_3WIRE Use MOSI (=spid) for both sending and receiving data. SPI_DEVICE_POSITIVE_CS Make CS positive during a transaction instead of negative. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 392 The data lines used at address phase is the same as data phase (otherwise, only one data line is used at address phase) Type Definitions typedef struct spi_transaction_t spi_transaction_t typedef void (*transaction_cb_t)(spi_transaction_t *trans) typedef struct spi_device_t *spi_device_handle_t Handle for a device on a SPI bus. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 393: Spi Slave Driver

    SPI Slave driver is a program that controls ESP32-S2’s SPI peripherals while they function as slaves. Overview of ESP32-S2’s SPI peripherals ESP32-S2 integrates two general purpose SPI controllers which can be used as slave nodes driven by an off-chip SPI master SPI2 and SPI3 have independent signal buses with the same respective names.
  • Page 394 Chapter 2. API Reference Term Definition Host The SPI controller peripheral external to ESP32-S2 that initiates SPI transmissions over the bus, and acts as an SPI Master. Device SPI slave device (general purpose SPI controller). Each Device shares the MOSI, MISO and SCLK signals but is only active on the bus when the Host asserts the De- vice’s individual CS line.
  • Page 395 Speed and Timing Considerations Transaction Interval The ESP32-S2 SPI slave peripherals are designed as general purpose Devices controlled by a CPU. As opposed to dedicated slaves, CPU-based SPI Devices have a limited number of pre-defined registers. All transactions must be handled by the CPU, which means that the transfers and responses are not real-time, and there might be noticeable latency.
  • Page 396 Free a SPI bus claimed as a SPI slave interface. Return • ESP_ERR_INVALID_ARG if parameter is invalid • ESP_ERR_INVALID_STATE if not all devices on the bus are freed • ESP_OK on success Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 397 Not const because we may want to write status back into the transaction description. • ticks_to_wait: Ticks to wait until there’s a returned item; use portMAX_DELAY to never time out. Structures Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 398 User-defined variable. Can be used to store eg transaction ID. Macros SPI_SLAVE_TXBIT_LSBFIRST Transmit command/address/data LSB first instead of the default MSB first. SPI_SLAVE_RXBIT_LSBFIRST Receive data LSB first instead of the default MSB first. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 399: Spi Slave Half Duplex

    The SPI slave will exclusively use the SPI peripheral, pins of the bus before it’s deinitialized. Most config- urations of the slave should be done as soon as the slave is being initialized. spi_bus_config_t specifies should initialized, while spi_slave_hd_slot_config_t specifies how the SPI Slave driver should work. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 400 SPI Slave instance (by force casting), or point it to a context structure. All the callbacks will be called with this arg argument you set when the callbacks are initialized. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 401 Note: On ESP32-S2, the shared registers are read/written in words by the application, but read/written in bytes by the master. There’s no guarantee four continuous bytes read from the master are from the same word written by the slave’s application.
  • Page 402 • [out] out_data: Output buffer to store the read data • len: Length to read, not larger than SOC_SPI_MAXIMUM_BUFFER_SIZE-addr void spi_slave_hd_write_buffer(spi_host_device_t host_id, int addr, uint8_t *data, size_t len) Write the shared registers. Parameters • host_id: Host to write the shared registers Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 403 *data Buffer to send, must be DMA capable. size_t len Len of data to send/receive. For receiving the buffer length should be multiples of 4 bytes, otherwise the extra part will be truncated. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 404 SPI mode, representing a pair of (CPOL, CPHA) configuration: • 0: (0, 0) • 1: (0, 1) • 2: (1, 0) • 3: (1, 1) uint32_t spics_io_num CS GPIO pin for this device. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 405: Temperature Sensor

    Being built-in means that the temperature sensor should work on any ESP32-S2 regardless of what board the chip is embedded in. The temperature sensor module contains an 8-bit Sigma-Delta ADC and a temperature offset DAC.
  • Page 406 API Reference - Normal Temp Sensor Header File • components/driver/esp32s2/include/driver/temp_sensor.h Functions esp_err_t temp_sensor_set_config(temp_sensor_config_t tsens) Set parameter of temperature sensor. Return • ESP_OK Success Parameters • tsens: esp_err_t temp_sensor_get_config(temp_sensor_config_t *tsens) Get parameter of temperature sensor. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 407 Public Members temp_sensor_dac_offset_t dac_offset The temperature measurement range is configured with a built-in temperature offset DAC. uint8_t clk_div Default: 6 Macros TSENS_CONFIG_DEFAULT() temperature sensor default setting. Enumerations enum temp_sensor_dac_offset_t temperature sensor range option. Values: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 408: Touch Sensor

    The touch pad sensing process is under the control of a hardware-implemented finite-state machine (FSM) which is initiated by software or a dedicated hardware timer. For design, operation, and control registers of a touch sensor, see ESP32-S2 Technical Reference Manual > On-Chip Sensors and Analog Signal Processing [PDF].
  • Page 409 Relationship between the voltage range (high / low reference voltages), speed (slope), and measurement time is shown in the figure below. Fig. 12: Touch pad - relationship between measurement parameters The last chart Output represents the touch sensor reading, i.e., the count of pulses collected within the measurement time. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 410 If measurements are noisy, you can filter them with provided API functions. The ESP32-S2’s touch functionality provide two sets of APIs for doing this. There is an internal touch channel that is not connected to any external GPIO. The measurements from this denoise pad can be used to filters out interference introduced on all channels, such as noise introduced by the power supply...
  • Page 411 The touch channel is generally adjacent to the trace, so the connection state of the idle channel affects the stability and sensitivity of the test channel. The CONN_HIGHZ(high resistance) setting increases the sensitivity of touch channels. The CONN_GND(grounding) setting increases the stability of touch channels. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 412 Configure parameter for each touch channel. Note Touch num 0 is denoise channel, please use touch_pad_denoise_enable to set denoise function Return • ESP_OK Success • ESP_ERR_INVALID_ARG if argument wrong • ESP_FAIL if touch pad not initialized Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 413 When the touch reading of a touch channel exceeds the measurement threshold, a timeout interrupt will be generated. If disable: the FSM does not check if the channel under measurement times out. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 414 – TOUCH_PAD_MAX Reset basaline of all channels esp_err_t touch_pad_filter_set_config(const touch_filter_config_t *filter_info) set parameter of touch sensor filter and detection algorithm. For more details on the detection algorithm, please refer to the application documentation. Return • ESP_OK Success Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 415 EMI. Return • ESP_OK Success esp_err_t touch_pad_denoise_disable(void) disable denoise function. Return • ESP_OK Success esp_err_t touch_pad_denoise_read_data(uint32_t *data) Get denoise measure value (TOUCH_PAD_NUM0). Return • ESP_OK Success Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 416 *count) Get measure count of proximity channel. The proximity sensor measurement is the accumulation of touch channel measurements. Note All proximity channels use the same count value. So please pass the parameter TOUCH_PAD_MAX. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 417 Set the trigger threshold of touch sensor in deep sleep. The threshold determines the sensitivity of the touch sensor. Note In general, the touch threshold during sleep can use the threshold parameter parameters before sleep. Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 418 • raw_data: pointer to accept touch sensor raw data esp_err_t touch_pad_sleep_channel_reset_benchmark(void) Reset benchmark of touch sensor sleep channel. Return • ESP_OK Success esp_err_t touch_pad_sleep_channel_read_proximity_cnt(touch_pad_t pad_num, uint32_t *proximity_cnt) Read proximity count of touch sensor sleep channel. Return • ESP_OK Success Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 419 Set touch sensor high voltage threshold of chanrge. The touch sensor measures the channel capacitance value by charging and discharging the channel. So the high threshold should be less than the supply voltage. Return • ESP_OK on success • ESP_ERR_INVALID_ARG if argument is wrong Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 420 Parameters • pad_num: pointer to touch pad which caused wakeup esp_err_t touch_pad_set_fsm_mode(touch_fsm_mode_t mode) Set touch sensor FSM mode, the test action can be triggered by the timer, as well as by the software. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 421 1. TOUCH_PAD_NUM5_GPIO_NUM is the GPIO number of channel 5 (12); 2. TOUCH_PAD_GPIO4_CHANNEL is the channel number of GPIO 4 (channel 0). Header File • components/soc/esp32s2/include/soc/touch_sensor_channel.h Macros TOUCH_PAD_GPIO1_CHANNEL TOUCH_PAD_NUM1_GPIO_NUM TOUCH_PAD_GPIO2_CHANNEL TOUCH_PAD_NUM2_GPIO_NUM TOUCH_PAD_GPIO3_CHANNEL TOUCH_PAD_NUM3_GPIO_NUM TOUCH_PAD_GPIO4_CHANNEL TOUCH_PAD_NUM4_GPIO_NUM TOUCH_PAD_GPIO5_CHANNEL TOUCH_PAD_NUM5_GPIO_NUM Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 422 Touch sensor waterproof configuration Public Members touch_pad_t guard_ring_pad Waterproof. Select touch channel use for guard pad. Guard pad is used to detect the large area of water covering the touch panel. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 423 If clear the sleep channel, point this pad to TOUCH_PAD_NUM0 bool en_proximity enable proximity function for sleep pad Macros TOUCH_PAD_BIT_MASK_ALL TOUCH_PAD_SLOPE_DEFAULT TOUCH_PAD_TIE_OPT_DEFAULT TOUCH_PAD_BIT_MASK_MAX TOUCH_PAD_HIGH_VOLTAGE_THRESHOLD TOUCH_PAD_LOW_VOLTAGE_THRESHOLD TOUCH_PAD_ATTEN_VOLTAGE_THRESHOLD TOUCH_PAD_IDLE_CH_CONNECT_DEFAULT TOUCH_PAD_THRESHOLD_MAX If set touch threshold max value, The touch sensor can’t be in touched status Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 424 Touch pad channel Values: TOUCH_PAD_NUM0 = 0 Touch pad channel 0 is GPIO4(ESP32) TOUCH_PAD_NUM1 Touch pad channel 1 is GPIO0(ESP32) / GPIO1(ESP32-S2) TOUCH_PAD_NUM2 Touch pad channel 2 is GPIO2(ESP32) / GPIO2(ESP32-S2) TOUCH_PAD_NUM3 Touch pad channel 3 is GPIO15(ESP32) / GPIO3(ESP32-S2)
  • Page 425 Chapter 2. API Reference TOUCH_PAD_NUM9 Touch pad channel 9 is GPIO32(ESP32) / GPIO9(ESP32-S2) TOUCH_PAD_NUM10 Touch channel 10 is GPIO10(ESP32-S2) TOUCH_PAD_NUM11 Touch channel 11 is GPIO11(ESP32-S2) TOUCH_PAD_NUM12 Touch channel 12 is GPIO12(ESP32-S2) TOUCH_PAD_NUM13 Touch channel 13 is GPIO13(ESP32-S2) TOUCH_PAD_NUM14 Touch channel 14 is GPIO14(ESP32-S2)
  • Page 426 Initial level of charging voltage, high level TOUCH_PAD_TIE_OPT_MAX enum touch_fsm_mode_t Touch sensor FSM mode Values: TOUCH_FSM_MODE_TIMER = 0 To start touch FSM by timer TOUCH_FSM_MODE_SW To start touch FSM by software trigger TOUCH_FSM_MODE_MAX Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 427 Values: TOUCH_PAD_DENOISE_CAP_L0 = 0 Denoise channel internal reference capacitance is 5pf TOUCH_PAD_DENOISE_CAP_L1 = 1 Denoise channel internal reference capacitance is 6.4pf TOUCH_PAD_DENOISE_CAP_L2 = 2 Denoise channel internal reference capacitance is 7.8pf Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 428 Note On ESP32S2. There is an error in the IIR calculation. The magnitude of the error is twice the filter coefficient. So please select a smaller filter coefficient on the basis of meeting the filtering requirements. Recommended filter coefficient selection IIR_16. Values: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 429: Touch Element

    These parameters include touch channel threshold, waterproof shield sensor driver-level and etc. Touch Element library sets touch sensor interrupt and esp-timer routine up and the hardware information of touch sensor (channel Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 430 Touch Element library [Not supported by viewer] [Not supported by viewer] Fig. 13: Touch Element architecture The features in relation to the Touch Element library in ESP32-S2 are given in the table below. Features ESP32S2 ✓ ✓ ✓ Touch Element waterproof ✓...
  • Page 431 • Sleep mode wakeup source • Hardware internal de-noise • Hardware filter • Hardware waterproof sensor • Hardware proximity sensor The channels are located as follows: Channel ESP32-S2 Channel 0 GPIO 0 (reserved) Channel 1 GPIO 1 Channel 2 GPIO 2...
  • Page 432 Touch Sensor Shield channel External resistor Guard channel Water stream Water drop Guard ring pad Normal touch pad Shield grid pad Fig. 14: Touch sensor application system components Fig. 15: Touch sensor signals Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 433 Touch matrix button consumes several channels(at least 2 + 2 = 4 channels), it gives a solution to use fewer channels and get more buttons. ESP32-S2 supports up to 49 buttons. Touch matrix button looks like as the picture below: Touch Element Library Usage Using this library should follow the initialization flow below:...
  • Page 434 Chapter 2. API Reference Touch button Fig. 17: Touch button Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 435 Chapter 2. API Reference Touch Slider Fig. 18: Touch slider Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 436 Chapter 2. API Reference Touch Matrix button Fig. 19: Touch matrix Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 437 Touch Element library event mask available compo- nents/touch_element/include/touch_element/touch_element.h, user could use those events mask to subscribe specified event or combine them to subscribe multiple events. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 438 /* ---------------------------------------------- TOUCH_ELEM_DISP_CALLBACK -------- --------------------------------------- */ → void element_handler(touch_xxxx_handle_t out_handle, touch_xxxx_message_t out_ message, void *arg) → //Event handler logic void app_main() touch_xxxx_set_dispatch_method(element_handle, TOUCH_ELEM_DISP_CALLBACK); Set TOUCH_ELEM_DISP_CALLBACK as the dispatch method → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 439 All the Touch Element library examples could be found in the peripherals/touch_element directory of ESP-IDF ex- amples. API Reference - Touch Element core Header File • components/touch_element/include/touch_element/touch_element.h Functions esp_err_t touch_element_install(const touch_elem_global_config_t *global_config) Touch element processing initialization. Note To reinitialize the touch element object, call touch_element_uninstall() first Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 440 Note Shield-Sensor: It always uses channel 14 as the shield channel, so user must connect the channel 14 and Shield-Layer in PCB since it will generate a synchronous signal automatically Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 441 Touch element software configuration. Public Members float waterproof_threshold_divider Waterproof guard channel threshold divider. uint8_t processing_period Processing period(ms) uint8_t intr_message_size Interrupt message queue size. uint8_t event_message_size Event message queue size. struct touch_elem_hw_config_t Touch element hardware configuration. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 442 Software configuration. struct touch_elem_waterproof_config_t Touch element waterproof configuration passed to touch_element_waterproof_install. Public Members touch_pad_t guard_channel Waterproof Guard-Sensor channel number (index) float guard_sensitivity Waterproof Guard-Sensor sensitivity. struct touch_elem_message_t Touch element event message type from touch_element_message_receive() Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 443 Touch element handle type. Values: TOUCH_ELEM_TYPE_BUTTON Touch element button. TOUCH_ELEM_TYPE_SLIDER Touch element slider. TOUCH_ELEM_TYPE_MATRIX Touch element matrix button. enum touch_elem_dispatch_t Touch element event dispatch methods (event queue/callback) Values: TOUCH_ELEM_DISP_EVENT Event queue dispatch. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 444 Note Touch button only support three kind of event masks, they are TOUCH_ELEM_EVENT_ON_PRESS, TOUCH_ELEM_EVENT_ON_RELEASE, TOUCH_ELEM_EVENT_ON_LONGPRESS. You can use those event masks in any combination to achieve the desired effect. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 445 • [in] threshold_time: Threshold time (ms) of long press event occur const touch_button_message_t *touch_button_get_message(const touch_elem_message_t *element_message) Touch button get message. This function decodes the element message from touch_element_message_receive() and return a button mes- sage pointer. Return Touch button message pointer Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 446 Button handle. typedef void (*touch_button_callback_t)(touch_button_handle_t, touch_button_message_t void *) Button callback type. Enumerations enum touch_button_event_t Button event type. Values: TOUCH_BUTTON_EVT_ON_PRESS Button Press event. TOUCH_BUTTON_EVT_ON_RELEASE Button Release event. TOUCH_BUTTON_EVT_ON_LONGPRESS Button LongPress event. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 447 Note Touch slider only support three kind of event masks, they are TOUCH_ELEM_EVENT_ON_PRESS, TOUCH_ELEM_EVENT_ON_RELEASE. You can use those event masks in any combination to achieve the desired effect. Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 448 This function decodes the element message from touch_element_message_receive() and return a slider message pointer. Return Touch slider message pointer Parameters • [in] element_message: element message Structures struct touch_slider_global_config_t Slider initialization configuration passed to touch_slider_install. Public Members float quantify_lower_threshold Slider signal quantification threshold. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 449 Slider event. touch_slider_position_t position Slider position. Macros TOUCH_SLIDER_GLOBAL_DEFAULT_CONFIG() Type Definitions typedef uint32_t touch_slider_position_t Slider position data type. typedef touch_elem_handle_t touch_slider_handle_t Slider instance handle. typedef void (*touch_slider_callback_t)(touch_slider_handle_t, touch_slider_message_t void *) Slider callback type. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 450 • [in] matrix_config: Matrix button configuration • [out] matrix_handle: Matrix button handle esp_err_t touch_matrix_delete(touch_matrix_handle_t matrix_handle) Release resources allocated using touch_matrix_create() Return • ESP_OK: Successfully released resources • ESP_ERR_INVALID_STATE: Touch matrix driver was not initialized Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 451 This function sets the threshold time (ms) for a long press event. If a matrix button is pressed and held for a period of time that exceeds the threshold time, a long press event is triggered. Espressif Systems Release v4.4...
  • Page 452 Matrix button y-axis channels sensitivity array. uint8_t x_channel_num The number of channels in x-axis. uint8_t y_channel_num The number of channels in y-axis. struct touch_matrix_position_t Matrix button position data type. Public Members uint8_t x_axis Matrix button x axis position. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 453: Two-Wire Automotive Interface (Twai)

    It is compatible with ISO11898-1 Classical frames, thus can support Standard Frame Format (11-bit ID) and Extended Frame Format (29-bit ID). The ESP32-S2’s peripherals contains a TWAI controller that can be configured to communicate on a TWAI bus via an external transceiver.
  • Page 454 Bus-Off: A node becomes Bus-Off when the TEC becomes greater than or equal to 256. A Bus-Off node is unable influence the bus in any manner (essentially disconnected from the bus) thus eliminating itself from the bus. A node will remain in the Bus-Off state until it undergoes bus-off recovery. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 455 The TWAI controller’s interface consists of 4 signal lines known as TX, RX, BUS-OFF, and CLKOUT. These four signal lines can be routed through the GPIO Matrix to the ESP32-S2’s GPIO pads. Fig. 20: Signal lines of the TWAI controller TX and RX: The TX and RX signal lines are required to interface with an external transceiver.
  • Page 456 The Baudrate Prescaler is used to determine the period of each time quantum by dividing the TWAI controller’s source clock (80 MHz APB clock). On the ESP32-S2, the brp can be any even number from 2 to 32768. Espressif Systems Release v4.4...
  • Page 457 Dual Filter Mode will use the acceptance code and mask to define two separate filters allowing for increased flexi- bility of ID’s to accept, but does not allow for all 29-bits of an extended ID to be filtered. The following diagram Espressif Systems Release v4.4...
  • Page 458 Driver Operation The TWAI driver is designed with distinct states and strict rules regarding the functions or conditions that trigger a state transition. The following diagram illustrates the various states and their transitions. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 459 These bit field members can also be toggled using the the flags member of twai_message_t and the following message flags: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 460 The usage of macro initializers is not mandatory and each of the configuration structures can be manually. Message Transmission The following code snippet demonstrates how to transmit a message via the usage of the twai_message_t type and twai_transmit() function. #include "driver/twai.h" (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 461 #include "driver/twai.h" //Reconfigure alerts to detect Error Passive and Bus-Off error states uint32_t alerts_to_enable TWAI_ALERT_ERR_PASS TWAI_ALERT_BUS_OFF; (twai_reconfigure_alerts(alerts_to_enable, NULL) ESP_OK) { printf("Alerts reconfigured\n"); else printf("Failed to reconfigure alerts"); (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 462 This example can be used to verify if the connec- tions between the TWAI controller and the external transceiver are working correctly. The example can be found via peripherals/twai/twai_self_test. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 463 Timing segment 1 (Number of time quanta, between 1 to 16) uint8_t tseg_2 Timing segment 2 (Number of time quanta, 1 to 8) uint8_t sjw Synchronization Jump Width (Max time quanta jump for synchronize from 1 to 4) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 464 TWAI_MODE_NO_ACK Transmission does not require acknowledgment. Use this mode for self testing TWAI_MODE_LISTEN_ONLY The TWAI controller will not influence the bus (No transmissions or acknowledgments) but can receive messages Header File • components/driver/include/driver/twai.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 465 If the TX queue is full, this function will block until more space becomes available or until it times out. If the TX queue is disabled (TX queue length = 0 in configuration), this function Espressif Systems Release v4.4...
  • Page 466 figuring, this function can read those alerts. Return • ESP_OK: Alerts reconfigured • ESP_ERR_INVALID_STATE: TWAI driver is not installed Parameters • [in] alerts_enabled: Bit field of alerts to enable (see documentation for alert flags) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 467 Structure for general configuration of the TWAI driver. Note Macro initializers are available for this structure Public Members twai_mode_t mode Mode of TWAI controller gpio_num_t tx_io Transmit GPIO number gpio_num_t rx_io Receive GPIO number Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 468 Number of messages that were lost due to a RX FIFO overrun uint32_t arb_lost_count Number of instances arbitration was lost uint32_t bus_error_count Number of instances a bus error has occurred Macros TWAI_IO_UNUSED Marks GPIO as unused in TWAI configuration Enumerations Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 469: Universal Asynchronous Receiver/Transmitter (Uart)

    RS232, RS422, RS485. A UART provides a widely adopted and cheap method to realize full-duplex or half-duplex data exchange among different devices. The ESP32-S2 chip has two UART controllers (UART0 and UART1), each featuring an identical set of registers to simplify programming and for more flexibility.
  • Page 470 QueueHandle_t uart_queue; // Install UART driver using an event queue here ESP_ERROR_CHECK(uart_driver_install(UART_NUM_1, uart_buffer_size, \ uart_buffer_size, 10, &uart_queue, 0)); Once this step is complete, you can connect the external UART device and check the communication. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 471 UART_NUM_1; uint8_t data[128]; length ESP_ERROR_CHECK(uart_get_buffered_data_len(uart_num, (size_t*)&length)); length uart_read_bytes(uart_num, data, length, 100); If the data in the Rx FIFO buffer is no longer needed, you can clear the buffer by calling uart_flush(). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 472 There are many interrupts that can be generated following specific UART states or detected errors. The full list of available interrupts is provided in ESP32-S2 Technical Reference Manual > UART Controller (UART) > UART Interrupts and UHCI Interrupts [PDF]. You can enable or disable specific interrupts by calling...
  • Page 473 Note: The following section will use [UART_REGISTER_NAME].[UART_FIELD_BIT] to refer to UART register fields/bits. For more information on a specific option bit, see ESP32-S2 Technical Reference Manual > UART Controller (UART) > Register Summary [PDF]. Use the register name to navigate to the register description and then find the field/bit.
  • Page 474 However, it requires suppressing null bytes during transmis- sion by setting UART_RS485_CONF_REG.UART_RS485RXBY_TX_EN to 1 and UART_RS485_CONF_REG. UART_RS485TX_RX_EN to 0. This setup can work in any RS485 UART mode or even in UART_MODE_UART. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 475 Setting up UART driver to communicate over RS485 interface in half- duplex mode. This example is similar to peripherals/uart/uart_echo allows communication through an RS485 interface chip connected to ESP32-S2 pins. peripherals/uart/nmea0183_parser Obtaining GPS information by parsing NMEA0183 statements received from GPS via the UART peripheral.
  • Page 476 Get the UART parity mode configuration. Return • ESP_FAIL Parameter error • ESP_OK Success, result will be put in (*parity_mode) Parameters • uart_num: UART port number, the max port number is (UART_NUM_MAX -1). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 477 • enable: switch on or off • rx_thresh_xon: low water mark • rx_thresh_xoff: high water mark esp_err_t uart_get_hw_flow_ctrl(uart_port_t uart_num, uart_hw_flowcontrol_t *flow_ctrl) Get the UART hardware flow control configuration. Return • ESP_FAIL Parameter error Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 478 Disable UART TX interrupt (TXFIFO_EMPTY INTERRUPT) Return • ESP_OK Success • ESP_FAIL Parameter error Parameters • uart_num: UART port number esp_err_t uart_enable_tx_intr(uart_port_t uart_num, int enable, int thresh) Enable UART TX interrupt (TXFIFO_EMPTY INTERRUPT) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 479 • cts_io_num: UART CTS pin GPIO number. esp_err_t uart_set_rts(uart_port_t uart_num, int level) Manually set the UART RTS pin level. Note UART must be configured with hardware flow control disabled. Return • ESP_OK Success • ESP_FAIL Parameter error Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 480 This function will not wait for enough space in TX FIFO. It will just fill the available TX FIFO and return when the FIFO is full. Note This function should only be used when UART TX buffer is not enabled. Return • (-1) Parameter error Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 481 Note Instead of waiting the data sent out, this function will clear UART rx buffer. In order to send all the data in tx FIFO, we can use uart_wait_tx_done function. Return • ESP_OK Success • ESP_FAIL Parameter error Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 482 The following APIs will modify the pattern position info: uart_flush_input, uart_read_bytes, uart_driver_delete, uart_pop_pattern_pos It is the application’s responsibility to ensure atomic access to the pattern queue and the rx data buffer when using pattern detect feature. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 483 Return • ESP_OK Success • ESP_ERR_INVALID_ARG Parameter error • ESP_ERR_INVALID_STATE Driver is not installed Parameters • uart_num: UART_NUM_0, UART_NUM_1 or UART_NUM_2 • threshold: Threshold value above which RX fifo full interrupt is generated Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 484 Return • ESP_OK on success • ESP_ERR_INVALID_ARG if uart_num is incorrect or wakeup_threshold is outside of [3, 0x3ff] range. Parameters • uart_num: UART number, the max port number is (UART_NUM_MAX -1). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 485 UART interrupt configuration parameters for uart_intr_config function. Public Members uint32_t intr_enable_mask UART interrupt enable mask, choose from UART_XXXX_INT_ENA_M under UART_INT_ENA_REG(i), connect with bit-or operator uint8_t rx_timeout_thresh UART timeout interrupt threshold (unit: time of sending one byte) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 486 UART event types used in the ring buffer. Values: UART_DATA UART data event UART_BREAK UART break event UART_BUFFER_FULL UART RX buffer full event UART_FIFO_OVF UART FIFO overflow event UART_FRAME_ERR UART RX frame error event Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 487 If the software flow control is enabled and the data amount in rxfifo is more than xoff_thrd, an xoff_char will be sent struct uart_config_t UART configuration parameters for uart_param_config function. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 488 RS485 UART mode (used for test purposes) enum uart_word_length_t UART word length constants. Values: UART_DATA_5_BITS = 0x0 word length: 5bits UART_DATA_6_BITS = 0x1 word length: 6bits UART_DATA_7_BITS = 0x2 word length: 7bits UART_DATA_8_BITS = 0x3 word length: 8bits Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 489 UART irda_tx signal UART_SIGNAL_IRDA_RX_INV = (0x1 << 1) inverse the UART irda_rx signal UART_SIGNAL_RXD_INV = (0x1 << 2) inverse the UART rxd signal UART_SIGNAL_CTS_INV = (0x1 << 3) inverse the UART cts signal Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 490 CTS pin via IO_MUX (this is UART_NUM_0). Similar to the above macro but specifies the pin function which is also part of the IO_MUX assignment. Header File • components/soc/esp32s2/include/soc/uart_channel.h Macros UART_GPIO1_DIRECT_CHANNEL UART_NUM_0_TXD_DIRECT_GPIO_NUM UART_GPIO3_DIRECT_CHANNEL UART_NUM_0_RXD_DIRECT_GPIO_NUM UART_GPIO19_DIRECT_CHANNEL UART_NUM_0_CTS_DIRECT_GPIO_NUM UART_GPIO22_DIRECT_CHANNEL UART_NUM_0_RTS_DIRECT_GPIO_NUM UART_TXD_GPIO1_DIRECT_CHANNEL Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 491: Usb Device Driver

    2.2.24 USB Device Driver Overview The driver allows users to use ESP32-S2 chips to develop USB devices on top the TinyUSB stack. TinyUSB is integrating with ESP-IDF to provide USB features of the framework. Using this driver the chip works as a composite device supporting to represent several USB devices simultaneously.
  • Page 492 Chapter 2. API Reference Hardware USB Connection • Any board with the ESP32-S2 chip with USB connectors or with exposed USB’ s D+ and D- (DATA+/DATA-) pins. If the board has no USB connector but has the pins, connect pins directly to the host (e.g. with do-it-yourself cable from any USB connection cable).
  • Page 493 How to set up ESP32-S2 chip to get log output via Serial Device connec- tion peripherals/usb/tusb_sample_descriptor How to set up ESP32-S2 chip to work as a Generic USB Device with a user-defined descriptor peripherals/usb/tusb_serial_device How to set up ESP32-S2 chip to work as a USB Serial Device Espressif Systems Release v4.4...
  • Page 494 Pointer to an array of string descriptors bool external_phy Should USB use an external PHY Header File • components/tinyusb/additions/include/tinyusb_types.h Macros USB_ESPRESSIF_VID USB_STRING_DESCRIPTOR_ARRAY_SIZE Type Definitions typedef const char *tusb_desc_strarray_device_t[USB_STRING_DESCRIPTOR_ARRAY_SIZE] Enumerations enum tinyusb_usbdev_t Values: TINYUSB_USBDEV_0 Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 495 • timeout_ticks: - waiting until flush will be considered as failed esp_err_t tinyusb_cdcacm_read(tinyusb_cdcacm_itf_t itf, uint8_t *out_buf, size_t out_buf_sz, size_t *rx_data_size) Read a content to the array, and defines it’s size to the sz_store. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 496 Describes an event passing to the input of a callbacks. Public Members cdcacm_event_type_t type Event type cdcacm_event_rx_wanted_char_data_t rx_wanted_char_data Data input of the callback_rx_wanted_char callback cdcacm_event_line_state_changed_data_t line_state_changed_data Data input of the callback_line_state_changed callback cdcacm_event_line_coding_changed_data_t line_coding_changed_data Data input of the line_coding_changed callback Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 497 CDC_EVENT_LINE_CODING_CHANGED Header File • components/tinyusb/additions/include/tusb_console.h Functions esp_err_t esp_tusb_init_console(int cdc_intf) Redirect output to the USB serial. Return esp_err_t - ESP_OK, ESP_FAIL or an error code Parameters • cdc_intf: - interface number of TinyUSB’s CDC Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 498: Usb Host

    Warning: The USB Host Library API is a beta version thus is subject to change. The following document lists the API and types of the USB Host Library (that is currently under development). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 499 Register a client of the USB Host Library. • This function registers a client of the USB Host Library • Once a client is registered, its processing function usb_host_client_handle_events() should be called re- peatedly Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 500 • A client must close all devices it has opened before deregistering Note This function can block Return esp_err_t Parameters • [in] client_hdl: Client handle • [in] dev_hdl: Device handle esp_err_t usb_host_device_free_all(void) Indicate that all devices can be freed when possible. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 501 • This function simple returns a pointer to the cached descriptor Note This function can block Note No control transfer is sent. A device’s active configuration descriptor is cached on enumeration Return esp_err_t Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 502 Return esp_err_t Parameters • dev_hdl: Device handle • bEndpointAddress: Endpoint address esp_err_t usb_host_endpoint_clear(usb_device_handle_t dev_hdl, uint8_t bEndpointAddress) Clear a halt on a particular endpoint. • The device must have been opened by a client Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 503 • On completion, the transfer’ s callback will be called from the client’ s usb_host_client_handle_events() function. Return esp_err_t Parameters • [in] client_hdl: Client handle • [in] transfer: Initialized transfer object Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 504 Client’s event callback function void *callback_arg Event callback function argument Macros USB_HOST_LIB_EVENT_FLAGS_NO_CLIENTS All clients have been deregistered from the USB Host Library USB_HOST_LIB_EVENT_FLAGS_ALL_FREE The USB Host Library has freed all devices Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 505 Given a particular descriptor within a full configuration descriptor, get the next descriptor of a particular type (i.e., using the bDescriptorType value) within the configuration descriptor. Return usb_standard_desc_t* Next descriptor, NULL if end descriptor is not found or configuration descrip- tor reached Parameters • [in] cur_desc: Current descriptor Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 506 On output, it is the offset of the endpoint descriptor. const usb_ep_desc_t *usb_parse_endpoint_descriptor_by_address(const usb_config_desc_t *config_desc, uint8_t bInterfaceNumber, uint8_t bAlternate- Setting, uint8_t bEndpointAddress, int *offset) Get an endpoint descriptor based on an endpoint’s address. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 507 Basic information of an enumerated device. Public Members usb_speed_t speed Device’s speed uint8_t dev_addr Device’s address uint8_t bMaxPacketSize0 The maximum packet size of the device’s default endpoint uint8_t bConfigurationValue Device’s current configuration number Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 508 Context variable for transfer to associate transfer with something const int num_isoc_packets Only relevant to Isochronous. Number of service periods (i.e., intervals) to transfer data buffer over. usb_isoc_packet_desc_t isoc_packet_desc[0] Descriptors for each Isochronous packet Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 509 USB_SPEED_FULL USB Full Speed (12 Mbit/s) enum usb_transfer_type_t The type of USB transfer. Note The enum values need to match the bmAttributes field of an EP descriptor Values: USB_TRANSFER_TYPE_CTRL = 0 USB_TRANSFER_TYPE_ISOCHRONOUS USB_TRANSFER_TYPE_BULK Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 510 Number of bytes to transfer if there is a data stage struct usb_setup_packet_t::[anonymous] [anonymous] uint8_t val[USB_SETUP_PACKET_SIZE] union usb_standard_desc_t #include <usb_types_ch9.h> USB standard descriptor. All USB standard descriptors start with these two bytes. Use this type when traversing over configuration descriptors Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 511 Index of string descriptor describing the device’s serial number uint8_t bNumConfigurations Number of possible configurations struct usb_device_desc_t::[anonymous] USB_DESC_ATTR uint8_t val[USB_DEVICE_DESC_SIZE] union usb_config_desc_t #include <usb_types_ch9.h> Structure representing a short USB configuration descriptor. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 512 Class code (assigned by USB-IF) uint8_t bFunctionSubClass Subclass code (assigned by USB-IF) uint8_t bFunctionProtocol Protocol code (assigned by USB-IF) uint8_t iFunction Index of string descriptor describing this function struct usb_iad_desc_t::[anonymous] USB_DESC_ATTR uint8_t val[USB_IAD_DESC_SIZE] Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 513 Interval for polling Isochronous and Interrupt endpoints. Expressed in frames or microframes depending on the device operating speed (1 ms for Low-Speed and Full-Speed or 125 us for USB High-Speed and above). struct usb_ep_desc_t::[anonymous] USB_DESC_ATTR Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 514 USB_B_DESCRIPTOR_TYPE_INTERFACE_ASSOCIATION USB_B_DESCRIPTOR_TYPE_SECURITY Descriptor types from Wireless USB spec. USB_B_DESCRIPTOR_TYPE_KEY USB_B_DESCRIPTOR_TYPE_ENCRYPTION_TYPE USB_B_DESCRIPTOR_TYPE_BOS USB_B_DESCRIPTOR_TYPE_DEVICE_CAPABILITY USB_B_DESCRIPTOR_TYPE_WIRELESS_ENDPOINT_COMP USB_B_DESCRIPTOR_TYPE_WIRE_ADAPTER USB_B_DESCRIPTOR_TYPE_RPIPE USB_B_DESCRIPTOR_TYPE_CS_RADIO_CONTROL USB_B_DESCRIPTOR_TYPE_PIPE_USAGE Descriptor types from UAS specification. USB_SETUP_PACKET_SIZE Size of a USB control transfer setup packet in bytes. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 515 Initializer for a SET_ADDRESS request. Sets the address of a connected device USB_SETUP_PACKET_INIT_GET_DEVICE_DESC(setup_pkt_ptr) Initializer for a request to get a device’s device descriptor. USB_SETUP_PACKET_INIT_GET_CONFIG(setup_pkt_ptr) Initializer for a request to get a device’s current configuration number. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 516 Vendor specific subclass code. USB_CONFIG_DESC_SIZE Size of a short USB configuration descriptor in bytes. Note The size of a full USB configuration includes all the interface and endpoint descriptors of that configu- ration. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 517 See Table 9-1 of USB2.0 specification for more details Note The USB_DEVICE_STATE_NOT_ATTACHED is not part of the USB2.0 specification, but is a catch all state for devices that need to be cleaned up after a sudden disconnection or port error. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 518: Application Protocols

    • DH property files • Certificates/private keys file APIs Internal asio settings for ESP include • EXCEPTIONS are enabled in ASIO if enabled in menuconfig • TYPEID is enabled in ASIO if enabled in menuconfig Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 519: Esp-Mqtt

    • MQTT over SSL samples: – mqtts://mqtt.eclipseprojects.io: MQTT over SSL, port 8883 – mqtts://mqtt.eclipseprojects.io:8884: MQTT over SSL, port 8884 • MQTT over Websocket samples: – ws://mqtt.eclipseprojects.io:80/mqtt • MQTT over Websocket Secure samples: – wss://mqtt.eclipseprojects.io:443/mqtt • Minimal configurations: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 520 • keepalive: determines how many seconds the client will wait for a ping response before disconnecting, default is 120 seconds. • disable_auto_reconnect: enable to stop the client from reconnecting to server after errors or discon- nects Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 521 The type of error will determine which parts of the error_handle struct is filled. API Reference Header File • components/mqtt/esp-mqtt/include/mqtt_client.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 522 Return message_id of the subscribe message on success -1 on failure Parameters • client: mqtt client handle • topic: • qos: esp_mqtt_client_unsubscribe(esp_mqtt_client_handle_t client, const char *topic) Unsubscribe the client from defined topic. Notes: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 523 • Cannot be called from the mqtt event handler Return ESP_OK ESP_ERR_INVALID_ARG on wrong initialization Parameters • client: mqtt client handle esp_err_t esp_mqtt_set_config(esp_mqtt_client_handle_t client, const esp_mqtt_client_config_t *config) Set configuration structure, typically used when updating the config (i.e. on “before_connect”event. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 524 MQTT broker on connection int esp_transport_sock_errno errno from the underlying socket struct esp_mqtt_event_t MQTT event configuration structure Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 525 Complete MQTT broker URI uint32_t port MQTT server port const char *client_id default client id is ESP32_CHIPID% where CHIPID% are last 3 bytes of MAC address in hex format const char *username MQTT username Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 526 If it is not NULL, also client_cert_pem has to be provided. PEM-format must have a terminating NULL-character. DER-format requires the length to be passed in client_key_len size_t client_key_len Length of the buffer pointed to by client_key_pem. May be 0 for null-terminated pem Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 527 MQTT_ERROR_TYPE_TCP_TRANSPORT error type hold all sorts of transport layer errors, including ESP- TLS error, but in the past only the errors from MQTT_ERROR_TYPE_ESP_TLS layer were reported, so the ESP-TLS error type is re-defined here for backward compatibility Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 528 • retain retain flag of the message Note: Multiple MQTT_EVENT_DATA could be fired for one message, if it is longer than internal buffer. In that case only first event contains topic pointer and length, other contain data only with current data length and current data offset updating. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 529 MQTT over SSL, using scheme: mqtts MQTT_TRANSPORT_OVER_WS MQTT over Websocket, using scheme:: ws MQTT_TRANSPORT_OVER_WSS MQTT over Websocket Secure, using scheme: wss enum esp_mqtt_protocol_ver_t MQTT protocol version used for connection Values: MQTT_PROTOCOL_UNDEFINED = 0 MQTT_PROTOCOL_V_3_1 MQTT_PROTOCOL_V_3_1_1 Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 530: Esp-Tls

    ESP-TLS menuconfig. Then the pointer to PSK hint and key should be provided to the esp_tls_cfg_t structure. The ESP-TLS will use the PSK for server verification only when no other option regarding the server verification is selected. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 531 1) Directly add wolfssl as a component in your project with following three commands.: (First change directory (cd) to your project directory) mkdir components cd components git clone https://github.com/espressif/esp-wolfssl.git 2) Add wolfssl as an extra component in your project. • Download wolfssl with: git clone https://github.com/espressif/esp-wolfssl.git •...
  • Page 532 Digital Signature with ESP-TLS ESP-TLS provides support for using the Digital Signature (DS) with ESP32-S2. Use of the DS for TLS is supported only when ESP-TLS is used with mbedTLS (default stack) as its underlying SSL/TLS stack. For more details on...
  • Page 533 *cfg, esp_tls_t *tls) Create a new non-blocking TLS/SSL connection with a given “HTTP”url. The behaviour is same as esp_tls_conn_new() API. However this API accepts host’s url. Return • -1 If connection establishment fails. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 534 Return the number of application data bytes remaining to be read from the current record. This API is a wrapper over mbedtls’s mbedtls_ssl_get_bytes_avail() API. Return • -1 in case of invalid arg • bytes available in the application data record read buffer Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 535 NULL if caller does not care about esp_tls_code esp_err_t esp_tls_get_and_clear_error_type(esp_tls_error_handle_t h, esp_tls_error_type_t err_type, int *error_code) Returns the last error captured in esp_tls of a specific type The error information is cleared internally upon return. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 536 *hint hint in PSK authentication mode in string format struct tls_keep_alive_cfg esp-tls client session ticket ctx Keep alive parameters structure Public Members bool keep_alive_enable Enable keep-alive timeout int keep_alive_idle Keep-alive idle time (second) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 537 Client key in a buffer Format may be PEM or DER, depending on mbedtls-support This buffer should be NULL terminated in case of PEM const unsigned char *clientkey_pem_buf Client key legacy name unsigned int clientkey_bytes Size of client key pointed to by clientkey_pem_buf (including NULL-terminator in case of PEM format) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 538 ESP-TLS Connection Handle. Public Members mbedtls_ssl_context ssl TLS/SSL context mbedtls_entropy_context entropy mbedTLS entropy context structure mbedtls_ctr_drbg_context ctr_drbg mbedTLS ctr drbg context structure. CTR_DRBG is deterministic random bit generation based on AES- Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 539 ESP-TLS preshared key and hint structure. typedef struct tls_keep_alive_cfg tls_keep_alive_cfg_t esp-tls client session ticket ctx Keep alive parameters structure typedef struct esp_tls_cfg esp_tls_cfg_t ESP-TLS configuration parameters. Note Note about format of certificates: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 540: Openssl-Apis

    • Chapter 2. SSL Context Function • Chapter 3. SSL Function • Chapter 4. SSL X509 Certification and Private Key Function Chapter 1. SSL Context Method Create 1.1 const SSL_METHOD* SSLv3_client_method (void) Arguments: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 541 1.3 const SSL_METHOD* TLSv1_1_client_method (void) Arguments: none Return: TLSV1.1 version SSL context client method point Description: create the target SSL context method Example: void example(void) const SSL_METHOD *method = TLSv1_1_client_method(); (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 542 SSL context method, it's always to be TLSV1.2 Example: void example(void) const SSL_METHOD *method = TLSv1_2_client_method(); 1.6 const SSL_METHOD* SSLv3_server_method (void) Arguments: none Return: SSLV3.0 version SSL context server method point Description: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 543 1.8 const SSL_METHOD* TLSv1_1_server_method (void) Arguments: none Return: TLSV1.1 version SSL context server method point Description: create the target SSL context method Example: void example(void) const SSL_METHOD *method = TLSv1_1_server_method(); 1.9 const SSL_METHOD* TLSv1_2_server_method (void) Arguments: none Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 544 2.1 SSL_CTX* SSL_CTX_new (const SSL_METHOD * method) Arguments: method - the SSL context method point Return: context point Description: create a SSL context Example: void example(void) SSL_CTX *ctx = SSL_CTX_new(SSLv3_server_method()); (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 545 Return: 1 : OK 0 : failed Description: set the SSL context version Example: void example(void) SSL_CTX *ctx; const SSL_METHOD *meth; ..SSL_CTX_set_ssl_version(ctx, meth); 2.4 const SSL_METHOD* SSL_CTX_get_ssl_method (SSL_CTX * ctx) Arguments: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 546 Return: SSL method Description: create a SSL Example: void example(void) SSL *ssl; SSL_CTX *ctx; ..ssl = SSL_new(ctx); 3.2 void SSL_free (SSL * ssl) Arguments: ssl - SSL point Return: none Description: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 547 Return: 1 : OK 0 : failed, connect is close by remote -1 : a error catch Description: connect to the remote SSL server Example: void example(void) SSL *ssl; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 548 Return: 1 : OK 0 : failed, connect is close by remote -1 : a error catch Description: shutdown the connection Example: void example(void) SSL *ssl; int ret; ..ret = SSL_shutdown(ssl); Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 549 Example: void example(void) SSL *ssl; char *buf; int len; int ret; ..ret = SSL_read(ssl, buf, len); 3.9 int SSL_write (SSL * ssl, const void * buffer, int len) Arguments: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 550 SSL context Description: get SSL context of the SSL Example: void example(void) SSL *ssl; SSL_CTX *ctx; ..ctx = SSL_get_SSL_CTX(ssl); 3.11 int SSL_get_shutdown (const SSL * ssl) Arguments: ssl - SSL point Return: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 551 SSL *ssl; int mode = 0; ..SSL_set_shutdown(ssl, mode); 3.13 const SSL_METHOD* SSL_get_ssl_method (SSL * ssl) Arguments: ssl - SSL point Return: SSL method Description: set SSL shutdown mode Example: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 552 3.15 int SSL_pending (const SSL * ssl) Arguments: ssl - SSL point Return: data bytes Description: get received data bytes Example: void example(void) int ret; SSL *ssl; ..(continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 553 < 0 : a error catch Description: get the socket of the SSL Example: void example(void) int ret; SSL *ssl; ..ret = SSL_get_fd(ssl); 3.18 int SSL_get_rfd (const SSL * ssl) Arguments: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 554 SSL *ssl; ..ret = SSL_get_wfd(ssl); 3.20 int SSL_set_fd (SSL * ssl, int fd) Arguments: ssl - SSL point - socket id Return: 1 : OK 0 : failed Description: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 555 = SSL_set_rfd(ssl, socket); 3.22 int SSL_set_wfd (SSL * ssl, int fd) Arguments: ssl - SSL point - socket id Return: 1 : OK 0 : failed Description: set write only socket to SSL Example: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 556 3.24 const char* SSL_get_version (const SSL * ssl) Arguments: ssl - SSL point Return: SSL version string Description: get the SSL current version string Example: void example(void) char *version; SSL *ssl; ..version = SSL_get_version(ssl); Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 557 Example: void example(void) int val; char *str; ..str = SSL_alert_desc_string(val); 3.27 const char* SSL_alert_desc_string_long (int value) Arguments: value - SSL description Return: alert value long string Description: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 558 3.29 const char* SSL_alert_type_string_long (int value) Arguments: value - SSL type description Return: alert type long string Description: get alert type long string Example: void example(void) int val; char *str; ..(continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 559 SSL is reading Example: void example(void) SSL *ssl; char *str; ..str = SSL_rstate_string_long(ssl); 3.32 const char* SSL_state_string (const SSL * ssl) Arguments: ssl - SSL point Return: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 560 ..str = SSL_state_string(ssl); 3.34 int SSL_get_error (const SSL * ssl, int ret_code) Arguments: - SSL point ret_code - SSL return code Return: SSL error number Description: get SSL error code Example: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 561 3.36 int SSL_want_nothing (const SSL * ssl) Arguments: ssl - SSL point Return: 0 : false 1 : true Description: check if SSL want nothing Example: void example(void) SSL *ssl; int ret; ..ret = SSL_want(ssl); Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 562 SSL *ssl; int ret; ..ret = SSL_want_write(ssl); Chapter 4. SSL X509 Certification and Private Key Function 4.1 X509 * d2i_X509 (X509 ** cert, const unsigned char * buffer, long len) Arguments: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 563 SSL *ssl; X509 *new; ..ret = SSL_add_client_CA(ssl, new); 4.3 int SSL_CTX_add_client_CA (SSL_CTX * ctx, X509 * x) Arguments: ctx - SSL context point - CA certification point Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 564 X509 *cert; ..cert = SSL_get_certificate(ssl); 4.5 long SSL_get_verify_result (const SSL * ssl) Arguments: ssl - SSL point Return: the result of verifying Description: get the verifying result of the SSL certification Example: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 565 - certification length - data point Return: 1 : OK 0 : failed Description: load the ASN1 certification into SSL context Example: void example(void) int ret; SSL_CTX *ctx; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 566 - private key length Return: 1 : OK 0 : failed Description: load the ASN1 private key into SSL context Example: void example(void) int ret; int pk; SSL_CTX *ctx; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 567 - SSL point len - data bytes - data point Return: 1 : OK 0 : failed Description: load certification into the SSL Example: void example(void) int ret; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 568: Esp Http Client

    • esp_http_client_cleanup(): After completing our esp_http_client’s task, this is the last function to be called. It will close the connection (if any) and free up all the memory allocated to the HTTP client Application Example Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 569 To allow the HTTP client to take full advantage of persistent connections, you should do as many of your file transfers as possible using the same handle. Persistent Connections example esp_err_t err; esp_http_client_config_t config (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 570 • esp_http_client_init(): to create and handle • esp_http_client_set_* or esp_http_client_delete_*: to modify the http connection infor- mation (optional) • esp_http_client_open(): Open the http connection with write_len parameter, write_len=0 if we only need read Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 571 This call MUST have a corresponding call to esp_http_client_cleanup when the operation is complete. Return • esp_http_client_handle_t • NULL if any errors Parameters • [in] config: The configurations, see http_client_config_t Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 572 • [out] data: Point to post data pointer esp_err_t esp_http_client_set_header(esp_http_client_handle_t client, const char *key, const char *value) Set http request header, this function must be called after esp_http_client_init and before any perform function. Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 573 Set http request password. The value of password parameter will be assigned to password buffer. If the password parameter is NULL then password buffer will be freed. Return • ESP_OK • ESP_ERR_INVALID_ARG Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 574 This function will be open the connection, write all header strings and return. Return • ESP_OK • ESP_FAIL Parameters • [in] client: The esp_http_client handle • [in] write_len: HTTP Content length need to write to the server Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 575 • (-1) Chunked transfer • Content-Length value as bytes Parameters • [in] client: The esp_http_client handle esp_err_t esp_http_client_close(esp_http_client_handle_t client) Close http connection, still kept all http request resources. Return • ESP_OK • ESP_FAIL Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 576 Return • Length of data was read Parameters • [in] client: The esp_http_client handle • buffer: The buffer • [in] len: The buffer length Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 577 *user_data user_data context, from esp_http_client_config_t user_data char *header_key For HTTP_EVENT_ON_HEADER event_id, it’s store current http header key char *header_value For HTTP_EVENT_ON_HEADER event_id, it’s store current http header value Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 578 HTTP Method int timeout_ms Network timeout in milliseconds bool disable_auto_redirect Disable HTTP automatic redirects int max_redirection_count Max number of redirections on receiving HTTP redirect status code, using default value if zero Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 579 The error exceeds the number of HTTP redirects ESP_ERR_HTTP_CONNECT Error open the HTTP connection ESP_ERR_HTTP_WRITE_DATA Error write HTTP data ESP_ERR_HTTP_FETCH_HEADER Error read HTTP header from server ESP_ERR_HTTP_INVALID_TRANSPORT There are no transport support for the input scheme Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 580 Occurs when finish a HTTP session HTTP_EVENT_DISCONNECTED The connection has been disconnected enum esp_http_client_transport_t HTTP Client transport. Values: HTTP_TRANSPORT_UNKNOWN = 0x0 Unknown HTTP_TRANSPORT_OVER_TCP Transport over tcp HTTP_TRANSPORT_OVER_SSL Transport over ssl enum esp_http_client_method_t HTTP method. Values: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 581 HTTP PROPPATCH Method HTTP_METHOD_MKCOL HTTP MKCOL Method HTTP_METHOD_MAX enum esp_http_client_auth_type_t HTTP Authentication type. Values: HTTP_AUTH_TYPE_NONE = 0 No authention HTTP_AUTH_TYPE_BASIC HTTP Basic authentication HTTP_AUTH_TYPE_DIGEST HTTP Disgest authentication enum HttpStatus_Code Enum for the HTTP status codes. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 582: Http Server

    2.3.6 HTTP Server Overview The HTTP Server component provides an ability for running a lightweight web server on ESP32-S2. Following are detailed steps to use the API exposed by HTTP Server: • httpd_start(): Creates an instance of HTTP server, allocate memory/resources for it depending upon the specified configuration and outputs a handle to the server instance.
  • Page 583 /* Start the httpd server */ (httpd_start(&server, &config) ESP_OK) { /* Register URI handlers */ httpd_register_uri_handler(server, &uri_get); httpd_register_uri_handler(server, &uri_post); /* If server failed to start, handle will be NULL */ return server; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 584 ESP_OK; Check the example under protocols/http_server/persistent_sockets. Websocket server HTTP server provides a simple websocket support if the feature is enabled in menuconfig, please see CON- FIG_HTTPD_WS_SUPPORT. Please check the example under protocols/http_server/ws_echo_server Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 585 *uri, httpd_method_t method) Unregister a URI handler. Return • ESP_OK : On successfully deregistering the handler • ESP_ERR_INVALID_ARG : Null arguments • ESP_ERR_NOT_FOUND : Handler with specified URI and method not found Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 586 Note This API is supposed to be called either from the context of • an http session APIs where sockfd is a valid parameter • a URI handler where sockfd is obtained using httpd_req_to_sockfd() Return • ESP_OK : On successfully registering override Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 587 • Zero : Field not found / Invalid request / Null arguments Parameters • [in] r: The request being responded to • [in] field: The header field to be searched in the request esp_err_t httpd_req_get_hdr_value_str(httpd_req_t *r, const char *field, char *val, size_t val_size) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 588 • [in] buf_len: Length of output buffer esp_err_t httpd_query_key_value(const char *qry, const char *key, char *val, size_t val_size) Helper function to get a URL query tag from a query string of the type param1=val1&param2=val2. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 589 *r, const char *buf, ssize_t buf_len) API to send a complete HTTP response. This API will send the data as an HTTP response to the request. This assumes that you have the entire response Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 590 API to send a complete string as HTTP response. This API simply calls http_resp_send with buffer length set to string length assuming the buffer contains a null terminated string Return • ESP_OK : On successfully sending the response packet Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 591 • ESP_OK : On success • ESP_ERR_INVALID_ARG : Null arguments • ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer Parameters • [in] r: The request being responded to • [in] type: The Content Type of the response Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 592 • ESP_OK : On successfully sending the response packet • ESP_ERR_INVALID_ARG : Null arguments • ESP_ERR_HTTPD_RESP_SEND : Error in raw send • ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer Parameters • [in] r: The request being responded to static esp_err_t httpd_resp_send_408(httpd_req_t Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 593 • HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() Parameters • [in] r: The request being responded to • [in] buf: Buffer from where the fully constructed packet is to be read • [in] buf_len: Length of the buffer Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 594 • [in] handler_fn: User implemented handler function (Pass NULL to unset any previously set handler) esp_err_t httpd_start(httpd_handle_t *handle, const httpd_config_t *config) Starts the web server. Create an instance of HTTP server and allocate memory/resources for it depending upon the specified config- uration. Example usage: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 595 Note Some protocols require that the web server generate some asynchronous data and send it to the persis- tently opened connection. This facility is for use by such protocols. Return • ESP_OK : On successfully queueing the work • ESP_FAIL : Failure in ctrl socket • ESP_ERR_INVALID_ARG : Null arguments Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 596 Return global user context Parameters • [in] handle: Handle to server returned by httpd_start void *httpd_get_global_transport_ctx(httpd_handle_t handle) Get HTTPD global transport context (it was set in the server config struct) Return global transport context Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 597 • [out] client_fds: Array of client fds Structures struct httpd_config HTTP Server Configuration Structure. Note Use HTTPD_DEFAULT_CONFIG() to initialize the configuration to a default value and then modify only those fields that are specifically determined by the use case. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 598 Custom session opening callback. Called on a new session socket just after accept(), but before reading any data. This is an opportunity to set up e.g. SSL encryption using global_transport_ctx and the send/recv/pending session overrides. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 599 If the underlying socket gets closed, and this pointer is non-NULL, the web server will free up the context by calling free(), unless free_ctx function is set. httpd_free_ctx_fn_t free_ctx Pointer to free context hook Function to free session context Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 600 HTTP Response 204 HTTPD_207 HTTP Response 207 HTTPD_400 HTTP Response 400 HTTPD_404 HTTP Response 404 HTTPD_408 HTTP Response 408 HTTPD_500 HTTP Response 500 HTTPD_TYPE_JSON HTTP Content type JSON HTTPD_TYPE_TEXT HTTP Content type text/HTML Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 601 • [in] buf: buffer with bytes to send • [in] buf_len: data size • [in] flags: flags for the send() function typedef int (*httpd_recv_func_t)(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags) Prototype for HTTPDs low-level recv function. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 602 Every instance of the server will have a unique handle. typedef enum http_method httpd_method_t HTTP Method Type wrapper over “enum http_method”available in “http_parser”library. typedef void (*httpd_free_ctx_fn_t)(void *ctx) Prototype for freeing context data (if any) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 603 • [in] arg: The arguments for this work function Enumerations enum httpd_err_code_t Error codes sent as HTTP response in case of errors encountered during processing of an HTTP request. Values: HTTPD_500_INTERNAL_SERVER_ERROR = 0 HTTPD_501_METHOD_NOT_IMPLEMENTED HTTPD_505_VERSION_NOT_SUPPORTED HTTPD_400_BAD_REQUEST HTTPD_401_UNAUTHORIZED HTTPD_403_FORBIDDEN Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 604: Https Server

    The initial session setup can take about two seconds, or more with slower clock speeds or more verbose logging. Subsequent requests through the open secure socket are much faster (down to under 100 ms). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 605 Client verify authority certificate (CA used to sign clients, or client cert itself size_t client_verify_cert_len Client verify authority cert len const uint8_t *prvtkey_pem Private key size_t prvtkey_len Private key byte length httpd_ssl_transport_mode_t transport_mode Transport Mode (default secure) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 606: Icmp Echo

    It can be achieved by creating a ping session and sending/parsing ICMP echo packets periodically. To make this internal procedure much easier for users, ESP-IDF provides some out-of-box APIs. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 607 /* convert URL to IP address */ ip_addr_t target_addr; struct addrinfo hint; struct addrinfo *res NULL; memset(&hint, 0, sizeof(hint)); memset(&target_addr, 0, sizeof(target_addr)); getaddrinfo("www.espressif.com", NULL, &hint, &res); struct in_addr addr4 ((struct sockaddr_in *) (res->ai_addr))->sin_addr; inet_addr_to_ip4addr(ip_2_ip4(&target_addr), &addr4); (continues on next page) Espressif Systems Release v4.4...
  • Page 608 • ESP_OK: create ping session successfully, user can take the ping handle to do follow-on jobs Parameters • config: ping configuration • cbs: a bunch of callback functions invoked by internal ping task • hdl_out: handle of ping session Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 609 Invoked by internal ping thread when receive ICMP echo reply packet timeout. void (*on_ping_end)(esp_ping_handle_t hdl, void *args) Invoked by internal ping thread when a ping session is finished. struct esp_ping_config_t Type of “ping”configuration. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 610 Sequence number of a ping procedure ESP_PING_PROF_TTL Time to live of a ping procedure ESP_PING_PROF_REQUEST Number of request packets sent out ESP_PING_PROF_REPLY Number of reply packets received ESP_PING_PROF_IPADDR IP address of replied target ESP_PING_PROF_SIZE Size of received packet Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 611: Esp Local Control

    HTTPD_SSL_CONFIG_DEFAULT(); /* Load server certificate */ extern const unsigned char cacert_pem_start[] asm("_binary_cacert_pem_ start"); → extern const unsigned char cacert_pem_end[] asm("_binary_cacert_pem_end "); → https_conf.cacert_pem cacert_pem_start; https_conf.cacert_len cacert_pem_end cacert_pem_start; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 612 TYPE_TIMESTAMP and READONLY, which are used for setting the type and flags fields here. /* Create a timestamp property */ esp_local_ctrl_prop_t timestamp .name "timestamp", .type TYPE_TIMESTAMP, .size sizeof(int32_t), .flags READONLY, (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 613 %s",␣ props[i].name); → return ESP_ERR_INVALID_ARG; else ESP_LOGI(TAG, "Setting %s", props[i].name); /* For keeping it simple, lets only log the incoming data */ ESP_LOG_BUFFER_HEX_LEVEL(TAG, prop_values[i].data, prop_values[i].size, ESP_LOG_INFO); return ESP_OK; For complete example see protocols/esp_local_ctrl Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 614 Function for obtaining HTTPD transport mode. esp_err_t esp_local_ctrl_start(const esp_local_ctrl_config_t *config) Start local control service. Return • ESP_OK : Success • ESP_FAIL : Failure Parameters • [in] config: Pointer to configuration structure esp_err_t esp_local_ctrl_stop(void) Stop local control service. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 615 • [in] handler: Endpoint handler function • [in] user_ctx: User data Unions union esp_local_ctrl_transport_config_t #include <esp_local_ctrl.h> Transport mode (BLE / HTTPD) configuration. Public Members esp_local_ctrl_transport_config_ble_t *ble This is same as protocomm_ble_config_t. See protocomm_ble.h for available configuration parameters. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 616 Handlers for receiving and responding to local control commands for getting and setting properties. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 617 Pointer to function which will be internally invoked on usr_ctx for freeing the context resources when esp_local_ctrl_stop() is called. struct esp_local_ctrl_proto_sec_cfg Protocom security configs Public Members esp_local_ctrl_proto_sec_t version This sets protocom security version, sec0/sec1 or custom If custom, user must provide handle via proto_sec_custom_handle below Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 618 This is a forward declaration for protocomm_ble_config_t. To use this, application must set CON- FIG_BT_BLUEDROID_ENABLED and include protocomm_ble.h. typedef struct httpd_ssl_config esp_local_ctrl_transport_config_httpd_t Configuration for transport mode HTTPD. This is a forward declaration for httpd_ssl_config_t. To use this, application must set CON- FIG_ESP_HTTPS_SERVER_ENABLE and include esp_https_server.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 619: Mdns Service

    • hostname: the hostname that the device will respond to. If not set, the hostname will be read from the interface. Example: my-esp32s2 will resolve to my-esp32s2.local • default_instance: friendly name for your device, like Jhon's ESP32-S2 Thing. If not set, hostname will be used.
  • Page 620 "_arduino", "_tcp", 3232, NULL, 0); mdns_service_add(NULL, "_myservice", "_udp", 1234, NULL, 0); //NOTE: services must be added before their properties can be set //use custom instance for the web server mdns_service_instance_name_set("_http", "_tcp", "Jhon's ESP32-S2 Web Server"); mdns_txt_item_t serviceTxtData[3] {"board","{esp32s2}"}, {"u","user"}, {"p","password"}...
  • Page 621 "Query Failed"); return; if(!results){ ESP_LOGW(TAG, "No results found!"); return; mdns_print_results(results); mdns_query_results_free(results); Example of using the methods above: void my_app_some_method(){ //search for esp32s2-mdns.local resolve_mdns_host("esp32s2-mdns"); //search for HTTP servers find_mdns_service("_http", "_tcp"); (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 622 • hostname: Hostname to add • address_list: The IP address list of the host esp_err_t mdns_delegate_hostname_remove(const char *hostname) Remove a delegated hostname All the services added to this host will also be removed. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 623 • instance_name: instance name to set. If NULL, global instance name or hostname will be used Note that MDNS_MULTIPLE_INSTANCE config option needs to be enabled for adding multiple instances with the same instance type. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 624 • hostname: service hostname. If NULL, local hostname will be used. esp_err_t mdns_service_instance_name_set(const char *service_type, const char *proto, const char *instance_name) Set instance name for service. Return • ESP_OK success • ESP_ERR_INVALID_ARG Parameter error Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 625 Note The value length of txt items will be automatically decided by strlen Return • ESP_OK success • ESP_ERR_INVALID_ARG Parameter error • ESP_ERR_NOT_FOUND Service not found • ESP_ERR_NO_MEM memory error Parameters • service_type: service type (_http, _ftp, etc) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 626 • value: the new value of the key • value_len: the length of the value esp_err_t mdns_service_txt_item_set_for_host(const char *service_type, const char *proto, const char *hostname, const char *key, const char *value) Set/Add TXT item for service TXT record with hostname. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 627 • ESP_ERR_INVALID_ARG Parameter error • ESP_ERR_NOT_FOUND Service not found • ESP_ERR_NO_MEM memory error Parameters • service_type: service type (_http, _ftp, etc) • proto: service protocol (_tcp, _udp) • key: the key that you want to remove Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 628 *name, const char *service_type, const char *proto, uint16_t type, uint32_t timeout, size_t max_results, mdns_result_t **results) Query mDNS for host or service All following query methods are derived from this one. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 629 *instance_name, const char *service_type, const char *proto, uint32_t timeout, mdns_result_t **result) Query mDNS for TXT record. Return • ESP_OK success • ESP_ERR_INVALID_STATE mDNS is not running • ESP_ERR_NO_MEM memory error • ESP_ERR_INVALID_ARG parameter error Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 630 Structures struct mdns_txt_item_t mDNS basic text item structure Used in mdns_service_add() Public Members const char *key item key name const char *value item value string struct mdns_ip_addr_s mDNS query linked list IP item Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 631 *txt_value_len array of txt value len of each record size_t txt_count number of txt items mdns_ip_addr_t *addr linked list of IP addresses found Macros MDNS_TYPE_A MDNS_TYPE_PTR MDNS_TYPE_TXT MDNS_TYPE_AAAA MDNS_TYPE_SRV MDNS_TYPE_OPT MDNS_TYPE_NSEC MDNS_TYPE_ANY Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 632: Esp-Modbus

    502. It does not require a checksum calculation, as lower layers already provide checksum protection. The following document (and included code snippets) requires some familiarity with the Modbus protocol. Refer to the Modbus Organization’s with protocol specifications for specifics. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 633 The following sections give an overview of how to use the ESP_Modbus component found under compo- nents/freemodbus. The sections cover initialization of a Modbus port, and the setup a master or slave device ac- cordingly: • Modbus Port Initialization Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 634 NULL; // Pointer to allocate interface structure // Initialization of Modbus slave for TCP esp_err_t err mbc_slave_init_tcp(&slave_handler); (slave_handler NULL ESP_OK) { // Error handling is performed here ESP_LOGE(TAG, "mb controller initialization fail."); Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 635 Limits, options of characteristic used during processing of alarm in user application (optional) Options accessParameter Can be used in user application to define the behavior of the characteristic dur- access ing processing of data in user application; PAR_PERMS_READ_WRITE_TRIGGER, type PAR_PERMS_READ, PAR_PERMS_READ_WRITE_TRIGGER; Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 636 { CID_SW_VER2, STR("Software_version_2"), STR("--"), MB_DEVICE_ADDR2, MB_PARAM_ INPUT, 2, 1, → 0, PARAM_TYPE_U16, 2, OPTS( 0,0,0 ), PAR_PERMS_READ_WRITE_ TRIGGER }, → { CID_TEMP_DATA_2, STR("Temperature_2"), STR("C"), MB_DEVICE_ADDR2, MB_PARAM_ HOLDING, 0, 2, → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 637 // version of IP protocol .ip_mode MB_MODE_TCP, // Port communication mode .ip_addr (void*)slave_ip_address_table, // assign table of IP addresses .ip_netif_ptr esp_netif_ptr // esp_netif_ptr pointer to the␣ corresponding network interface → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 638 ESP_OK) { ESP_LOGI(TAG, "Characteristic #%d %s (%s) value = (0x%08x) read successful. ", → param_descriptor->cid, (char*)param_descriptor->param_key, (char*)param_descriptor->param_units, *(uint32_t*)temp_data); else ESP_LOGE(TAG, "Characteristic #%d (%s) read fail, err = 0x%x (%s).", (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 639 Note: One slave can define several area descriptors per each type of Modbus register area with different start_offset. Register area is defined by using the mb_register_area_descriptor_t structure. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 640 The function initializes the Modbus controller interface and its active context (tasks, RTOS objects and other resources). mbc_slave_setup() The function is used to setup communication parameters of the Modbus stack. Example initialization of Modbus TCP communication: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 641 CONFIG_FMB_CONTROLLER_NOTIFY_QUEUE_SIZE key can be used to configure the notification queue size. The timeout parameter allows a timeout to be specified when waiting for a notification. The mb_param_info_t structure contains information about accessed parameter. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 642 If the examples do not work as expected and slave and master boards are not able to communicate correctly, it is possible to find the reason for errors. The most important errors are described in master example output and formatted as below: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 643 • protocols/modbus/serial/mb_slave • protocols/modbus/serial/mb_master • protocols/modbus/tcp/mb_tcp_slave • protocols/modbus/tcp/mb_tcp_master Please refer to the specific example README.md for details. Protocol References • https://modbus.org/specs.php: Modbus Organization with protocol specifications. API Reference Header File • components/freemodbus/common/include/esp_modbus_common.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 644 Modbus address type void *ip_addr Modbus address table for connection void *ip_netif_ptr Modbus network interface struct mb_communication_info_t::[anonymous] [anonymous] Macros MB_CONTROLLER_STACK_SIZE MB_CONTROLLER_PRIORITY MB_DEVICE_ADDRESS MB_DEVICE_SPEED MB_UART_PORT MB_PAR_INFO_TOUT MB_PARITY_NONE _XFER_4_RD(dst, src) _XFER_2_RD(dst, src) _XFER_4_WR(dst, src) _XFER_2_WR(dst, src) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 645 Modbus Event Write Coils. MB_EVENT_COILS_RD = BIT5 Modbus Event Read Coils. MB_EVENT_DISCRETE_RD = BIT6 Modbus Event Read Discrete bits. MB_EVENT_STACK_STARTED = BIT7 Modbus Event Stack started enum mb_param_type_t Type of Modbus parameter. Values: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 646 • [out] handler: handler(pointer) to master data structure esp_err_t mbc_master_init(mb_port_type_t port_type, void **handler) Initialize Modbus Master controller and stack for Serial port. Return • ESP_OK Success • ESP_ERR_NO_MEM Parameter error • ESP_ERR_NOT_SUPPORTED Port type not supported Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 647 • [in] data_ptr: pointer to data buffer to send or received data (dependent of command field in request) esp_err_t mbc_master_get_cid_info(uint16_t cid, const mb_parameter_descriptor_t **param_info) Get information about supported characteristic defined as cid. Uses parameter description table to get this Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 648 • [out] value: pointer to data buffer of parameter (actual representation of json value field in binary form) • [out] type: pointer to parameter type associated with the name returned from parameter lookup table. Unions union mb_parameter_opt_t #include <esp_modbus_master.h> Modbus parameter options for description table. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 649 Float, U8, U16, U32, ASCII, etc. mb_descr_size_t param_size Number of bytes in the parameter. mb_parameter_opt_t param_opts Parameter options used to check limits and etc. mb_param_perms_t access Access permissions based on mode Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 650 PARAM_SIZE_U16 = 0x02 Unsigned 16 PARAM_SIZE_U32 = 0x04 Unsigned 32 PARAM_SIZE_FLOAT = 0x04 Float size PARAM_SIZE_ASCII = 0x08 ASCII size PARAM_SIZE_ASCII24 = 0x18 ASCII24 size PARAM_MAX_SIZE enum mb_param_perms_t Permissions for the characteristics. Values: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 651 Initialize Modbus Slave controller interface handle. Parameters • [in] handler: - pointer to slave interface data structure esp_err_t mbc_slave_destroy(void) Destroy Modbus controller and stack. Return • ESP_OK Success • ESP_ERR_INVALID_STATE Parameter error esp_err_t mbc_slave_start(void) Start Modbus communication stack. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 652 Timestamp of Modbus Event (uS) uint16_t mb_offset Modbus register offset mb_event_group_t type Modbus event type uint8_t *address Modbus data storage address size_t size Modbus event register size (number of registers) struct mb_register_area_descriptor_t Parameter storage area descriptor. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 653: Esp Websocket Client

    2.3.12 ESP WebSocket Client Overview The ESP WebSocket client is an implementation of WebSocket protocol client for ESP32-S2 Features • Supports WebSocket over TCP, TLS with mbedtls • Easy to setup with URI • Multiple instances (Multiple clients in one application) Configuration...
  • Page 654 Limitations and Known Issues • The client is able to request the use of a subprotocol from the server during the handshake, but does not do any subprotocol related checks on the response from the server. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 655 • Cannot be called from the websocket event handler Return esp_err_t Parameters • [in] client: The client esp_err_t esp_websocket_client_destroy(esp_websocket_client_handle_t client) Destroy the WebSocket connection and free all resources. This function must be the last function to call for an Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 656 • Client waits until server echos the CLOSE frame • Client waits until server closes the connection • Client is stopped the same way as by the esp_websocket_client_stop() Notes: – Cannot be called from the websocket event handler Return esp_err_t Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 657 • event_handler_arg: User context Structures struct esp_websocket_event_data_t Websocket event data. Public Members const char *data_ptr Data pointer int data_len Data length uint8_t op_code Received opcode esp_websocket_client_handle_t client esp_websocket_client_handle_t context void *user_context user_data context, from esp_websocket_client_config_t user_data Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 658 If it is not NULL, also client_cert has to be provided. PEM-format must have a terminating NULL-character. DER-format requires the length to be passed in client_key_len Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 659 Once the Websocket has been connected to the server, no data exchange has been performed WEBSOCKET_EVENT_DISCONNECTED The connection has been disconnected WEBSOCKET_EVENT_DATA When receiving data from the server, possibly multiple portions of the packet Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 660: Esp Serial Slave Link

    2.3.13 ESP Serial Slave Link Overview Espressif provides several chips that can work as slaves. These slave devices rely on some common buses, and have their own communication protocols over those buses. The esp_serial_slave_link component is designed for the master to communicate with ESP slave devices through those protocols over the bus drivers.
  • Page 661 1-bit mode. For example, in QIO mode, address and data (IN and OUT) should be sent on all 4 data wires (MOSI, MISO, WP, and HD). Here’s the modes supported by ESP32-S2 SPI slave and the wire number used in corresponding modes. Mode...
  • Page 662 1. The slave loads 4092 bytes of data onto the RDDMA 2. The master do seven RDDMA transactions, each of them are 512 bytes long, and reads the first 3584 bytes from the slave Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 663 • Bus: The bus over which the master and the slave communicate with each other. • Slave protocol: The special communication protocol specified by Espressif HW/SW over the bus. • TX buffer num: a counter, which is on the slave and can be read by the master, indicates the accumulated buffer numbers that the slave has loaded to the hardware to receive data from the master.
  • Page 664 find the slave has reset its counter. Application Example The example below shows how ESP32-S2 SDIO host and slave communicate with each other. The host use the ESSL SDIO. peripherals/sdio. Please refer to the specific example README.md for details.
  • Page 665 Reset the counters of this component. Usually you don’t need to do this unless you know the slave is reset. Return • ESP_OK: Success • ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode • ESP_ERR_INVALID_ARG: Invalid argument, handle is not init. Parameters • handle: Handle of an ESSL device. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 666 *value_o, uint32_t wait_ms) Read general purpose R/W registers (8-bit) of ESSL slave. Return • ESP_OK Success • One of the error codes from SDMMC/SPI host controller Parameters • handle: Handle of a essl device. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 667 • wait_ms: Millisecond to wait before timeout, will not wait at all if set to 0-9. esp_err_t essl_get_intr_ena(essl_handle_t handle, uint32_t *ena_mask_o, uint32_t wait_ms) Get interrupt enable bits of ESSL slave. Return • ESP_OK Success • One of the error codes from SDMMC host controller Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 668 Configuration for the ESSL SDIO device. Public Members sdmmc_card_t *card The initialized sdmmc card pointer of the slave. int recv_buffer_size The pre-negotiated recv buffer size used by both the host and the slave. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 669 • wait_ms: Time to wait before timeout (reserved for future use, user should set this to 0). esp_err_t essl_spi_write_reg(void *arg, uint8_t addr, uint8_t value, uint8_t *out_value, uint32_t wait_ms) Write to the shared registers. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 670 • flags: SPI_TRANS_* flags to control the transaction mode of the transaction to send. esp_err_t essl_spi_rdbuf_polling(spi_device_handle_t spi, uint8_t *out_data, int addr, int len, uint32_t flags) Read the shared buffer from the slave in polling way. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 671 • spi: SPI device handle representing the slave • [out] out_data: Buffer to hold the received data, strongly suggested to be in the DRAM and aligned to 4 • len: Total length of data to receive. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 672 • or other return value from :cpp:func:spi_device_transmit. Parameters • spi: SPI device handle representing the slave • data: Buffer for data to send, strongly suggested to be in the DRAM • seg_len: Length of this segment Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 673: Esp X509 Certificate Bundle

    The bundle comes with the complete list of root certificates from Mozilla’s NSS root certificate store. Using the gen_crt_bundle.py python utility the certificates’subject name and public key are stored in a file and embedded in the ESP32-S2 binary. When generating the bundle you may choose between: •...
  • Page 674 Simple HTTPS example that uses ESP-TLS to establish a secure socket connection using the certificate bundle with two custom certificates added for verification: protocols/https_x509_bundle. HTTPS example that uses ESP-TLS and the default bundle: protocols/https_request. HTTPS example that uses mbedTLS and the default bundle: protocols/https_mbedtls. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 675: Ip Network Layer

    (or non-provisioning) use cases. Following features are available for provisioning : • Communication security at application level - – protocomm_security0 (no security) – protocomm_security1 (curve25519 key exchange + AES-CTR encryption) • Proof-of-possession (support with protocomm_security1 only) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 676 → * ie. could be dynamically allocated and freed at the time of␣ endpoint → * removal */ const static protocomm_security_pop_t pop_obj .data (const uint8_t *) strdup(pop_string), .len strlen(pop_string) (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 677 For complete example see provisioning/legacy/ble_prov /* Example function for launching a secure protocomm instance over BLE */ protocomm_t *start_pc() protocomm_t *pc protocomm_new(); /* Endpoint UUIDs */ protocomm_ble_name_uuid_t nu_lookup_table[] {"security_endpoint", 0xFF51}, {"echo_req_endpoint", 0xFF52} (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 678 • protocomm_t* : On success • NULL : No memory for allocating new instance void protocomm_delete(protocomm_t *pc) Delete a protocomm instance. This API will deallocate a protocomm instance that was created using protocomm_new(). Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 679 Frees internal resources used by a transport session. Note • An endpoint must be bound to a valid protocomm instance, created using protocomm_new(). Return • ESP_OK : Request handled successfully • ESP_ERR_INVALID_ARG : Null instance/name arguments Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 680 This API will remove a registered security endpoint identified by an endpoint name. Return • ESP_OK : Success • ESP_ERR_NOT_FOUND : Endpoint with specified name doesn’t exist • ESP_ERR_INVALID_ARG : Null instance/name arguments Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 681 Note Structure of the protocomm object is kept private Header File • components/protocomm/include/security/protocomm_security.h Structures struct protocomm_security_pop Proof Of Possession for authenticating a secure session. Public Members const uint8_t *data Pointer to buffer containing the proof of possession data Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 682 Protocomm security object structure. The member functions are used for implementing secure protocomm sessions. Note This structure should not have any dynamic members to allow re-entrancy Header File • components/protocomm/include/security/protocomm_security0.h Header File • components/protocomm/include/security/protocomm_security1.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 683 Config parameters for protocomm HTTP server. Public Members uint16_t port Port on which the HTTP server will listen size_t stack_size Stack size of server task, adjusted depending upon stack usage of endpoint handler Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 684 • [in] pc: Same protocomm instance that was passed to protocomm_ble_start() Structures struct name_uuid This structure maps handler required by protocomm layer to UUIDs which are used to uniquely identify BLE characteristics from a smartphone or a similar client device. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 685: Unified Provisioning

    Android applications. Or developers can extend the device-side and phone-app side implementations to accommodate their requirements for sending additional configuration data. Following are the important features of this implementation. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 686 2. Application Security: The unified provisioning subsystem provides application level security (security1) that provides data protection and authentication (through proof-of-possession) if the application does not use the transport level security or if the transport level security is not sufficient for the use-case. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 687 Chapter 2. API Reference Fig. 27: Typical Provisioning Process Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 688 In case of SoftAP+HTTP transport the end-point corresponds to URI whereas in case of BLE the end-point corresponds to GATT characteristic with specific UUID. Developers can create custom end-points and implement handler for the data that is received or sent over the same end-point. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 689: Wi-Fi Provisioning

    The manager can be de-initialized at any moment by making a call to wifi_prov_mgr_deinit(). wifi_prov_mgr_config_t config .scheme wifi_prov_scheme_ble, .scheme_event_handler WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM ESP_ERROR_CHECK( wifi_prov_mgr_init(config) ); The configuration structure wifi_prov_mgr_config_t has a few fields to specify the behavior desired of the manager : Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 690 Chapter 2. API Reference Fig. 29: Security1 Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 691 *reason (wifi_prov_sta_fail_ reason_t *)event_data; → ESP_LOGE(TAG, "Provisioning failed!\n\tReason : %s" "\n\tPlease reset to factory and retry␣ provisioning", → (*reason WIFI_PROV_STA_AUTH_ERROR) "Wi-Fi station authentication failed" "Wi-Fi␣ access-point not found"); → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 692 • Security 0 is simply plain text communication. In this case the pop is simply ignored Provisioning for details about the security features. const char *service_name "my_device"; const char *service_key "password"; wifi_prov_security_t security WIFI_PROV_SECURITY_1; const char *pop "abcd1234"; ESP_ERROR_CHECK( wifi_prov_mgr_start_provisioning(security, pop, service_ name, service_key) ); → Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 693 UUID like 55cc____-fb27-4f80-be02-3c60828b7451, with unique values at the 12th and 13th bytes. Once connected to the device, the provisioning related protocomm endpoints can be identified as follows : Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 694 14 % 3 = 2 channels. So, when scan is started, the first 3 channels will be scanned, followed by a 120ms delay, and then the next 3 channels, and so on, until all the 14 channels have been Espressif Systems Release v4.4...
  • Page 695 The right amount of de- lay ensures that the transport resources are freed only after the response from the protocomm handler reaches the client side application. Application Examples For complete example implementation see provisioning/wifi_prov_mgr Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 696 Return • ESP_OK : Retrieved provision state successfully • ESP_FAIL : Wi-Fi not initialized • ESP_ERR_INVALID_ARG : Null argument supplied • ESP_ERR_INVALID_STATE : Manager not initialized Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 697 Wi-Fi state, i.e. after receiving the first query and sending Wi-Fi state connected response the service is stopped immediately. void wifi_prov_mgr_wait(void) Wait for provisioning service to finish. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 698 Note After session establishment, the additional endpoints must be targeted first by the client side application before sending Wi-Fi configuration, because once Wi-Fi configuration finishes the provisioning service is stopped and hence all endpoints are unregistered Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 699 • ESP_FAIL : Provisioning app not running Parameters • [out] state: Pointer to wifi_prov_sta_state_t variable to be filled esp_err_t wifi_prov_mgr_get_wifi_disconnect_reason(wifi_prov_sta_fail_reason_t *reason) Get reason code in case of Wi-Fi station disconnection during provisioning. Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 700 • wifi_prov_scheme_ble : for provisioning over BLE transport + GATT server • wifi_prov_scheme_softap : for provisioning over SoftAP transport + HTTP server • wifi_prov_scheme_console : for provisioning over Serial UART transport + Console (for debugging) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 701 Event handler that can be set for the purpose of incorporating application specific behavior. Use WIFI_PROV_EVENT_HANDLER_NONE when not used. Macros WIFI_PROV_EVENT_HANDLER_NONE Event handler can be set to none if not used. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 702 These are same as the security modes provided by protocomm Values: WIFI_PROV_SECURITY_0 = 0 No security (plain-text communication) WIFI_PROV_SECURITY_1 This secure communication mode consists of X25519 key exchange • proof of possession (pop) based authentication • AES-CTR encryption Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 703 Return • ESP_OK : Success • ESP_ERR_INVALID_ARG : Null argument Parameters • [in] mfg_data: Custom manufacturer data • [in] mfg_data_len: Manufacturer data length Macros WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BLE WIFI_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BT Header File • components/wifi_provisioning/include/wifi_provisioning/scheme_softap.h Functions Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 704 WiFi status data to be sent in response to get_status request from master. Public Members wifi_prov_sta_state_t wifi_state WiFi state of the station wifi_prov_sta_fail_reason_t fail_reason Reason for disconnection (valid only when wifi_state is WIFI_STATION_DISCONNECTED) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 705 Internal handlers for receiving and responding to protocomm requests from master. This passed priv_data protocomm request handler (refer wifi_prov_config_data_handler()) when calling protocomm_add_endpoint(). Enumerations enum wifi_prov_sta_state_t WiFi STA status for conveying back to the provisioning master. Values: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 706: Storage Api

    (or close and then reopen) the file in read-only mode. 6. Optionally, call the FatFs library functions directly. In this case, use paths without a VFS prefix (for example, "/hello.txt"). 7. Close all open files. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 707 *base_path, const sdmmc_host_t *host_config, const void *slot_config, const esp_vfs_fat_mount_config_t *mount_config, sdmmc_card_t **out_card) Convenience function to get FAT filesystem on SD card registered in VFS. This is an all-in-one function which does the following: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 708 • other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers Parameters • base_path: path where partition should be registered (e.g. “/sdcard”) • host_config_input: Pointer to structure describing SDMMC host. This structure can be initialized using SDSPI_HOST_DEFAULT() macro. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 709 Note Wear levelling is not used when FAT is mounted in read-only mode using this function. Return • ESP_OK on success • ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with given label Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 710 DRESULT (*write)(unsigned char pdrv, const unsigned char *buff, uint32_t sector, unsigned count) sector write function DRESULT (*ioctl)(unsigned char pdrv, unsigned char cmd, void *buff) function to get info about disk and do some misc operations Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 711: Manufacturing Utility

    Before using this utility, please make sure that: • The path to Python is added to the PATH environment variable. • You have installed the packages from requirement.txt, the file in the root of the esp-idf directory. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 712 Note: The first line in the file should always contain the key names. All the keys from the configuration file should be present here in the same order. This file can have additional columns (keys). The additional keys will be treated as metadata and would not be part of the final binary files. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 713 -------+ → Commands: Run mfg_gen.py {command} -h additional help +-----+--------------+------------------------------------------------------------- -------+ → | No. | Parameter Description ␣ → +=====+==============+====================================================================+ generate Generate NVS partition ␣ → +-----+--------------+------------------------------------------------------------- -------+ → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 714 +---------------------+-------------------------------------------------------- ------------+ → --version {1,2} Set multipage blob version. ␣ → Version Multipage blob support disabled. ␣ → Version Multipage blob support enabled. ␣ → Default: Version ␣ → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 715 To generate only encryption keys: Usage: python mfg_gen.py generate-key [-h] [--keyfile KEYFILE] [--outdir OUTDIR] Optional Arguments: +--------------------+--------------------------------------------------------- -------------+ → Parameter Description ␣ → +====================+======================================================================+ -h, --help show this help message exit ␣ → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 716: Non-Volatile Storage Library

    Note: NVS works best for storing many small values, rather than a few large values of the type‘string’ and‘blob’ . If you need to store large blobs or strings, consider using the facilities provided by the FAT filesystem on top of the Espressif Systems Release v4.4...
  • Page 717 Security, tampering, and robustness NVS is not directly compatible with the ESP32-S2 flash encryption sys- tem. However, data can still be stored in encrypted form if NVS encryption is used together with ESP32-S2 flash encryption. Please refer to NVS Encryption for more details.
  • Page 718 Build and flash the partition table idf.py partition-table partition-table-flash ii) Store the keys in the NVS key partition (on the flash) with the help of parttool.py (see Partition Tool section in partition-tables for more details) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 719 Demonstrates how to read a single integer value from, and write it to NVS. The value checked in this example holds the number of the ESP32-S2 module restarts. The value’s function as a counter is only possible due to its storing in NVS.
  • Page 720 +----------+ Structure of a page For now, we assume that flash sector size is 4096 bytes and that ESP32-S2 flash encryption hardware operates on 32-byte blocks. It is possible to introduce some settings configurable at compile-time (e.g., via Espressif Systems Release v4.4...
  • Page 721 SPI flash driver and SPI flash cache can support these other sizes). Page consists of three parts: header, entry state bitmap, and entries themselves. To be compatible with ESP32-S2 flash encryption, the entry size is 32 bytes. For integer types, an entry holds one key-value pair. For strings and blobs, an entry holds part of key-value pair (more on that in the entry structure description).
  • Page 722 | NS=1 Type=uint32_t Key="channel" Value=6 Key "channel" in namespace "wifi" +-------------------------------------------+ | NS=0 Type=uint8_t Key="pwm" Value=2 Entry describing namespace "pwm" +-------------------------------------------+ | NS=2 Type=uint16_t Key="channel" Value=20 | Key "channel" in namespace "pwm" +-------------------------------------------+ Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 723 • ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures • one of the error codes from the underlying flash storage driver Parameters • [in] partition_label: Label of the partition. Must be no longer than 16 characters. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 724 Erase custom partition. Erase all content of specified custom partition. Note If the partition is initialized, this function first de-initializes it. Afterwards, the partition has to be ini- tialized again to be used. Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 725 API. Parameters • [in] partition: Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL. • [out] cfg: Pointer to nvs security configuration structure. Pointer must be non-NULL. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 726 This function is the same as nvs_set_i8 except for the data type. esp_err_t nvs_set_i32(nvs_handle_t handle, const char *key, int32_t value) set int32_t value for given key This function is the same as nvs_set_i8 except for the data type. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 727 • ESP_ERR_NVS_NOT_FOUND if the requested key doesn’t exist • ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL • ESP_ERR_NVS_INVALID_NAME if key name doesn’t satisfy constraints • ESP_ERR_NVS_INVALID_LENGTH if length is not sufficient to store data Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 728 "server_name", NULL, &required_size); char* server_name = malloc(required_size); nvs_get_str(my_handle, "server_name", server_name, &required_size); // Example (without error checking) of using nvs_get_blob to get a binary data into a static array: uint8_t mac_addr[6]; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 729 • ESP_ERR_NVS_PART_NOT_FOUND if the partition with specified name is not found • ESP_ERR_NVS_NOT_FOUND id namespace doesn’t exist yet and mode is NVS_READONLY • ESP_ERR_NVS_INVALID_NAME if namespace name doesn’t satisfy constraints • ESP_ERR_NO_MEM in case memory could not be allocated for the internal structures Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 730 • ESP_OK if erase operation was successful • ESP_ERR_NVS_INVALID_HANDLE if handle has been closed or is NULL • ESP_ERR_NVS_READ_ONLY if handle was opened as read only • other error codes from the underlying storage driver Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 731 Note that to find out the total number of entries occupied by the namespace, add one to the returned value used_entries (if err is equal to ESP_OK). Because the name space entry takes one entry. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 732 Note that any copies of the iterator will be invalid after this call. Return NULL if no entry was found, valid nvs_iterator_t otherwise. Parameters • [in] iterator: Iterator obtained from nvs_entry_find function. Must be non-NULL. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 733 Id namespace doesn’t exist yet and mode is NVS_READONLY ESP_ERR_NVS_TYPE_MISMATCH The type of set or get operation doesn’t match the type of value stored in NVS ESP_ERR_NVS_READ_ONLY Storage handle was opened as read only Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 734 NVS partition is marked as encrypted with generic flash encryption. This is forbidden since the NVS encryption works differently. ESP_ERR_NVS_CONTENT_DIFFERS Internal error; never returned by nvs API functions. NVS key is different in comparison NVS_DEFAULT_PART_NAME Default partition name of the NVS partition in the partition table Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 735 Type uint32_t NVS_TYPE_I32 = 0x14 Type int32_t NVS_TYPE_U64 = 0x08 Type uint64_t NVS_TYPE_I64 = 0x18 Type int64_t NVS_TYPE_STR = 0x21 Type string NVS_TYPE_BLOB = 0x42 Type blob NVS_TYPE_ANY = 0xff Must be last Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 736: Nvs Partition Generator Utility

    # symbol. Below is an example dump of such a CSV file: key,type,encoding,value <-- column header namespace_name,namespace,, <-- First entry should be of type "namespace" key1,data,u8,1 key2,file,string,/path/to/file Note: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 737 ␣ → +-----+------------+--------------------------------------------------------------- -------+ → Commands: Run nvs_partition_gen.py {command} -h additional help +-----+--------------+------------------------------------------------------------- -------+ → | No. | Parameter Description ␣ → +=====+==============+====================================================================+ generate Generate NVS partition ␣ → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 738 +-----------------+------------------------------------------------------- -------------+ → --version {1,2} Set multipage blob version. ␣ → Version Multipage blob support disabled. ␣ → Version Multipage blob support enabled. ␣ → Default: Version ␣ → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 739 You can run the utility to generate only encryption keys using the command below: python nvs_partition_gen.py generate-key To generate encrypted NVS partition: Usage: python nvs_partition_gen.py encrypt [-h] [--version {1,2}] [--keygen] [--keyfile KEYFILE] [--inputkey␣ INPUTKEY] → [--outdir OUTDIR] input output size Positional Arguments: (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 740 Output directory to store files created ␣ → (Default: current directory) ␣ → +---------------------+--------------------------------------------------- -----------------+ → You can run the utility to encrypt NVS partition using the command below: A sample CSV file is provided with the utility: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 741 Path to output decrypted binary file ␣ → +--------------+---------------------------------------------------------- ------------+ → Optional Arguments: +---------------------+--------------------------------------------------- -----------------+ → Parameter Description ␣ → +=====================+====================================================================+ -h, --help show this help message exit ␣ → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 742: Sd/Sdio/Mmc Driver

    The SD/SDIO/MMC driver currently supports SD memory, SDIO cards, and eMMC chips. This is a protocol level driver built on top of SDMMC and SD SPI host drivers. SDMMC and SD SPI host drivers (driver/include/driver/sdmmc_host.h and driver/include/driver/sdspi_host.h) pro- vide API functions for: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 743 • One of the error codes from SDMMC host controller Parameters • card: pointer to card information structure previously initialized using sdmmc_card_init esp_err_t sdmmc_write_sectors(sdmmc_card_t *card, const void *src, size_t start_sector, size_t sec- tor_count) Write given number of sectors to SD/MMC card Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 744 This function performs read operation using CMD53 in byte mode. For block mode, see sd- mmc_io_read_blocks. Return • ESP_OK on success • ESP_ERR_INVALID_SIZE if size exceeds 512 bytes • One of the error codes from SDMMC host controller Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 745 • addr: byte address within IO function where writing starts • src: data to be written • size: number of bytes to read, must be divisible by the card block size. esp_err_t sdmmc_io_enable_int(sdmmc_card_t *card) Enable SDIO interrupt in the SDMMC host Return Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 746 • ESP_ERR_INVALID_SIZE: if the CIS size fields are not correct. Parameters • buffer: Buffer to parse • buffer_size: Size of the buffer. • fp: File pointer to print to, set to NULL to print to stdout. Header File • components/driver/include/driver/sdmmc_types.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 747 Public Members int sd_spec SD Physical layer specification version, reported by card int bus_width bus widths supported by card: BIT(0) —1-bit bus, BIT(2) —4-bit bus struct sdmmc_ext_csd_t Decoded values of Extended Card Specific Data Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 748 This structure defines properties of SD/MMC host and functions of SD/MMC host which can be used by upper layers. Public Members uint32_t flags flags defining host properties int slot slot number, to be passed to host functions int max_freq_khz max frequency supported by the host Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 749 SCR (SD card Configuration Register) value sdmmc_ext_csd_t ext_csd decoded EXT_CSD (Extended Card Specific Data) register value uint16_t rca RCA (Relative Card Address) uint16_t max_freq_khz Maximum frequency, in kHz, supported by the card Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 750: Spi Flash Api

    SDMMC_FREQ_HIGHSPEED SD High speed (limited by clock divider) SDMMC_FREQ_PROBING SD/MMC probing speed SDMMC_FREQ_52M MMC 52MHz speed SDMMC_FREQ_26M MMC 26MHz speed Type Definitions typedef uint32_t sdmmc_response_t[4] SD/MMC command response buffer 2.5.6 SPI Flash API Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 751 Users can also customize their own flash chip driver, see Overriding Default Chip Drivers for more details. Warning: Customizing SPI Flash Chip Drivers is considered an “expert”feature. Users should only do so at their own risk. (See the notes below) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 752 // Other function pointers .get_chip_caps spi_flash_chip_eon_get_caps, • You also can see how to implement this in the example storage/custom_flash_driver. 4. Add linking dependency from spi_flash component to the new custom_chip_driver component, by adding the Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 753 (for firmware execution) and the SPI1 peripheral (controlled by the drivers including this SPI Flash driver). Hence, operations to SPI1 will cause significant influence to the whole system. This kind of operations include calling SPI Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 754 Flash API or other drivers on SPI1 bus, any operations like read/write/erase or other user defined SPI operations, regardless to the main flash or other SPI slave devices. On ESP32-S2, these caches must be disabled while reading/writing/erasing. When the caches are disabled This means that all CPUs must be running code from IRAM and must only be reading data from DRAM while flash write operations occur.
  • Page 755 Memory mapping API ESP32-S2 features memory hardware which allows regions of flash memory to be mapped into instruction and data address spaces. This mapping works only for read operations. It is not possible to modify contents of flash memory by writing to a mapped memory region.
  • Page 756 (in the hal/include/hal folder). This interface provides some common functions to communicate with the chip. In other files of the SPI HAL, some of these functions are implemented with existing ESP32-S2 memory-spi function- alities. However due to the speed limitations of ESP32-S2, the HAL layer can’ t provide high-speed implementations to some reading commands (So we didn’t do it at all).
  • Page 757 Configurations for the SPI Flash to init. Public Members spi_host_device_t host_id Bus to use. int cs_io_num GPIO pin to output the CS signal. esp_flash_io_mode_t io_mode IO mode to read from the Flash. esp_flash_speed_t speed Speed of the Flash clock. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 758 • chip: Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init(). • [out] out_id: Pointer to receive unique ID value. Return • ESP_OK on success, or a flash error code if operation failed. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 759 Read the list of individually protectable regions of this SPI flash chip. Note Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the ‘chip->drv’field). Return ESP_OK on success, or a flash error code if operation failed. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 760 • or a flash error code if operation failed. esp_err_t esp_flash_write(esp_flash_t *chip, const void *buffer, uint32_t address, uint32_t length) Write data to the SPI flash chip. There are no alignment constraints on buffer, address or length. Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 761 • chip: Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted. Structures struct esp_flash_region_t Structure for describing a region of flash. Public Members uint32_t offset Start address of this region. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 762 *chip_drv Pointer to chip-model-specific “adapter”structure. If NULL, will be detected during initialisation. const esp_flash_os_functions_t *os_func Pointer to os-specific hook structure. Call esp_flash_init_os_functions() to setup this field, after the host is properly initialized. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 763 Address to perform operation on. const uint8_t *mosi_data Output data to salve. uint8_t *miso_data [out] Input data from slave, little endian uint32_t flags Flags for this transaction. Set to 0 for now. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 764 (*flash_encryption_check)(uint32_t address, uint32_t length) Check if is qualified to encrypt the buffer Parameters • address: the address of written flash partition. • length: Buffer size. struct spi_flash_host_inst_t SPI Flash Host driver instance Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 765 *host, uint32_t address, uint32_t len, uint32_t *align_addr, uint32_t page_size) Slicer for read data. The read should be called iteratively with the return value of this function. Return Length that can be actually read in one read call Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 766 Type Definitions typedef struct spi_flash_host_driver_s spi_flash_host_driver_t Enumerations enum esp_flash_speed_t SPI flash clock speed values, always refer to them by the enum rather than the actual value (more speed may be appended into the list). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 767 SPI_FLASH_OPI_DTR Only support on OPI flash, flash read and write under DTR mode. SPI_FLASH_READ_MODE_MAX The fastest io mode supported by the host is ESP_FLASH_READ_MODE_MAX-1. API Reference - Partition Table Header File • components/spi_flash/include/esp_partition.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 768 This function is also useful to take partition data which may be in a RAM buffer and convert it to a pointer to the permanent partition data stored in flash. Pointers returned from this function can be compared directly to the address of any pointer returned from esp_partition_get(), as a test for equality. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 769 • dst: Pointer to the buffer where data should be stored. Pointer must be non-NULL and buffer must be at least ‘size’bytes long. • src_offset: Address of the data to be read, relative to the beginning of the partition. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 770 • out_handle: Output, handle which should be used for spi_flash_munmap call esp_err_t esp_partition_get_sha256(const esp_partition_t *partition, uint8_t *sha_256) Get SHA-256 digest for required partition. For apps with SHA-256 appended to the app image, the result is the appended SHA-256 value for the app Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 771 Output, if non-NULL, receives the pointer to the resulting esp_partition_t structure esp_err_t esp_partition_deregister_external(const esp_partition_t *partition) Deregister the partition previously registered using esp_partition_register_external. Return • ESP_OK on success • ESP_ERR_NOT_FOUND if the partition pointer is not found Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 772 Note Partition types with integer value 0x00-0x3F are reserved for partition types defined by ESP-IDF. Any other integer value 0x40-0xFE can be used by individual applications, without restriction. Values: ESP_PARTITION_TYPE_APP = 0x00 Application partition type. ESP_PARTITION_TYPE_DATA = 0x01 Data partition type. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 773 ESP_PARTITION_SUBTYPE_APP_OTA_13 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 13 OTA partition 13. ESP_PARTITION_SUBTYPE_APP_OTA_14 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 14 OTA partition 14. ESP_PARTITION_SUBTYPE_APP_OTA_15 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 15 OTA partition 15. ESP_PARTITION_SUBTYPE_APP_OTA_MAX = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 16 Max subtype of OTA partition. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 774 • src_addr: Source offset in flash. Should be multiple of 4096 bytes. • data_length: Length of data to encrypt in bytes. Will be rounded up to next multiple of 4096 bytes. void esp_flash_write_protect_crypt_cnt(void) Write protect FLASH_CRYPT_CNT. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 775: Spiffs Filesystem

    SPIFFS, instead of myfile.txt in the directory /spiffs/tmp. • It is not a real-time stack. One write operation might take much longer than another. • For now, it does not detect or handle bad blocks. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 776 Lists.txt files Optionally, user can opt to have the image automatically flashed together with the app binaries, partition tables, etc. on idf.py flash or make flash by specifying FLASH_IN_PROJECT. For example, in Make: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 777 • Partition Offset: Starting address of the partition (can be obtained from a partition table) To pack a folder into a 1-Megabyte image, run: mkspiffs -c [src_folder] -b 4096 0x100000 spiffs.bin To flash the image onto ESP32-S2 at offset 0x110000, run: python esptool.py --chip esp32s2 --port [port] --baud [baud] write_flash -z␣ 0x110000 spiffs.bin →...
  • Page 778 • partition_label: Optional, label of the partition to check. If not specified, first partition with subtype=spiffs is used. esp_err_t esp_spiffs_format(const char *partition_label) Format the SPIFFS partition Return • ESP_OK if successful • ESP_FAIL on error Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 779: Virtual Filesystem Component

    FAT driver. FS registration To register an FS driver, an application needs to define an instance of the esp_vfs_t structure and populate it with function pointers to FS APIs: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 780 5. Results are collected from each VFS driver and all drivers are stopped by deinitiazation of the environment for checking events. 6. The select() call ends and returns the appropriate results. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 781 If you use select() for socket file descriptors only then you can enable the CON- FIG_LWIP_USE_ONLY_LWIP_SELECT option to reduce the code size and improve performance. Note: Don’t change the socket driver during an active select() call or you might experience some undefined behavior. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 782 Applications which use the UART driver can instruct VFS to use the driver’ s interrupt driven, blocking read and write functions instead. This can be done using a call to the esp_vfs_dev_uart_use_driver function. It is also possible to revert to the basic non-blocking functions using a call to esp_vfs_dev_uart_use_nonblocking. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 783 _reent *r, const char *path, int flags, int mode) int esp_vfs_close(struct _reent *r, int fd) int esp_vfs_fstat(struct _reent *r, int fd, struct stat *st) int esp_vfs_stat(struct _reent *r, const char *path, struct stat *st) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 784 Unregister a virtual filesystem with the given index Return ESP_OK if successful, ESP_ERR_INVALID_STATE if VFS for the given index hasn’t been reg- istered Parameters • vfs_id: The VFS ID returned by esp_vfs_register_with_id Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 785 Parameters • sem: semaphore structure which was passed to the driver by the start_select call void esp_vfs_select_triggered_isr(esp_vfs_select_sem_t sem, BaseType_t *woken) Notification from a VFS driver about a read/write/error condition (ISR version) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 786 _p suffix and set flags member to ESP_VFS_FLAG_DEFAULT. If the FS driver doesn’t provide some of the functions, set corresponding members to NULL. Public Members int flags ESP_VFS_FLAG_CONTEXT_PTR or ESP_VFS_FLAG_DEFAULT Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 787 (*unlink_p)(void *ctx, const char *path) unlink with context pointer int (*unlink)(const char *path) unlink without context pointer int (*rename_p)(void *ctx, const char *src, const char *dst) rename with context pointer Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 788 (*ioctl_p)(void *ctx, int fd, int cmd, va_list args) ioctl with context pointer int (*ioctl)(int fd, int cmd, va_list args) ioctl without context pointer int (*fsync_p)(void *ctx, int fd) fsync with context pointer int (*fsync)(int fd) fsync without context pointer Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 789 (*socket_select)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout) socket select function for socket FDs with the functionality of POSIX select(); this should be set only for the socket VFS Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 790 Set the line endings to sent to UART. This specifies the conversion between newlines (‘’, LF) on stdout and line endings sent over UART: • ESP_LINE_ENDINGS_CRLF: convert LF to CRLF • ESP_LINE_ENDINGS_CR: convert LF to CR • ESP_LINE_ENDINGS_LF: no modification Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 791 VFS to use simple functions for reading and writing UART Read is non-blocking, write is busy waiting until TX FIFO has enough space. These functions are used by default. Header File • components/vfs/include/esp_vfs_eventfd.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 792: Wear Levelling Api

    2.5.9 Wear Levelling API Overview Most of flash memory and especially SPI flash that is used in ESP32-S2 has a sector-based organization and also has a limited number of erase/modification cycles per memory sector. The wear levelling component helps to distribute wear and tear among sectors more evenly without requiring any attention from the user.
  • Page 793 • base_path: path where FATFS partition should be mounted (e.g. “/spiflash”) • partition_label: label of the partition which should be used • mount_config: pointer to structure with extra parameters for mounting FATFS • [out] wl_handle: wear levelling driver handle Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 794 • ESP_OK, if the operation completed successfully; • or one of error codes from lower-level flash driver. Parameters • handle: WL partition handle esp_err_t wl_erase_range(wl_handle_t handle, size_t start_addr, size_t size) Erase part of the WL storage. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 795 • handle: WL module handle that was initialized before size_t wl_sector_size(wl_handle_t handle) Get sector size of the WL instance. Return sector size, in bytes Parameters • handle: WL module handle that was initialized before Macros WL_INVALID_HANDLE Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 796: System Api

    ESP32-S2’s memory, followed by the data with a length of data_len. The data offset for each segment in the image is calculated in the following way: • offset for 0 Segment = sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t).
  • Page 797 0) load → For more details on the type of memory segments and their address ranges, see ESP32-S2 Technical Reference Manual > System and Memory > Internal Memory [PDF]. 3. The image has a single checksum byte after the last segment. This byte is written on a sixteen byte padded boundary, so the application image might need padding.
  • Page 798 This digest is separate to secure boot and only used for detecting corruption. For secure boot signed images, the signature is appended after this (and the simple hash is included in the signed data). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 799 The magic word for the esp_image_header_t structure. ESP_IMAGE_MAX_SEGMENTS Max count of segments in the image. ESP_APP_DESC_MAGIC_WORD The magic word for the esp_app_desc structure that is in DROM. Enumerations enum esp_chip_id_t ESP chip ID. Values: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 800 Chapter 2. API Reference ESP_CHIP_ID_ESP32 = 0x0000 chip ID: ESP32 ESP_CHIP_ID_ESP32S2 = 0x0002 chip ID: ESP32-S2 ESP_CHIP_ID_ESP32C3 = 0x0005 chip ID: ESP32-C3 ESP_CHIP_ID_ESP32S3 = 0x0009 chip ID: ESP32-S3 ESP_CHIP_ID_ESP32H2 = 0x000A chip ID: ESP32-H2 ESP_CHIP_ID_INVALID = 0xFFFF Invalid chip ID (we defined it to make sure the esp_chip_id_t is 2 bytes size) enum esp_image_spi_mode_t SPI flash mode, used in esp_image_header_t.
  • Page 801: Application Level Tracing

    This feature allows to transfer arbitrary data between host and ESP32-S2 via JTAG interface with small overhead on program execution. Developers can use this library to send application specific state of execution to the host and receive commands or other type of info in the opposite direction at runtime.
  • Page 802 • size: Pointer to store size of read data. Before call to this function pointed memory must hold requested size of data • tmo: Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 803 *ptr, size_t size, size_t nmemb, void *stream) Read file on host. This function has the same semantic as ‘fread’except for the first argument. Return Number of read items. See fread for details. Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 804 ESP_APPTRACE_DEST_UART0 UART0 destination. ESP_APPTRACE_DEST_MAX = ESP_APPTRACE_DEST_UART0 ESP_APPTRACE_DEST_NUM Header File • components/app_trace/include/esp_sysview_trace.h Functions static esp_err_t esp_sysview_flush(uint32_t tmo) Flushes remaining data in SystemView trace buffer to host. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 805: The Async Memcpy Api

    2.6.3 The Async memcpy API Overview ESP32-S2 has a DMA engine which can help to offload internal memory copy operations from the CPU in a asyn- chronous way. The async memcpy API wraps all DMA configurations and operations, the signature of esp_async_memcpy() is almost the same to the standard libc one.
  • Page 806 Uninstall driver (optional) esp_async_memcpy_uninstall() is used to uninstall asynchronous memcpy driver. It’s not necessary to uninstall the driver after each memcpy operation. If you know your application won’t use this driver anymore, then Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 807 • [in] cb_isr: Callback function, which got invoked in interrupt context. Set to NULL can bypass the callback. • [in] cb_args: User defined argument to be passed to the callback function Structures struct async_memcpy_event_t Type of async memcpy event object. Public Members void *data Event data Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 808: Console

    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. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 809 If hint string returned by hints callback is dynamically allocated or needs to be otherwise recycled, the function which performs such cleanup should be registered via linenoiseSetFreeHintsCallback(). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 810 • The command handler function. A few other functions are provided by the command registration module: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 811 • ESP_ERR_INVALID_ARG if the configuration is invalid Parameters • config: console configuration esp_err_t esp_console_deinit(void) de-initialize console module Note Call this once when done using console module functions Return • ESP_OK on success • ESP_ERR_INVALID_STATE if not initialized yet Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 812 • 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); Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 813 • [out] ret_repl: return REPL handle after initialization succeed, return NULL otherwise esp_err_t esp_console_start_repl(esp_console_repl_t *repl) Start REPL environment. Note Once the REPL got started, it won’t be stopped until user call repl->del(repl) to destory the REPL environment. Return • ESP_OK on success Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 814 UART channel number (count from zero) int baud_rate Comunication baud rate. int tx_gpio_num GPIO number for TX path, -1 means using default one. int rx_gpio_num GPIO number for RX path, -1 means using default one. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 815 ESP_CONSOLE_REPL_CONFIG_DEFAULT() Default console repl configuration value. ESP_CONSOLE_DEV_UART_CONFIG_DEFAULT() ESP_CONSOLE_DEV_CDC_CONFIG_DEFAULT() Type Definitions typedef struct linenoiseCompletions linenoiseCompletions typedef int (*esp_console_cmd_func_t)(int argc, char **argv) Console command main function. Return console command return code, 0 indicates “success” Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 816: Efuse Manager

    Hardware description The ESP32-S2 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).
  • Page 817 Write protection for␣ FIELD_1 → WR_DIS.FIELD_2, EFUSE_BLK0, Write protection for␣ FIELD_2 (includes B1 and B2) → WR_DIS.FIELD_2.B1, EFUSE_BLK0, Write protection for␣ FIELD_2.B1 → WR_DIS.FIELD_2.B2, EFUSE_BLK0, Write protection for␣ FIELD_2.B2 → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 818 "esp_efuse_table.h" or "esp_efuse_custom_table.h" Supported coding scheme Coding schemes are used to protect against data corruption. ESP32-S2 supports two coding schemes: • None. EFUSE_BLK0 is stored with four backups, meaning each bit is stored four times. This backup scheme is automatically applied by the hardware and is not visible to software. EFUSE_BLK0 can be written many times.
  • Page 819 There are some eFuse APIs useful to work with states of keys. • esp_efuse_get_purpose_field() - Returns a pointer to a key purpose for an eFuse key block. • esp_efuse_get_key() - Returns a pointer to a key block. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 820 EFUSE_BLK0 SDIO_TIEH EFUSE_BLK0 SDIO_FORCE EFUSE_BLK0 ENCRYPT_CONFIG EFUSE_BLK0 CONSOLE_DEBUG_DISABLE EFUSE_BLK0 ABS_DONE_0 EFUSE_BLK0 DISABLE_JTAG EFUSE_BLK0 DISABLE_DL_ENCRYPT EFUSE_BLK0 DISABLE_DL_DECRYPT EFUSE_BLK0 DISABLE_DL_CACHE EFUSE_BLK0 ENCRYPT_FLASH_KEY EFUSE_BLK1 SECURE_BOOT_KEY EFUSE_BLK2 MAC_CUSTOM_CRC EFUSE_BLK3 MAC_CUSTOM EFUSE_BLK3 ADC1_TP_LOW EFUSE_BLK3 (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 821 ... → Verifying eFuse table... The number of bits not included in square brackets is free (bits in EFUSE_BLK0 are reserved for Espressif). All fields are checked for overlapping. 2. Fill a line for field: field_name, efuse_block, bit_start, bit_count, comment.
  • Page 822 5 ms DIS_LEGACY_SPI_BOOT (BLOCK0) Disables Legacy SPI boot mode ␣ = False R/W (0b0) → UART_PRINT_CHANNEL (BLOCK0) Selects the default UART for␣ printing boot msg = UART0 R/W (0b0) → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 823 WAFER_VERSION (BLOCK1) WAFER version ␣ = A R/W (0b000) → PKG_VERSION (BLOCK1) Package version = ESP32-S2, QFN 7x7 56 pins R/W (0x0) BLOCK1_VERSION (BLOCK1) BLOCK1 efuse version ␣ = 0 R/W (0b000) → OPTIONAL_UNIQUE_ID (BLOCK2)(0 errors): Optional unique 128-bit ID...
  • Page 824 = 0 R/W (0b000000) → SPI_PAD_CONFIG_Q (BLOCK1) SPI Q (D1) pad ␣ = 0 R/W (0b000000) → SPI_PAD_CONFIG_D (BLOCK1) SPI D (D0) pad ␣ = 0 R/W (0b000000) → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 825 Rspi. Typically this voltage is 3.3 V). → To get a dump for all eFuse registers. espefuse.py -p PORT dump Connecting..Detecting chip type... ESP32-S2 BLOCK0 ) [0 ] read_regs: 00000000 00000000␣ 00000000 00000000 00000000 00000000 → MAC_SPI_8M_0...
  • Page 826 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. Return • ESP_OK: The operation was successfully completed. • ESP_ERR_INVALID_ARG: Error in the passed arguments. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 827 • ESP_OK: The operation was successfully completed. • ESP_ERR_INVALID_ARG: Error in the passed arguments. • ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. • ESP_ERR_NOT_SUPPORTED: The block does not support this command. Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 828 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. Return • ESP_OK: The operation was successfully completed. • ESP_ERR_INVALID_ARG: Error in the passed arguments. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 829 • 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 setting ROM log scheme • ESP_ERR_INVALID_STATE This eFuse is write protected or has been burned already Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 830 Note Please note that reading in the batch mode does not show uncommitted changes. Example of using the batch writing mode. the batch writing mode esp_efuse_batch_write_begin(); writing functions usual esp_efuse_write_field_blob(ESP_EFUSE_...); esp_efuse_write_field_cnt(ESP_EFUSE_...); (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 831 Parameters • [in] block: A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX esp_err_t esp_efuse_set_key_dis_read(esp_efuse_block_t block) Sets a read protection for the key block. Return • ESP_OK: Successful. • ESP_ERR_INVALID_ARG: Error in the passed arguments. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 832 Returns the current purpose set for an efuse key block. Return • Value: If Successful, it returns the value of the purpose related to the given key block. • ESP_EFUSE_KEY_PURPOSE_MAX: Otherwise. Parameters • [in] block: A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 833 • [in] num_digest: The number of digest in range 0..2 esp_err_t esp_efuse_set_digest_revoke(unsigned num_digest) Sets the Secure Boot public key digest revocation bit. Return • ESP_OK: Successful. • ESP_ERR_INVALID_ARG: Error in the passed arguments. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 834 • ESP_ERR_CODING: Error range of data does not match the coding scheme. Parameters • [in] purposes: Array of purposes (purpose[number_of_keys]). • [in] keys: Array of keys (uint8_t keys[number_of_keys][32]). Each key is 32 bytes long. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 835 ESP_EFUSE_ROM_LOG_ALWAYS_ON Always enable ROM logging ESP_EFUSE_ROM_LOG_ON_GPIO_LOW ROM logging is enabled when specific GPIO level is low during start up ESP_EFUSE_ROM_LOG_ON_GPIO_HIGH ROM logging is enabled when specific GPIO level is high during start up Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 836: Error Codes And Helper Functions

    • buflen: Size of buffer buf. At most buflen bytes are written into the buf buffer (including the terminating null byte). 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 Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 837: Esp Https Ota

    Type Definitions typedef int esp_err_t 2.6.7 ESP HTTPS OTA Overview esp_https_ota provides simplified APIs to perform firmware upgrades over HTTPS. It’s an abstraction layer over existing OTA APIs. Application Example Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 838 firmware image. Return • ESP_OK: OTA data updated, next reboot will use specified partition. • ESP_FAIL: For generic failure. • ESP_ERR_INVALID_ARG: Invalid argument Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 839 Note This API can be called just before esp_https_ota_finish() to validate if the complete image was indeed received. Return • false • true Parameters • [in] https_ota_handle: pointer to esp_https_ota_handle_t structure 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. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 840 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()) Return • -1 On failure or chunked encoding • total bytes of image Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 841: Posix Threads Support

    This means that a thread will only stop running if a higher priority task is ready to run, the thread blocks on an OS synchronization structure like a mutex, or the thread calls any of the functions sleep, vTaskDelay(), or usleep. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 842 Recursive type for “recursive” mutexes). This means that they have the same priority inheritance behaviour as mutexes created with xSemaphoreCreateMutex(). • pthread_mutex_init() • pthread_mutex_destroy() • pthread_mutex_lock() • pthread_mutex_timedlock() • pthread_mutex_trylock() • pthread_mutex_unlock() • pthread_mutexattr_init() • pthread_mutexattr_destroy() Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 843 Note: These functions can be called from tasks created using either pthread or FreeRTOS APIs Note: There are other options for thread local storage in ESP-IDF, including options with higher performance. See Thread Local Storage. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 844 Other POSIX Threads functions (not listed here) are not implemented and will produce either a compiler or a linker error if referenced from an ESP-IDF application. If you identify a useful API that you would like to see implemented in ESP-IDF, please open a feature request on GitHub <https://github.com/espressif/esp-idf/issues> with the details. ESP-IDF Extensions...
  • Page 845: Event Loop Library

    Events are occurrences of note. For example, for WiFi, a successful connection to the access point may be an event. Events are referenced using a two part identifier which are discussed more here. Event loops are the vehicle by which Espressif Systems Release v4.4...
  • Page 846 // For simplicity sake this example calls esp_event_post_to from app_main, but␣ posting can be done from → // any other tasks (which is the more interesting use case). esp_event_post_to(loop_handle, MY_EVENT_BASE, MY_EVENT_ID, ...); (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 847 The creation, deletion, handler registration/unregistration and posting of events is done through a variant of the APIs for user event loops. The table below enumerates those variants, and the user event loops equivalent. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 848 Espressif Systems Release v4.4...
  • Page 849 • ESP_ERR_NO_MEM: Cannot allocate memory for event loops list • ESP_FAIL: Failed to create task loop • Others: Fail esp_err_t esp_event_loop_delete_default(void) Delete the default event loop. Return • ESP_OK: Success • Others: Fail Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 850 • [in] event_id: the id of the event to register the handler for • [in] event_handler: the handler function which gets called when the event is dispatched • [in] event_handler_arg: data, aside from event data, that is passed to the handler when it is called Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 851 • [in] event_base: the base id of the event to register the handler for • [in] event_id: the id of the event to register the handler for • [in] event_handler: the handler function which gets called when the event is dispatched Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 852 • [in] event_base: the base of the event with which to unregister the handler • [in] event_id: the id of the event with which to unregister the handler • [in] event_handler: the handler to unregister Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 853 This function does the same as esp_event_handler_instance_unregister_with, except that it unregisters the handler instance from the default event loop. Return • ESP_OK: Success • ESP_ERR_INVALID_ARG: Invalid combination of event base and event id • Others: Fail Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 854 • ESP_OK: Success • ESP_FAIL: Event queue for the default event loop full • ESP_ERR_INVALID_ARG: Invalid combination of event base and event id, data size of more than 4 bytes • Others: Fail Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 855 → handler format: address ev:base,id inv:total_invoked run:total_runtime where: address address of the handler function base,id the event specified by event base and id this handler␣ executes (continues on next page) → Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 856 (*esp_event_handler_t)(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data) function called when an event is posted to the queue typedef void *esp_event_handler_instance_t context identifying an instance of a registered event handler Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 857 Note This API is part of the legacy event system. New code should use event library API in esp_event.h void esp_event_set_default_wifi_handlers(void) Install default event handlers for Wi-Fi interfaces (station and AP) Note This API is part of the legacy event system. New code should use event library API in esp_event.h Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 858 ESP32 station WPS enrollee mode failed reason code received system_event_sta_wps_er_success_t sta_er_success ESP32 station WPS enrollee success system_event_ap_staconnected_t sta_connected a station connected to ESP32 soft-AP system_event_ap_stadisconnected_t sta_disconnected a station disconnected to ESP32 soft-AP system_event_ap_probe_req_rx_t ap_probereqrecved ESP32 soft-AP receive probe request packet Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 859 Argument structure of event typedef wifi_event_ap_probe_req_rx_t system_event_ap_probe_req_rx_t Argument structure of event typedef wifi_event_ftm_report_t system_event_ftm_report_t Argument structure of SYSTEM_EVENT_FTM_REPORT event typedef ip_event_ap_staipassigned_t system_event_ap_staipassigned_t Argument structure of event typedef ip_event_got_ip_t system_event_sta_got_ip_t Argument structure of event Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 860 SYSTEM_EVENT_STA_WPS_ER_SUCCESS ESP32 station wps succeeds in enrollee mode SYSTEM_EVENT_STA_WPS_ER_FAILED ESP32 station wps fails in enrollee mode SYSTEM_EVENT_STA_WPS_ER_TIMEOUT ESP32 station wps timeout in enrollee mode SYSTEM_EVENT_STA_WPS_ER_PIN ESP32 station wps pin code in enrollee mode Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 861: Freertos

    Number of members in this enum 2.6.10 FreeRTOS Overview This section contains documentation of FreeRTOS types, functions, and macros. It is automatically generated from FreeRTOS header files. Note: ESP-IDF FreeRTOS is based on Vanilla FreeRTOS v10.4.3 Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 862 The wrapper function will then log an error and abort the application, as illustrated below: E (25) FreeRTOS: FreeRTOS task should not return. Aborting now! abort() was called at PC 0x40085c53 on core 0 Note: As ESP32-S2 is a single core SoC, the CONFIG_FREERTOS_UNICORE configuration is always set. ESP-IDF FreeRTOS Applications Unlike Vanilla FreeRTOS, users must not call vTaskStartScheduler().
  • Page 863 Task to be created. 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; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 864 • pvParameters: Pointer that will be used as the parameter for the task being created. • uxPriority: The priority at which the task will run. • pxStackBuffer: Must point to a StackType_t array that has at least ulStackDepth indexes - Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 865 Function that implements the task. "NAME", Text name task. STACK_SIZE, Stack size bytes, words. ( void ) 1, Parameter passed into the task. (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 866 "ATask", pcName just a text name the task to assist debugging. 100, usStackDepth the stack size DEFINED IN WORDS. NULL, pvParameters passed into the task function function␣ parameters. → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 867 • pxCreatedTask: Used to pass back a handle by which the created task can be referenced. Example usage: Create an TaskParameters_t structure that defines the task to be created. The StaticTask_t variable only included the structure when (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 868 The other two of the maximum definable regions are unused so zero. static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] Base address Length Parameters { ucOneKByte, 1024, portMPU_REGION_READ_WRITE }, { 0, (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 869 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. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 870 Wait next cycle. xWasDelayed xTaskDelayUntil( &xLastWakeTime, xFrequency ); Perform action here. xWasDelayed value can be used to determine whether a deadline was missed the code here took too long. (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 871 ) != tskIDLE_PRIORITY ) // The task has changed it's priority. // ... // Is our priority higher than the created task? if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) ) (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 872 • 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 Espressif Systems Release v4.4...
  • Page 873 TaskHandle_t xHandle; Create a task, storing the handle. xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle␣ → // ... Use the handle to suspend the created task. vTaskSuspend( xHandle ); (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 874 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 Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 875 Example usage: void vTaskCode( void pvParameters ) for( ;; ) Task code goes here. At some point we want to end the real time kernel processing so call vTaskEndScheduler (); (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 876 BaseType_t xTaskResumeAll(void) Resumes scheduler activity after it was suspended by a call to vTaskSuspendAll(). xTaskResumeAll() only resumes the scheduler. It does not unsuspend tasks that were previously suspended by a call to vTaskSuspend(). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 877 NOTE: This function takes a relatively long time to complete and should be used sparingly. Return 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 Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 878 • pxHookFunction: Pointer to the hook function. TaskHookFunction_t xTaskGetApplicationTaskTag(TaskHandle_t xTask) Returns the pxHookFunction value assigned to the task xTask. Do not call from an interrupt service routine - call xTaskGetApplicationTaskTagFromISR() instead. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 879 • ppxIdleTaskTCBBuffer: A handle to a statically allocated TCB buffer • ppxIdleTaskStackBuffer: A handle to a statically allocated Stack buffer for thie idle task • pulIdleTaskStackSize: A pointer to the number of elements that will fit in the allocated stack buffer Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 880 ); → // For percentage calculations. ulTotalRunTime /= 100UL; // Avoid divide by zero errors. if( ulTotalRunTime > 0 ) // For each populated position in the pxTaskStatusArray array, (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 881 Lists all the current tasks, along with their current state and stack usage high water mark. Tasks are reported as blocked (‘B’), ready (‘R’), deleted (‘D’) or suspended (‘S’). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 882 1 for this function to be available. The application must also then provide definitions for port- CONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 883 • uxIndexToNotify: The index within the target task’s array of notification values to which the notification is to be sent. uxIndexToNotify must be less than config- Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 884 , and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifica- tions within the array. xTaskNotifyFromISR() is the original API function, and remains backward compatible Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 885 A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of the task’s notification values. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 886 (uint32_t). The constant configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the array, and (for backward compatibility) defaults to 1 if left undefined. Prior to FreeRTOS V10.4.0 there was only one notification value per task. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 887 A notification sent to a task can optionally perform an action, such as update, overwrite or increment one of the task’s notification values. In that way task notifications can be used to send data to a task, or be used as light weight and fast binary or counting semaphores. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 888 , and all task notification API functions operated on that value. Replacing the single notification value with an array of notification values necessitated a new set of API functions that could address specific notifications Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 889 Determines if pxTicksToWait ticks has passed since a time was captured using a call to vTaskSetTimeOut- State(). The captured time includes the tick count and the number of times the tick count has overflowed. Example Usage: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 890 • pxTicksToWait: The number of ticks to check for timeout i.e. if pxTicksToWait ticks have passed since pxTimeOut was last updated (either by vTaskSetTimeOutState() or xTaskCheckFor- TimeOut()), the timeout has occurred. If the timeout has not occurred, pxTicksToWait is updated Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 891 Note This may alter the stack (depending on the portable implementation) so must be used with care! taskEXIT_CRITICAL_FROM_ISR(x) taskEXIT_CRITICAL_ISR() taskDISABLE_INTERRUPTS() Macro to disable all maskable interrupts. taskENABLE_INTERRUPTS() Macro to enable microcontroller interrupts. taskSCHEDULER_SUSPENDED taskSCHEDULER_NOT_STARTED taskSCHEDULER_RUNNING vTaskDelayUntil(pxPreviousWakeTime, xTimeIncrement) xTaskNotify(xTaskToNotify, ulValue, eAction) xTaskNotifyIndexed(xTaskToNotify, uxIndexToNotify, ulValue, eAction) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 892 Actual FreeRTOS semaphores are given using the xSemaphoreGive() API function, the equivalent action that instead uses a task notification is xTaskNotify- GiveIndexed(). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 893 Defines the prototype to which the application task hook function must conform. typedef void (*TlsDeleteCallbackFunction_t)(int, void *) Prototype of local storage pointer deletion callback. Enumerations enum eTaskState Task states returned by eTaskGetState. Values: eRunning = 0 eReady eBlocked eSuspended Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 894 Create a queue capable of containing pointers to AMessage structures. These should be passed by pointer they contain a lot of data. xQueue2 xQueueCreate( 10, sizeof( struct AMessage ) ); // ... (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 895 Example usage: struct AMessage char ucMessageID; char ucData[ } xMessage; QueueHandle_t xQueue; Task to create a queue post a value. void vATask( void *pvParameters ) (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 896 Return pdTRUE if an item was successfully received from the queue, otherwise pdFALSE. Parameters • xQueue: The handle to the queue from which the item is to be received. • pvBuffer: Pointer to the buffer into which the received item will be copied. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 897 Rest of task code. Return pdTRUE if an item was successfully received from the queue, otherwise pdFALSE. Parameters • xQueue: The handle to the queue from which the item is to be received. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 898 } while( portINPUT_BYTE( BUFFER_COUNT ) ); Now the buffer empty we can switch context necessary. Note that the name of the yield function required port specific. if( xHigherPriorityTaskWokenByPost ) (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 899 'c'; xQueueSend( xQueue, ( void ) &cValueToPost, xTicksToWait ); ISR that outputs the characters received on the queue. void vISR_Routine( void ) (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 900 If you are not using a kernel aware debugger then this function can be ignored. Parameters • xQueue: The handle of the queue being removed from the registry. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 901 3, then uxEventQueueLength should be set to (5 + 3), or 8. BaseType_t xQueueAddToSet(QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet) Adds a queue or semaphore to a queue set that was previously created by a call to xQueueCreateSet(). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 902 QueueSetMemberHandle_t xQueueSelectFromSetFromISR(QueueSetHandle_t xQueueSet) A version of xQueueSelectFromSet() that can be used from an ISR. Macros xQueueCreate(uxQueueLength, uxItemSize) Creates a new queue instance, and returns a handle by which the new queue can be referenced. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 903 Example usage: struct AMessage char ucMessageID; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 904 See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage: struct AMessage char ucMessageID; char ucData[ } xMessage; uint32_t ulVar 10UL; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 905 Post an item to the back of a queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage: struct AMessage char ucMessageID; char ucData[ (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 906 Post an item on a queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueSendFromISR () for an alternative which may be used in an ISR. Example usage: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 907 Post an item on a queue. If the queue is already full then overwrite the value held in the queue. The item is queued by copy, not by reference. This function must not be called from an interrupt service routine. See xQueueOverwriteFromISR () for an alternative which may be used in an ISR. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 908 Items are queued by copy not reference so it is preferable to only queue small items, especially when called from an ISR. In most cases it would be preferable to store a pointer to the item being queued. Espressif Systems Release v4.4...
  • Page 909 BaseType_t xHigherPriorityTaskWoken; We have woken a task at the start of the ISR. xHigherPriorityTaskWoken pdFALSE; Loop until the buffer empty. Obtain a byte from buffer. portINPUT_BYTE( RX_REGISTER_ADDRESS ); (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 910 100; xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); Reading from queue will now return 100. (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 911 RX_REGISTER_ADDRESS ); Post the byte. xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); } while( portINPUT_BYTE( BUFFER_COUNT ) ); Now the buffer empty we can switch context necessary. if( xHigherPriorityTaskWoken ) (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 912 The old vSemaphoreCreateBinary() macro is now deprecated in favour of this xSemaphoreCreateBinary() function. Note that binary semaphores created using the vSemaphoreCreateBinary() macro are created in a state such that the first call to ‘take’the semaphore would pass, whereas binary semaphores created using Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 913 NULL, so the function will not attempt any dynamic memory allocation, therefore the function will not return return NULL. xSemaphore xSemaphoreCreateBinaryStatic( &xSemaphoreBuffer ); (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 914 Release the // semaphore. xSemaphoreGive( xSemaphore ); else We could obtain the semaphore can therefore access the shared resource safely. Return pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime expired without the semaphore Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 915 ); xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); Now the mutex can be taken by other tasks. else We could obtain the mutex can therefore access the shared resource safely. (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 916 Return pdTRUE if the semaphore was released. pdFALSE if an error occurred. Semaphores are imple- mented using queues. An error can occur if there is no space on the queue to post a message - indicating Espressif Systems Release v4.4...
  • Page 917 // unwound. This just demonstrative purposes. xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); xSemaphoreGiveRecursive( xMutex ); Now the mutex can be taken by other tasks. (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 918 = 0; static BaseType_t xHigherPriorityTaskWoken; // A timer tick has occurred. // ... Do other time functions. // Is it time for vATask () to run? (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 919 Mutexes created using this function can be accessed using the xSemaphoreTake() and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros must not be used. This type of semaphore uses a priority inheritance mechanism so a task ‘taking’ a semaphore MUST ALWAYS Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 920 A mutex cannot be used before it has been created. xMutexBuffer into xSemaphoreCreateMutexStatic() so no dynamic memory allocation // attempted. xSemaphore xSemaphoreCreateMutexStatic( &xMutexBuffer ); As no dynamic memory allocation was performed, xSemaphore cannot be NULL, so there no need to check Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 921 (see https://www.FreeRTOS.org/a00111.html). If a recursive mutex is created using xSemaphoreCre- ateRecursiveMutexStatic() then the application writer must provide the memory that will get used by the mutex. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 922 In this usage scenario an event handler will ‘give’a semaphore each time an event occurs (incrementing the semaphore count value), and a handler task will ‘take’a semaphore each time it processes an event Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 923 (decrementing the semaphore count value). The count value is therefore the difference between the number of events that have occurred and the number that have been processed. In this case it is desirable for the initial count value to be zero. 2) Resource management. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 924 If the semaphore is a counting semaphore then uxSemaphoreGetCount() returns its current count value. If the semaphore is a binary semaphore then uxSemaphoreGetCount() returns 1 if the semaphore is available, and 0 if the semaphore is not available. Type Definitions typedef QueueHandle_t SemaphoreHandle_t Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 925 // Do not use a block time if calling a timer API function from a // timer callback function, as doing so could cause a deadlock! xTimerStop( pxTimer, 0 ); (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 926 • pcTimerName: A text name that is assigned to the timer. This is done purely to assist debugging. The kernel itself only ever references a timer by its handle, and never by its name. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 927 Obtain the address of the variable to increment from timer puxVariableToIncrement ( UBaseType_t pvTimerGetTimerID(␣ xExpiredTimer ); → Increment the variable to show the timer callback has executed. ( *puxVariableToIncrement )++; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 928 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or equal to 1000. The timer period must be greater than 0. • uxAutoReload: If uxAutoReload is set to pdTRUE then the timer will expire repeatedly with a Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 929 ResetFromISR(), xTimerChangePeriod() and xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the active state. Example usage: * // This function assumes xTimer has already been created. void vAFunction( TimerHandle_t xTimer ) (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 930 ( BaseType_t ) ulParameter2; ...Perform the processing here... An ISR that receives data packets from multiple interfaces void vAnISR( void ) BaseType_t xInterfaceToService, xHigherPriorityTaskWoken; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 931 Blocked state (so not using any processing time) for space to become available on the timer queue if the queue is found to be full. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 932 • ppxTimerTaskTCBBuffer: A handle to a statically allocated TCB buffer • ppxTimerTaskStackBuffer: A handle to a statically allocated Stack buffer for thie idle task • pulTimerTaskStackSize: A pointer to the number of elements that will fit in the allocated stack buffer Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 933 See the xTimerCreate() API function example usage scenario. xTimerStop(xTimer, xTicksToWait) BaseType_t xTimerStop( TimerHandle_t xTimer, TickType_t xTicksToWait ); Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 934 500ms. This will also cause the timer to start. Block a maximum of ticks change period command cannot immediately be sent to the timer (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 935 See the xTimerChangePeriod() API function example usage scenario. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 936 Perform the rest of the key processing here. void main( void ) int32_t x; Create then start the one-shot timer that responsible turning the back-light off no keys are pressed within a second period. (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 937 BaseType_t xTimerStartFromISR( TimerHandle_t xTimer, BaseType_t *pxHigherPriorityTaskWoken ); A version of xTimerStart() that can be called from an interrupt service routine. Example usage: * // This scenario assumes xBacklightTimer has already been created. When a (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 938 The timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY configuration constant. Parameters • xTimer: The handle of the timer being started/restarted. • pxHigherPriorityTaskWoken: The timer service/daemon task spends most of its time in Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 939 (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerStopFromISR() function. If xTimerStopFromISR() sets this value to pdTRUE then a context switch should be per- Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 940 (the task that was interrupted), then *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the xTimerChangePeriodFromISR() function. If xTimerChangePeriodFromISR() sets this value to Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 941 Return pdFAIL will be returned if the reset command could not be sent to the timer command queue. pdPASS will be returned if the command was successfully sent to the timer command queue. When the command Espressif Systems Release v4.4...
  • Page 942 = xEventGroupCreate(); // Was the event group created successfully? if( xCreatedEventGroup == NULL ) // The event group was not created because there was insufficient // FreeRTOS heap available. (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 943 This function cannot be called from an interrupt. Example usage: #define BIT_0 ( 1 << 0 ) #define BIT_4 ( 1 << 4 ) void aFunction( EventGroupHandle_t xEventGroup ) EventBits_t uxBits; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 944 • xTicksToWait: The maximum amount of time (specified in ‘ticks’) to wait for one/all (de- pending on the xWaitForAllBits value) of the bits specified by uxBitsToWaitFor to become set. EventBits_t xEventGroupClearBits(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsTo- Clear) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 945 #define BIT_4 ( 1 << 4 ) void aFunction( EventGroupHandle_t xEventGroup ) EventBits_t uxBits; Set bit xEventGroup. uxBits xEventGroupSetBits( xEventGroup, The event group being updated. BIT_0 BIT_4 );// The bits being set. (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 946 ( 1 << 1 ) #define TASK_2_BIT ( 1 << 2 ) #define ALL_SYNC_BITS ( TASK_0_BIT | TASK_1_BIT | TASK_2_BIT ) Use an event group to synchronise three tasks. assumed this event (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 947 All three tasks have reached the synchronisation point when the ALL_SYNC_BITS are set. Wait indefinitely this to happen. xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY ); xEventGroupSync() was called with an indefinite block time, so (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 948 An event group which it assumed has already been created by a call to // xEventGroupCreate(). EventGroupHandle_t xEventGroup; void anInterruptHandler( void ) Clear bit xEventGroup. xResult xEventGroupClearBitsFromISR( xEventGroup, The event group being updated. (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 949 • xEventGroup: The event group in which the bits are to be set. • uxBitsToSet: A bitwise value that indicates the bit or bits to set. For example, to set bit 3 only, Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 950 ( void ucArrayToSend,␣ sizeof( ucArrayToSend ), x100ms ); → if( xBytesSent sizeof( ucArrayToSend ) ) The call to xStreamBufferSend() times out before there was enough (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 951 (ISR). Example use: A stream buffer that has already been created. StreamBufferHandle_t xStreamBuffer; void vAnInterruptServiceRoutine( void ) size_t xBytesSent; char *pcStringToSend "String to send"; (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 952 0. Use xStreamBufferReceive() to read from a stream buffer from a task. Use xStreamBufferReceiveFromISR() to read from a stream buffer from an interrupt service routine (ISR). Example use: Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 953 StreamBuffer_t xStreamBuffer; void vAnInterruptServiceRoutine( void ) uint8_t ucRxData[ size_t xReceivedBytes; BaseType_t xHigherPriorityTaskWoken pdFALSE; Initialised to pdFALSE. Receive the next stream from stream buffer. xReceivedBytes xStreamBufferReceiveFromISR( xStreamBuffer, ( void ) ucRxData, (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 954 Queries a stream buffer to see if it is empty. A stream buffer is empty if it does not contain any data. Return If the stream buffer is empty then pdTRUE is returned. Otherwise pdFALSE is returned. Parameters • xStreamBuffer: The handle of the stream buffer being queried. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 955 See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for additional information. Return If a task was removed from the Blocked state then pdTRUE is returned. Otherwise pdFALSE is returned. Parameters • xStreamBuffer: The handle of the stream buffer to which data was written. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 956 The stream buffer was created successfully can now be used. Return If NULL is returned, then the stream buffer cannot be created because there is insufficient heap Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 957 For example, if a task is blocked on a read of an empty stream buffer that has a trigger level of 1 then the task Espressif Systems Release v4.4...
  • Page 958 FreeRTOS to allocate the message buffer data structures and storage area. A non- NULL value being returned indicates that the message buffer has been created successfully - the returned value should be stored as the handle to the created message buffer. Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 959 (the reader). It is safe for the writer and reader to be different tasks or interrupts, but, unlike other FreeRTOS objects, it is not safe to have multiple different writers or multiple different readers. If there are to Espressif Systems Release v4.4...
  • Page 960 (without timing out), provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any CPU time when they are in the Blocked state. xMessageBufferSendFromISR(xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriority- TaskWoken) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 961 24 bytes (20 bytes of message data and 4 bytes to hold the message length). • pxHigherPriorityTaskWoken: It is possible that a message buffer will have a task blocked Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 962 • xTicksToWait: The maximum amount of time the task should remain in the Blocked state to wait for a message, should the message buffer be empty. xMessageBufferReceive() will return im- mediately if xTicksToWait is zero and the message buffer is empty. The block time is specified Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 963 • xMessageBuffer: The handle of the message buffer from which a message is being received. • pvRxData: A pointer to the buffer into which the received message is to be copied. • xBufferLengthBytes: The length of the buffer pointed to by the pvRxData parameter. This Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 964 10, then the size of the largest message that can be written to the message buffer is 6 bytes. Parameters • xMessageBuffer: The handle of the message buffer being queried. xMessageBufferSpacesAvailable(xMessageBuffer) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 965 *MessageBufferHandle_t Type by which message buffers are referenced. For example, a call to xMessageBufferCreate() returns an MessageBufferHandle_t variable that can then be used as a parameter to xMessageBufferSend(), xMessage- BufferReceive(), etc. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 966: Freertos Additions

    Note: No-Split buffers and Allow-Split buffers will always store items at 32-bit aligned addresses. Therefore, when retrieving an item, the item pointer is guaranteed to be 32-bit aligned. This is useful especially when you need to send some data to the DMA. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 967 → dma_item_t item; UBaseType_t res xRingbufferSendAcquire(buf_handle, &item, DMA_ITEM_SIZE(buffer_size), pdMS_TO_TICKS(1000)); (res pdTRUE) { printf("Failed to acquire memory for item\n"); item->dma_desc (lldesc_t) { .size buffer_size, .length buffer_size, .eof .owner .buf &item->buf, (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 968 { printf("%c", item2[i]); vRingbufferReturnItem(buf_handle, (void *)item2); printf("\n"); else //Failed to receive item printf("Failed to receive item\n"); The following example demonstrates retrieving and returning an item from a byte buffer using xRingbuffer- ReceiveUpTo() vRingbufferReturnItem() Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 969 Using SendAcquire and SendComplete Items in No-Split buffers are acquired (by SendAcquire) in strict FIFO order and must be sent to the buffer by SendComplete for the data to be accessible by the consumer. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 970 The diagrams assume a buffer of 128 bytes with 56 bytes of free space that wraps around and a sent item of 28 bytes. Fig. 33: Wrap around in No-Split buffers Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 971 However, the freeing of space must occur in FIFO order, therefore not returning the earliest retrieved item will prevent the space of subsequent items from being freed. Espressif Systems Release v4.4...
  • Page 972 SelectFromSet(). To check whether the selected queue set member is the ring buffer, call xRingbuffer- CanRead(). The following example demonstrates queue set usage with ring buffers. #include "freertos/queue.h" #include "freertos/ringbuf.h" //Create ring buffer and queue set RingbufHandle_t buf_handle xRingbufferCreate(1028, RINGBUF_TYPE_NOSPLIT); (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 973 //32-bit aligned size #define BUFFER_TYPE RINGBUF_TYPE_NOSPLIT //Allocate ring buffer data structure and storage area into external RAM StaticRingbuffer_t *buffer_struct (StaticRingbuffer_t *)heap_caps_ malloc(sizeof(StaticRingbuffer_t), MALLOC_CAP_SPIRAM); → uint8_t *buffer_storage (uint8_t *)heap_caps_malloc(sizeof(uint8_t)*BUFFER_SIZE,␣ MALLOC_CAP_SPIRAM); → (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 974 Note: Tick interrupt stays active whilst cache is disabled and hence vApplicationTickHook() (legacy case) or ESP-IDF tick hooks must be placed in internal RAM. Please refer to the SPI flash API documentation for more Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 975 Return A handle to the created ring buffer, or NULL in case of error. Parameters • [in] xBufferSize: Size of the buffer in bytes. Note that items require space for overhead in no-split/allow-split buffers Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 976 • [in] pvItem: Pointer to data to insert. NULL is allowed if xItemSize is 0. • [in] xItemSize: Size of data to insert. • [out] pxHigherPriorityTaskWoken: Value pointed to will be set to pdTRUE if the function woke up a higher priority task. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 977 Return • Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. • NULL when the ring buffer is empty, *pxItemSize is untouched in that case. Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 978 • NULL on timeout, *pxItemSize is untouched in that case. Parameters • [in] xRingbuffer: Ring buffer to retrieve the item from • [out] pxItemSize: Pointer to a variable to which the size of the retrieved item will be written. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 979 This gives the real time free space available for an item/data in the ring buffer. This represents the maximum size an item/data can have if it was currently sent to the ring buffer. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 980 • [out] uxWrite: Pointer use to store write pointer position • [out] uxAcquire: Pointer use to store acquire pointer position • [out] uxItemsWaiting: Pointer use to store number of items (bytes for byte buffer) waiting to be retrieved Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 981 Register a callback to be called from the specified core’s idle hook. The callback should return true if it should be called by the idle hook once per interrupt (or FreeRTOS tick), and return false if it should be called repeatedly as fast as possible by the idle hook. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 982 Parameters • [in] old_idle_cb: Callback to be unregistered void esp_deregister_freertos_tick_hook_for_cpu(esp_freertos_tick_cb_t old_tick_cb, UBaseType_t cpuid) Unregister a tick callback from the tick hook of the specified core. Parameters • [in] old_tick_cb: Callback to be unregistered Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 983: Heap Memory Allocation

    Because ESP32-S2 uses multiple types of RAM, it also contains multiple heaps with different capabilities. A capabilities-based memory allocator allows apps to make heap allocations for different purposes. For most purposes, the standard libc malloc() and free() functions can be used for heap allocation without any special consideration.
  • Page 984 find the amount of IRAM used by the app. D/IRAM Some memory in the ESP32-S2 is available as either DRAM or IRAM. If memory is allocated from a D/IRAM region, the free heap size for both types of memory will decrease.
  • Page 985 • ptr: Pointer to the memory allocated void *heap_caps_aligned_calloc(size_t alignment, size_t n, size_t size, uint32_t caps) Allocate a aligned chunk of memory which has the given capabilities. The initialized value in the memory is set to zero. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 986 Returns the largest value of s for which heap_caps_malloc(s, caps) will succeed. Return Size of largest free block in bytes. Parameters • caps: Bitwise OR of MALLOC_CAP_* flags indicating the type of memory Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 987 • addr: Address in memory. Check for corruption in region containing this address. • print_errors: Print specific errors if heap corruption is found. void heap_caps_malloc_extmem_enable(size_t limit) Enable malloc() in external memory and set limit below which malloc() attempts are placed in internal memory. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 988 Return the size that a particular pointer was allocated with. Note The app will crash with an assertion failure if the pointer is not valid. Return Size of the memory allocated at this block. Parameters Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 989 (*esp_alloc_failed_hook_t)(size_t size, uint32_t caps, const char *func- tion_name) callback called when a allocation operation fails, if registered Parameters • size: in bytes of failed allocation • caps: capabillites requested of failed allocation • function_name: function which generated the failure Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 990 Add a region of memory to the collection of heaps at runtime, with custom capabilities. Similar to heap_caps_add_region(), only custom memory capabilities are specified by the caller. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 991 Semantics are the same as standard malloc(), only the returned buffer will be allocated in the specified heap. Return Pointer to new memory, or NULL if allocation fails. Parameters • heap: Handle to a registered heap. • size: Size of desired buffer. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 992 The lock argument is supplied to the MULTI_HEAP_LOCK() and MULTI_HEAP_UNLOCK() macros, de- fined in multi_heap_platform.h. The lock in question must be recursive. When the heap is first registered, the associated lock is NULL. Parameters • heap: Handle to a registered heap. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 993 • info: Pointer to a structure to fill with heap metadata. Structures struct multi_heap_info_t Structure to access heap metadata via multi_heap_get_info. Public Members size_t total_free_bytes Total free bytes in the heap. Equivalent to multi_free_heap_size(). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 994: Heap Memory Debugging

    Heap corruption detection allows you to detect various types of heap memory errors: • Out of bounds writes & buffer overflow. • Writes to freed memory. • Reads from freed or uninitialized memory, Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 995 ESP_WATCHPOINT_STORE. Note that watchpoints are per-CPU and are set on the current running CPU only, so if you don’t know which CPU is corrupting memory then you will need to call this function on both CPUs. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 996 However it allows easier detection of memory corruption bugs which are much more subtle to find otherwise. It is recommended to only enable this mode when debugging, not in production. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 997 • In the project configuration menu, navigate to Component settings -> Heap Memory Debugging -> Heap tracing and select Standalone option (see CONFIG_HEAP_TRACING_DEST). • Call the function heap_trace_init_standalone() early in the program, to register a buffer which can be used to record the memory trace. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 998 • XX bytes is number of bytes allocated • @ 0x... is the heap address returned from malloc/calloc. • CPU x is the CPU (0 or 1) running when the allocation was made. Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 999 To gather and analyse heap trace do the following on the host: 1. Build the program and download it to the target as described in Getting Started Guide. 2. Run OpenOCD (see JTAG Debugging). Espressif Systems Release v4.4 Submit Document Feedback...
  • Page 1000 [0.002782950] HEAP: Freed bytes @ 0x3ffb40b8 from task "main" on core 0 by: /home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590 /home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590 [0.002798700] HEAP: Freed bytes @ 0x3ffb50bc from task "main" on core 0 by: /home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590 /home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590 (continues on next page) Espressif Systems Release v4.4 Submit Document Feedback...

Table of Contents

Save PDF