# 触摸元件

[English]

## 概述

触摸元件库是基于触摸传感器驱动设计的高度抽象的元件库，该库提供了统一且友好的软件接口，可以快速构建电容式触摸传感器的应用。

警告

目前的触摸元件库仍然基于旧的触摸传感器驱动。如您不需要使用触摸元件库，请参考新的 电容式触摸传感器 驱动。

### 架构

触摸元件库通过触摸传感器驱动程序配置触摸传感器外设。使用时，部分必要的硬件参数需要传递给函数 `touch_element_install()`，但只有在调用 `touch_element_start()` 函数后，才会自动配置这些参数。这些参数配置会对实时系统产生很大的影响，因此步骤顺序很重要，必须在调用启动函数之后进行配置，确保系统正常运行。

上述参数包括触摸通道阈值、防水屏蔽传感器驱动级别等。触摸元件库会设置触摸传感器中断和 esp_timer 例程，并在触摸传感器中断服务例程中获取触摸传感器的硬件信息（通道状态、通道编号）。当特定通道事件发生时，硬件信息将传递给 esp_timer 回调例程，esp_timer 回调例程将触摸传感器通道信息分配给触摸元件（例如按键、滑条等）。随后，触摸元件库运行特定算法，更新触摸元件状态或计算其位置，并将结果分派给相应的处理程序。

因此，在使用触摸元件库时，你无需关注触摸传感器外设的工作细节，该库会处理大部分硬件信息，并将更有意义的信息传递给事件处理程序。

下图展示了触摸元件库的工作流程。

触摸元件库架构

下表展示了 ESP32-S2 中与触摸元件库有关的功能。

功能 | ESP32-S2
--- | ---
防水 | ✔
按键 | ✔
触摸滑条 | ✔
矩阵按键 | ✔

### 外设

ESP32-S2 集成了一个触摸传感器外设，具有多个物理通道。

- 14 个物理电容触摸通道

- 定时器或软件 FSM 触发模式

- 高达 5 种中断（高阈值和低阈值中断、测量单通道完成和测量所有通道完成中断、测量超时中断）

- 睡眠模式唤醒源

- 硬件内置降噪

- 硬件滤波器

- 硬件防水传感器

- 硬件近场感应传感器

这些通道的具体位置如下：

通道 | ESP32-S2
--- | ---
通道 0 | GPIO 0（保留）
通道 1 | GPIO 1
通道 2 | GPIO 2
通道 3 | GPIO 3
通道 4 | GPIO 4
通道 5 | GPIO 5
通道 6 | GPIO 6
通道 7 | GPIO 7
通道 8 | GPIO 8
通道 9 | GPIO 9
通道 10 | GPIO 10
通道 11 | GPIO 11
通道 12 | GPIO 12
通道 13 | GPIO 13
通道 14 | GPIO 14

这些通道的具体位置如下：

通道 | ESP32-S2
--- | ---
通道 0 | GPIO 0（有效）
通道 1 | GPIO 1
通道 2 | GPIO 2
通道 3 | GPIO 3
通道 4 | GPIO 4
通道 5 | GPIO 5
通道 6 | GPIO 6
通道 7 | GPIO 7
通道 8 | GPIO 8
通道 9 | GPIO 9

## 术语

触摸元件库的有关术语如下：

术语 | 定义
--- | ---
触摸传感器 (touch sensor) | 芯片内部的触摸传感器外设
触摸通道 (touch channel) | 触摸传感器外设内的触摸通道
触摸焊盘 (touch pad) | 外部物理触摸焊盘，通常位于 PCB 内部
降噪通道 (de-noise channel) | 内部降噪通道，始终为通道 0 且已预留
屏蔽传感器 (shield sensor) | 防水传感器之一，用于小面积的水滴检测，并补偿水滴对读数的影响
防护传感器 (guard sensor) | 防水传感器之一，用于大面积的涉水检测，并临时禁用触摸传感器
屏蔽通道 (shield channel) | 防水屏蔽传感器连接的通道，始终为通道 14
防护通道 (guard channel) | 防水防护传感器连接的通道
屏蔽焊盘 (shield pad) | 外部物理屏蔽焊盘，通常是网格状，与防水传感器相连
防护焊盘 (guard pad) | 外部物理防护焊盘，通常是环状，与防护传感器相连

触摸传感器应用程序系统组件

### 触摸传感器信号

触摸传感器可提供以下信号：

- 原始信号：从触摸传感器获取、未经滤波的信号。

- 平滑信号：原始信号通过内部硬件滤波器滤波后的信号。

- 基准信号：经过滤波的信号，已过滤极低频噪声。

以上信号均可通过触摸传感器驱动程序 API 获取。

触摸传感器信号

### 触摸传感器信号阈值

触摸传感器阈值支持重新配置，可用于确定触摸传感器状态。当平滑信号和基准信号间的差值大于阈值，即 `（平滑信号 - 基准信号）> 信号阈值` 时，触摸通道状态改变，并触发触摸中断。

触摸传感器信号阈值

### 灵敏度

触摸传感器的一个重要性能参数，该值越大，表明触摸传感器越灵敏。可以通过以下公式计算：

\[Sensitivity = \frac{Signal_{press} - Signal_{release}}{Signal_{release}} = \frac{Signal_{delta}}{Signal_{benchmark}}\]

### 防水性能

防水性能是触摸传感器的硬件功能，包括防护传感器和屏蔽传感器（始终连接到通道 14），可以抵御一定程度的水滴影响，并检测水流。

### 触摸按键

触摸按键占用触摸传感器的一个通道，外观如下图所示：

触摸按键

### 触摸滑条

触摸滑条占用触摸传感器的多个通道（至少三个），占用的通道越多，滑条的采样分辨率和准确度越高。触摸滑条外观如下图所示：

触摸滑条

### 触摸矩阵

触摸矩阵按键占用触摸传感器的多个通道（至少 2 + 2 = 4 个通道），它支持通过较少通道获取更多按键。ESP32-S2 最多支持 49 个按键。触摸矩阵按键外观如下图所示：

触摸矩阵

## 使用触摸元件库

使用触摸元件库时，请遵循以下初始化流程：

1. 调用 `touch_element_install()`，初始化触摸元件库。

2. 调用 `touch_xxxx_install()`，初始化触摸元件（按键、滑条等）。

3. 调用 `touch_xxxx_create()`，创建新元件实例。

4. 调用 `touch_xxxx_subscribe_event()`，订阅事件通知。

5. 调用 `touch_xxxx_set_dispatch_method()`，选择事件通知的传递方式。

6. 选择使用回调函数传递事件通知时，调用 `touch_xxxx_set_callback()`，设置事件处理函数。

7. 调用 `touch_element_start()`，启用触摸元件库。

8. 选择使用回调函数传递事件通知时，若事件发生，驱动核心会调用回调函数，你无需做任何处理；选择使用事件任务传递事件通知时，你需要创建一个事件任务，并调用 `touch_element_message_receive()`，循环获取信息。

9. （可选）如果要暂停触摸元件的实时系统，或因某种原因无法获取触摸元件信息，应调用 `touch_element_stop()`，暂停触摸元件系统，然后再次调用 `touch_element_start()` 恢复系统。

上述流程代码如下所示：

    static touch_xxx_handle_t element_handle; //声明一个触摸元件句柄

    //定义订阅的事件处理函数
    void event_handler(touch_xxx_handle_t out_handle, touch_xxx_message_t out_message, void *arg)
    {
        //事件处理逻辑
    }

    void app_main()
    {
        //使用默认初始化器配置触摸元件库
        touch_elem_global_config_t global_config = TOUCH_ELEM_GLOBAL_DEFAULT_CONFIG();
        touch_element_install(&global_config);

        //使用默认初始化器配置触摸元件
        touch_xxx_global_config_t elem_global_config = TOUCH_XXXX_GLOBAL_DEFAULT_CONFIG();
        touch_xxx_install(&elem_global_config);

        //创建新的实例
        touch_xxx_config_t element_config = {
            ...
            ...
        };
        touch_xxx_create(&element_config, &element_handle);

        //通过事件掩码订阅特定事件
        touch_xxx_subscribe_event(element_handle, TOUCH_ELEM_EVENT_ON_PRESS | TOUCH_ELEM_EVENT_ON_RELEASE, NULL);

        //选择使用回调函数传递事件通知
        touch_xxx_set_dispatch_method(element_handle, TOUCH_ELEM_DISP_CALLBACK);

        //注册回调函数
        touch_xxx_set_callback(element_handle, event_handler);

        //启用触摸元件库处理
        touch_element_start();
    }

### 初始化

1. 要初始化触摸元件库，请调用 `touch_element_install()` 函数，并传递一个 `touch_elem_global_config_t` 类型的实例作为参数，以配置触摸传感器外设和触摸元件库。默认初始化器位于 `TOUCH_ELEM_GLOBAL_DEFAULT_CONFIG()` 中，此默认配置适用于多数常见应用场景。建议在充分了解触摸传感器外设前，不要更改默认配置，以免影响系统。

2. 要初始化特定的触摸元件，需要调用其构造函数 `touch_xxxx_install()`。在调用此构造函数前，所有触摸元件都不会工作，以节省内存。因此，若要设置所需元件，需要为每个要使用的触摸元件分别调用构造函数。

### 启动触摸元件实例

1. 要创建新的触摸元件实例，请调用 `touch_xxxx_create()`，选择一个通道，并将其 灵敏度 传递给新的元件实例。

2. 要订阅事件通知，请调用 `touch_xxxx_subscribe_event()`。触摸元件库提供了多个事件，事件掩码存放在 components/touch_element/include/touch_element/touch_element.h 中。通过使用这些事件掩码，可以订阅单个特定事件，或将单个事件组合在一起，订阅多个事件。

3. 要配置传递事件通知的方式，请调用 `touch_xxxx_subscribe_event()`。触摸元件库提供了两种方式: `TOUCH_ELEM_DISP_EVENT` 和 `TOUCH_ELEM_DISP_CALLBACK`，支持以不同方式获取并处理触摸元件信息。

### 事件处理

如果配置的是 `TOUCH_ELEM_DISP_EVENT`，需要启用一个事件处理任务获取触摸元件信息。调用 `touch_element_message_receive()` 可以获取所有元件的原始信息，随后通过调用相应的信息解码器 `touch_xxxx_get_message()`，提取特定类型元件的信息，获取有关触摸操作的详细数据。如果配置的是 `TOUCH_ELEM_DISP_CALLBACK`，在触摸元件开始工作之前，需要调用 `touch_xxxx_set_callback()`，传递一个事件处理函数，有关触摸操作的详细数据都会传递到该事件处理函数。

警告

由于事件处理函数在元件库的核心运行，即在 esp-timer 回调中运行，请避免执行可能导致阻塞或延迟的操作，如调用 `vTaskDelay()`。

事件处理过程代码如下所示：

    /* ---------------------------------------------- TOUCH_ELEM_DISP_EVENT ----------------------------------------------- */
    void element_handler_task(void *arg)
    {
        touch_elem_message_t element_message;
        while(1) {
            if (touch_element_message_receive(&element_message, Timeout) == ESP_OK) {
                const touch_xxxx_message_t *extracted_message = touch_xxxx_get_message(&element_message); //信息解码
                ... //事件处理逻辑
            }
        }
    }
    void app_main()
    {
        ...

        touch_xxxx_set_dispatch_method(element_handle, TOUCH_ELEM_DISP_EVENT);  //设置以 TOUCH_ELEM_DISP_EVENT 传递事件通知
        xTaskCreate(&element_handler_task, "element_handler_task", 2048, NULL, 5, NULL);  //创建一个事件处理任务

        ...
    }
    /* -------------------------------------------------------------------------------------------------------------- */

    ...
    /* ---------------------------------------------- TOUCH_ELEM_DISP_CALLBACK ----------------------------------------------- */
    void element_handler(touch_xxxx_handle_t out_handle, touch_xxxx_message_t out_message, void *arg)
    {
        //事件处理逻辑
    }

    void app_main()
    {
        ...

        touch_xxxx_set_dispatch_method(element_handle, TOUCH_ELEM_DISP_CALLBACK);  //设置以 ``TOUCH_ELEM_DISP_CALLBACK`` 传递事件通知
        touch_xxxx_set_callback(element_handle, element_handler);  //注册事件处理函数

        ...
    }
    /* -------------------------------------------------------------------------------------------------------------- */

