Language: EN

esp32-touch-pins

How to use touch pins on an ESP32

The touch pins on the ESP32 are a very interesting feature that allows us to perform capacitive detection.

Capacitive detection is based on the property that all objects (including humans) can store a small amount of electric charge.

When we touch a touch pin, we change the capacitance in the circuit. The ESP32 can detect this change in capacitance, allowing us to determine if a touch has occurred.

It is possible to create a touch panel by connecting any conductive object to these pins, such as aluminum foil, conductive fabric, conductive paint, among others.

Touch Pins on the ESP32

The ESP32 has multiple touch pins (generally labeled as T0, T1, T2, etc). The number of touch pins may vary depending on the specific development board you are using.

The touch sensors of the ESP32, in general, work quite well. They have good sensitivity and low noise, allowing us to use them even with fairly small pads.

Additionally, the capacitive touch pins can be used to wake the ESP32 from deep sleep mode.

How to Read the Touch Pins of the ESP32

It’s really very simple to use the touch pins of the ESP32 under the Arduino environment. We just need to use the touchRead function.

touchRead(int pin);

Code Examples

Reading Touch Pins

For example, this is how we could read one of the touch pins.

const int touchPin0 = 4;

void setup() 
{
  Serial.begin(115200);
  delay(1000);
  Serial.println("ESP32 - Touch Raw Test");
}

void loop() {
  auto touch0raw = touchRead(touchPin0); // perform the reading
  Serial.println(touch0raw);  
  delay(1000);
}

Reading Touch Pins with Threshold

If we wanted to add a threshold for touch sensor detection, it’s not much more complicated.

const int touchPin0 = 4;
const int touchThreshold = 40; // Sensor threshold

void setup() {
    Serial.begin(115200);
    delay(1000); // Delay to launch the serial monitor
    Serial.println("ESP32 - Touch Threshold Demo");
}

void loop() {
	auto touch0raw = touchRead(touchPin0); // perform the reading   
    
    if(touch0raw < touchThreshold )
    {
        Serial.println("Touch detected");
    }
    delay(500);
}

Reading Touch Pins with Interrupts

And if we wanted to use a hardware interrupt to read the touch sensor, the code would look something like this.

int threshold = 40;
volatile bool touch1detected = false;

void gotTouch1(){
 touch1detected = true;
}

void setup() {
  Serial.begin(115200);
  delay(1000); // give me time to bring up serial monitor
  
  Serial.println("ESP32 Touch Interrupt Test");
  touchAttachInterrupt(T2, gotTouch1, threshold);
}

void loop(){
  if(touch1detected)
  {
    touch1detected = false;
    Serial.println("Touch 1 detected");
  }
}


References: