I2C LCD display on / off with toggle state


I need some help related to LCD backlight.

I want to turn ON backlight when pump state change either ON to OFF or OFF to ON and stay on for few second then turn OFF.

below part of the sketch is only working when state change ON to OFF but when ON it will keep on.

bool backlightState = false;
uint32_t backlightStartTime = 0;
bool Pump_State = false;

  if (Pump_State == true)
    backlightState = true;
    backlightStartTime = millis();
     lcd.backlight(); // turn on backlight.

  if ( backlightState == true && millis() - backlightStartTime >= 3000 )
    backlightState = false;
   lcd.noBacklight(); // turn off backlight


Have a look at the state change detection method to detect the transition from on to off or off to on (instead of is off or is on).

And for timing the delay without delay() the beginner's guide to millis().