### 使用防水功能

1. 一旦初始化触摸元件的防水功能，防水屏蔽传感器会始终处于开启状态。防水屏蔽传感器为可选项，如果不需要，可以通过配置结构体，将 `TOUCH_WATERPROOF_GUARD_NOUSE` 传递给 `touch_element_waterproof_install()`。

2. 要关联触摸元件与防护传感器，请调用 `touch_element_waterproof_add()`，将触摸元件句柄添加到触摸元件防水功能的掩码列表中。触摸元件与防护传感器关联后，水流触发防护传感器时会关闭触摸元件，为其提供保护。

查看使用触摸元件防水功能的示例代码，请前往 ESP-IDF 示例的 peripherals/touch_sensor/touch_element/touch_element_waterproof 目录。

配置防水功能的代码如下所示：

    void app_main()
    {
        ...

        touch_xxxx_install();                 //初始化实例（按键、滑条等）
        touch_xxxx_create(&element_handle);  //创建新的触摸元件

        ...

        touch_element_waterproof_install();              //初始化触摸元件防水功能
        touch_element_waterproof_add(element_handle);   //关联触摸元件与防护传感器

        ...
    }

### 从 Light/Deep-sleep 模式唤醒

仅触摸按键可配置为唤醒源。

使用触摸传感器，可以唤醒从 Light-sleep 或 Deep-sleep 模式中唤醒芯片。在 Light-sleep 模式下，任何已安装的触摸按键都可以唤醒芯片。但在 Deep-sleep 模式下，只有睡眠按键可以唤醒芯片，触摸传感器还会立即进行校准。如果手指没有及时离开，可能导致校准参考值出错。尽管在手指离开后，校准参考值会自行恢复，不会影响驱动逻辑，但如果你不想在从 Deep-sleep 模式唤醒时看到错误的校准参考值，可以调用 `touch_element_sleep_enable_wakeup_calibration()`，禁用唤醒校准功能。

    void app_main()
    {
        ...
        touch_element_install();
        touch_button_install();                 //初始化触摸按键
        touch_button_create(&element_handle);  //创建新的触摸元件

        ...

        // ESP_ERROR_CHECK(touch_element_enable_light_sleep(&sleep_config));
        ESP_ERROR_CHECK(touch_element_enable_deep_sleep(button_handle[0], &sleep_config));
        // ESP_ERROR_CHECK(touch_element_sleep_enable_wakeup_calibration(button_handle[0], false)); //（可选）禁用唤醒校准，防止基准值更新为错误值

        touch_element_start();

        ...
    }

## 应用示例

- peripherals/touch_sensor/touch_element/touch_element_waterproof 演示了如何使用触摸元件库来设置带有防水保护的电容式触摸传感器。

- peripherals/touch_sensor/touch_element/touch_slider 演示了如何使用触摸元件库来设置和操作触摸滑条。

- peripherals/touch_sensor/touch_element/touch_elements_combination 演示了如何使用触摸元件库来设置多种类型的触摸元件，并在一个任务中处理所有的事件消息。

- peripherals/touch_sensor/touch_element/touch_matrix 演示了如何通过触摸元件库，在 ESP32-S2 开发板上使用电容式触摸传感器来构建触摸矩阵。

- peripherals/touch_sensor/touch_element/touch_button 演示了如何通过触摸元件库，在 ESP32-S2 开发板上设置和使用触摸按键。

## API 参考 - 触摸元件核心

### Header File

- components/touch_element/include/touch_element/touch_element.h

- This header file can be included with:

  >     #include "touch_element/touch_element.h"

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

  >     REQUIRES touch_element

  > or

  >     PRIV_REQUIRES touch_element

### Functions

esp_err_t touch_element_install(const touch_elem_global_config_t *global_config)

  Touch element processing initialization.

  备注

  To reinitialize the touch element object, call touch_element_uninstall() first

  参数:

    global_config -- [in] Global initialization configuration structure

  返回:

    - ESP_OK: Successfully initialized

    - ESP_ERR_INVALID_ARG: Invalid argument

    - ESP_ERR_NO_MEM: Insufficient memory

    - ESP_ERR_INVALID_STATE: Touch element is already initialized

    - Others: Unknown touch driver layer or lower layer error

esp_err_t touch_element_start(void)

  Touch element processing start.

  This function starts the touch element processing system

  备注

  This function must only be called after all the touch element instances finished creating

  返回:

    - ESP_OK: Successfully started to process

    - Others: Unknown touch driver layer or lower layer error

esp_err_t touch_element_stop(void)

  Touch element processing stop.

  This function stops the touch element processing system

  备注

  This function must be called before changing the system (hardware, software) parameters

  返回:

    - ESP_OK: Successfully stopped to process

    - Others: Unknown touch driver layer or lower layer error

void touch_element_uninstall(void)

  Release resources allocated using touch_element_install.

esp_err_t touch_element_message_receive(touch_elem_message_t *element_message, uint32_t ticks_to_wait)

  Get current event message of touch element instance.

  This function will receive the touch element message (handle, event type, etc...) from te_event_give(). It will block until a touch element event or a timeout occurs.

  参数:

    - element_message -- [out] Touch element event message structure

    - ticks_to_wait -- [in] Number of FreeRTOS ticks to block for waiting event

  返回:

    - ESP_OK: Successfully received touch element event

    - ESP_ERR_INVALID_STATE: Touch element library is not initialized

    - ESP_ERR_INVALID_ARG: element_message is null

    - ESP_ERR_TIMEOUT: Timed out waiting for event

