# Capacitive Touch Sensor

[中文]

## Introduction

A touch sensor system is built on a substrate which carries electrodes and relevant connections under a protective flat surface. When the surface is touched, the capacitance variation is used to evaluate if the touch was valid.

The sensing pads can be arranged in different combinations (e.g., matrix, slider), so that a larger area or more points can be detected. The touch pad sensing process is under the control of a hardware-implemented finite-state machine (FSM) which is initiated by software or a dedicated hardware timer.

For design, operation, and control registers of a touch sensor, see ESP32 Technical Reference Manual > On-Chip Sensors and Analog Signal Processing [PDF].

In-depth design details of touch sensors and firmware development guidelines for the ESP32 are available in Touch Sensor Application Note.

## Overview of Capacitive Touch Sensor Versions

Hardware Version | Chip | Main Features
--- | --- | ---
V1 | ESP32 | Version 1, the channel value decreases when it is touched
V2 | ESP32-S2 | Version 2, the channel value increases when it is touched Supports hardware filter, benchmark, waterproof, proximity sensing and sleep wake-up
ESP32-S3 | Version 2, support proximity measurement done interrupt
V3 | ESP32-P4 | Version 3, support frequency hopping

## Measurement Principle

The touch sensor will charge and discharge the touch channel by the internal current or voltage bias. Due to the internal capacitance and the stray capacitance in the circuit, the signals on the touch pins will present as a sawtooth wave. When the finger is approaching or touched on the touch pad, the capacitance of the touch channel increases, which leads to a slower charge and discharge, and a longer sawtooth period.

The touch sensor charges and discharges the touch channel within a fixed time and counts the number of charge-discharge cycles, and the count result serves as the raw data. The duration of a single charge-discharge measurement can be specified by `touch_sensor_sample_config_t::charge_times`, and the interval between two measurements can be specified by `touch_sensor_config_t::meas_interval_us`.

Touch Sensor Working Principle

## Overview of Touch Sensor Channels

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

## Terminology in the Driver

- Touch Sensor Controller: The controller of the touch sensor, responsible for configuring and managing the touch sensor.

- Touch Sensor Channel: A specific touch sensor sampling channel. A touch sensor module has multiple touch channels, which are usually connected to the touch pad for measuring the capacitance change. In the driver, sampling of one channel is called one `measurement` and the scanning of all registered channels is called one `scan`.

- Touch Sensor Sampling Configuration: Touch sensor sampling configuration refers to all the hardware configurations that related to the sampling. It can determine how the touch channels sample by setting the number of charging times, charging frequency, measurement interval, etc. The ESP32 only support one set of sample configuration, so it doesn't support frequency hopping.

## File Structure

File Structure of Touch Sensor Driver

## Finite-state Machine

The following diagram shows the state machine of the touch sensor driver, which describes the driver state after calling a function, and the constraint of the state transition.

Finite-state Machine of Touch Sensor Driver

The diagram above is the finite-state machine of the touch sensor driver, which describes how the state transferred by invoking different APIs. `<other_configurations>` in the diagram stands for the other optional configurations, like reconfigurations to the touch sensor controller or channels, callback registration, filter, and so on.

Note

`touch_channel_read_data()` can be called at any time after the channel is registered (i.e., since `INIT` state), but please take care of the validation of the data.

## Functionality Introduction

Categorized by functionality, the APIs of Capacitive Touch Sensor mainly include:

- Touch Sensor Controller Management

- Touch Sensor Channel Management

- Filter Configuration

- Callback

- Enable and Disable

- Continuous Scan

- Oneshot Scan

- Read Measurement Data

- Sleep Wake-up Configuration

### Touch Sensor Controller Management

Touch Sensor is controlled by controller handle `touch_sensor_handle_t`, it can be initialized and allocated by `touch_sensor_new_controller()`.

    // Some target has multiple sets of sample configuration can be set, here take one for example
    #define SAMPLE_NUM 1
    touch_sensor_handle_t sens_handle = NULL;
    // sample configuration
    touch_sensor_sample_config_t sample_cfg[SAMPLE_NUM] = {
        // Specify sample configuration or apply the default sample configuration via `TOUCH_SENSOR_Vn_DEFAULT_SAMPLE_CONFIG`
        // ...
    };
    // Use the default touch controller configuration
    touch_sensor_config_t touch_cfg = TOUCH_SENSOR_DEFAULT_BASIC_CONFIG(SAMPLE_NUM, sample_cfg);
    // Allocate a new touch sensor controller handle
    ESP_ERROR_CHECK(touch_sensor_new_controller(&touch_cfg, &sens_handle));

