🛠 Détecter un contact avec les broches tactiles capacitives
Objectives
Leverage the specific advantage of the ESP32-S2: 14 hardware capacitive touch pins (GPIO1 to GPIO14). Learn to read capacitance with touchRead, calibrate a threshold, and trigger an action upon finger contact.
Hardware
- ESP32-S2 board
- Adhesive copper tape (or metal plate, or simply a 5 cm wire)
- 1 LED + 330 Ω resistor
- Dupont cables
Complete code
// Tactile capacitif sur ESP32-S2 (GPIO1 a GPIO14 seulement)
const uint8_t TACT_PIN = 4; // broche tactile capacitive
const uint8_t LED_PIN = 2;
uint16_t seuil = 0; // calibre au demarrage
void setup {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
delay(500);
uint32_t somme = 0;
for (int i = 0; i < 50; i++) { somme += touchRead(TACT_PIN); delay(5); }
seuil = somme / 50 + 2000; // valeur au repos + marge
Serial.printf("Seuil calibre : %u\n", seuil);
}
void loop {
uint16_t valeur = touchRead(TACT_PIN);
bool touche = valeur > seuil;
digitalWrite(LED_PIN, touche ? HIGH : LOW);
static uint16_t derniere = 0;
if (abs((int)valeur - (int)derniere) > 100) { // limite le spam
Serial.printf("touch=%u touche=%s\n", valeur, touche ? "OUI" : "non");
derniere = valeur;
}
delay(50);
}
Expected verification
At startup, the program calibrates the threshold based on the resting value. The serial monitor displays the measured capacitance; as soon as a finger touches the copper plate, the value exceeds the threshold, the LED turns on, and "touch=YES" is displayed. Without contact, the LED remains off.
Common errors
- Choosing a pin outside GPIO1-14: only this range is touch-capable on the S2; a
touchReadon GPIO2 returns an inconsistent value. - Hardcoding the threshold in the code without calibration: humidity and wiring shift the resting value, so always calibrate at startup.
- Calibrating with a finger on the sensor: the threshold becomes skewed and no contact is detected anymore; remove your hand during
setup. - Touch wire too long without insulation: the sensor becomes unstable, keep it under 10 cm.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinorespiration.inoArduinodht22.inoArduinooled-i2c.inoArduinoserveur-web.inoArduino