esp_err_t touch_element_waterproof_install(const touch_elem_waterproof_config_t *waterproof_config)

  Touch element waterproof initialization.

  This function enables the hardware waterproof, then touch element system uses Shield-Sensor and Guard-Sensor to mitigate the influence of water-drop and water-stream.

  备注

  If the waterproof function is used, Shield-Sensor can not be disabled and it will use channel 14 as it's internal channel. Hence, the user can not use channel 14 for another propose. And the Guard-Sensor is not necessary since it is optional.

  备注

  Shield-Sensor: It always uses channel 14 as the shield channel, so user must connect the channel 14 and Shield-Layer in PCB since it will generate a synchronous signal automatically

  备注

  Guard-Sensor: This function is optional. If used, the user must connect the guard channel and Guard-Ring in PCB. Any channels user wants to protect should be added into Guard-Ring in PCB.

  参数:

    waterproof_config -- [in] Waterproof configuration

  返回:

    - ESP_OK: Successfully initialized

    - ESP_ERR_INVALID_STATE: Touch element library is not initialized

    - ESP_ERR_INVALID_ARG: waterproof_config is null or invalid Guard-Sensor channel

    - ESP_ERR_NO_MEM: Insufficient memory

void touch_element_waterproof_uninstall(void)

  Release resources allocated using touch_element_waterproof_install()

esp_err_t touch_element_waterproof_add(touch_elem_handle_t element_handle)

  Add a masked handle to protect while Guard-Sensor has been triggered.

  This function will add an application handle (button, slider, etc...) as a masked handle. While Guard-Sensor has been triggered, waterproof function will start working and lock the application internal state. While the influence of water is reduced, the application will be unlock and reset into IDLE state.

  备注

  The waterproof protection logic must follow the real circuit in PCB, it means that all of the channels inside the input handle must be inside the Guard-Ring in real circuit.

  参数:

    element_handle -- [in] Touch element instance handle

  返回:

    - ESP_OK: Successfully added a masked handle

    - ESP_ERR_INVALID_STATE: Waterproof is not initialized

    - ESP_ERR_INVALID_ARG: element_handle is null

esp_err_t touch_element_waterproof_remove(touch_elem_handle_t element_handle)

  Remove a masked handle to protect.

  This function will remove an application handle from masked handle table.

  参数:

    element_handle -- [in] Touch element instance handle

  返回:

    - ESP_OK: Successfully removed a masked handle

    - ESP_ERR_INVALID_STATE: Waterproof is not initialized

    - ESP_ERR_INVALID_ARG: element_handle is null

    - ESP_ERR_NOT_FOUND: Failed to search element_handle from waterproof mask_handle list

esp_err_t touch_element_enable_light_sleep(const touch_elem_sleep_config_t *sleep_config)

  Touch element light sleep initialization.

  备注

  It should be called after touch button element installed. Any of installed touch element can wake up from the light sleep

  参数:

    sleep_config -- [in] Sleep configurations, set NULL to use default config

  返回:

    - ESP_OK: Successfully initialized touch sleep

    - ESP_ERR_INVALID_STATE: Touch element is not installed or touch sleep has been installed

    - ESP_ERR_INVALID_ARG: inputted argument is NULL

    - ESP_ERR_NO_MEM: no memory for touch sleep struct

    - ESP_ERR_NOT_SUPPORTED: inputted wakeup_elem_handle is not touch_button_handle_t type, currently only touch_button_handle_t supported

esp_err_t touch_element_disable_light_sleep(void)

  Release the resources that allocated by touch_element_enable_deep_sleep()

  This function will also disable the touch sensor to wake up the device

  返回:

    - ESP_OK: uninstall success

    - ESP_ERR_INVALID_STATE: touch sleep has not been installed

esp_err_t touch_element_enable_deep_sleep(touch_elem_handle_t wakeup_elem_handle, const touch_elem_sleep_config_t *sleep_config)

  Touch element deep sleep initialization.

  This function will enable the device wake-up from deep sleep or light sleep by touch sensor

  备注

  It should be called after touch button element installed. Only one touch button can be registered as the deep sleep wake-up button

  参数:

    - wakeup_elem_handle -- [in] Touch element instance handle for waking up the device, only support button element

    - sleep_config -- [in] Sleep configurations, set NULL to use default config

  返回:

    - ESP_OK: Successfully initialized touch sleep

    - ESP_ERR_INVALID_STATE: Touch element is not installed or touch sleep has been installed

    - ESP_ERR_INVALID_ARG: inputted argument is NULL

    - ESP_ERR_NO_MEM: no memory for touch sleep struct

    - ESP_ERR_NOT_SUPPORTED: inputted wakeup_elem_handle is not touch_button_handle_t type, currently only touch_button_handle_t supported

esp_err_t touch_element_disable_deep_sleep(void)

  Release the resources that allocated by touch_element_enable_deep_sleep()

  This function will also disable the touch sensor to wake up the device

  返回:

    - ESP_OK: uninstall success

    - ESP_ERR_INVALID_STATE: touch sleep has not been installed

esp_err_t touch_element_sleep_enable_wakeup_calibration(touch_elem_handle_t element_handle, bool en)

  Touch element wake up calibrations.

  This function will also disable the touch sensor to wake up the device

  返回:

    - ESP_OK: uninstall success

    - ESP_ERR_INVALID_STATE: touch sleep has not been installed

### Structures

struct touch_elem_sw_config_t

  Touch element software configuration.

  Public Members

  float waterproof_threshold_divider

    Waterproof guard channel threshold divider.

  uint8_t processing_period

    Processing period(ms)

  uint8_t intr_message_size

    Interrupt message queue size.

  uint8_t event_message_size

    Event message queue size.

