Skip to content

uPesy only delivers currently in France.

Contents Menu Expand Light mode Dark mode Auto light/dark mode

Use ESP32 Capacitive Touch Sensor with Arduino Code

The ESP32 has capacitive sensors that can be used as a touch button. These are the famous “TOUCH” we find on the pinouts. There are 10 available on ESP32 uPesy boards.

My beautiful legend0

Pinout of the uPesy ESP32 Wroom Devkit board

What is that?

Capacitive sensors are widely used to detect the pressure of our fingers, especially on touch screens. They can be used on the ESP32 to replace mechanical pushbuttons.

My beautiful legend0

Capacitive touch sensors

Capacitive sensors are based on the change in capacitance (of a capacitor) when the sensor is touched. This variation is read and converted by the ADC (Analog to digital converter).

Note

Keep in mind that these capacitive sensors will not be as reliable as push buttons, especially for the use we are going to make of them .

Indeed, many parasitic capacitances come into play and can modify the measured values.

My beautiful legend0

Parasitic capacitors

It will be necessary to consider all these parameters and make an electronic circuit much more accurate and complicated to have good measurements.

My beautiful legend0

Hard to do an easier circuit :)

Use on the ESP32

The code to use the capacitive sensors is pretty straightforward: only one function is needed touchRead() .

touchRead(4);
//ou
touchRead(T0);

Note

The function parameter is either the pin number (here GPIO4) or the number of the capacitive sensor associated with the pin (here T0).

Usage is very similar to the analogRead() function.

With a short code, the measured values ​​are displayed in the serial monitor:

void setup() {
    Serial.begin(115200);
    delay(1000); // Delai pour lancer le moniteur série
    Serial.println("ESP32 Touch Demo");
}

void loop() {
    Serial.println(touchRead(4));
    delay(500);
}
My beautiful legend0

Curve displayed in the serial plotter

The hollows correspond to the moment the wire is touched. To determine if the wire has been touched, a threshold value must be defined. If we are below this threshold value, then the button has been touched.

Note

The threshold value depends on the material used (wire, length, breadboard …) and must be adjusted.

The code with the threshold is:

int capacitiveValue = 100;
int threshold = 20; //Seuil a ajuster

void setup() {
    Serial.begin(115200);
    delay(1000); // Delai pour lancer le moniteur série
    Serial.println("ESP32 Touch Demo");
}

void loop() {
    capacitiveValue = touchRead(4);
    if(capacitiveValue < threshold ){
        Serial.println("Fil touché");
        }
    delay(500);
}

That’s it for programming! You can also add aluminum foil at the end of the wire for better sensitivity. https://www.instructables.com/id/How-To-Use-Touch-Sensors-With-Arduino/

We use cookies to make your visit to the site as pleasant as possible. Privacy Policy