# 电容式触摸传感器

[English]

## 概述

触摸传感器系统由保护覆盖层、触摸电极、绝缘基板和走线组成，保护覆盖层位于最上层，绝缘基板上设有电极及走线。触摸覆盖层将引起电容变化，根据电容变化，可以判断此次触摸是否为有效触摸行为。

触摸传感器可以以矩阵或滑条等方式组合使用，从而覆盖更大触感区域及更多触感点。触摸传感由软件或专用硬件计时器发起，由有限状态机 (FSM) 硬件控制。

如需了解触摸传感器设计、操作及其控制寄存器等相关信息，请参考《ESP32 技术参考手册》(PDF) 中“片上传感器与模拟信号处理”章节。

请参考 触摸传感器应用方案简介，查看触摸传感器设计详情和固件开发指南。

## 电容式触摸传感器版本概览

硬件版本 | 芯片 | 主要特征
--- | --- | ---
V1 | ESP32 | 第一代触摸传感器，触摸时读数变小
V2 | ESP32-S2 | 第二代触摸传感器，触摸时读数变大 新增硬件滤波器、基线、防水防潮、接近感应、睡眠唤醒功能
ESP32-S3 | 第二代触摸传感器，新增接近感应测量完成中断
V3 | ESP32-P4 ESP32-H4 ESP32-S31 | 第三代触摸传感器，新增跳频扫描

## 测量原理

触摸传感器通过硬件内部的电流或电压偏置对触摸通道进行充电和放电操作，由于触摸通道存在内部电容和电路中的寄生电容，充放电时在通道引脚上表现为锯齿波。当手指贴近或者触摸该通道时，通道、人体和大地之间形成充放电回路，使得触摸通道耦合的电容增大，充放电速度变慢，即锯齿波周期增大。

触摸传感器会在固定时间内对触摸通道进行充放电，并统计充放电次数，其计数结果即为原始数据。其中单次测量的充放电持续时间可由 `touch_sensor_sample_config_t::charge_times` 指定，两次测量中间的间隔时间可由 `touch_sensor_config_t::meas_interval_us` 指定。

触摸传感器工作原理示意图

## 触摸通道概览

通道 | GPIO
--- | ---
CH0 | IO4
CH1 | IO0
CH2 | IO2
CH3 | IO15
CH4 | IO13
CH5 | IO12
CH6 | IO14
CH7 | IO27
CH8 | IO33
CH9 | IO32

## 驱动中的术语介绍

- 触摸传感器控制器：触摸传感器驱动的控制器，负责触摸传感器的配置和管理。

- 触摸传感器通道：具体的一路触摸传感器采样通道。一个触摸传感器模块具有多个通道，一般连接到触摸板上，用于测量该触摸板电容的变化。驱动中把对 一个 通道的采样称为 `测量`，而对 所有 注册通道的 `测量` 称为一次 `扫描`。

- 触摸传感器采样配置：触摸传感器采样配置是驱动中对采样有关的硬件配置的统称。采样配置负责触摸传感器通道的采样，其配置决定了触摸通道的充放电次数、充放电频率、测量间隔等。ESP32 仅支持一套采样配置，不支持跳频采样。

## 文件结构

触摸传感器驱动文件结构图

## 驱动状态机

下图为触摸传感器驱动的状态机，描述了调用不同函数后驱动的运行状态，以及状态变迁的约束。

触摸传感器驱动状态机示意图

上图为触摸传感器驱动的状态机，描述了调用不同函数后状态的变换关系。其中 `<other_configurations>` 部分为可选的配置项，包括对触摸驱动控制器和触摸通道的重新配置、回调函数注册等。

备注

`touch_channel_read_data()` 可在获取触摸通道句柄后（即 `INIT` 后）任意状态调用，但请注意读数值的有效性。

## 功能介绍

ESP32 的电容式触摸传感器驱动提供的 API 按功能主要可分为：

- 触摸传感器控制器管理

- 触摸传感器通道管理

- 滤波器配置

- 回调函数

- 启用和禁用

- 连续扫描

- 单次扫描

- 测量值读数

- 睡眠唤醒配置

### 触摸传感器控制器管理

触摸传感器驱动通过触摸传感器控制器句柄 `touch_sensor_handle_t` 控制。调用 `touch_sensor_new_controller()` 函数即可初始化触摸传感器控制器并得到控制器句柄。

    // 有些芯片支持多套采样配置，这里以一套为例
    #define SAMPLE_NUM 1
    touch_sensor_handle_t sens_handle = NULL;
    // 采样配置
    touch_sensor_sample_config_t sample_cfg[SAMPLE_NUM] = {
        // 指定采样配置或通过 `TOUCH_SENSOR_Vn_DEFAULT_SAMPLE_CONFIG` 使用默认采样配置
        // ...
    };
    // 默认控制器配置
    touch_sensor_config_t touch_cfg = TOUCH_SENSOR_DEFAULT_BASIC_CONFIG(SAMPLE_NUM, sample_cfg);
    // 申请一个新的触摸传感器控制器句柄
    ESP_ERROR_CHECK(touch_sensor_new_controller(&touch_cfg, &sens_handle));

删除触摸传感器驱动控制器时需调用 `touch_sensor_del_controller()` 函数，从而释放该控制器所占用的软硬件资源。注意，需要将基于该控制器申请的其他资源销毁或释放后才能删除该控制器。如该控制器下仍有触摸通道未被删除，则无法直接删除。

    ESP_ERROR_CHECK(touch_sensor_del_controller(sens_handle));

在触摸传感器驱动控制器初始化后，且未启用触摸传感器时，可调用 `touch_sensor_reconfig_controller()` 函数对该控制器进行重新配置。

    touch_sensor_config_t touch_cfg = {
        // 控制器的新配置
        // ...
    };
    ESP_ERROR_CHECK(touch_sensor_reconfig_controller(sens_handle, &touch_cfg));

### 触摸传感器通道管理

一个触摸传感器具有多个测量通道，每个触摸传感器通道由句柄 `touch_channel_handle_t` 控制。调用 `touch_sensor_new_channel()` 函数即可初始化触摸传感器通道并得到通道句柄。

    // ...
    touch_channel_config_t chan_cfg = {
        // 触摸通道配置
        // ...
    };
    touch_channel_handle_t chan_handle = NULL;
    int chan_id = 0;
    // 申请一个新的触摸通道句柄
    ESP_ERROR_CHECK(touch_sensor_new_channel(sens_handle, chan_id, &chan_cfg, &chan_handle));

删除触摸传感器通道时需调用 `touch_sensor_del_channel()` 函数，从而释放该通道所占用的软硬件资源。

    ESP_ERROR_CHECK(touch_sensor_del_channel(chan_handle));

在触摸传感器驱动通道初始化后，且未启用触摸传感器时，可调用 `touch_sensor_reconfig_channel()` 函数对该通道进行重新配置。

    touch_channel_config_t chan_cfg = {
        // 触摸通道新配置
        // ...
    };
    ESP_ERROR_CHECK(touch_sensor_reconfig_channel(chan_handle, &chan_cfg));

### 滤波器配置

触摸传感器可以通过配置滤波器来提升不同场景下的数据稳定性。调用 `touch_sensor_config_filter()` 并指定 `touch_sensor_filter_config_t` 来配置基线值和读数值的滤波策略和更新方式，配置后对所有启用的触摸通道都生效。

若需要注销滤波器，可再次调用 `touch_sensor_config_filter()` 并将第二个参数（即 `touch_sensor_filter_config_t` 的配置结构体指针）设为 `NULL` 来注销滤波器功能。

触摸传感器版本 v1 本身不支持硬件滤波器，但是驱动中可以基于 `esp_timer` 设置周期性触发的软件滤波器。可以通过 `touch_sensor_filter_config_t::interval_ms` 来制定软件滤波触发的间隔时间，另外 `touch_sensor_filter_config_t::data_filter_fn` 接口支持指定自定义滤波函数，若无特殊滤波器要求，也可将该接口设为 `NULL` 来使用驱动中的默认滤波器。

    // ...
    touch_sensor_filter_config_t filter_config = {
        // 滤波器配置
        // ...
    };
    // 注册滤波器
    ESP_ERROR_CHECK(touch_sensor_config_filter(sens_handle, &filter_config));
    // ...
    // 注销滤波器
    ESP_ERROR_CHECK(touch_sensor_config_filter(sens_handle, NULL));

### 回调函数

通过调用 `touch_sensor_register_callbacks()` 注册各类触摸传感器事件回调函数，当触摸传感器通道触发如触摸 `on_active`、释放 `on_inactive` 等事件时，就会调用对应的回调函数通知上层应用，以便对触摸事件进行处理。

例如，测量值超出当前的测量通道的 `基线值` + `触发阈值`，则该通道将被触发，并调用 `on_active` 事件的回调函数，通知应用层该触摸通道被 `触发`。同理，若处于 `触发` 状态的通道测量值小于 `基线值` + `触发阈值`，则该通道将回到未触发状态，并调用 `on_inactive` 事件的回调函数，通知应用层该触摸通道被 `释放`。

备注

为保证触发和释放事件的稳定性，触摸传感器可配置 `触发阈值` 的迟滞比较裕量和 `去抖动计数` 来避免短时间内由噪声和读数抖动引起的反复触发和释放。

具体可注册的回调时间请参考 `touch_event_callbacks_t`。

    touch_event_callbacks_t callbacks = {
        .on_active = example_touch_on_active_cb,
        // 其他回调函数
        // ...
    };
    // 注册回调函数
    ESP_ERROR_CHECK(touch_sensor_register_callbacks(sens_handle, &callbacks, NULL));

    // 通过把相应回调设为 NULL 以注销回调函数
    callbacks.on_active = NULL;
    // 其他需要注销的回调函数
    // ...
    ESP_ERROR_CHECK(touch_sensor_register_callbacks(sens_handle, &callbacks, NULL));

### 启用和禁用

配置完成触摸传感器控制器以及通道后，可调用 `touch_sensor_enable()` 函数启用该控制器，启用后控制器处于 `就绪` 状态，会对注册的通道上电，可以开始扫描并采集触摸数据。注意，控制器启用后无法更新配置，只能进行扫描采样和读数操作。若要更新配置，需先调用 `touch_sensor_disable()` 函数禁用控制器，方可重新配置控制器、通道等。

    // 启用触摸传感器
    ESP_ERROR_CHECK(touch_sensor_enable(sens_handle));
    // ...
    // 禁用触摸传感器
    ESP_ERROR_CHECK(touch_sensor_disable(sens_handle));

### 连续扫描

在控制器启用后，调用 `touch_sensor_start_continuous_scanning()` 函数可开始对所有已注册的触摸通道进行连续扫描，每次扫描都会更新对应通道的测量值。调用 `touch_sensor_stop_continuous_scanning()` 函数后则停止扫描。

    // 开始连续扫描
    ESP_ERROR_CHECK(touch_sensor_start_continuous_scanning(sens_handle));
    // ...
    // 停止连续扫描
    ESP_ERROR_CHECK(touch_sensor_stop_continuous_scanning(sens_handle));

### 单次扫描

在控制器启用后，调用 `touch_sensor_trigger_oneshot_scanning()` 函数可触发一次对所有已注册的触摸通道的扫描。注意，单次扫描为阻塞函数，调用后会保持阻塞直到扫描结束后返回。此外在开始连续扫描后，无法再触发单次扫描。

    // 触发单次扫描，并设置超时时间为 1000 ms
    ESP_ERROR_CHECK(touch_sensor_trigger_oneshot_scanning(sens_handle, 1000));

### 测量值读数

调用 `touch_channel_read_data()` 可读取每个通道不同种类的数据，例如基线值、经过滤波后的平滑值等。支持的数据类型请参考 `touch_chan_data_type_t`。

    #define SAMPLE_NUM  1  // 以一套采样配置为例
    uint32_t smooth_data[SAMPLE_NUM] = {};
    // 读取滤波后的平滑数据
    ESP_ERROR_CHECK(touch_channel_read_data(chan_handle, TOUCH_CHAN_DATA_TYPE_SMOOTH, smooth_data));

### 睡眠唤醒配置

ESP32 支持触摸传感器将芯片从 Light-sleep 或 Deep-sleep 状态中唤醒。可通过调用 `touch_sensor_config_sleep_wakeup()` 并配置 `touch_sleep_config_t` 来注册接近感应功能。

注册触摸传感器的睡眠唤醒功能后，处于睡眠状态下的芯片仍将继续保持对触摸传感器的采样，这将会导致芯片睡眠后的功耗增加，可通过减少充放电次数、增加采样间隔等方式来降低功耗。

另外，请注意在主核睡眠期间的采样、唤醒等操作均由硬件完成，本驱动由于运行在主核上，无法提供读数、配置等功能。

- Light-sleep 状态唤醒：通过指定 `slp_wakeup_lvl` 为 `TOUCH_LIGHT_SLEEP_WAKEUP` 即可启用触摸传感器 Light-sleep 唤醒功能。注意任何已注册的触摸传感器通道都会在 Light-sleep 状态下保持采样并支持唤醒 Light-sleep。

- Deep-sleep 状态唤醒：通过指定 `slp_wakeup_lvl` 为 `TOUCH_DEEP_SLEEP_WAKEUP` 即可启用触摸传感器 Deep-sleep 唤醒功能。注意版本 v1 启用 Deep-sleep 唤醒后，会在 Deep-sleep 中保持 RTC 电源域开启，以维持触摸传感器工作，此时任何已注册的触摸传感器通道都可以在 Deep-sleep 状态下保持采样并支持唤醒 Deep-sleep。

若需要注销睡眠唤醒功能，可再次调用 `touch_sensor_config_sleep_wakeup()` 并将第二个参数（即 `touch_sleep_config_t` 的配置结构体指针）设为 `NULL` 来注销睡眠唤醒功能。

    touch_sleep_config_t light_slp_cfg = TOUCH_SENSOR_DEFAULT_LSLP_CONFIG();
    // 注册 Light-sleep 唤醒功能
    ESP_ERROR_CHECK(touch_sensor_config_sleep_wakeup(sens_handle, &light_slp_cfg));
    // ...
    // 注销睡眠唤醒功能
    ESP_ERROR_CHECK(touch_sensor_config_sleep_wakeup(sens_handle, NULL));
    // 默认 Deep-sleep 唤醒配置：RTC_PERIPH 电源域在 Deep-sleep 状态下保持上电，
    // 且所有使能 Touch 通道都能正常唤醒
    touch_sleep_config_t deep_slp_cfg = TOUCH_SENSOR_DEFAULT_DSLP_CONFIG();
    // 默认 Deep-sleep 掉电唤醒配置：RTC_PERIPH 电源域在 Deep-sleep 状态下掉电，
    // 仅有指定的 sleep pad 能正常唤醒
    // touch_sleep_config_t deep_slp_cfg = TOUCH_SENSOR_DEFAULT_DSLP_PD_CONFIG(sleep_channel, slp_chan_thresh1, ...);
    // 注册 Deep-sleep 唤醒功能
    ESP_ERROR_CHECK(touch_sensor_config_sleep_wakeup(sens_handle, &deep_slp_cfg));

## 应用示例

> - peripherals/touch_sensor/touch_sens_basic 演示了如何注册触摸通道并读取数据，并说明了硬件要求及项目配置。

> - peripherals/touch_sensor/touch_sens_sleep 演示了如何通过触摸传感器将芯片从 Light Sleep 或 Deep Sleep 状态唤醒。

## 应用注意事项

### 触摸传感器功耗问题

由于触摸传感器的测量需要对电容进行充放电，所以它是一个比较耗能的外设。在一些对功耗要求比较高的应用中，可采用以下几个方法来降低触摸传感器功耗。

- 减少触摸通道数量：可在同一通道上复用多种功能（如单双击、长按等），从而减少触摸传感器的数量。

- 增加测量间隔：通过增大 `touch_sensor_config_t::meas_interval_us` 测量间隔，来降低测量频率，从而降低功耗。

- 降低单次测量时间：通过降低 `touch_sensor_sample_config_t::charge_duration_ms` 单次测量时间，来减少充放电次数，从而降低功耗。

- 降低充放电幅度：`touch_sensor_sample_config_t::charge_volt_lim_l` 和 `touch_sensor_sample_config_t::charge_volt_lim_h` 用于指定放电时的电压下限和充电时的电压上限，同时降低这两个电压值以及上下限之间的压差可降低功耗。

- 降低电流偏置强度：降低 `touch_channel_config_t::charge_speed` 充放电速度（即电流偏置的电流大小）从而降低功耗。

## API 参考

### Header File

- components/esp_driver_touch_sens/include/driver/touch_sens.h

- This header file can be included with:

  >     #include "driver/touch_sens.h"

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

  >     REQUIRES esp_driver_touch_sens

  > or

  >     PRIV_REQUIRES esp_driver_touch_sens

### Functions

esp_err_t touch_sensor_new_controller(const touch_sensor_config_t *sens_cfg, touch_sensor_handle_t *ret_sens_handle)

  Allocate a new touch sensor controller.

  备注

  The touch sensor driver will be in INIT state after this function is called successfully.

  参数:

    - sens_cfg -- [in] Touch sensor controller configurations

    - ret_sens_handle -- [out] The return handle of the touch controller instance

  返回:

    - ESP_OK On success

    - ESP_ERR_NO_MEM No memory for the touch sensor controller

    - ESP_ERR_INVALID_ARG Invalid argument or NULL pointer

    - ESP_ERR_INVALID_STATE The touch sensor controller is already allocated

esp_err_t touch_sensor_del_controller(touch_sensor_handle_t sens_handle)

  Delete the touch sensor controller.

  备注

  This function can be called when the touch sensor controller is NOT enabled (i.e. INIT state).

  参数:

    sens_handle -- [in] Touch sensor controller handle

  返回:

    - ESP_OK On success

    - ESP_ERR_INVALID_ARG Invalid argument or NULL pointer

    - ESP_ERR_INVALID_STATE Controller not disabled or still some touch channels not deleted

esp_err_t touch_sensor_new_channel(touch_sensor_handle_t sens_handle, int chan_id, const touch_channel_config_t *chan_cfg, touch_channel_handle_t *ret_chan_handle)

  Allocate a new touch channel from the touch sensor controller.

  备注

  This function can be called when the touch sensor controller is NOT enabled (i.e. INIT state).

  参数:

    - sens_handle -- [in] Touch sensor controller handle

    - chan_id -- [in] Touch channel index

    - chan_cfg -- [in] Touch channel configurations

    - ret_chan_handle -- [out] The return handle of the touch channel instance

  返回:

    - ESP_OK On success

    - ESP_ERR_NO_MEM No memory for the touch sensor channel

    - ESP_ERR_INVALID_ARG Invalid argument or NULL pointer

    - ESP_ERR_INVALID_STATE The touch sensor controller has not disabled or this channel has been allocated

esp_err_t touch_sensor_del_channel(touch_channel_handle_t chan_handle)

  Delete the touch channel.

  备注

  This function can be called when the touch sensor controller is NOT enabled (i.e. INIT state).

  备注

  If the channel has been enabled other sub-features like proximity sensing, sleep wakeup, waterproof, denoise. The attached sub-features will be disabled while deleting the channel.

  参数:

    chan_handle -- [in] Touch channel handle

  返回:

    - ESP_OK On success

    - ESP_ERR_INVALID_ARG Invalid argument or NULL pointer

    - ESP_ERR_INVALID_STATE The touch sensor controller has not disabled

esp_err_t touch_sensor_reconfig_controller(touch_sensor_handle_t sens_handle, const touch_sensor_config_t *sens_cfg)

  Re-configure the touch sensor controller.

  备注

  This function can be called when the touch sensor controller is NOT enabled (i.e. INIT state).

  备注

  The re-configuration only applies to the touch controller, so it requires the controller handle that allocated from `touch_sensor_new_controller`, meanwhile, it won't affect the touch channels, no matter the channels are allocated or not.

  参数:

    - sens_handle -- [in] Touch sensor controller handle

    - sens_cfg -- [in] Touch sensor controller configurations

  返回:

    - ESP_OK On success

    - ESP_ERR_INVALID_ARG Invalid argument or NULL pointer

    - ESP_ERR_INVALID_STATE The touch sensor controller has not disabled

esp_err_t touch_sensor_reconfig_channel(touch_channel_handle_t chan_handle, const touch_channel_config_t *chan_cfg)

  Re-configure the touch channel.

  备注

  This function can be called when the touch sensor controller is NOT enabled (i.e. INIT state).

  备注

  The re-configuration only applies to a particular touch channel, so it requires the channel handle that allocated from `touch_sensor_new_channel`

  参数:

    - chan_handle -- [in] Touch channel handle

    - chan_cfg -- [in] Touch channel configurations

  返回:

    - ESP_OK On success

    - ESP_ERR_INVALID_ARG Invalid argument or NULL pointer

    - ESP_ERR_INVALID_STATE The touch sensor controller has not disabled

esp_err_t touch_sensor_config_filter(touch_sensor_handle_t sens_handle, const touch_sensor_filter_config_t *filter_cfg)

  Configure the touch sensor filter.

  备注

  This function is allowed to be called after the touch sensor is enabled

  参数:

    - sens_handle -- [in] Touch sensor controller handle

    - filter_cfg -- [in] Filter configurations, set NULL to disable the filter

  返回:

    - ESP_OK: Configure the filter success

    - ESP_ERR_INVALID_ARG: The sensor handle is NULL

esp_err_t touch_sensor_enable(touch_sensor_handle_t sens_handle)

  Enable the touch sensor controller.

  备注

  This function can be called when the touch sensor controller is NOT enabled (i.e. INIT state). And the touch sensor driver will be in ENABLED state after this function is called successfully.

  备注

  Enable the touch sensor will power on the registered touch channels

  参数:

    sens_handle -- [in] Touch sensor controller handle

  返回:

    - ESP_OK On success

    - ESP_ERR_INVALID_ARG Invalid argument or NULL pointer

    - ESP_ERR_INVALID_STATE The touch sensor controller has already enabled

esp_err_t touch_sensor_disable(touch_sensor_handle_t sens_handle)

  Disable the touch sensor controller.

  备注

  This function can only be called after the touch sensor controller is enabled (i.e. ENABLED state). And the touch sensor driver will be in INIT state after this function is called successfully.

  备注

  Disable the touch sensor will power off the registered touch channels

  参数:

    sens_handle -- [in] Touch sensor controller handle

  返回:

    - ESP_OK On success

    - ESP_ERR_INVALID_ARG Invalid argument or NULL pointer

    - ESP_ERR_INVALID_STATE The touch sensor controller has already disabled

esp_err_t touch_sensor_start_continuous_scanning(touch_sensor_handle_t sens_handle)

  Start the scanning of the registered touch channels continuously.

  备注

  This function can only be called after the touch sensor controller is enabled (i.e. ENABLED state). And the touch sensor driver will be in SCANNING state after this function is called successfully. And it can also be called in ISR/callback context.

  备注

  The hardware FSM (Finite-State Machine) of touch sensor will be driven by its hardware timer continuously and repeatedly. i.e., the registered channels will be scanned one by one repeatedly.

  参数:

    sens_handle -- [in] Touch sensor controller handle

  返回:

    - ESP_OK On success

    - ESP_ERR_INVALID_ARG Invalid argument or NULL pointer

    - ESP_ERR_INVALID_STATE The touch sensor controller is not enabled or the continuous scanning has started

esp_err_t touch_sensor_stop_continuous_scanning(touch_sensor_handle_t sens_handle)

  Stop the continuous scanning of the registered touch channels immediately.

  备注

  This function can only be called after the continuous scanning started (i.e. SCANNING state). And the touch sensor driver will be in ENABLED state after this function is called successfully. And it can also be called in ISR/callback context.

  备注

  Stop the hardware timer and reset the FSM (Finite-State Machine) of the touch sensor controller

  参数:

    sens_handle -- [in] Touch sensor controller handle

  返回:

    - ESP_OK On success

    - ESP_ERR_INVALID_ARG Invalid argument or NULL pointer

    - ESP_ERR_INVALID_STATE The continuous scanning has stopped

esp_err_t touch_sensor_trigger_oneshot_scanning(touch_sensor_handle_t sens_handle, int timeout_ms)

  Trigger an oneshot scanning for all the registered channels.

  备注

  This function can only be called after the touch sensor controller is enabled (i.e. ENABLED state). And the touch sensor driver will be in SCANNING state after this function is called successfully, and then switch back to ENABLED state after the scanning is done or timeout.

  备注

  The block time of this function depends on various factors, In common practice, recommend to set the timeout to several seconds or wait forever, because oneshot scanning can't last for so long.

  参数:

    - sens_handle -- [in] Touch sensor controller handle

    - timeout_ms -- [in] Set a positive value or zero means scan timeout in milliseconds Set a negative value means wait forever until finished scanning

  返回:

    - ESP_OK On success

    - ESP_ERR_TIMEOUT Timeout to finish the oneshot scanning

    - ESP_ERR_INVALID_ARG Invalid argument

    - ESP_ERR_INVALID_STATE The touch sensor controller is not enabled or the continuous scanning has started

esp_err_t touch_sensor_register_callbacks(touch_sensor_handle_t sens_handle, const touch_event_callbacks_t *callbacks, void *user_ctx)

  Register the touch sensor callbacks.

  备注

  This function can be called when the touch sensor controller is NOT enabled (i.e. INIT state).

  参数:

    - sens_handle -- [in] Touch sensor controller handle

    - callbacks -- [in] Callback functions

    - user_ctx -- [in] User context that will be passed to the callback functions

  返回:

    - ESP_OK On success

    - ESP_ERR_INVALID_ARG NULL pointer

    - ESP_ERR_INVALID_STATE Touch sensor controller has not disabled