struct touch_elem_hw_config_t

  Touch element hardware configuration.

  Public Members

  touch_high_volt_t upper_voltage

    Touch sensor channel upper charge voltage.

  touch_volt_atten_t voltage_attenuation

    Touch sensor channel upper charge voltage attenuation (Diff voltage is upper - attenuation - lower)

  touch_low_volt_t lower_voltage

    Touch sensor channel lower charge voltage.

  touch_pad_conn_type_t suspend_channel_polarity

    Suspend channel polarity (High Impedance State or GND)

  touch_pad_denoise_grade_t denoise_level

    Internal de-noise level.

  touch_pad_denoise_cap_t denoise_equivalent_cap

    Internal de-noise channel (Touch channel 0) equivalent capacitance.

  touch_smooth_mode_t smooth_filter_mode

    Smooth value filter mode (This only apply to touch_pad_filter_read_smooth())

  touch_filter_mode_t benchmark_filter_mode

    Benchmark filter mode.

  uint16_t sample_count

    The count of sample in each measurement of touch sensor.

  uint16_t sleep_cycle

    The cycle (RTC slow clock) of sleep.

  uint8_t benchmark_debounce_count

    Benchmark debounce count.

  uint8_t benchmark_calibration_threshold

    Benchmark calibration threshold.

  uint8_t benchmark_jitter_step

    Benchmark jitter filter step (This only works at while benchmark filter mode is jitter filter)

struct touch_elem_global_config_t

  Touch element global configuration passed to touch_element_install.

  Public Members

  touch_elem_hw_config_t hardware

    Hardware configuration.

  touch_elem_sw_config_t software

    Software configuration.

struct touch_elem_waterproof_config_t

  Touch element waterproof configuration passed to touch_element_waterproof_install.

  Public Members

  touch_pad_t guard_channel

    Waterproof Guard-Sensor channel number (index)

  float guard_sensitivity

    Waterproof Guard-Sensor sensitivity.

struct touch_elem_sleep_config_t

  Touch element sleep configuration passed to touch_element_enable_light_sleep or touch_element_enable_deep_sleep.

  Public Members

  uint16_t sample_count

    scan times in every measurement, normally equal to the 'sample_count' field in 'touch_elem_hw_config_t'.

  uint16_t sleep_cycle

    sleep_cycle decide the interval between two measurements， t_sleep = sleep_cycle / (RTC_SLOW_CLK frequency), normally equal to the 'sleep_cycle' field in 'touch_elem_hw_config_t'.

struct touch_elem_message_t

  Touch element event message type from touch_element_message_receive()

  Public Members

  touch_elem_handle_t handle

    Touch element handle.

  touch_elem_type_t element_type

    Touch element type.

  void *arg

    User input argument.

  uint8_t child_msg[8]

    Encoded message.

### Macros

TOUCH_ELEM_GLOBAL_DEFAULT_CONFIG()

TOUCH_ELEM_EVENT_NONE

  None event.

TOUCH_ELEM_EVENT_ON_PRESS

  On Press event.

TOUCH_ELEM_EVENT_ON_RELEASE

  On Release event.

TOUCH_ELEM_EVENT_ON_LONGPRESS

  On LongPress event.

TOUCH_ELEM_EVENT_ON_CALCULATION

  On Calculation event.

TOUCH_WATERPROOF_GUARD_NOUSE

  Waterproof no use guard sensor.

### Type Definitions

typedef void *touch_elem_handle_t

  Touch element handle type.

typedef uint32_t touch_elem_event_t

  Touch element event type.

### Enumerations

enum touch_elem_type_t

  Touch element handle type.

  Values:

  enumerator TOUCH_ELEM_TYPE_BUTTON

    Touch element button.

  enumerator TOUCH_ELEM_TYPE_SLIDER

    Touch element slider.

  enumerator TOUCH_ELEM_TYPE_MATRIX

    Touch element matrix button.

enum touch_elem_dispatch_t

  Touch element event dispatch methods (event queue/callback)

  Values:

  enumerator TOUCH_ELEM_DISP_EVENT

    Event queue dispatch.

  enumerator TOUCH_ELEM_DISP_CALLBACK

    Callback dispatch.

  enumerator TOUCH_ELEM_DISP_MAX

## API 参考 - 触摸按键

### Header File

- components/touch_element/include/touch_element/touch_button.h

- This header file can be included with:

  >     #include "touch_element/touch_button.h"

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

  >     REQUIRES touch_element

  > or

  >     PRIV_REQUIRES touch_element

### Functions

esp_err_t touch_button_install(const touch_button_global_config_t *global_config)

  Touch Button initialize.

  This function initializes touch button global and acts on all touch button instances.

  参数:

    global_config -- [in] Button object initialization configuration

  返回:

    - ESP_OK: Successfully initialized touch button

    - ESP_ERR_INVALID_STATE: Touch element library was not initialized

    - ESP_ERR_INVALID_ARG: button_init is NULL

    - ESP_ERR_NO_MEM: Insufficient memory

void touch_button_uninstall(void)

  Release resources allocated using touch_button_install()

esp_err_t touch_button_create(const touch_button_config_t *button_config, touch_button_handle_t *button_handle)

  Create a new touch button instance.

  备注

  The sensitivity has to be explored in experiments, Sensitivity = (Raw(touch) - Raw(release)) / Raw(release) * 100%

  参数:

    - button_config -- [in] Button configuration

    - button_handle -- [out] Button handle

  返回:

    - ESP_OK: Successfully create touch button

    - ESP_ERR_INVALID_STATE: Touch button driver was not initialized

    - ESP_ERR_NO_MEM: Insufficient memory

    - ESP_ERR_INVALID_ARG: Invalid configuration struct or arguments is NULL

esp_err_t touch_button_delete(touch_button_handle_t button_handle)

  Release resources allocated using touch_button_create()

  参数:

    button_handle -- [in] Button handle

  返回:

    - ESP_OK: Successfully released resources

    - ESP_ERR_INVALID_STATE: Touch button driver was not initialized

    - ESP_ERR_INVALID_ARG: button_handle is null

    - ESP_ERR_NOT_FOUND: Input handle is not a button handle

esp_err_t touch_button_subscribe_event(touch_button_handle_t button_handle, uint32_t event_mask, void *arg)

  Touch button subscribes event.

  This function uses event mask to subscribe to touch button events, once one of the subscribed events occurs, the event message could be retrieved by calling touch_element_message_receive() or input callback routine.

  备注

  Touch button only support three kind of event masks, they are TOUCH_ELEM_EVENT_ON_PRESS, TOUCH_ELEM_EVENT_ON_RELEASE, TOUCH_ELEM_EVENT_ON_LONGPRESS. You can use those event masks in any combination to achieve the desired effect.

  参数:

    - button_handle -- [in] Button handle

    - event_mask -- [in] Button subscription event mask

    - arg -- [in] User input argument

  返回:

    - ESP_OK: Successfully subscribed touch button event

    - ESP_ERR_INVALID_STATE: Touch button driver was not initialized

    - ESP_ERR_INVALID_ARG: button_handle is null or event is not supported

