avoiding immediately turning relay on or off.

I have a relay to control the backlight of the lcd using a relay.

    // Turn on LCD backlight when motion detected at night and day.
    digitalWrite(RELAY2, (photoresistorValue >= 700) || pir_sensor_value);

but sometimes

photoresistorValue

is closely shuffling near ± 700 ,
so I want to know a way that of a condition is set to true it should not immidiately turn of relay but wait for a while instead to meet the new condition .

Treat the photoresistorValue as a switch and debounce it.

Use hysteresis. Turn the backlight on at or greater than 700, but off at, say, 650 or less.

groundFungus:
Use hysteresis. Turn the backlight on at or greater than 700, but off at, say, 650 or less.

Agreed, this is how it's done in many products (eg thermostats)

Can you please review my code?

int RELAY2 = D4;
int RELAY3 = D5;
int RELAY4 = D6;
int photoresistor = A0;
int pir_sensor_value = 0;
int photoresistorValue = 0;

#define PIR_SENSOR_PIN D7

int backlightState = HIGH ;
int reading = LOW;
int relay2State;
int lastRelay2State = LOW;

unsigned long lastDebounceTime = 0; // the last time the output 
unsigned long debounceDelay = 50; // the debounce time; increase of the output flickers.

void setup() {
    //Initilize the relay control pins as output
    pinMode(RELAY2, OUTPUT);
    pinMode(RELAY3, OUTPUT); // D5
    pinMode(RELAY4, OUTPUT);
    pinMode(photoresistor, INPUT);
    pinMode(PIR_SENSOR_PIN, INPUT);  
}

void loop (){
   if (photoresistorValue >= 700 || pir_sensor_value){
        reading = HIGH;
    }
    else {
        reading = LOW;
    }
    if (reading != lastRelay2State) {
        // reset the debouncing timer
        lastDebounceTime = millis();
    }
    
    if ((millis() - lastDebounceTime) > debounceDelay) {
        // whatever the reading is at, it's been there for longer than the debounce
        // delay, so take it as the actual current state:
    
        // if the button state has changed:
            if (reading != relay2State) {
              relay2State = reading;
        
              // only toggle the LED if the new button state is HIGH
              if (relay2State == HIGH) {
                backlightState = !backlightState;
              }
            }
        }
    // Set the backlight of lcd
    digitalWrite(RELAY2, backlightState);
}

Well, it doesn't compile, so not really.

seaurchin:
Can you please review my code?

please share the whole sketch, and add descriptions/comments where neccesairy

Now it shoudld work I have udpated my code, the debounce doesnt seem to be working correctly the backlight stays on forever.