To delete the controller handle and free the software and hardware resources, please call `touch_sensor_del_controller()`. But note that you need to delete the other resources that based on the controller first, like the registered touch channels, otherwise it can't be deleted directly.

    ESP_ERROR_CHECK(touch_sensor_del_controller(sens_handle));

You can also update the configurations via `touch_sensor_reconfig_controller()` before the controller is enabled.

    touch_sensor_config_t touch_cfg = {
        // New controller configurations
        // ...
    };
    ESP_ERROR_CHECK(touch_sensor_reconfig_controller(sens_handle, &touch_cfg));

### Touch Sensor Channel Management

There are multiple touch channels in the touch sensor module, the touch sensor channel is controlled by the channel handle `touch_channel_handle_t`. It can be initialized and allocated by `touch_sensor_new_channel()`.

    // ...
    touch_channel_config_t chan_cfg = {
        // Touch channel configurations
        // ...
    };
    touch_channel_handle_t chan_handle = NULL;
    int chan_id = 0;
    // Allocate a new touch sensor controller handle
    ESP_ERROR_CHECK(touch_sensor_new_channel(sens_handle, chan_id, &chan_cfg, &chan_handle));

To delete the touch channel handle and free the software and hardware resources, please call `touch_sensor_del_channel()`.

    ESP_ERROR_CHECK(touch_sensor_del_channel(chan_handle));

You can also update the configurations via `touch_sensor_reconfig_channel()` before the controller is enabled.

    touch_channel_config_t chan_cfg = {
        // New touch channel configurations
        // ...
    };
    ESP_ERROR_CHECK(touch_sensor_reconfig_channel(chan_handle, &chan_cfg));

### Filter Configuration

The filter can help to increase the stability in different use cases. The filter can be registered by calling `touch_sensor_config_filter()` and specify the configurations `touch_sensor_filter_config_t`. These configurations mainly determine how to filter and update the benchmark and read data. Please note that all touch channels will share this filter.

To deregister the filter, you can call `touch_sensor_config_filter()` again, and set the second parameter (i.e. `touch_sensor_filter_config_t` pointer) to `NULL`.

The touch sensor version v1 does not natively support the hardware filter, but the driver can set up a periodically triggered software filter based on `esp_timer`. The interval for the software filter can be specified by `touch_sensor_filter_config_t::interval_ms`. Additionally, the `touch_sensor_filter_config_t::data_filter_fn` supports to specify a custom filtering function. If there are no special filter requirements, this interface can be set to `NULL` to use the default filter in the driver.

    // ...
    touch_sensor_filter_config_t filter_config = {
        // Filter configurations
        // ...
    };
    // Register the filter
    ESP_ERROR_CHECK(touch_sensor_config_filter(sens_handle, &filter_config));
    // ...
    // Deregister the filter
    ESP_ERROR_CHECK(touch_sensor_config_filter(sens_handle, NULL));

### Callback

Calling `touch_sensor_register_callbacks()` to register the touch sensor event callbacks. Once the touch sensor events (like `on_active`, `on_inactive`) trigger, the corresponding callbacks will be invoked, so that to deal with the event in the upper application.

For the general example, when the measured data of the current touch channel exceed the `benchmark` + `active_threshold`, this channel is activated, and the driver will call `on_active` callback to inform the application layer. Similar, when the active channel measured a lower data than `benchmark` + `active_threshold`, then this channel will be inactivated, and `on_inactive` will be called to inform this channel is released.

Note

To ensure the stability of the triggering and releasing, `active_hysteresis` and `debounce_cnt` can be configured to avoid the frequent triggering that caused by jitter and noise.

Please refer to `touch_event_callbacks_t` for the details about the supported callbacks.

    touch_event_callbacks_t callbacks = {
        .on_active = example_touch_on_active_cb,
        // Other callbacks
        // ...
    };
    // Register callbacks
    ESP_ERROR_CHECK(touch_sensor_register_callbacks(sens_handle, &callbacks, NULL));

    // To deregister callbacks, set the corresponding callback to NULL
    callbacks.on_active = NULL;
    // Other callbacks to deregister
    // ...
    ESP_ERROR_CHECK(touch_sensor_register_callbacks(sens_handle, &callbacks, NULL));

### Enable and Disable

After finished the configuration of the touch controller and touch channels, `touch_sensor_enable()` can be called to enable the touch sensor controller. It will enter `READY` status and power on the registered channels, then you can start scanning and sampling the touch data. Note that you can only do scanning and reading operation once the controller is enabled. If you want to update the controller or channel configurations, you need to call `touch_sensor_disable()` first.

    // Enable touch sensor
    ESP_ERROR_CHECK(touch_sensor_enable(sens_handle));
    // ...
    // Disable touch sensor
    ESP_ERROR_CHECK(touch_sensor_disable(sens_handle));

### Continuous Scan

With the touch controller enabled, `touch_sensor_start_continuous_scanning()` can be called to start the continuous scanning to all the registered touch channels. The read data of these touch channels will be updated automatically in each scan. Calling `touch_sensor_stop_continuous_scanning()` can stop the continuous scan.

    // Start continuous scan
    ESP_ERROR_CHECK(touch_sensor_start_continuous_scanning(sens_handle));
    // ...
    // Stop continuous scan
    ESP_ERROR_CHECK(touch_sensor_stop_continuous_scanning(sens_handle));

### Oneshot Scan

With the touch controller enabled, `touch_sensor_trigger_oneshot_scanning()` can be called to trigger an one-time scan to all the registered touch channels. Note that oneshot scan is a blocking function, it will keep blocking and only return when the scan is finished. Moreover, you can't trigger an oneshot scan after the continuous scan has started.

    // Trigger an oneshot scan with timeout 1000 ms
    ESP_ERROR_CHECK(touch_sensor_trigger_oneshot_scanning(sens_handle, 1000));

### Read Measurement Data

Call `touch_channel_read_data()` to read the data with different types. Like, benchmark, smooth data, etc. You can refer to `touch_chan_data_type_t` for the supported data types.

    #define SAMPLE_NUM  1  // Take one sample configuration set for example
    uint32_t smooth_data[SAMPLE_NUM] = {};
    // Read the smooth data
    ESP_ERROR_CHECK(touch_channel_read_data(chan_handle, TOUCH_CHAN_DATA_TYPE_SMOOTH, smooth_data));

### Sleep Wake-up Configuration

The ESP32 supports waking-up the chip from light sleep or deep sleep with the touch sensor as a wake-up source. The wake-up functionality can be registered by calling `touch_sensor_config_sleep_wakeup()` and specifying the configurations `touch_sleep_config_t`.

After registering the touch sensor sleep wake-up, the chip will continue to sample the touch channels after sleep, which will increase the power consumption during the sleep. To reduce the sleep power consumption, you can reduce the number of charging and discharging times, increase the sampling interval, etc.

Moreover, please note that the operations like sampling, wake-up are all done by hardware when the main core is sleeping. Since this driver runs on the main core, it cannot provide functions such as reading or configuring during the sleep.

- Light sleep wake-up: you need to set `slp_wakeup_lvl` to `TOUCH_LIGHT_SLEEP_WAKEUP` to enable the light sleep wake-up by touch sensor. Note that any registered touch channel can wake-up the chip from light sleep.

- Deep sleep wake-up: you need to set `slp_wakeup_lvl` to `TOUCH_DEEP_SLEEP_WAKEUP` to enable the deep sleep wake-up by touch sensor. Note that in version v1, enabling Deep-sleep wake-up will keep the RTC domain power on during the deep-sleep to maintain the operation of the touch sensor. At this time, any registered touch sensor channels can continue sampling and support waking up from Deep-sleep.

To deregister the sleep wake-up function, you can call `touch_sensor_config_sleep_wakeup()` again, and set the second parameter (i.e. `touch_sleep_config_t` pointer) to `NULL`.

    touch_sleep_config_t light_slp_cfg = TOUCH_SENSOR_DEFAULT_LSLP_CONFIG();
    // Register the light sleep wake-up
    ESP_ERROR_CHECK(touch_sensor_config_sleep_wakeup(sens_handle, &light_slp_cfg));
    // ...
    // Deregister the light sleep wake-up
    ESP_ERROR_CHECK(touch_sensor_config_sleep_wakeup(sens_handle, NULL));
    // Default Deep-sleep wake-up configurations: RTC_PERIPH will keep power on during the Deep-sleep,
    // All enabled touch channel can wake-up the chip from Deep-sleep
    touch_sleep_config_t deep_slp_cfg = TOUCH_SENSOR_DEFAULT_DSLP_CONFIG();
    // Default Deep-sleep wake-up power down configurations: RTC_PERIPH will be powered down during the Deep-sleep,
    // only the specified sleep pad can wake-up the chip from Deep-sleep
    // touch_sleep_config_t deep_slp_cfg = TOUCH_SENSOR_DEFAULT_DSLP_PD_CONFIG(sleep_channel, slp_chan_thresh1, ...);
    // Register the deep sleep wake-up
    ESP_ERROR_CHECK(touch_sensor_config_sleep_wakeup(sens_handle, &deep_slp_cfg));

## Application Examples

> - peripherals/touch_sensor/touch_sens_basic demonstrates how to register touch channels and read the data, including hardware requirements and project configuration instructions.

> - peripherals/touch_sensor/touch_sens_sleep demonstrates how to wake up the chip from the light or deep sleep by the touch sensor.

## Application Notes

### Touch Sensor Power Consumption Issues

Due to the capacitive charging and discharging operation in the touch sensor measurements, it is a relatively high power-consuming peripheral. In applications with high power consumption requirements, the following methods can be helpful to reduce the power consumption.

- Reduce the number of touch channels: Multiple functions (such as single-press, double-press, long press, etc.) can be multiplexed on the same channel, thereby reducing the number of touch sensors.

- Increase the measurement interval: By increasing the measurement interval `touch_sensor_config_t::meas_interval_us`, the measurement frequency will be reduced, thereby lowering down the power consumption.

- Reduce single measurement duration: By decreasing the single measurement duration `touch_sensor_sample_config_t::charge_duration_ms`, the number of charging and discharging cycles is reduced, resulting in lower power consumption.

- Lower down the charging and discharging amplitudes: `touch_sensor_sample_config_t::charge_volt_lim_l` and `touch_sensor_sample_config_t::charge_volt_lim_h` can specify the lower voltage limit during the discharging and the upper voltage limit during the charging. Reducing both voltage limitations and the voltage error between them can also decrease the power consumption.

- Reduce the current bias intensity: Lowering down `touch_channel_config_t::charge_speed` (i.e., the current magnitude of the current bias) can help to reduce the power consumption.

## API Reference

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

  Note

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

  Parameters:

    - sens_cfg -- [in] Touch sensor controller configurations

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

  Returns:

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

  Note

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

  Parameters:

    sens_handle -- [in] Touch sensor controller handle

  Returns:

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

  Note

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

  Parameters:

    - 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

  Returns:

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

  Note

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

  Note

  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.

  Parameters:

    chan_handle -- [in] Touch channel handle

  Returns:

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

  Note

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

  Note

  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.

  Parameters:

    - sens_handle -- [in] Touch sensor controller handle

    - sens_cfg -- [in] Touch sensor controller configurations

  Returns:

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

  Note

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

  Note

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

  Parameters:

    - chan_handle -- [in] Touch channel handle

    - chan_cfg -- [in] Touch channel configurations

  Returns:

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

  Note

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

  Parameters:

    - sens_handle -- [in] Touch sensor controller handle

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

  Returns:

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

  Note

  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.

  Note

  Enable the touch sensor will power on the registered touch channels

  Parameters:

    sens_handle -- [in] Touch sensor controller handle

  Returns:

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

  Note

  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.

  Note

  Disable the touch sensor will power off the registered touch channels

  Parameters:

    sens_handle -- [in] Touch sensor controller handle

  Returns:

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

  Note

  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.

  Note

  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.

  Parameters:

    sens_handle -- [in] Touch sensor controller handle

  Returns:

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

  Note

  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.

  Note

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

  Parameters:

    sens_handle -- [in] Touch sensor controller handle

  Returns:

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

  Note

  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.

  Note

  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.

  Parameters:

    - 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

  Returns:

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

  Note

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

  Parameters:

    - sens_handle -- [in] Touch sensor controller handle

    - callbacks -- [in] Callback functions

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

  Returns:

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

  Note

  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.

  Note

  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.

  Parameters:

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

  Returns:

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

  Note

  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.

  Parameters:

    - 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

  Returns:

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

  Parameters:

    - chan_handle -- [in] Touch channel handle

    - chan_info -- [out] Touch channel information

  Returns:

    - 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

### Macros

TOUCH_TOTAL_CHAN_NUM

  The total channel number of the touch sensor

TOUCH_SAMPLE_CFG_NUM

  The supported max sample configuration number

TOUCH_MIN_CHAN_ID

  The minimum available channel id of the touch pad

TOUCH_MAX_CHAN_ID

  The maximum available channel id of the touch pad

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

  Note

  Set NULL for the unused callbacks.

  Note

  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.

    Note

    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)

    Note

    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.

    Note

    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)

    Note

    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.

    Note

    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

  Parameters:

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

  Note

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

  Parameters:

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

  Note

  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.

  Note

  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.

  Note

  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.

  Note

  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.

  Note

  Currently same as base event data

typedef touch_base_event_data_t touch_inactive_event_data_t

  Inactive event data.

  Note

  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

Was this page helpful?

- Thank you! We received your feedback.
- If you have any comments, fill in Espressif Documentation Feedback Form.

- We value your feedback.
- Let us know how we can improve this page by filling in Espressif Documentation Feedback Form.