# 通用异步接收器/发送器 (UART)

[English]

## 简介

通用异步接收器/发送器 (UART) 属于一种硬件功能，通过使用 RS232、RS422、RS485 等常见异步串行通信接口来处理通信时序要求和数据帧。UART 是实现不同设备之间全双工或半双工数据交换的一种常用且经济的方式。

ESP32 芯片有 3 个 UART 控制器（也称为端口），每个控制器都有一组相同的寄存器以简化编程并提高灵活性。

每个 UART 控制器可以独立配置波特率、数据位长度、位顺序、停止位位数、奇偶校验位等参数。所有具备完整功能的 UART 控制器都能与不同制造商的 UART 设备兼容，并且支持红外数据协会 (IrDA) 定义的标准协议。

## 功能概述

下文介绍了如何使用 UART 驱动程序的函数和数据类型在 ESP32 和其他 UART 设备之间建立通信。基本编程流程分为以下几个步骤：

1. 安装驱动程序 - 为 UART 驱动程序分配 ESP32 资源

2. 设置通信参数 - 设置波特率、数据位、停止位等

3. 设置通信管脚 - 分配连接设备的管脚

4. 运行 UART 通信 - 发送/接收数据

5. 使用中断 - 触发特定通信事件的中断

6. 删除驱动程序 - 如无需 UART 通信，则释放已分配的资源

步骤 1 到 3 为配置阶段，步骤 4 为 UART 运行阶段，步骤 5 和 6 为可选步骤。

UART 驱动程序函数通过 `uart_port_t` 识别不同的 UART 控制器。调用以下所有函数均需此标识。

### 安装驱动程序

首先，请调用 `uart_driver_install()` 安装驱动程序并指定以下参数：

- UART 控制器编号

- Rx 环形缓冲区的大小

- Tx 环形缓冲区的大小

- 事件队列大小

- 指向事件队列句柄的指针

- 分配中断的标志

该函数将为 UART 驱动程序分配所需的内部资源。

    // Setup UART buffered IO with event queue
    const int uart_buffer_size = (1024 * 2);
    QueueHandle_t uart_queue;
    // Install UART driver using an event queue here
    ESP_ERROR_CHECK(uart_driver_install(UART_NUM_2, uart_buffer_size, uart_buffer_size, 10, &uart_queue, 0));

### 设置通信参数

其次，UART 通信参数可以在一个步骤中完成全部配置，也可以在多个步骤中单独配置。

#### 一次性配置所有参数

调用函数 `uart_param_config()` 并向其传递 `uart_config_t` 结构体，`uart_config_t` 结构体应包含所有必要的参数。请参考以下示例。

    const uart_port_t uart_num = UART_NUM_2;
    uart_config_t uart_config = {
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS,
        .rx_flow_ctrl_thresh = 122,
    };
    // Configure UART parameters
    ESP_ERROR_CHECK(uart_param_config(uart_num, &uart_config));

了解配置硬件流控模式的更多信息，请参考 peripherals/uart/uart_echo。

#### 分步依次配置每个参数

调用下表中的专用函数，能够单独配置特定参数。如需重新配置某个参数，也可使用这些函数。

单独配置特定参数的函数
配置参数 | 函数
--- | ---
波特率 | `uart_set_baudrate()`
传输位 | 调用 `uart_set_word_length()` 设置 `uart_word_length_t`
奇偶控制 | 调用 `uart_parity_t` 设置 `uart_set_parity()`
停止位 | 调用 `uart_set_stop_bits()` 设置 `uart_stop_bits_t`
硬件流控模式 | 调用 `uart_set_hw_flow_ctrl()` 设置 `uart_hw_flowcontrol_t`
通信模式 | 调用 `uart_set_mode()` 设置 `uart_mode_t`

表中每个函数都可使用 `_get_` 对应项来查看当前设置值。例如，查看当前波特率值，请调用 `uart_get_baudrate()`。

### 设置通信管脚

通信参数设置完成后，可以配置其他 UART 设备连接的 GPIO 管脚。调用函数 `uart_set_pin()`，指定配置 Tx、Rx、RTS、CTS、DTR 和 DSR 信号的 GPIO 管脚编号。如要为特定信号保留当前分配的管脚编号，可传递宏 `UART_PIN_NO_CHANGE`。

请为不使用的管脚都指定为宏 `UART_PIN_NO_CHANGE`。

    // Set UART pins(TX: IO4, RX: IO5, RTS: IO18, CTS: IO19, DTR: UNUSED, DSR: UNUSED)
    ESP_ERROR_CHECK(uart_set_pin(UART_NUM_2, 4, 5, 18, 19, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));

### 运行 UART 通信

串行通信由每个 UART 控制器的有限状态机 (FSM) 控制。

发送数据的过程分为以下步骤：

1. 将数据写入 Tx FIFO 缓冲区

2. FSM 序列化数据

3. FSM 发送数据

接收数据的过程类似，只是步骤相反：

1. FSM 处理且并行化传入的串行流

2. FSM 将数据写入 Rx FIFO 缓冲区

3. 从 Rx FIFO 缓冲区读取数据

因此，应用程序仅会通过 `uart_write_bytes()` 和 `uart_read_bytes()` 从特定缓冲区写入或读取数据，其余工作由 FSM 完成。

#### 发送数据

发送数据准备好后，调用函数 `uart_write_bytes()`，并向其传递数据缓冲区的地址和数据长度。该函数会立即或在有足够可用空间时将数据复制到 Tx 环形缓冲区，随后退出。当 Tx FIFO 缓冲区中有可用空间时，中断服务例程 (ISR) 会在后台将数据从 Tx 环形缓冲区移动到 Tx FIFO 缓冲区。调用函数请参考以下代码。

    // Write data to UART.
    char* test_str = "This is a test string.\n";
    uart_write_bytes(uart_num, (const char*)test_str, strlen(test_str));

函数 `uart_write_bytes_with_break()` 与 `uart_write_bytes()` 类似，但在传输结束时会添加串行中断信号。“串行中断信号”意味着 Tx 线保持低电平的时间长于一个数据帧。

    // Write data to UART, end with a break signal.
    uart_write_bytes_with_break(uart_num, "test break\n",strlen("test break\n"), 100);

能够将数据写入 Tx FIFO 缓冲区的另一函数是 `uart_tx_chars()`。 与 `uart_write_bytes()` 不同，此函数在没有可用空间之前不会阻塞。相反，它将写入所有可以立即放入硬件 Tx FIFO 的数据，然后返回写入的字节数。

“配套”函数 `uart_wait_tx_done()` 用于监听 Tx FIFO 缓冲区的状态，并在缓冲区为空时返回。

    // Wait for packet to be sent
    const uart_port_t uart_num = UART_NUM_2;
    ESP_ERROR_CHECK(uart_wait_tx_done(uart_num, 100)); // wait timeout is 100 RTOS ticks (TickType_t)

#### 接收数据

一旦 UART 接收了数据，并将其保存在 Rx FIFO 缓冲区中，就需要使用函数 `uart_read_bytes()` 检索数据。读取数据之前，调用 `uart_get_buffered_data_len()` 能够查看 Rx FIFO 缓冲区中可用的字节数。请参考以下示例。

    // Read data from UART.
    const uart_port_t uart_num = UART_NUM_2;
    uint8_t data[128];
    int length = 0;
    ESP_ERROR_CHECK(uart_get_buffered_data_len(uart_num, (size_t*)&length));
    length = uart_read_bytes(uart_num, data, length, 100);

如果不再需要 Rx FIFO 缓冲区中的数据，可以调用 `uart_flush()` 清空缓冲区。

#### 软件流控

如果硬件流控处于禁用状态，可使用函数 `uart_set_rts()` 和 `uart_set_dtr()` 分别手动设置 RTS 和 DTR 信号电平。

#### 通信方式选择

UART 控制器支持多种通信模式，使用函数 `uart_set_mode()` 可以选择模式。选择特定模式后，UART 驱动程序将处理已连接 UART 设备的相应行为。例如，使用 RTS 线控制 RS485 驱动芯片，能够实现半双工 RS485 通信。

    // Setup UART in rs485 half duplex mode
    ESP_ERROR_CHECK(uart_set_mode(uart_num, UART_MODE_RS485_HALF_DUPLEX));

### 使用中断

根据特定的 UART 状态或检测到的错误，可以生成许多不同的中断。ESP32 技术参考手册 > UART 控制器 (UART) > UART 中断 [PDF] 中提供了可用中断的完整列表。调用 `uart_enable_intr_mask()` 或 `uart_disable_intr_mask()` 能够分别启用或禁用特定中断。

UART 驱动提供了一种便利的方法来处理特定的中断，即将中断包装成相应的事件。这些事件定义在 `uart_event_type_t` 中，FreeRTOS 队列功能可将这些事件报告给用户应用程序。

要接收已发生的事件，请调用 `uart_driver_install()` 函数并获取返回的事件队列句柄，可参考上述 示例代码。

UART 驱动可处理的事件包括：

- FIFO 空间溢出 (`UART_FIFO_OVF`)：当接收到的数据超过 FIFO 的存储能力时，Rx FIFO 会触发中断。

  > - （可选）配置 FIFO 阈值：在结构体 `uart_intr_config_t` 中输入阈值，然后调用 `uart_intr_config()` 使能配置。这有助于驱动及时处理 RX FIFO 中的数据，避免 FIFO 溢出。

  > - 启用中断：调用函数 `uart_enable_rx_intr()`

  > - 禁用中断：调用函数 `uart_disable_rx_intr()`

      const uart_port_t uart_num = UART_NUM_2;
      // Configure a UART interrupt threshold and timeout
      uart_intr_config_t uart_intr = {
          .intr_enable_mask = UART_INTR_RXFIFO_FULL | UART_INTR_RXFIFO_TOUT,
          .rxfifo_full_thresh = 100,
          .rx_timeout_thresh = 10,
      };
      ESP_ERROR_CHECK(uart_intr_config(uart_num, &uart_intr));

      // Enable UART RX FIFO full threshold and timeout interrupts
      ESP_ERROR_CHECK(uart_enable_rx_intr(uart_num));

- 模式检测 (`UART_PATTERN_DET`)：在检测到重复接收/发送同一字符的“模式”时触发中断，例如，模式检测可用于检测命令字符串末尾是否存在特定数量的相同字符（“模式”）。可以调用以下函数：

  > - 配置并启用此中断：调用 `uart_enable_pattern_det_baud_intr()`

  > - 禁用中断：调用 `uart_disable_pattern_det_intr()`

      //Set UART pattern detect function
      uart_enable_pattern_det_baud_intr(EX_UART_NUM, '+', PATTERN_CHR_NUM, 9, 0, 0);

- 其他事件：UART 驱动可处理的其他事件包括数据接收 (`UART_DATA`)、环形缓冲区已满 (`UART_BUFFER_FULL`)、在停止位后检测到 NULL (`UART_BREAK`)、奇偶校验错误 (`UART_PARITY_ERR`)、以及帧错误 (`UART_FRAME_ERR`)。

括号中的字符串为相应的事件名称。请参考 peripherals/uart/uart_events 中处理 UART 事件的示例。

### 删除驱动程序

如不再需要与 `uart_driver_install()` 建立通信，则可调用 `uart_driver_delete()` 删除驱动程序，释放已分配的资源。

### 宏指令

API 还定义了一些宏指令。例如，`UART_HW_FIFO_LEN` 定义了硬件 FIFO 缓冲区的长度，`UART_BITRATE_MAX` 定义了 UART 控制器支持的最大波特率。

## RS485 特定通信模式简介

备注

下文将使用 `[UART_REGISTER_NAME].[UART_FIELD_BIT]` 指代 UART 寄存器字段/位。了解特定模式位的更多信息，请参考 ESP32 技术参考手册 > UART 控制器 (UART) > 寄存器摘要 [PDF]。请搜索寄存器名称导航至寄存器描述，找到相应字段/位。

- `UART_RS485_CONF_REG.UART_RS485_EN`：设置此位将启用 RS485 通信模式支持。

- `UART_RS485_CONF_REG.UART_RS485TX_RX_EN`：设置此位，发送器的输出信号将环回到接收器的输入信号。

- `UART_RS485_CONF_REG.UART_RS485RXBY_TX_EN`：设置此位，如果接收器繁忙，发送器仍将发送数据（由硬件自动解决冲突）。

ESP32 的 RS485 UART 硬件能够检测数据报传输期间的信号冲突，并在启用此中断时生成中断 `UART_RS485_CLASH_INT`。术语冲突表示发送的数据报与另一端接收到的数据报不同。数据冲突通常与总线上其他活跃设备的存在有关，或者是由于总线错误而出现。

冲突检测功能允许在激活和触发中断时处理冲突。中断 `UART_RS485_FRM_ERR_INT` 和 `UART_RS485_PARITY_ERR_INT` 可与冲突检测功能一起使用，在 RS485 模式下分别控制帧错误和奇偶校验位错误。UART 驱动程序支持此功能，通过选择 `UART_MODE_RS485_APP_CTRL` 模式可以使用（参考函数 `uart_set_mode()`）。

冲突检测功能可与电路 A 和电路 C 一起使用（参考章节 接口连接选项）。调用函数 `uart_get_collision_flag()` 能够查看是否触发冲突检测标志。在使用电路 A 或 B 时，DTR 或 RTS 管脚可以连接到收发器芯片的 DE/~RE 管脚，以实现半双工通信。

UART 驱动支持通过向 `uart_set_mode()` 函数传入 `UART_MODE_RS485_HALF_DUPLEX` 来启用 RS485 半双工通信模式。DTR 信号在 RS485 模式下由硬件直接控制，而 RTS 信号由 UART 驱动程序控制。当主机开始向 Tx FIFO 缓冲区写入数据时，UART 驱动程序会自动置位 RTS 信号（逻辑 1）；最后一位数据传输完成后，驱动程序就会取消置位 RTS 信号（逻辑 0）。要使用此模式，软件必须禁用硬件流控功能。由于切换是在中断处理程序中进行的，因此 RTS 线上会相对 DTR 线有一定延迟。

备注

ESP32 的 DTR 信号仅在 UART0 上可用。对于其他 UART 端口，只能将 RTS 信号连接到收发器芯片的 DE/~RE 管脚。

### 接口连接选项

本节提供了示例原理图来介绍 ESP32 RS485 接口连接的基本内容。

备注

- 下列原理图不一定包含所有必要元素。

- 模拟设备 ADM483 和 ADM2483 是 RS485 收发器的常见示例，也可使用其他类似的收发器。

#### 电路 A：冲突检测电路

            VCC ---------------+
                               |
                       +-------x-------+
            RXD <------| R             |
                       |              B|----------<> B
            TXD ------>| D    ADM483   |
    ESP                |               |     RS485 bus side
        DTR/RTS ------>| DE            |
                       |              A|----------<> A
                  +----| /RE           |
                  |    +-------x-------+
                  |            |
                 GND          GND

推荐这一电路，因为该电路较为简单，同时能够检测冲突。持续启用线路驱动中的接收器时，UART 将会监控 RS485 总线。启用 `UART_RS485_CONF_REG.UART_RS485TX_RX_EN` 位时，UART 外设会执行回波抑制。

#### 电路 B：无冲突检测的手动切换发射器/接收器

            VCC ---------------+
                               |
                       +-------x-------+
            RXD <------| R             |
                       |              B|-----------<> B
            TXD ------>| D    ADM483   |
    ESP                |               |     RS485 bus side
        DTR/RTS --+--->| DE            |
                  |    |              A|-----------<> A
                  +----| /RE           |
                       +-------x-------+
                               |
                              GND

该电路无法检测冲突。置位 `UART_RS485_CONF_REG.UART_RS485TX_RX_EN` 位时，电路将抑制硬件收到的空字节。这种情况下 `UART_RS485_CONF_REG.UART_RS485RXBY_TX_EN` 位不适用。

#### 电路 C：自动切换发射器/接收器

     VCC1 <-------------------+-----------+           +-------------------+----> VCC2
                   10K ____   |           |           |                   |
                  +---|____|--+       +---x-----------x---+    10K ____   |
                  |                   |                   |   +---|____|--+
    RX <----------+-------------------| RXD               |   |
                       10K ____       |                  A|---+---------------<> A (+)
                  +-------|____|------| PV    ADM2483     |   |    ____  120
                  |   ____            |                   |   +---|____|---+  RS485 bus side
          VCC1 <--+--|____|--+------->| DE                |                |
                  10K        |        |                  B|---+------------+--<> B (-)
                          ---+    +-->| /RE               |   |    ____
             10K          |       |   |                   |   +---|____|---+
            ____       | /-C      +---| TXD               |    10K         |
    TX >---|____|--+_B_|/   NPN   |   |                   |                |
                       |\         |   +---x-----------x---+                |
                       | \-E      |       |           |                    |
                          |       |       |           |                    |
                         GND1    GND1    GND1        GND2                 GND2

这种电气隔离电路不需要用软件应用程序或驱动程序控制 RTS 管脚，因为电路能够自动控制收发器方向。但是在传输过程中，需要将 `UART_RS485_CONF_REG.UART_RS485RXBY_TX_EN` 设置为 1 并将 `UART_RS485_CONF_REG.UART_RS485TX_RX_EN` 设置为 0 来抑制空字节。此设置可以在任何 RS485 UART 模式下工作，包括 `UART_MODE_UART`。

## 应用示例

- peripherals/uart/uart_async_rxtxtasks 演示了通过同一 UART 接口完成两个独立任务的通信。其中一个任务定期发送 "Hello world"，另一个任务接收并打印 UART 接收到的数据。

- peripherals/uart/uart_echo 演示了使用 UART 接口回显接收到的所有数据。

- peripherals/uart/uart_echo_rs485 演示了如何使用 UART 软件驱动程序以 RS485 半双工传输模式回显接收到的 UART 数据，要求外部连接总线驱动器。

- peripherals/uart/uart_events 演示了如何使用 UART 驱动程序处理特殊的 UART 事件，从 UART0 读取数据，并将数据回显到监视控制台。

- peripherals/uart/uart_repl 演示了如何使用和连接两个 UART 接口，使用于标准输出的 UART 可以发送命令并接收来自另一个控制台 UART 的回复，无需人工交互。

- peripherals/uart/uart_select 演示了在 UART 接口上使用 `select()` 函数来同步 I/O 多路复用，允许从/向各种来源（如 UART 和套接字）进行非阻塞读写操作，从而立即处理准备就绪的资源。

- peripherals/uart/nmea0183_parser 演示了如何使用 ESP UART 事件驱动程序和 ESP 事件循环库来解析来自 GPS/BDS/GLONASS 模块的 NMEA-0183 数据流，并输出常见的信息，如 UTC 时间、纬度、经度、海拔和速度。

## API 参考

### Header File

- components/esp_driver_uart/include/driver/uart.h

- This header file can be included with:

  >     #include "driver/uart.h"

- This header file is a part of the API provided by the `esp_driver_uart` component. To declare that your component depends on `esp_driver_uart`, add the following to your CMakeLists.txt:

  >     REQUIRES esp_driver_uart

  > or

  >     PRIV_REQUIRES esp_driver_uart

### Functions