esp_err_t touch_channel_read_data(touch_channel_handle_t chan_handle, touch_chan_data_type_t type, uint32_t *data)

  Read the touch channel data according to the types.

  备注

  This function can be called no matter the touch sensor controller is enabled or not (i.e. ENABLED or SCANNING state). And it can also be called in ISR/callback context.

  备注

  Specially, `TOUCH_CHAN_DATA_TYPE_PROXIMITY` data type will be read from the cached data in the driver, because the proximity data need to be accumulated in several scan times that specified by `touch_proximity_config_t::scan_times`. For other data types, the data are read from the hardware registers directly (not cached in the driver). The channel data in the register will be updated once the measurement of this channels is done, And keep locked until the next measurement is done.

  参数:

    - chan_handle -- [in] Touch channel handle

    - type -- [in] Specify the data type to read

    - data -- [out] The data array pointer. If the target supports multiple sample configurations (SOC_TOUCH_SAMPLE_CFG_NUM), the array length should be equal to the frequency hopping number that specified in `touch_sensor_config_t::sample_cfg_num`, otherwise the array length should be 1.

  返回:

    - ESP_OK On success

    - ESP_ERR_INVALID_ARG Invalid argument or NULL pointer

esp_err_t touch_sensor_config_sleep_wakeup(touch_sensor_handle_t sens_handle, const touch_sleep_config_t *sleep_cfg)

  Configure the touch sensor to wake-up the chip from sleep.

  备注

  Call this function to enable/disable the touch sensor wake-up the chip from deep/light sleep To only enable the touch sensor wake-up the chip from light sleep, set the `touch_sleep_config_t::deep_slp_chan` to NULL. During the light sleep, all enabled touch channels will keep working, and any one of them can wake-up the chip from light sleep. To enable the touch sensor wake-up the chip from both light and deep sleep, set the `touch_sleep_config_t::deep_slp_chan` to an enabled channel. During the deep sleep, only this specified channels can work and wake-up the chip from the deep sleep, and other enabled channels can only wake-up the chip from light sleep.

  参数:

    - sens_handle -- [in] Touch sensor controller handle

    - sleep_cfg -- [in] Sleep wake-up configurations, set NULL to disable the touch sensor wake-up the chip from sleep

  返回:

    - ESP_OK: Configure the sleep channel success

    - ESP_ERR_INVALID_ARG: The sensor handle is NULL

    - ESP_ERR_INVALID_STATE: The touch sensor is enabled

esp_err_t touch_sensor_get_channel_info(touch_channel_handle_t chan_handle, touch_chan_info_t *chan_info)

  Get the touch channel information by the channel handle.

  参数:

    - chan_handle -- [in] Touch channel handle

    - chan_info -- [out] Touch channel information

  返回:

    - ESP_OK: Success to get the channel information

    - ESP_ERR_INVALID_ARG: NULL pointer

### Structures

struct touch_chan_info_t

  Touch channel information.

  Public Members

  int chan_id

    Touch channel number

  int chan_gpio

    Corresponding GPIO of this channel

  uint32_t abs_active_thresh[TOUCH_SAMPLE_CFG_NUM]

    The configured absolute threshould of this channel (only used for V1)

  uint32_t active_thresh[TOUCH_SAMPLE_CFG_NUM]

    The configured relative threshould of this channel (used except V1)

  uint32_t can_wake_dp_slp

    Whether this channel can wakeup from deep sleep

  uint32_t is_proxi

    Whether this channel is used for proximity sensing

  uint32_t is_guard

    Whether this channel is used for waterproof guard channel

  uint32_t is_shield

    Whether this channel is used for waterproof shield channel

  struct touch_chan_info_t flags

    Channel sub-feature flags

### Header File

- components/esp_driver_touch_sens/include/driver/touch_sens_types.h

- This header file can be included with:

  >     #include "driver/touch_sens_types.h"

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

  >     REQUIRES esp_driver_touch_sens

  > or

  >     PRIV_REQUIRES esp_driver_touch_sens

### Type Definitions

typedef struct touch_sensor_s *touch_sensor_handle_t

  The handle of touch sensor controller

typedef struct touch_channel_s *touch_channel_handle_t

  The handle of touch channel

### Enumerations

enum touch_sleep_wakeup_level_t

  The chip sleep level that allows the touch sensor to wake-up.

  Values:

  enumerator TOUCH_LIGHT_SLEEP_WAKEUP

    Only enable the touch sensor to wake up the chip from light sleep

  enumerator TOUCH_DEEP_SLEEP_WAKEUP

    Enable the touch sensor to wake up the chip from deep sleep or light sleep

### Header File

- components/esp_driver_touch_sens/hw_ver1/include/driver/touch_version_types.h

- This header file can be included with:

  >     #include "driver/touch_version_types.h"

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

  >     REQUIRES esp_driver_touch_sens

  > or

  >     PRIV_REQUIRES esp_driver_touch_sens

### Structures

struct touch_sensor_sample_config_t

  Sample configurations of the touch sensor.

  Public Members

  float charge_duration_ms

    Charge duration time of one measurement on a touch channel

  touch_volt_lim_h_t charge_volt_lim_h

    The upper voltage limit while charging a touch pad. i.e., the touch controller won't charge the touch pad higher than this high voltage limitation.

  touch_volt_lim_l_t charge_volt_lim_l

    The lower voltage limit while discharging a touch pad. i.e., the touch controller won't discharge the touch pad lower than this low voltage limitation.

