Control the back light LED of a LCD

Hello everybody. I would like to write a code that when I push the buttom tunr the LED ON FOR 5 SECONDS and then OFF . while I am doing this , arduino read the dth sensor data every 2 seconds simultaneously.
I wrote a code that is not working appropriately. could you help me please?

#include <LiquidCrystal.h>
#include "DHT.h"
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#define DHTPIN A0 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 22 (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);
unsigned long lcdState = 0;
unsigned long lcdInterval = 2000;
int pushB = 7;
unsigned long ledButInterval = 100;
unsigned long pushBstate = 0;
int led = 8;

void setup() {
pinMode(led, OUTPUT);
pinMode(pushB, INPUT);
dht.begin();
lcd.begin(16, 2);
lcd.print("DHT11 Sensor");
delay(2000);
lcd.clear();

}
void loop() {
unsigned long current = millis();
if (current - lcdState >= lcdInterval) {
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
lcd.setCursor(0, 0);
lcd.print("Humidity: ");
lcd.print(hif);
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.print(hic);
current = lcdState;
}
if (current - pushB >= ledButInterval) {
int B = digitalRead(pushB);
if ( B != 0) {
digitalWrite(led, HIGH);

} else {
digitalWrite(led, LOW);
}
}
}

You have several potential issues:

  1. In your DHT section you should change:
    current = lcdState;

to:

    lcdState = current;
  1. Do you have a pull-up or pull-down resistor on your button? The way you code is written implies you do. If not then use INPUT_PULLUP when configuring the pin mode.

  2. If you want to start a 5 second "timer" when you press the button then you need to look for a change in the state of the button NOT the actual state of the button.

  3. When the button is pressed you can turn on the LED then determine when to turn it off the same way you determine when to read the DHT

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.