esp_err_t touch_button_set_dispatch_method(touch_button_handle_t button_handle, touch_elem_dispatch_t dispatch_method)

  Touch button set dispatch method.

  This function sets a dispatch method that the driver core will use this method as the event notification method.

  参数:

    - button_handle -- [in] Button handle

    - dispatch_method -- [in] Dispatch method (By callback/event)

  返回:

    - ESP_OK: Successfully set dispatch method

    - ESP_ERR_INVALID_STATE: Touch button driver was not initialized

    - ESP_ERR_INVALID_ARG: button_handle is null or dispatch_method is invalid

esp_err_t touch_button_set_callback(touch_button_handle_t button_handle, touch_button_callback_t button_callback)

  Touch button set callback.

  This function sets a callback routine into touch element driver core, when the subscribed events occur, the callback routine will be called.

  备注

  Button message will be passed from the callback function and it will be destroyed when the callback function return.

  警告

  Since this input callback routine runs on driver core (esp-timer callback routine), it should not do something that attempts to Block, such as calling vTaskDelay().

  参数:

    - button_handle -- [in] Button handle

    - button_callback -- [in] User input callback

  返回:

    - ESP_OK: Successfully set callback

    - ESP_ERR_INVALID_STATE: Touch button driver was not initialized

    - ESP_ERR_INVALID_ARG: button_handle or button_callback is null

esp_err_t touch_button_set_longpress(touch_button_handle_t button_handle, uint32_t threshold_time)

  Touch button set long press trigger time.

  This function sets the threshold time (ms) for a long press event. If a button is pressed and held for a period of time that exceeds the threshold time, a long press event is triggered.

  参数:

    - button_handle -- [in] Button handle

    - threshold_time -- [in] Threshold time (ms) of long press event occur

  返回:

    - ESP_OK: Successfully set the threshold time of long press event

    - ESP_ERR_INVALID_STATE: Touch button driver was not initialized

    - ESP_ERR_INVALID_ARG: button_handle is null or time (ms) is not lager than 0

const touch_button_message_t *touch_button_get_message(const touch_elem_message_t *element_message)

  Touch button get message.

  This function decodes the element message from touch_element_message_receive() and return a button message pointer.

  参数:

    element_message -- [in] element message

  返回:

    Touch button message pointer

### Structures

struct touch_button_global_config_t

  Button initialization configuration passed to touch_button_install.

  Public Members

  float threshold_divider

    Button channel threshold divider.

  uint32_t default_lp_time

    Button default LongPress event time (ms)

struct touch_button_config_t

  Button configuration (for new instance) passed to touch_button_create()

  Public Members

  touch_pad_t channel_num

    Button channel number (index)

  float channel_sens

    Button channel sensitivity.

struct touch_button_message_t

  Button message type.

  Public Members

  touch_button_event_t event

    Button event.

### Macros

TOUCH_BUTTON_GLOBAL_DEFAULT_CONFIG()

### Type Definitions

typedef touch_elem_handle_t touch_button_handle_t

  Button handle.

typedef void (*touch_button_callback_t)(touch_button_handle_t, touch_button_message_t*, void*)

  Button callback type.

### Enumerations

enum touch_button_event_t

  Button event type.

  Values:

  enumerator TOUCH_BUTTON_EVT_ON_PRESS

    Button Press event.

  enumerator TOUCH_BUTTON_EVT_ON_RELEASE

    Button Release event.

  enumerator TOUCH_BUTTON_EVT_ON_LONGPRESS

    Button LongPress event.

  enumerator TOUCH_BUTTON_EVT_MAX

## API 参考 - 触摸滑条

### Header File

- components/touch_element/include/touch_element/touch_slider.h

- This header file can be included with:

  >     #include "touch_element/touch_slider.h"

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

  >     REQUIRES touch_element

  > or

  >     PRIV_REQUIRES touch_element

### Functions

esp_err_t touch_slider_install(const touch_slider_global_config_t *global_config)

  Touch slider initialize.

  This function initializes touch slider object and acts on all touch slider instances.

  参数:

    global_config -- [in] Touch slider global initialization configuration

  返回:

    - ESP_OK: Successfully initialized touch slider

    - ESP_ERR_INVALID_STATE: Touch element library was not initialized

    - ESP_ERR_INVALID_ARG: slider_init is NULL

    - ESP_ERR_NO_MEM: Insufficient memory

void touch_slider_uninstall(void)

  Release resources allocated using touch_slider_install()

esp_err_t touch_slider_create(const touch_slider_config_t *slider_config, touch_slider_handle_t *slider_handle)

  Create a new touch slider instance.

  备注

  The index of Channel array and sensitivity array must be one-one correspondence

  参数:

    - slider_config -- [in] Slider configuration

    - slider_handle -- [out] Slider handle

  返回:

    - ESP_OK: Successfully create touch slider

    - ESP_ERR_INVALID_STATE: Touch slider driver was not initialized

    - ESP_ERR_INVALID_ARG: Invalid configuration struct or arguments is NULL

    - ESP_ERR_NO_MEM: Insufficient memory

esp_err_t touch_slider_delete(touch_slider_handle_t slider_handle)

  Release resources allocated using touch_slider_create.

  参数:

    slider_handle -- [in] Slider handle

  返回:

    - ESP_OK: Successfully released resources

    - ESP_ERR_INVALID_STATE: Touch slider driver was not initialized

    - ESP_ERR_INVALID_ARG: slider_handle is null

    - ESP_ERR_NOT_FOUND: Input handle is not a slider handle

