My code is basically to use a capacitive touch sensor as a switch to turn on and off an LED strip. I have made some progress since my last post, but the led strip flickers when pressed and doesn't turn on/off half of the time. What am I doing wrong?
#include <CapacitiveSensor.h>
CapacitiveSensor cs_4_8 = CapacitiveSensor(4, 8); // 1M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
//new variables------------
int sensorTolerance = 1000;
bool sensorSwitch = false;
long sensor1;
int counter = 0;
//-------------------------
void setup()
{
cs_4_8.set_CS_AutocaL_Millis(0xFFFFFFFF);// turn off autocalibrate on channel 1 - just as an example
Serial.begin(9600);
pinMode(5, OUTPUT);
}
void loop() {
sensor1 = cs_4_8.capacitiveSensor(50);
Serial.println(sensor1); // print sensor output
if (sensor1 >= sensorTolerance && counter == 0)
{
sensorSwitch = true;
counter = 1;
}
else if (sensor1 >= sensorTolerance && counter == 1)
{
sensorSwitch = false;
counter = 0;
}
//if switch is true or 'ON' turn on LED
if(sensorSwitch == true){
analogWrite(5, 100);
}
//if switch is false or 'OFF' turn off LED
else if (sensorSwitch == false) {
analogWrite(5, 0);
}
}