ESP32 touch pin to control relay

Hello,
So I am using the touch pins of an ESP32 to control a relay to start a device, I have achieved my goal but the issue Im having is that due to interference the capacitance of the touch pins reduces below my threshold sometimes even going to 0, thereby triggering my relay without even giving input, so i figured id try to introduce a time function (millis()) to read the value for say 2 secs and until and unless the same value is read for that said time, only then would the relay get triggered, im having trouble with the code as millis() is continuous as soon as it starts, could you guys look at my code and help me solve my trouble?

const int touchPin5 = 13;

const int relay5 = 19;

const int threshold = 40;

int stayOn = 3000;

unsigned long startTime = 0;

void setup()
{
Serial.begin(9600);
Serial.println("Touch sensor tutorial ESP32");

pinMode (relay5, OUTPUT);
digitalWrite(relay5, HIGH);

}

void loop()
{
int touchValue5;
touchValue5 = touchRead(touchPin5);
Serial.print("Touch0 value is = ");
Serial.println( touchValue5);
delay(500);

if(touchValue5 < threshold)
{

digitalWrite(relay5, HIGH); 

}
if((touchValue5 < threshold) && ((millis() - startTime) + 2000UL) > (millis() - startTime))
{
Serial.println(millis() - startTime);
digitalWrite(relay5, LOW);
Serial.println(" - LED ON");
delay(stayOn);
digitalWrite(relay5, HIGH);

}

}

Thank You & Cheers

The easier you make it to read and copy your code the more likely it is that you will get help

Please follow the advice given in the link below when posting code , use code tags and post the code here

One obvious problem is that you never save the value of startTime so it will always be zero

Have you read this tutorial: Using millis() for timing. A beginners guide ?
From the code you posted I suspect not, it will help you use millis() for timing.

So how do i rectify my code?

I rectified my code. and its working as to how i want it, thanks for the suggestions

1 Like

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.