🛠 Détecter un contact avec les broches tactiles capacitives

ESP32-S2 · intermediaire · Schéma : IMG-esp32-s2-intermediaire-2-esp32-s2-tactile-capacitif.svg — Plaque de cuivre autocollante reliée au GPIO4 de l'ESP32-S2 servant de touche tactile capacitive, LED avec résistance de 330 Ω sur GPIO2, doigt posé sur la plaque.

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials