Help me pls

Hi all
I am new with arduino and have 1 question
i am using capacitive measure for turning on and off led

#include <CapacitiveSensor.h>
CapacitiveSensor capSensor = CapacitiveSensor (4,2);
int threshold = 1000;
const int ledPin = 12 ;
void setup () {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}
void loop(){
  long sensorValue = capSensor.capacitiveSensor(30);
  Serial.println(sensorValue);
  if (sensorValue > threshold) {
    digitalWrite(ledPin, HIGH);
  }
  else {
    digitalWrite(ledPin, LOW);
  }
  delay(10);
}

now wen touch te metal the led is turning on and wen releas its turning of
i want to make it wen press to turn on and to turn of wen press it again
i cant make the Button State Change Detection wike i say i am new and still noob
ty all

Hello, welcome to the forum. :slight_smile:

Please edit your post, select the code, and put it between [code][/code] tags.

You can do that by hitting the # button above the posting area.

Read this before posting a programming question

add a 'flag' to tell you if it is on or off

void loop(){
  long sensorValue = capSensor.capacitiveSensor(30);
  Serial.println(sensorValue);
  if ( sensorValue > threshold) {
    if (onFlag == 0){    
    digitalWrite(ledPin, HIGH);
    onFlag = 1;
  }
    if (onFlag == 1){
    digitalWrite(ledPin, LOW);
    onFlag = 0;
  }
  delay(10);
  }
}

with changes noting happends cant turn on and off the ledd

And what does the serial output tell you?

now i am tring this but now the led is turning on wen press but in second press noting happends remaning on

void loop(){
  long sensorValue = capSensor.capacitiveSensor(30);
  Serial.println(sensorValue);
  if ( sensorValue > threshold) {
    onFlag=onFlag+1 ;}
  if (onFlag>=2){
      onFlag=0;}
      
    
  if (onFlag=1){

    digitalWrite(ledPin, HIGH);}
    else{

    digitalWrite(ledPin, LOW);
    }
  delay(10);
  }

 if (onFlag=1){ wrong,

should be

if (onFlag==1){

= is an assignment == is a comparison (equality test)

anyway, CrossRoads' code is better, I suspect you did the same mistake when you tried it ;)

  if (onFlag=1){

http://www.gammon.com.au/forum/?id=12153#trap3

Ty all
I undarstanda my mistakes and all done

 #include <CapacitiveSensor.h>
CapacitiveSensor capSensor = CapacitiveSensor (4,2);
int threshold = 1000;
int buttoncounter=0;
const int ledPin = 12 ;
void setup () {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}
void loop(){
  long sensorValue = capSensor.capacitiveSensor(30);
  Serial.println(sensorValue);
  if (sensorValue > threshold) {
    buttoncounter++;
  
  }
  if (buttoncounter % 2==1){
    digitalWrite(ledPin, HIGH);}
    else {
      digitalWrite(ledPin, LOW);}
  delay(10);
}