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

[English]

## 简介

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

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

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

此外，ESP32-P4 芯片还有一个满足低功耗需求的 LP UART 控制器。LP UART 是原 UART 的功能剪裁版本。它只支持基础 UART 功能，不支持 IrDA 或 RS485 协议，并且只有一块较小的 RAM 存储空间。想要全面了解的 UART 及 LP UART 功能区别，请参考 ESP32-P4 技术参考手册 > UART 控制器 (UART) > 主要特性 [PDF]。

ESP32-P4 芯片也支持 UART DMA 模式, 请参考 UART DMA (UHCI) 以获得更多信息.

## 功能概述

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

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

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

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

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

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

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

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

此外，LP UART 控制器的编程需要注意 使用主核驱动 LP UART 控制器。

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_1, 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_1;
    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_config_t::backup_before_sleep` 会使能在进入睡眠模式前备份 UART 配置寄存器并在退出睡眠后恢复这些寄存器。这个功能使 UART 能够在系统唤醒后继续正常工作，即使其电源域在睡眠过程中被完全关闭。此选项需要用户在功耗和内存使用之间取得平衡。如果功耗不是一个问题，可以禁用这个选项来节省内存。

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

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

单独配置特定参数的函数
配置参数 | 函数
--- | ---
波特率 | `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 信号的 GPIO 管脚编号。如要为特定信号保留当前分配的管脚编号，可传递宏 `UART_PIN_NO_CHANGE`。

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

    // Set UART pins(TX: IO4, RX: IO5, RTS: IO18, CTS: IO19)
    ESP_ERROR_CHECK(uart_set_pin(UART_NUM_1, 4, 5, 18, 19));

### 运行 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_1;
    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_1;
    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-P4 技术参考手册 > 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_1;
      // 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 控制器支持的最大波特率。

### 使用主核驱动 LP UART 控制器

UART 驱动程序还适配了在 Active 模式下对 LP UART 控制器的驱动。LP UART 的配置流程和普通 UART 没有本质上的差别，除了有以下几点需要注意：

- LP UART 控制器的端口号为 `LP_UART_NUM_0`。

- LP UART 控制器的可选时钟源可以在 `lp_uart_sclk_t` 中找到。

- LP UART 控制器的硬件 FIFO 大小要远小于普通 UART 控制器的硬件 FIFO 大小，其值为 `SOC_LP_UART_FIFO_LEN`。

- LP UART 控制器的 GPIO 引脚只能从 LP GPIO 引脚中选择。

## RS485 特定通信模式简介

备注

下文将使用 `[UART_REGISTER_NAME].[UART_FIELD_BIT]` 指代 UART 寄存器字段/位。了解特定模式位的更多信息，请参考 ESP32-P4 技术参考手册 > 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-P4 的 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 一起使用（参考章节 接口连接选项）。在使用电路 A 或 B 时，连接到总线驱动 DE 管脚的 RTS 管脚应由用户应用程序控制。调用函数 `uart_get_collision_flag()` 能够查看是否触发冲突检测标志。

ESP32-P4 UART 控制器本身不支持半双工通信，因其无法自动控制连接到 RS485 总线驱动 RE/DE 输入的 RTS 管脚。然而，半双工通信能够通过 UART 驱动程序对 RTS 管脚的软件控制来实现，调用 `uart_set_mode()` 并选择 `UART_MODE_RS485_HALF_DUPLEX` 模式能够启用这一功能。

主机开始向 Tx FIFO 缓冲区写入数据时，UART 驱动程序会自动置位 RTS 管脚（逻辑 1）；最后一位数据传输完成后，驱动程序就会取消置位 RTS 管脚（逻辑 0）。要使用此模式，软件必须禁用硬件流控功能。此模式适用于下文所有已用电路。

### 接口连接选项

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

备注

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

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

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

            VCC ---------------+
                               |
                       +-------x-------+
            RXD <------| R             |
                       |              B|----------<> B
            TXD ------>| D    ADM483   |
    ESP                |               |     RS485 bus side
            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
            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/ 下可用的代码示例。

代码示例 | 描述
--- | ---
peripherals/uart/uart_echo | 配置 UART 设置、安装 UART 驱动程序以及通过 UART1 接口读取/写入。
peripherals/uart/uart_events | 报告各种通信事件，使用模式检测中断。
peripherals/uart/uart_async_rxtxtasks | 通过同一 UART 在两个独立的 FreeRTOS 任务中发送和接收数据。
peripherals/uart/uart_select | 针对 UART 文件描述符使用同步 I/O 多路复用。
peripherals/uart/uart_echo_rs485 | 设置 UART 驱动程序以半双工模式通过 RS485 接口进行通信。此示例与 peripherals/uart/uart_echo 类似，但允许通过连接到 ESP32-P4 管脚的 RS485 接口芯片进行通信。
peripherals/uart/nmea0183_parser | 解析通过 UART 外设从 GPS 收到的 NMEA0183 语句来获取 GPS 信息。

## 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

    - 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_FULL & TX_TIMEOUT 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_FULL & TX_TIMEOUT INTERRUPT)

  参数:

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

    - enable -- 1: enable; 0: disable

    - thresh -- Threshold of TX interrupt, 0 ~ UART_HW_FIFO_LEN(uart_num)

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

esp_err_t uart_set_pin(uart_port_t uart_num, int tx_io_num, int rx_io_num, int rts_io_num, int cts_io_num)

  Assign signals of a UART peripheral to GPIO pins.

  备注

  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.

  参数:

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

    - tx_io_num -- UART TX pin GPIO number.

    - rx_io_num -- UART RX pin GPIO number.

    - rts_io_num -- UART RTS pin GPIO number.

    - cts_io_num -- UART CTS pin GPIO number.

  返回:

    - ESP_OK Success

    - ESP_FAIL Parameter error

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, TickType_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, TickType_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.

### 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

  lp_uart_sclk_t lp_source_clk

    LP_UART source clock selection

  uint32_t backup_before_sleep

    If set, the driver will backup/restore the HP UART registers before entering/after exiting sleep mode. By this approach, the system can power off HP UART's power domain. This can save power, but at the expense of more RAM being consumed

  struct uart_config_t::[anonymous] 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.

### Macros

UART_PIN_NO_CHANGE

UART_FIFO_LEN

  Length of the HP UART HW FIFO.

UART_HW_FIFO_LEN(uart_num)

  Length of the UART HW FIFO.

UART_BITRATE_MAX

  Maximum configurable bitrate.

### Type Definitions

typedef intr_handle_t uart_isr_handle_t

### Enumerations

enum uart_event_type_t

  UART event types used in the ring buffer.

  Values:

  enumerator UART_DATA

    UART data event

  enumerator UART_BREAK

    UART break event

  enumerator UART_BUFFER_FULL

    UART RX buffer full event

  enumerator UART_FIFO_OVF

    UART FIFO overflow event

  enumerator UART_FRAME_ERR

    UART RX frame error event

  enumerator UART_PARITY_ERR

    UART RX parity event

  enumerator UART_DATA_BREAK

    UART TX data and break event

  enumerator UART_PATTERN_DET

    UART pattern detected

  enumerator UART_WAKEUP

    UART wakeup event

  enumerator UART_EVENT_MAX

    UART event max index

### Header File

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

- This header file can be included with:

  >     #include "hal/uart_types.h"

### Structures

struct uart_at_cmd_t

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

  Public Members

  uint8_t cmd_char

    UART AT cmd char

  uint8_t char_num

    AT cmd char repeat number

  uint32_t gap_tout

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

  uint32_t pre_idle

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

  uint32_t post_idle

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

struct uart_sw_flowctrl_t

  UART software flow control configuration parameters.

  Public Members

  uint8_t xon_char

    Xon flow control char

  uint8_t xoff_char

    Xoff flow control char

  uint8_t xon_thrd

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

  uint8_t xoff_thrd

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

### Type Definitions

typedef soc_periph_uart_clk_src_legacy_t uart_sclk_t

  UART source clock.

typedef soc_periph_lp_uart_clk_src_t lp_uart_sclk_t

  LP_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_3

    UART port 3

  enumerator UART_NUM_4

    UART port 4

  enumerator LP_UART_NUM_0

    LP UART port 0

  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

### GPIO 查找宏指令

UART 外设有供直接连接的专用 IO_MUX 管脚，但也可用非直接的 GPIO 矩阵将信号配置到其他管脚。如要直接连接，需要知道哪一管脚为 UART 通道的专用 IO_MUX 管脚。GPIO 查找宏简化了查找和分配 IO_MUX 管脚的过程，可根据 IO_MUX 管脚编号或所需 UART 通道名称选择一个宏，该宏将返回匹配的对应项。请查看下列示例。

备注

如需较高的 UART 波特率（超过 40 MHz），即仅使用 IO_MUX 管脚时，可以使用此类宏。在其他情况下可以忽略这些宏，并使用 GPIO 矩阵为 UART 功能配置任一 GPIO 管脚。

1. `UART_NUM_2_TXD_DIRECT_GPIO_NUM` 返回 UART 通道 2 TXD 管脚的 IO_MUX 管脚编号（管脚 17）

2. `UART_GPIO19_DIRECT_CHANNEL` 在通过 IO_MUX 连接到 UART 外设时返回 GPIO 19 的 UART 编号（即 UART_NUM_0）

3. GPIO 19 在通过 IO_MUX 用作 UART CTS 管脚时，`UART_CTS_GPIO19_DIRECT_CHANNEL` 将返回 GPIO 19 的 UART 编号（即 UART_NUM_0）。该宏类似于上述宏，但指定了管脚功能，这也是 IO_MUX 分配的一部分。

### Header File

- components/soc/esp32p4/include/soc/uart_channel.h

- This header file can be included with:

  >     #include "soc/uart_channel.h"

### Macros

UART_GPIO37_DIRECT_CHANNEL

UART_NUM_0_TXD_DIRECT_GPIO_NUM

UART_GPIO38_DIRECT_CHANNEL

UART_NUM_0_RXD_DIRECT_GPIO_NUM

UART_GPIO8_DIRECT_CHANNEL

UART_NUM_0_RTS_DIRECT_GPIO_NUM

UART_GPIO9_DIRECT_CHANNEL

UART_NUM_0_CTS_DIRECT_GPIO_NUM

UART_TXD_GPIO37_DIRECT_CHANNEL

UART_RXD_GPIO38_DIRECT_CHANNEL

UART_RTS_GPIO8_DIRECT_CHANNEL

UART_CTS_GPIO9_DIRECT_CHANNEL

UART_GPIO10_DIRECT_CHANNEL

UART_NUM_1_TXD_DIRECT_GPIO_NUM

UART_GPIO11_DIRECT_CHANNEL

UART_NUM_1_RXD_DIRECT_GPIO_NUM

UART_GPIO12_DIRECT_CHANNEL

UART_NUM_1_RTS_DIRECT_GPIO_NUM

UART_GPIO13_DIRECT_CHANNEL

UART_NUM_1_CTS_DIRECT_GPIO_NUM

UART_TXD_GPIO10_DIRECT_CHANNEL

UART_RXD_GPIO11_DIRECT_CHANNEL

UART_RTS_GPIO12_DIRECT_CHANNEL

UART_CTS_GPIO13_DIRECT_CHANNEL

提供有关此文档的反馈