Touch pins on the ESP32 are a very interesting feature that allows us to perform capacitive sensing.
Capacitive sensing is based on the property that all objects (including humans) can store a small amount of electrical charge.
When we touch a touch pin, we change the capacitance in the circuit. The ESP32 can detect this change in capacitance, which allows 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 (usually labeled as T0, T1, T2, etc). The number of touch pins can vary depending on the specific development board you are using.
The ESP32’s touch sensors, in general, work quite well. They have good sensitivity and low noise. So we can use them even with fairly small pads.
Furthermore, the capacitive touch pins can be used to wake the ESP32 from deep sleep mode.
How to Read ESP32 Touch Pins
It is really very simple to use the ESP32’s touch pins in the Arduino environment. We simply 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 Threshold
If we wanted to add a threshold for touch sensor detection, it’s not much more complicated either.
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:

