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 do capacitive detection.

Capacitive detection is based on the ability of objects and humans to store a small amount of electric charge.

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

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

Touch pins on the ES32

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, are quite good. They have good sensitivity and low noise, so we can use them even with fairly small pads.

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

How to read the touch pins of the ESP32

It is really easy to use the touch pins of the ESP32 under the Arduino environment. We just have 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 a threshold

If we wanted to add a threshold for the touch sensor detection, it is not much more complicated. Sim

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 be 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: