ESP32 Touch Sensor – Unstable Values Output Issue

arduinocapacitiveesp32touch

I am trying to implement touch functionality of esp32 development board to toggle a led. But on uploading a simple touch detection sketch, output have spikes i.e. usually value remains near 100 but falls to around 30 randomly for no reason. This triggers false touch. I have tried this with two esp32 dev boards I have and the problem persists in both. Also I have tried this with and without external wire from the touch pin.

Code I've used:-

void setup() {
  Serial.begin(115200);
}

void loop() {
  Serial.println(touchRead(27));
  delay(10);
}

Serial plotter output:-

  1. Without external wire connected with touch pin
    Without external wire connected with touch pin

  2. With external wire connected with touch pin
    With external wire connected with touch pin

UPDATE:-
3. Actual touch represented by T1, T2, T3
Actual touch

Best Answer

On studying graph, it is observed that actual touch lasts around 80 to 100 ms and false touch lasts for much less time. Although I had tried some filters before but turns out that was just too complicated, a simple filter works fine (my siliness).

Working code:-

boolean touchStarted = false;
unsigned long touchTime = 0;
int threshold = 90;
int touchMinDuration = 100;

void setup() {
  Serial.begin(115200);
}

void loop() {
  int t = touchRead(27);
  if (t < threshold && !touchStarted) { // on fresh touch
    touchStarted = true;
    touchTime = millis();
  } else if (t >= threshold && touchStarted) { // untouched
    if (millis() - touchTime > touchMinDuration)
      touched;
    touchStarted = false;
  }
  delay(10);
}

void touched(){
  Serial.println("Touched");
}

Thanks to the comments which helped me to come on this solution.

Related Topic