esp_err_t touch_slider_subscribe_event(touch_slider_handle_t slider_handle, uint32_t event_mask, void *arg)

  Touch slider subscribes event.

  This function uses event mask to subscribe to touch slider events, once one of the subscribed events occurs, the event message could be retrieved by calling touch_element_message_receive() or input callback routine.

  备注

  Touch slider only support three kind of event masks, they are TOUCH_ELEM_EVENT_ON_PRESS, TOUCH_ELEM_EVENT_ON_RELEASE. You can use those event masks in any combination to achieve the desired effect.

  参数:

    - slider_handle -- [in] Slider handle

    - event_mask -- [in] Slider subscription event mask

    - arg -- [in] User input argument

  返回:

    - ESP_OK: Successfully subscribed touch slider event

    - ESP_ERR_INVALID_STATE: Touch slider driver was not initialized

    - ESP_ERR_INVALID_ARG: slider_handle is null or event is not supported

esp_err_t touch_slider_set_dispatch_method(touch_slider_handle_t slider_handle, touch_elem_dispatch_t dispatch_method)

  Touch slider set dispatch method.

  This function sets a dispatch method that the driver core will use this method as the event notification method.

  参数:

    - slider_handle -- [in] Slider handle

    - dispatch_method -- [in] Dispatch method (By callback/event)

  返回:

    - ESP_OK: Successfully set dispatch method

    - ESP_ERR_INVALID_STATE: Touch slider driver was not initialized

    - ESP_ERR_INVALID_ARG: slider_handle is null or dispatch_method is invalid

esp_err_t touch_slider_set_callback(touch_slider_handle_t slider_handle, touch_slider_callback_t slider_callback)

  Touch slider set callback.

  This function sets a callback routine into touch element driver core, when the subscribed events occur, the callback routine will be called.

  备注

  Slider message will be passed from the callback function and it will be destroyed when the callback function return.

  警告

  Since this input callback routine runs on driver core (esp-timer callback routine), it should not do something that attempts to Block, such as calling vTaskDelay().

  参数:

    - slider_handle -- [in] Slider handle

    - slider_callback -- [in] User input callback

  返回:

    - ESP_OK: Successfully set callback

    - ESP_ERR_INVALID_STATE: Touch slider driver was not initialized

    - ESP_ERR_INVALID_ARG: slider_handle or slider_callback is null

const touch_slider_message_t *touch_slider_get_message(const touch_elem_message_t *element_message)

  Touch slider get message.

  This function decodes the element message from touch_element_message_receive() and return a slider message pointer.

  参数:

    element_message -- [in] element message

  返回:

    Touch slider message pointer

### Structures

struct touch_slider_global_config_t

  Slider initialization configuration passed to touch_slider_install.

  Public Members

  float quantify_lower_threshold

    Slider signal quantification threshold.

  float threshold_divider

    Slider channel threshold divider.

  uint16_t filter_reset_time

    Slider position filter reset time (Unit is esp_timer callback tick)

  uint16_t benchmark_update_time

    Slider benchmark update time (Unit is esp_timer callback tick)

  uint8_t position_filter_size

    Moving window filter buffer size.

  uint8_t position_filter_factor

    One-order IIR filter factor.

  uint8_t calculate_channel_count

    The number of channels which will take part in calculation.

struct touch_slider_config_t

  Slider configuration (for new instance) passed to touch_slider_create()

  Public Members

  const touch_pad_t *channel_array

    Slider channel array.

  const float *sensitivity_array

    Slider channel sensitivity array.

  uint8_t channel_num

    The number of slider channels.

  uint8_t position_range

    The right region of touch slider position range, [0, position_range (less than or equal to 255)].

struct touch_slider_message_t

  Slider message type.

  Public Members

  touch_slider_event_t event

    Slider event.

  touch_slider_position_t position

    Slider position.

### Macros

TOUCH_SLIDER_GLOBAL_DEFAULT_CONFIG()

### Type Definitions

typedef uint32_t touch_slider_position_t

  Slider position data type.

typedef touch_elem_handle_t touch_slider_handle_t

  Slider instance handle.

typedef void (*touch_slider_callback_t)(touch_slider_handle_t, touch_slider_message_t*, void*)

  Slider callback type.

### Enumerations

enum touch_slider_event_t

  Slider event type.

  Values:

  enumerator TOUCH_SLIDER_EVT_ON_PRESS

    Slider on Press event.

  enumerator TOUCH_SLIDER_EVT_ON_RELEASE

    Slider on Release event.

  enumerator TOUCH_SLIDER_EVT_ON_CALCULATION

    Slider on Calculation event.

  enumerator TOUCH_SLIDER_EVT_MAX

## API 参考 - 触摸矩阵

### Header File

- components/touch_element/include/touch_element/touch_matrix.h

- This header file can be included with:

  >     #include "touch_element/touch_matrix.h"

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

  >     REQUIRES touch_element

  > or

  >     PRIV_REQUIRES touch_element

### Functions

esp_err_t touch_matrix_install(const touch_matrix_global_config_t *global_config)

  Touch matrix button initialize.

  This function initializes touch matrix button object and acts on all touch matrix button instances.

  参数:

    global_config -- [in] Touch matrix global initialization configuration

  返回:

    - ESP_OK: Successfully initialized touch matrix button

    - ESP_ERR_INVALID_STATE: Touch element library was not initialized

    - ESP_ERR_INVALID_ARG: matrix_init is NULL

    - ESP_ERR_NO_MEM: Insufficient memory

void touch_matrix_uninstall(void)

  Release resources allocated using touch_matrix_install()

esp_err_t touch_matrix_create(const touch_matrix_config_t *matrix_config, touch_matrix_handle_t *matrix_handle)

  Create a new touch matrix button instance.

  备注

  Channel array and sensitivity array must be one-one correspondence in those array

  备注

  Touch matrix button does not support Multi-Touch now

  参数:

    - matrix_config -- [in] Matrix button configuration

    - matrix_handle -- [out] Matrix button handle

  返回:

    - ESP_OK: Successfully create touch matrix button

    - ESP_ERR_INVALID_STATE: Touch matrix driver was not initialized

    - ESP_ERR_INVALID_ARG: Invalid configuration struct or arguments is NULL

    - ESP_ERR_NO_MEM: Insufficient memory

