Help with using capacitive touch sensor to turn on and off led strip

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);
  }

}

What am I doing wrong?

Several things.

  Serial.println(sensor1);  // print sensor output

Some string of text appears in the serial monitor, but you haven't a clue what that number means. Anonymous printing sucks. Stop doing that.

  if (sensor1 >= sensorTolerance && counter == 0)
  {
    sensorSwitch = true;
    counter = 1;
   
  }
  else if (sensor1 >= sensorTolerance && counter == 1)
  {
    sensorSwitch = false;
    counter = 0;
  }

Compound if statements, when the same condition appears in both the if and the else if statement, are NOT a good idea. Nested if statements are far easier to debug.

  if(sensorSwitch == true){

  else if (sensorSwitch == false) {

Where is the else clause to deal with all the other possible values?

Think about this. What happens if sensor1 (stupid name) contains a value that is not greater than the tolerance. What does that mean with respect to the value in counter or sensorSwitch?

What, exactly, are you counting?