esp_err_t uart_driver_install(uart_port_t uart_num, int rx_buffer_size, int tx_buffer_size, int queue_size, QueueHandle_t *uart_queue, int intr_alloc_flags)

  Install UART driver and set the UART to the default configuration.

  UART ISR handler will be attached to the same CPU core that this function is running on.

  备注

  Rx_buffer_size should be greater than UART_HW_FIFO_LEN(uart_num). Tx_buffer_size should be either zero or greater than UART_HW_FIFO_LEN(uart_num).

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - rx_buffer_size -- UART RX ring buffer size.

    - tx_buffer_size -- UART TX ring buffer size. If set to zero, driver will not use TX buffer, TX function will block task until all data have been sent out.

    - queue_size -- UART event queue size/depth.

    - uart_queue -- UART event queue handle (out param). On success, a new queue handle is written here to provide access to UART events. If set to NULL, driver will not use an event queue.

    - intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. Do not set ESP_INTR_FLAG_IRAM here (the driver's ISR handler is not located in IRAM)

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_driver_delete(uart_port_t uart_num)

  Uninstall UART driver.

  参数:

    uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

bool uart_is_driver_installed(uart_port_t uart_num)

  Checks whether the driver is installed or not.

  参数:

    uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

  返回:

    - true driver is installed

    - false driver is not installed

esp_err_t uart_set_word_length(uart_port_t uart_num, uart_word_length_t data_bit)

  Set UART data bits.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - data_bit -- UART data bits

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_get_word_length(uart_port_t uart_num, uart_word_length_t *data_bit)

  Get the UART data bit configuration.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - data_bit -- Pointer to accept value of UART data bits.

  返回:

    - ESP_FAIL Parameter error

    - ESP_OK Success, result will be put in (*data_bit)

esp_err_t uart_set_stop_bits(uart_port_t uart_num, uart_stop_bits_t stop_bits)

  Set UART stop bits.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - stop_bits -- UART stop bits

  返回:

    - ESP_OK Success

    - ESP_FAIL Fail

esp_err_t uart_get_stop_bits(uart_port_t uart_num, uart_stop_bits_t *stop_bits)

  Get the UART stop bit configuration.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - stop_bits -- Pointer to accept value of UART stop bits.

  返回:

    - ESP_FAIL Parameter error

    - ESP_OK Success, result will be put in (*stop_bit)

esp_err_t uart_set_parity(uart_port_t uart_num, uart_parity_t parity_mode)

  Set UART parity mode.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - parity_mode -- the enum of uart parity configuration

  返回:

    - ESP_FAIL Parameter error

    - ESP_OK Success

esp_err_t uart_get_parity(uart_port_t uart_num, uart_parity_t *parity_mode)

  Get the UART parity mode configuration.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - parity_mode -- Pointer to accept value of UART parity mode.

  返回:

    - ESP_FAIL Parameter error

    - ESP_OK Success, result will be put in (*parity_mode)

esp_err_t uart_get_sclk_freq(uart_sclk_t sclk, uint32_t *out_freq_hz)

  Get the frequency of a clock source for the HP UART port.

  参数:

    - sclk -- Clock source

    - out_freq_hz -- [out] Output of frequency, in Hz

  返回:

    - ESP_ERR_INVALID_ARG: if the clock source is not supported

    - otherwise ESP_OK

esp_err_t uart_set_baudrate(uart_port_t uart_num, uint32_t baudrate)

  Set desired UART baud rate.

  Note that the actual baud rate set could have a slight deviation from the user-configured value due to rounding error.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - baudrate -- UART baud rate.

  返回:

    - ESP_FAIL Parameter error, such as baud rate unachievable

    - ESP_OK Success

esp_err_t uart_get_baudrate(uart_port_t uart_num, uint32_t *baudrate)

  Get the actual UART baud rate.

  It returns the real UART rate set in the hardware. It could have a slight deviation from the user-configured baud rate.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - baudrate -- Pointer to accept value of UART baud rate

  返回:

    - ESP_FAIL Parameter error or the UART port is not enabled

    - ESP_OK Success, result will be put in (*baudrate)

esp_err_t uart_set_line_inverse(uart_port_t uart_num, uint32_t inverse_mask)

  Set UART line inverse mode.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - inverse_mask -- Choose the wires that need to be inverted. Using the ORred mask of `uart_signal_inv_t`

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_set_hw_flow_ctrl(uart_port_t uart_num, uart_hw_flowcontrol_t flow_ctrl, uint8_t rx_thresh)

  Set hardware flow control.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - flow_ctrl -- Hardware flow control mode

    - rx_thresh -- Threshold of Hardware RX flow control (0 ~ UART_HW_FIFO_LEN(uart_num)). Only when UART_HW_FLOWCTRL_RTS is set, will the rx_thresh value be set.

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_set_sw_flow_ctrl(uart_port_t uart_num, bool enable, uint8_t rx_thresh_xon, uint8_t rx_thresh_xoff)

  Set software flow control.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1)

    - enable -- switch on or off

    - rx_thresh_xon -- low water mark

    - rx_thresh_xoff -- high water mark

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

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.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - flow_ctrl -- Option for different flow control mode.

  返回:

    - ESP_FAIL Parameter error

    - ESP_OK Success, result will be put in (*flow_ctrl)

esp_err_t uart_clear_intr_status(uart_port_t uart_num, uint32_t clr_mask)

  Clear UART interrupt status.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - clr_mask -- Bit mask of the interrupt status to be cleared.

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_enable_intr_mask(uart_port_t uart_num, uint32_t enable_mask)

  Set UART interrupt enable.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - enable_mask -- Bit mask of the enable bits.

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_disable_intr_mask(uart_port_t uart_num, uint32_t disable_mask)

  Clear UART interrupt enable bits.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - disable_mask -- Bit mask of the disable bits.

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_enable_rx_intr(uart_port_t uart_num)

  Enable UART RX interrupt (RX_FULL & RX_TIMEOUT INTERRUPT)

  参数:

    uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_disable_rx_intr(uart_port_t uart_num)

  Disable UART RX interrupt (RX_FULL & RX_TIMEOUT INTERRUPT)

  参数:

    uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_disable_tx_intr(uart_port_t uart_num)

  Disable UART TX interrupt (TX_FIFO_EMPTY INTERRUPT)

  参数:

    uart_num -- UART port number

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_enable_tx_intr(uart_port_t uart_num, int enable, int thresh)

  Enable UART TX interrupt (TX_FIFO_EMPTY INTERRUPT)

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - enable -- Set to 1 to enable the interrupt

    - thresh -- Threshold of TX FIFO empty interrupt, 0 ~ UART_HW_FIFO_LEN(uart_num). If -1 is given, threshold configuration will be skipped.

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t _uart_set_pin6(uart_port_t uart_num, int tx_io_num, int rx_io_num, int rts_io_num, int cts_io_num, int dtr_io_num, int dsr_io_num)

static inline esp_err_t _uart_set_pin4(uart_port_t uart_num, int tx_io_num, int rx_io_num, int rts_io_num, int cts_io_num)

static inline esp_err_t __uart_set_pin_invalid_args__(int dummy, ...)

esp_err_t uart_set_rts(uart_port_t uart_num, int level)

  Manually set the UART RTS pin level.

  备注

  UART must be configured with hardware flow control disabled.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - level -- 1: RTS output low (active); 0: RTS output high (block)

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_set_dtr(uart_port_t uart_num, int level)

  Manually set the UART DTR pin level.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - level -- 1: DTR output low; 0: DTR output high

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_set_tx_idle_num(uart_port_t uart_num, uint16_t idle_num)

  Set UART idle interval after tx FIFO is empty.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - idle_num --

      idle interval after tx FIFO is empty(unit: the time it takes to send one bit

      under current baudrate)

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_param_config(uart_port_t uart_num, const uart_config_t *uart_config)

  Set UART configuration parameters.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - uart_config -- UART parameter settings

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error, such as baud rate unachievable

esp_err_t uart_intr_config(uart_port_t uart_num, const uart_intr_config_t *intr_conf)

  Configure UART interrupts.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - intr_conf -- UART interrupt settings

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_wait_tx_done(uart_port_t uart_num, uint32_t ticks_to_wait)

  Wait until UART TX FIFO is empty.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - ticks_to_wait -- Timeout, count in RTOS ticks

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

    - ESP_ERR_TIMEOUT Timeout

int uart_tx_chars(uart_port_t uart_num, const char *buffer, uint32_t len)

  Send data to the UART port from a given buffer and length.

  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.

  备注

  This function should only be used when UART TX buffer is not enabled.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - buffer -- data buffer address

    - len -- data length to send

  返回:

    - (-1) Parameter error

    - OTHERS (>=0) The number of bytes pushed to the TX FIFO

int uart_write_bytes(uart_port_t uart_num, const void *src, size_t size)

  Send data to the UART port from a given buffer and length,.

  If the UART driver's parameter 'tx_buffer_size' is set to zero: This function will not return until all the data have been sent out, or at least pushed into TX FIFO.

  Otherwise, if the 'tx_buffer_size' > 0, this function will return after copying all the data to tx ring buffer, UART ISR will then move data from the ring buffer to TX FIFO gradually.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - src -- data buffer address

    - size -- data length to send

  返回:

    - (-1) Parameter error

    - OTHERS (>=0) The number of bytes pushed to the TX FIFO

int uart_write_bytes_with_break(uart_port_t uart_num, const void *src, size_t size, int brk_len)

  Send data to the UART port from a given buffer and length,.

  If the UART driver's parameter 'tx_buffer_size' is set to zero: This function will not return until all the data and the break signal have been sent out. After all data is sent out, send a break signal.

  Otherwise, if the 'tx_buffer_size' > 0, this function will return after copying all the data to tx ring buffer, UART ISR will then move data from the ring buffer to TX FIFO gradually. After all data sent out, send a break signal.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - src -- data buffer address

    - size -- data length to send

    - brk_len -- break signal duration(unit: the time it takes to send one bit at current baudrate)

  返回:

    - (-1) Parameter error

    - OTHERS (>=0) The number of bytes pushed to the TX FIFO

int uart_read_bytes(uart_port_t uart_num, void *buf, uint32_t length, uint32_t ticks_to_wait)

  UART read bytes from UART buffer.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - buf -- pointer to the buffer.

    - length -- data length

    - ticks_to_wait -- sTimeout, count in RTOS ticks

  返回:

    - (-1) Error

    - OTHERS (>=0) The number of bytes read from UART buffer

esp_err_t uart_flush(uart_port_t uart_num)

  Alias of uart_flush_input. UART ring buffer flush. This will discard all data in the UART RX buffer.

  备注

  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.

  参数:

    uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_flush_input(uart_port_t uart_num)

  Clear input buffer, discard all the data is in the ring-buffer.

  备注

  In order to send all the data in tx FIFO, we can use uart_wait_tx_done function.

  参数:

    uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_get_buffered_data_len(uart_port_t uart_num, size_t *size)

  UART get RX ring buffer cached data length.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - size -- Pointer of size_t to accept cached data length

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_get_tx_buffer_free_size(uart_port_t uart_num, size_t *size)

  UART get TX ring buffer free space size for the next data to be enqueued.

  It returns the tight conservative bound for NOSPLIT ring buffer overall enqueueable payload across up to two chunks.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - size -- Pointer of size_t to accept the free space size

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

esp_err_t uart_disable_pattern_det_intr(uart_port_t uart_num)

  UART disable pattern detect function. Designed for applications like 'AT commands'. When the hardware detects a series of one same character, the interrupt will be triggered.

  参数:

    uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_enable_pattern_det_baud_intr(uart_port_t uart_num, char pattern_chr, uint8_t chr_num, int chr_tout, int post_idle, int pre_idle)

  UART enable pattern detect function. Designed for applications like 'AT commands'. When the hardware detect a series of one same character, the interrupt will be triggered.

  参数:

    - uart_num -- UART port number.

    - pattern_chr -- character of the pattern.

    - chr_num -- number of the character, 8bit value.

    - chr_tout -- timeout of the interval between each pattern characters, 16bit value, unit is the baud-rate cycle you configured. When the duration is more than this value, it will not take this data as at_cmd char.

    - post_idle -- idle time after the last pattern character, 16bit value, unit is the baud-rate cycle you configured. When the duration is less than this value, it will not take the previous data as the last at_cmd char

    - pre_idle -- idle time before the first pattern character, 16bit value, unit is the baud-rate cycle you configured. When the duration is less than this value, it will not take this data as the first at_cmd char.

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

int uart_pattern_pop_pos(uart_port_t uart_num)

  Return the nearest detected pattern position in buffer. The positions of the detected pattern are saved in a queue, this function will dequeue the first pattern position and move the pointer to next pattern position.

  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.

  备注

  If the RX buffer is full and flow control is not enabled, the detected pattern may not be found in the rx buffer due to overflow.

  参数:

    uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

  返回:

    - (-1) No pattern found for current index or parameter error

    - others the pattern position in rx buffer.

int uart_pattern_get_pos(uart_port_t uart_num)

  Return the nearest detected pattern position in buffer. The positions of the detected pattern are saved in a queue, This function do nothing to the queue.

  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.

  备注

  If the RX buffer is full and flow control is not enabled, the detected pattern may not be found in the rx buffer due to overflow.

  参数:

    uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

  返回:

    - (-1) No pattern found for current index or parameter error

    - others the pattern position in rx buffer.

esp_err_t uart_pattern_queue_reset(uart_port_t uart_num, int queue_length)

  Allocate a new memory with the given length to save record the detected pattern position in rx buffer.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1).

    - queue_length -- Max queue length for the detected pattern. If the queue length is not large enough, some pattern positions might be lost. Set this value to the maximum number of patterns that could be saved in data buffer at the same time.

  返回:

    - ESP_ERR_NO_MEM No enough memory

    - ESP_ERR_INVALID_STATE Driver not installed

    - ESP_FAIL Parameter error

    - ESP_OK Success

esp_err_t uart_set_mode(uart_port_t uart_num, uart_mode_t mode)

  UART set communication mode.

  备注

  This function must be executed after uart_driver_install(), when the driver object is initialized.

  参数:

    - uart_num -- Uart number to configure, the max port number is (UART_NUM_MAX -1).

    - mode -- UART UART mode to set

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

esp_err_t uart_set_rx_full_threshold(uart_port_t uart_num, int threshold)

  Set uart threshold value for RX fifo full.

  备注

  If application is using higher baudrate and it is observed that bytes in hardware RX fifo are overwritten then this threshold can be reduced

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1)

    - threshold -- Threshold value above which RX fifo full interrupt is generated

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_ERR_INVALID_STATE Driver is not installed

esp_err_t uart_set_tx_empty_threshold(uart_port_t uart_num, int threshold)

  Set uart threshold values for TX fifo empty.

  参数:

    - uart_num -- UART port number, the max port number is (UART_NUM_MAX -1)

    - threshold -- Threshold value below which TX fifo empty interrupt is generated

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_ERR_INVALID_STATE Driver is not installed

esp_err_t uart_set_rx_timeout(uart_port_t uart_num, const uint8_t tout_thresh)

  UART set threshold timeout for TOUT feature.

  参数:

    - uart_num -- Uart number to configure, the max port number is (UART_NUM_MAX -1).

    - tout_thresh -- This parameter defines timeout threshold in uart symbol periods. The maximum value of threshold is 126. tout_thresh = 1, defines TOUT interrupt timeout equal to transmission time of one symbol (~11 bit) on current baudrate. If the time is expired the UART_RXFIFO_TOUT_INT interrupt is triggered. If tout_thresh == 0, the TOUT feature is disabled.

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_ERR_INVALID_STATE Driver is not installed

esp_err_t uart_get_collision_flag(uart_port_t uart_num, bool *collision_flag)

  Returns collision detection flag for RS485 mode Function returns the collision detection flag into variable pointed by collision_flag. *collision_flag = true, if collision detected else it is equal to false. This function should be executed when actual transmission is completed (after uart_write_bytes()).

  参数:

    - uart_num -- Uart number to configure the max port number is (UART_NUM_MAX -1).

    - collision_flag -- Pointer to variable of type bool to return collision flag.

  返回:

    - ESP_OK Success

    - ESP_ERR_INVALID_ARG Parameter error

esp_err_t uart_set_wakeup_threshold(uart_port_t uart_num, int wakeup_threshold)

  Set the number of RX pin signal edges for light sleep wakeup.

  UART can be used to wake up the system from light sleep. This feature works by counting the number of positive edges on RX pin and comparing the count to the threshold. When the count exceeds the threshold, system is woken up from light sleep. This function allows setting the threshold value.

  Stop bit and parity bits (if enabled) also contribute to the number of edges. For example, letter 'a' with ASCII code 97 is encoded as 0100001101 on the wire (with 8n1 configuration), start and stop bits included. This sequence has 3 positive edges (transitions from 0 to 1). Therefore, to wake up the system when 'a' is sent, set wakeup_threshold=3.

  The character that triggers wakeup is not received by UART (i.e. it can not be obtained from UART FIFO). Depending on the baud rate, a few characters after that will also not be received. Note that when the chip enters and exits light sleep mode, APB frequency will be changing. To ensure that UART has correct Baud rate all the time, it is necessary to select a source clock which has a fixed frequency and remains active during sleep. For the supported clock sources of the chips, please refer to `uart_sclk_t` or `soc_periph_uart_clk_src_legacy_t`

  备注

  in ESP32, the wakeup signal can only be input via IO_MUX (i.e. GPIO3 should be configured as function_1 to wake up UART0, GPIO9 should be configured as function_5 to wake up UART1), UART2 does not support light sleep wakeup feature.

  参数:

    - uart_num -- UART number, the max port number is (UART_NUM_MAX -1).

    - wakeup_threshold -- number of RX edges for light sleep wakeup, value is 3 .. 0x3ff.

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_ARG if uart_num is incorrect or wakeup_threshold is outside of [3, 0x3ff] range.

esp_err_t uart_get_wakeup_threshold(uart_port_t uart_num, int *out_wakeup_threshold)

  Get the number of RX pin signal edges for light sleep wakeup.

  See description of uart_set_wakeup_threshold for the explanation of UART wakeup feature.

  参数:

    - uart_num -- UART number, the max port number is (UART_NUM_MAX -1).

    - out_wakeup_threshold -- [out] output, set to the current value of wakeup threshold for the given UART.

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_ARG if out_wakeup_threshold is NULL

esp_err_t uart_wait_tx_idle_polling(uart_port_t uart_num)

  Wait until UART tx memory empty and the last char send ok (polling mode).

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_FAIL Driver not installed

  参数:

    uart_num -- UART number

esp_err_t uart_set_loop_back(uart_port_t uart_num, bool loop_back_en)

  Configure TX signal loop back to RX module, just for the test usage.

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_FAIL Driver not installed

  参数:

    - uart_num -- UART number

    - loop_back_en -- Set true to enable the loop back function, else set it false.

void uart_set_always_rx_timeout(uart_port_t uart_num, bool always_rx_timeout_en)

  Configure behavior of UART RX timeout interrupt.

  When always_rx_timeout is true, timeout interrupt is triggered even if FIFO is full. This function can cause extra timeout interrupts triggered only to send the timeout event. Call this function only if you want to ensure timeout interrupt will always happen after a byte stream.

  参数:

    - uart_num -- UART number

    - always_rx_timeout_en -- Set to false enable the default behavior of timeout interrupt, set it to true to always trigger timeout interrupt.

esp_err_t uart_detect_bitrate_start(uart_port_t uart_num, const uart_bitrate_detect_config_t *config)

  Start to do a bitrate detection for an incoming data signal (auto baud rate detection)

  This function can act as a standalone API. No need to install UART driver before calling this function.

  It is recommended that the incoming data line contains alternating bit sequence, data bytes such as `0x55` or `0xAA`. Characters ‘NULL’, `0xCC` are not good for the measurement.

  参数:

    - uart_num -- The ID of the UART port to be used to do the measurement. Note that only HP UART ports have the capability.

    - config -- Pointer to the configuration structure for the UART port. If the port has already been acquired, this parameter is ignored.

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_FAIL No free uart port or source_clk invalid

esp_err_t uart_detect_bitrate_stop(uart_port_t uart_num, bool deinit, uart_bitrate_res_t *ret_res)

  Stop the bitrate detection.

  The measurement period should last for at least one-byte long if detecting UART baud rate, then call this function to stop and get the measurement result.

  参数:

    - uart_num -- The ID of the UART port

    - deinit -- Whether to release the UART port after finishing the measurement

    - ret_res -- [out] Structure to store the measurement results

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_ARG Parameter error

    - ESP_FAIL Unknown tick frequency

### Structures

struct uart_config_t

  UART configuration parameters for uart_param_config function.

  Public Members

  int baud_rate

    UART baud rate Note that the actual baud rate set could have a slight deviation from the user-configured value due to rounding error

  uart_word_length_t data_bits

    UART byte size

  uart_parity_t parity

    UART parity mode

  uart_stop_bits_t stop_bits

    UART stop bits

  uart_hw_flowcontrol_t flow_ctrl

    UART HW flow control mode (cts/rts)

  uint8_t rx_flow_ctrl_thresh

    UART HW RTS threshold

  uart_sclk_t source_clk

    UART source clock selection

  uint32_t allow_pd

    If set, driver allows the power domain to be powered off when system enters sleep mode. This can save power, but at the expense of more RAM being consumed to save register context.

  uint32_t backup_before_sleep

    Deprecated:

      , same meaning as allow_pd

  struct uart_config_t flags

    Configuration flags

struct uart_intr_config_t

  UART interrupt configuration parameters for uart_intr_config function.

  Public Members

  uint32_t intr_enable_mask

    UART interrupt enable mask, choose from UART_XXXX_INT_ENA_M under UART_INT_ENA_REG(i), connect with bit-or operator

  uint8_t rx_timeout_thresh

    UART timeout interrupt threshold (unit: time of sending one byte)

  uint8_t txfifo_empty_intr_thresh

    UART TX empty interrupt threshold.

  uint8_t rxfifo_full_thresh

    UART RX full interrupt threshold.

struct uart_event_t

  Event structure used in UART event queue.

  Public Members

  uart_event_type_t type

    UART event type

  size_t size

    UART data size for UART_DATA event

  bool timeout_flag

    UART data read timeout flag for UART_DATA event (no new data received during configured RX TOUT) If the event is caused by FIFO-full interrupt, then there will be no event with the timeout flag before the next byte coming.