struct touch_sensor_config_t

  Configurations of the touch sensor controller.

  Public Members

  uint32_t power_on_wait_us

    The waiting time between the channels power on and able to measure, to ensure the data stability

  float meas_interval_us

    Measurement interval of each channels

  touch_intr_trig_mode_t intr_trig_mode

    Interrupt trigger mode, the hardware touch interrupt can be triggered either above or below the absolute threshold

  touch_intr_trig_group_t intr_trig_group

    Which channel group can trigger the hardware touch interrupt

  uint32_t sample_cfg_num

    The sample configuration number that used for sampling, CANNOT exceed TOUCH_SAMPLE_CFG_NUM

  touch_sensor_sample_config_t *sample_cfg

    The array of this sample configuration configurations, the length should be specified in `touch_sensor_config_t::sample_cfg_num`

struct touch_channel_config_t

  Configurations of the touch sensor channel.

  Public Members

  uint32_t abs_active_thresh[TOUCH_SAMPLE_CFG_NUM]

    The absolute active threshould. The `on_active` and `on_hw_active` callback will trigger when

    - If touch_sensor_config_t::intr_trig_mode = TOUCH_INTR_TRIG_ON_BELOW_THRESH, the callback will keep triggering when the touch channel value below the threshold.

    - If touch_sensor_config_t::intr_trig_mode = TOUCH_INTR_TRIG_ON_ABOVE_THRESH, the callback will keep triggering when the touch channel value above the threshold.

  touch_charge_speed_t charge_speed

    The speed of charging and discharging the touch pad, the higher the speed, the faster charging and discharging

  touch_init_charge_volt_t init_charge_volt

    The initial voltage before charging/discharging a touch pad

  touch_chan_trig_group_t group

    The channel group that the channel belongs to. The group will be used to trigger the interrupt

struct touch_sw_filter_data_t

  Touch software filter data.

  Public Members

  uint32_t prev_output

    Previous output filtered data

  uint32_t curr_input

    Current input raw data that need to be filtered

struct touch_sensor_filter_config_t

  The configuration of the software filter.

  Public Members

  uint32_t interval_ms

    The software filter interval in milliseconds. The software filter will trigger periodically based on esp_timer

  touch_sw_filter_t data_filter_fn

    The data filter function pointer. You can specify your own filter algorithm, or set NULL to use default software filter

  void *user_filter_ctx

    User customized filter context pointer. This pointer will be passed to the second parameter of `touch_sw_filter_t` . So that users can access their customized filter context in the software filter function.

struct touch_sleep_config_t

  Configuration of the touch sensor sleep function.

  Public Members

  touch_sleep_wakeup_level_t slp_wakeup_lvl

    The sleep level that can be woke up by touch sensor.

  touch_sensor_config_dslp_t *deep_slp_sens_cfg

    Specify the touch sensor configuration during the deep sleep. Note that these configurations will no take effect immediately, they will be set automatically while the chip prepare to enter sleep. Set NULL to not change the configurations before entering sleep. The sleep configuration mainly aims at lower down the charging and measuring times, so that to save power consumption during the sleep. Only effective when the `touch_sleep_config_t::slp_wakeup_lvl` is `TOUCH_DEEP_SLEEP_WAKEUP`

struct touch_base_event_data_t

  Base event structure used in touch event queue.

  Public Members

  touch_channel_handle_t chan

    the current triggered touch channel handle

  int chan_id

    the current triggered touch channel number

struct touch_hw_active_event_data_t

  Active event data.

  Public Members

  uint32_t active_mask

    The current active channel mask. For the bits in the status mask, if the bit is set, the corresponding channel is active if the bit is cleared, the corresponding channel is inactive

struct touch_event_callbacks_t

  Touch sensor callbacks.

  备注

  Set NULL for the unused callbacks.

  备注

  The Touch Sensor V1 hardware interrupt callback is different compare to other versions. To align the behavior of the `on_active` and `on_inactive`, they are added as the software filter callbacks. Please configure the software filter by `touch_sensor_config_filter` before using hardware interrupt.

  Public Members

  bool (*on_sw_active)(touch_sensor_handle_t sens_handle, const touch_active_event_data_t *event, void *user_ctx)

    Touch sensor on software active event callback.

    备注

    This callback is triggered by the software periodical filter. It callbacks when any touch channel is activated.

    Param sens_handle:

      [in] Touch sensor controller handle, created from `touch_sensor_new_controller()`

    Param event:

      [in] Touch sensor active event data

    Param user_ctx:

      [in] User registered context, passed from `touch_sensor_register_callbacks()`

    Return:

      Whether a high priority task has been waken up by this callback function

  bool (*on_active)(touch_sensor_handle_t sens_handle, const touch_active_event_data_t *event, void *user_ctx)

    Touch sensor on software active event callback. (Alias of `on_sw_active` for compatibility)

    备注

    This callback is triggered by the software periodical filter. It callbacks when any touch channel is activated.

    Param sens_handle:

      [in] Touch sensor controller handle, created from `touch_sensor_new_controller()`

    Param event:

      [in] Touch sensor active event data

    Param user_ctx:

      [in] User registered context, passed from `touch_sensor_register_callbacks()`

    Return:

      Whether a high priority task has been waken up by this callback function

  bool (*on_sw_inactive)(touch_sensor_handle_t sens_handle, const touch_inactive_event_data_t *event, void *user_ctx)

    Touch sensor on software inactive event callback.

    备注

    This callback is triggered by the software periodical filter. It callbacks when any touch channel is de-activated.

    Param sens_handle:

      [in] Touch sensor controller handle, created from `touch_sensor_new_controller()`

    Param event:

      [in] Touch sensor active event data

    Param user_ctx:

      [in] User registered context, passed from `touch_sensor_register_callbacks()`

    Return:

      Whether a high priority task has been waken up by this callback function

  bool (*on_inactive)(touch_sensor_handle_t sens_handle, const touch_inactive_event_data_t *event, void *user_ctx)

    Touch sensor on software inactive event callback. (Alias of `on_sw_active` for compatibility)

    备注

    This callback is triggered by the software periodical filter. It callbacks when any touch channel is de-activated.

    Param sens_handle:

      [in] Touch sensor controller handle, created from `touch_sensor_new_controller()`

    Param event:

      [in] Touch sensor active event data

    Param user_ctx:

      [in] User registered context, passed from `touch_sensor_register_callbacks()`

    Return:

      Whether a high priority task has been waken up by this callback function

  bool (*on_hw_active)(touch_sensor_handle_t sens_handle, const touch_hw_active_event_data_t *event, void *user_ctx)

    Touch sensor on hardware active interrupt event callback.

    备注

    This callback is triggered by the hardware interrupt. It callbacks every time when any of the touch channel below or above (depended on touch_sensor_config_t::intr_trig_mode) the threshold.

    Param sens_handle:

      [in] Touch sensor controller handle, created from `touch_sensor_new_controller()`

    Param event:

      [in] Touch sensor active event data

    Param user_ctx:

      [in] User registered context, passed from `touch_sensor_register_callbacks()`

    Return:

      Whether a high priority task has been waken up by this callback function

### Macros

TOUCH_SENSOR_DEFAULT_BASIC_CONFIG(sample_cfg_number, sample_cfg_ptr)

  This file is only applicable to the touch hardware version1 Version 1 includes ESP32.

  Helper macro to the default configurations of the touch sensor controller

  参数:

    - sample_cfg_number -- [in] The number of the sample configurations, which can only be 1 here because there is only one sample configuration

    - sample_cfg_ptr -- [in] The pointer to the sample configurations

TOUCH_SENSOR_V1_DEFAULT_SAMPLE_CONFIG(duration_ms, volt_low, volt_high)

  Helper macro to the default sample configurations.

  备注

  This default configuration uses `sample frequency = clock frequency / 1`

  参数:

    - duration_ms -- [in] The measurement duration of the touch channel

    - volt_low -- [in] The low voltage limit of the touch channel

    - volt_high -- [in] The high voltage limit of the touch channel

TOUCH_SENSOR_DEFAULT_FILTER_CONFIG()

  Helper macro to the default filter configurations.

TOUCH_SENSOR_DEFAULT_LSLP_CONFIG()

  Helper macro to the default light sleep wake-up configurations.

  备注

  RTC_PERIPH will keep power on during the light sleep. Any enabled touch channel can wake-up the chip from light sleep.

TOUCH_SENSOR_DEFAULT_DSLP_CONFIG()

  Helper macro to the default deep sleep wake-up configurations.

  备注

  RTC_PERIPH will keep power on during the deep sleep. Any enabled touch channel can wake-up the chip from deep sleep.

### Type Definitions

typedef uint32_t (*touch_sw_filter_t)(touch_channel_handle_t chan_handle, const touch_sw_filter_data_t *filter_data, void *user_filter_ctx)

  Touch software filter prototype.

  备注

  Users can customize their own filter algorithm by this prototype

  Param chan_handle:

    [in] The handle of the touch channel that need to be filtered

  Param filter_data:

    [in] The data of the software filter

  Param user_filter_ctx:

    [in] User customized filter context pointer

  Return:

    - uint32_t The filtered data

typedef touch_sensor_config_t touch_sensor_config_dslp_t

  Touch sensor configuration during the deep sleep.

  备注

  Currently it is the same as the normal controller configuration. The deep sleep configuration only takes effect when the chip entered sleep, so that to update a more power efficient configuration.

typedef touch_base_event_data_t touch_active_event_data_t

  Active event data.

  备注

  Currently same as base event data

typedef touch_base_event_data_t touch_inactive_event_data_t

  Inactive event data.

  备注

  Currently same as base event data

### Enumerations

enum touch_chan_data_type_t

  The data type of the touch channel.

  Values:

  enumerator TOUCH_CHAN_DATA_TYPE_RAW

    The raw data of the touch channel

  enumerator TOUCH_CHAN_DATA_TYPE_SMOOTH

    The smooth data of the touch channel (need to config software filter fist)

enum touch_chan_trig_group_t

  Touch channel trigger group.

  Values:

  enumerator TOUCH_CHAN_TRIG_GROUP_1

    Channel will be added to the interrupt trigger group 1

  enumerator TOUCH_CHAN_TRIG_GROUP_2

    Channel will be added to the interrupt trigger group 2

  enumerator TOUCH_CHAN_TRIG_GROUP_BOTH

    Channel will be added to both interrupt trigger group 1 and 2

此文档对您有帮助吗？

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

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