switch light on/ off with pir sensor

hi all,

i am trying to switch lights on/off with pir sensor
(when motion detected lights go on and stay on, motion detected again lights go off)

the problem my variables turn to 0 after motion is detected
please see my code
is it possible to fix or pir sensor is not the right solution ?

the code:

const int sensor=2;
const int led=6;
int sensorvalue =0;
int state=0;

//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
const int calibrationTime = 30;

void setup() {
// put your setup code here, to run once:
pinMode (sensor,INPUT);
pinMode(led, OUTPUT);
Serial.begin (9600);
digitalWrite (sensor,LOW);

//give the sensor some time to calibrate
Serial.print(“calibrating sensor “);
for(int i = 0; i < calibrationTime; i++){
Serial.print(”.”);
delay(1000);
}
Serial.println(" done");
Serial.println(“SENSOR ACTIVE”);
}

void loop() {

sensorvalue = digitalRead (sensor);
Serial.print (" sensorvalue “);
Serial.print (sensorvalue);
Serial.print (” state ");
Serial.println (state);
if (sensorvalue ==1 && state==0);{
digitalWrite (led,HIGH);
delay (100);
state=1;} //lights on at this stage lights go off automatically !! please fix

if (sensorvalue==1 && state==1){
digitalWrite (led,LOW); //lights off
delay (200);
state=0;}
}

Next time please use auto format text (ctrl+T) in arduino program and code bar in this forum. Your post will be much more easier to read.

i am trying to switch lights on/off with pir sensor
(when motion detected lights go on and stay on, motion detected again lights go off)

If I understand correct you want to use PIR sensor as a switch? When PIR sensor is turning on OUTPUT is HIGH. When it's goes off OUTPUT is LOW. Do you want after PIR sensor is turning OFF lights stay ON? And after second motion detection when OUTPUT is HIGH turn lights OFF?

All what you need to do is change delay value more than PIR sensor OUTPUT time. :wink:

const int pirSensor = 2;
const int led = 6;
int sensorValue;
int state = 0;

void setup() {

  pinMode(pirSensor, INPUT);
  pinMode (led, OUTPUT);
  Serial.begin(9600);
}

void loop() {

  sensorValue = digitalRead(pirSensor);
  Serial.print (" sensorvalue ");
  Serial.print (sensorValue);
  Serial.print (" state ");
  Serial.println (state);

  if (sensorValue == HIGH)
  {
    if (state == 0)
    {
      state = 1;
      digitalWrite (led, HIGH);
      Serial.println(state);
      delay(500);
    }
    else {
      state = 0;
      digitalWrite (led, LOW);
      Serial.println(state);
      delay(500);
    }
  }
}