struct uart_bitrate_detect_config_t

  UART bitrate detection configuration parameters for `uart_detect_bitrate_start` function to acquire a new uart handle.

  Public Members

  int rx_io_num

    GPIO pin number for the incoming signal

  uart_sclk_t source_clk

    The higher the frequency of the clock source, the more accurate the detected bitrate value; The slower the frequency of the clock source, the slower the bitrate can be measured

struct uart_bitrate_res_t

  Structure to store the measurement results for UART bitrate detection within the measurement period.

  Formula to calculate the bitrate: If the signal is ideal, bitrate = clk_freq_hz * 2 / (low_period + high_period) If the signal is weak along falling edges, then you may use bitrate = clk_freq_hz * 2 / pos_period If the signal is weak along rising edges, then you may use bitrate = clk_freq_hz * 2 / neg_period

  Public Members

  uint32_t low_period

    Stores the minimum tick count of a low-level pulse

  uint32_t high_period

    Stores the minimum tick count of a high-level pulse

  uint32_t pos_period

    Stores the minimum tick count between two positive edges

  uint32_t neg_period

    Stores the minimum tick count between two negative edges

  uint32_t edge_cnt

    Stores the count of RX edge changes (10-bit counter, be careful, it could overflow)

  uint32_t clk_freq_hz

    The frequency of the tick being used to count the measurement results, in Hz

### Macros

UART_PIN_NO_CHANGE

UART_HW_FIFO_LEN(uart_num)

  Length of the UART HW FIFO.

UART_BITRATE_MAX

  Maximum configurable bitrate.

_GET_UART_SET_PIN_FUNC_NAME(_1, _2, _3, _4, _5, _6, _7, _FUNC_NAME, ...)

uart_set_pin(...)

  Assign signals of a UART peripheral to GPIO pins.

  备注

  If the GPIO number configured for a UART signal matches one of the IOMUX signals for that GPIO, the signal will be connected directly via the IOMUX. Otherwise the GPIO and signal will be connected via the GPIO Matrix. For example, if on an ESP32 the call `uart_set_pin(0, 1, 3, -1, -1)` is performed, as GPIO1 is UART0's default TX pin and GPIO3 is UART0's default RX pin, both will be connected to respectively U0TXD and U0RXD through the IOMUX, totally bypassing the GPIO matrix. The check is performed on a per-pin basis. Thus, it is possible to have RX pin binded to a GPIO through the GPIO matrix, whereas TX is binded to its GPIO through the IOMUX.

  备注

  It is possible to configure TX and RX to share the same IO (single wire mode), but please be aware of output conflict, which could damage the pad. Apply open-drain and pull-up to the pad ahead of time as a protection, or the upper layer protocol must guarantee no output from two ends at the same time.

  备注

  Variadic arguments

  - param: uart_num UART port number, the max port number is (UART_NUM_MAX -1).

  - param: tx_io_num UART TX pin GPIO number.

  - param: rx_io_num UART RX pin GPIO number.

  - param: rts_io_num UART RTS pin GPIO number.

  - param: cts_io_num UART CTS pin GPIO number.

  - param: dtr_io_num UART DTR pin GPIO number (optional). DTR signal is automatically controlled by hardware when UART is in RS485 mode.

  - param: dsr_io_num UART DSR pin GPIO number (optional).

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

### Enumerations

enum uart_event_type_t

  UART event types used in the ring buffer.

  Values:

  enumerator UART_DATA

    Triggered when the receiver either takes longer than rx_timeout_thresh to receive a byte, or when more data is received than what rxfifo_full_thresh specifies

  enumerator UART_BREAK

    Triggered when the receiver detects a NULL character

  enumerator UART_BUFFER_FULL

    Triggered when RX ring buffer is full

  enumerator UART_FIFO_OVF

    Triggered when the received data exceeds the capacity of the RX FIFO

  enumerator UART_FRAME_ERR

    Triggered when the receiver detects a data frame error

  enumerator UART_PARITY_ERR

    Triggered when a parity error is detected in the received data

  enumerator UART_DATA_BREAK

    Internal event triggered to signal a break afte data transmission

  enumerator UART_PATTERN_DET

    Triggered when a specified pattern is detected in the incoming data

  enumerator UART_EVENT_MAX

    Maximum index for UART events

### Header File

- components/esp_driver_uart/include/driver/uart_wakeup.h

- This header file can be included with:

  >     #include "driver/uart_wakeup.h"

- This header file is a part of the API provided by the `esp_driver_uart` component. To declare that your component depends on `esp_driver_uart`, add the following to your CMakeLists.txt:

  >     REQUIRES esp_driver_uart

  > or

  >     PRIV_REQUIRES esp_driver_uart

### Functions

esp_err_t uart_wakeup_setup(uart_port_t uart_num, const uart_wakeup_cfg_t *cfg)

  Initializes the UART wakeup functionality.

  This function configures the wakeup behavior for a specified UART port based on the provided configuration. The behavior depends on the selected wakeup mode and additional parameters such as active threshold or character sequence, if applicable. It is important that the provided configuration matches the capabilities of the SOC to ensure proper operation.

  参数:

    - uart_num -- The UART port to initialize for wakeup (e.g., UART_NUM_0, UART_NUM_1, etc.).

    - cfg -- Pointer to the `uart_wakeup_cfg_t` structure that contains the wakeup configuration settings.

  返回:

    - `ESP_OK` if the wakeup configuration was successfully applied.

    - `ESP_ERR_INVALID_ARG` if the provided configuration is invalid (e.g., threshold values out of range).

esp_err_t uart_wakeup_clear(uart_port_t uart_num, uart_wakeup_mode_t wakeup_mode)

  Clear the UART wakeup configuration.

  This function will clear the UART wakeup behavior and set to its default configuration.

  参数:

    - uart_num -- The UART port to initialize for wakeup (e.g., UART_NUM_0, UART_NUM_1, etc.).

    - wakeup_mode -- The UART wakeup mode set in `uart_wakeup_setup`.

  返回:

    - `ESP_OK` Clear wakeup configuration successfully.

### Structures

struct uart_wakeup_cfg_t

  Structure that holds configuration for UART wakeup.

  This structure is used to configure the wakeup behavior for a UART port. The wakeup mode can be selected from several options, such as active threshold, FIFO threshold, start bit detection, and character sequence detection. The availability of different wakeup modes depends on the SOC capabilities.

  Public Members

  uart_wakeup_mode_t wakeup_mode

    Wakeup mode selection

  uint16_t rx_edge_threshold

    Used in Active threshold wake-up; related: UART_WK_MODE_ACTIVE_THRESH; Configures the number of RXD edge changes to wake up the chip.

### Header File

- components/esp_hal_uart/include/hal/uart_types.h

- This header file can be included with:

  >     #include "hal/uart_types.h"

- This header file is a part of the API provided by the `esp_hal_uart` component. To declare that your component depends on `esp_hal_uart`, add the following to your CMakeLists.txt:

  >     REQUIRES esp_hal_uart

  > or

  >     PRIV_REQUIRES esp_hal_uart