esp_err_t touch_matrix_delete(touch_matrix_handle_t matrix_handle)

  Release resources allocated using touch_matrix_create()

  参数:

    matrix_handle -- [in] Matrix handle

  返回:

    - ESP_OK: Successfully released resources

    - ESP_ERR_INVALID_STATE: Touch matrix driver was not initialized

    - ESP_ERR_INVALID_ARG: matrix_handle is null

    - ESP_ERR_NOT_FOUND: Input handle is not a matrix handle

esp_err_t touch_matrix_subscribe_event(touch_matrix_handle_t matrix_handle, uint32_t event_mask, void *arg)

  Touch matrix button subscribes event.

  This function uses event mask to subscribe to touch matrix events, once one of the subscribed events occurs, the event message could be retrieved by calling touch_element_message_receive() or input callback routine.

  备注

  Touch matrix button only support three kind of event masks, they are TOUCH_ELEM_EVENT_ON_PRESS, TOUCH_ELEM_EVENT_ON_RELEASE, TOUCH_ELEM_EVENT_ON_LONGPRESS. You can use those event masks in any combination to achieve the desired effect.

  参数:

    - matrix_handle -- [in] Matrix handle

    - event_mask -- [in] Matrix subscription event mask

    - arg -- [in] User input argument

  返回:

    - ESP_OK: Successfully subscribed touch matrix event

    - ESP_ERR_INVALID_STATE: Touch matrix driver was not initialized

    - ESP_ERR_INVALID_ARG: matrix_handle is null or event is not supported

esp_err_t touch_matrix_set_dispatch_method(touch_matrix_handle_t matrix_handle, touch_elem_dispatch_t dispatch_method)

  Touch matrix button set dispatch method.

  This function sets a dispatch method that the driver core will use this method as the event notification method.

  参数:

    - matrix_handle -- [in] Matrix button handle

    - dispatch_method -- [in] Dispatch method (By callback/event)

  返回:

    - ESP_OK: Successfully set dispatch method

    - ESP_ERR_INVALID_STATE: Touch matrix driver was not initialized

    - ESP_ERR_INVALID_ARG: matrix_handle is null or dispatch_method is invalid

esp_err_t touch_matrix_set_callback(touch_matrix_handle_t matrix_handle, touch_matrix_callback_t matrix_callback)

  Touch matrix button set callback.

  This function sets a callback routine into touch element driver core, when the subscribed events occur, the callback routine will be called.

  备注

  Matrix message will be passed from the callback function and it will be destroyed when the callback function return.

  警告

  Since this input callback routine runs on driver core (esp-timer callback routine), it should not do something that attempts to Block, such as calling vTaskDelay().

  参数:

    - matrix_handle -- [in] Matrix button handle

    - matrix_callback -- [in] User input callback

  返回:

    - ESP_OK: Successfully set callback

    - ESP_ERR_INVALID_STATE: Touch matrix driver was not initialized

    - ESP_ERR_INVALID_ARG: matrix_handle or matrix_callback is null

esp_err_t touch_matrix_set_longpress(touch_matrix_handle_t matrix_handle, uint32_t threshold_time)

  Touch matrix button set long press trigger time.

  This function sets the threshold time (ms) for a long press event. If a matrix button is pressed and held for a period of time that exceeds the threshold time, a long press event is triggered.

  参数:

    - matrix_handle -- [in] Matrix button handle

    - threshold_time -- [in] Threshold time (ms) of long press event occur

  返回:

    - ESP_OK: Successfully set the time of long press event

    - ESP_ERR_INVALID_STATE: Touch matrix driver was not initialized

    - ESP_ERR_INVALID_ARG: matrix_handle is null or time (ms) is 0

const touch_matrix_message_t *touch_matrix_get_message(const touch_elem_message_t *element_message)

  Touch matrix get message.

  This function decodes the element message from touch_element_message_receive() and return a matrix message pointer.

  参数:

    element_message -- [in] element message

  返回:

    Touch matrix message pointer

### Structures

struct touch_matrix_global_config_t

  Matrix button initialization configuration passed to touch_matrix_install.

  Public Members

  float threshold_divider

    Matrix button channel threshold divider.

  uint32_t default_lp_time

    Matrix button default LongPress event time (ms)

struct touch_matrix_config_t

  Matrix button configuration (for new instance) passed to touch_matrix_create()

  Public Members

  const touch_pad_t *x_channel_array

    Matrix button x-axis channels array.

  const touch_pad_t *y_channel_array

    Matrix button y-axis channels array.

  const float *x_sensitivity_array

    Matrix button x-axis channels sensitivity array.

  const float *y_sensitivity_array

    Matrix button y-axis channels sensitivity array.

  uint8_t x_channel_num

    The number of channels in x-axis.

  uint8_t y_channel_num

    The number of channels in y-axis.

struct touch_matrix_position_t

  Matrix button position data type.

  Public Members

  uint8_t x_axis

    Matrix button x axis position.

  uint8_t y_axis

    Matrix button y axis position.

  uint8_t index

    Matrix button position index.

struct touch_matrix_message_t

  Matrix message type.

  Public Members

  touch_matrix_event_t event

    Matrix event.

  touch_matrix_position_t position

    Matrix position.

### Macros

TOUCH_MATRIX_GLOBAL_DEFAULT_CONFIG()

### Type Definitions

typedef touch_elem_handle_t touch_matrix_handle_t

  Matrix button instance handle.

typedef void (*touch_matrix_callback_t)(touch_matrix_handle_t, touch_matrix_message_t*, void*)

  Matrix button callback type.

### Enumerations

enum touch_matrix_event_t

  Matrix button event type.

  Values:

  enumerator TOUCH_MATRIX_EVT_ON_PRESS

    Matrix button Press event.

  enumerator TOUCH_MATRIX_EVT_ON_RELEASE

    Matrix button Press event.

  enumerator TOUCH_MATRIX_EVT_ON_LONGPRESS

    Matrix button LongPress event.

  enumerator TOUCH_MATRIX_EVT_MAX

此文档对您有帮助吗？

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

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