### Structures

struct uart_at_cmd_t

  UART AT cmd char configuration parameters Note that this function may different on different chip. Please refer to the TRM at confirguration.

  Public Members

  uint8_t cmd_char

    UART AT cmd char

  uint8_t char_num

    AT cmd char repeat number

  uint32_t gap_tout

    gap time(in baud-rate) between AT cmd char

  uint32_t pre_idle

    the idle time(in baud-rate) between the non AT char and first AT char

  uint32_t post_idle

    the idle time(in baud-rate) between the last AT char and the none AT char

struct uart_sw_flowctrl_t

  UART software flow control configuration parameters.

  Public Members

  uint8_t xon_char

    Xon flow control char

  uint8_t xoff_char

    Xoff flow control char

  uint8_t xon_thrd

    If the software flow control is enabled and the data amount in rxfifo is less than xon_thrd, an xon_char will be sent

  uint8_t xoff_thrd

    If the software flow control is enabled and the data amount in rxfifo is more than xoff_thrd, an xoff_char will be sent

### Type Definitions

typedef soc_periph_uart_clk_src_legacy_t uart_sclk_t

  UART source clock.

### Enumerations

enum uart_port_t

  UART port number, can be UART_NUM_0 ~ (UART_NUM_MAX -1).

  Values:

  enumerator UART_NUM_0

    UART port 0

  enumerator UART_NUM_1

    UART port 1

  enumerator UART_NUM_2

    UART port 2

  enumerator UART_NUM_MAX

    UART port max

enum uart_mode_t

  UART mode selection.

  Values:

  enumerator UART_MODE_UART

    mode: regular UART mode

  enumerator UART_MODE_RS485_HALF_DUPLEX

    mode: half duplex RS485 UART mode control by RTS pin

  enumerator UART_MODE_IRDA

    mode: IRDA UART mode

  enumerator UART_MODE_RS485_COLLISION_DETECT

    mode: RS485 collision detection UART mode (used for test purposes)

  enumerator UART_MODE_RS485_APP_CTRL

    mode: application control RS485 UART mode (used for test purposes)

enum uart_word_length_t

  UART word length constants.

  Values:

  enumerator UART_DATA_5_BITS

    word length: 5bits

  enumerator UART_DATA_6_BITS

    word length: 6bits

  enumerator UART_DATA_7_BITS

    word length: 7bits

  enumerator UART_DATA_8_BITS

    word length: 8bits

  enumerator UART_DATA_BITS_MAX

enum uart_stop_bits_t

  UART stop bits number.

  Values:

  enumerator UART_STOP_BITS_1

    stop bit: 1bit

  enumerator UART_STOP_BITS_1_5

    stop bit: 1.5bits

  enumerator UART_STOP_BITS_2

    stop bit: 2bits

  enumerator UART_STOP_BITS_MAX

enum uart_parity_t

  UART parity constants.

  Values:

  enumerator UART_PARITY_DISABLE

    Disable UART parity

  enumerator UART_PARITY_EVEN

    Enable UART even parity

  enumerator UART_PARITY_ODD

    Enable UART odd parity

enum uart_hw_flowcontrol_t

  UART hardware flow control modes.

  Values:

  enumerator UART_HW_FLOWCTRL_DISABLE

    disable hardware flow control

  enumerator UART_HW_FLOWCTRL_RTS

    enable RX hardware flow control (rts)

  enumerator UART_HW_FLOWCTRL_CTS

    enable TX hardware flow control (cts)

  enumerator UART_HW_FLOWCTRL_CTS_RTS

    enable hardware flow control

  enumerator UART_HW_FLOWCTRL_MAX

enum uart_signal_inv_t

  UART signal bit map.

  Values:

  enumerator UART_SIGNAL_INV_DISABLE

    Disable UART signal inverse

  enumerator UART_SIGNAL_IRDA_TX_INV

    inverse the UART irda_tx signal

  enumerator UART_SIGNAL_IRDA_RX_INV

    inverse the UART irda_rx signal

  enumerator UART_SIGNAL_RXD_INV

    inverse the UART rxd signal

  enumerator UART_SIGNAL_CTS_INV

    inverse the UART cts signal

  enumerator UART_SIGNAL_DSR_INV

    inverse the UART dsr signal

  enumerator UART_SIGNAL_TXD_INV

    inverse the UART txd signal

  enumerator UART_SIGNAL_RTS_INV

    inverse the UART rts signal

  enumerator UART_SIGNAL_DTR_INV

    inverse the UART dtr signal

enum uart_wakeup_mode_t

  Enumeration of UART wake-up modes.

  Values:

  enumerator UART_WK_MODE_ACTIVE_THRESH

    Wake-up triggered by active edge threshold

### GPIO 查找宏指令

一些 UART 外设有供直接连接的专用 IO_MUX 管脚。这些管脚可用于需要极高 UART 波特率的场景，即仅可使用 IO_MUX 管脚。在其他情况下，任一 GPIO 管脚都可用于 UART 通信，只需将信号通过 GPIO 矩阵路由即可。当特定的 UART 外设有专用 IO_MUX 管脚时，`UxTXD_GPIO_NUM` 和 `UxRXD_GPIO_NUM` 可用于查找对应的 IO_MUX 管脚编号。

### Header File

- components/soc/esp32/include/soc/uart_pins.h

- This header file can be included with:

  >     #include "soc/uart_pins.h"

### Macros

U0TXD_GPIO_NUM

U0RXD_GPIO_NUM

U0CTS_GPIO_NUM

U0RTS_GPIO_NUM

U0DTR_GPIO_NUM

U0DSR_GPIO_NUM

U1TXD_GPIO_NUM

U1RXD_GPIO_NUM

U1CTS_GPIO_NUM

U1RTS_GPIO_NUM

U1DTR_GPIO_NUM

U1DSR_GPIO_NUM

U2TXD_GPIO_NUM

U2RXD_GPIO_NUM

U2CTS_GPIO_NUM

U2RTS_GPIO_NUM

U2DTR_GPIO_NUM

U2DSR_GPIO_NUM

U0TXD_MUX_FUNC

U0RXD_MUX_FUNC

U0RTS_MUX_FUNC

U0CTS_MUX_FUNC

U0DTR_MUX_FUNC

U0DSR_MUX_FUNC

U1TXD_MUX_FUNC

U1RXD_MUX_FUNC

U1RTS_MUX_FUNC

U1CTS_MUX_FUNC

U1DTR_MUX_FUNC

U1DSR_MUX_FUNC

U2TXD_MUX_FUNC

U2RXD_MUX_FUNC

U2RTS_MUX_FUNC

U2CTS_MUX_FUNC

U2DTR_MUX_FUNC

U2DSR_MUX_FUNC

此文档对您有帮助吗？

- 反馈已收到，谢谢！
- 如果您有其他意见，欢迎填写乐鑫文档反馈表。

- 我们重视您的反馈。
- 您可以填写乐鑫文档反馈表告诉我们如何改进该文档。