Hey guys I need help to modify my code after the button is pressed, the loop runs indefinitely only after the button is pressed. The problem is that the code sometimes runs after the button is pressed. Thanks.
#include <LiquidCrystal.h>
// Initializes lcd library
#define DHT11Pin 7
//where the dht11 sensor data is going to
// ******** Variables Here *******
int run;
int buttonPin;
DHT dht(DHT11Pin, DHT11);
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
// ******** Setup Here ********
void setup() {
//Start serial or wire or whatever else you need
//Do all your other typical setup stuff
// put your setup code here, to run once:
// initialize the serial communications:
Serial.begin(9600);
//sets the rows and characters in the lcd
lcd.begin(16,2);
//lcd prints a welcome messege
lcd.print("Welcome IDEX");
delay(4000);
buttonPin = 6; // setting button to pin 6
pinMode(buttonPin, INPUT_PULLUP); // not sure what this does...
}
// *********** Main Program Here ***********
void loop() {
if(digitalRead(buttonPin) == LOW) // If button is pushed enter this loop
{
while(digitalRead(buttonPin) == HIGH) {
// wait 5 seconds between readings
delay(5000);
// get humidity
float humidity = dht.readHumidity();
// get temperature as C
int celsius = dht.readTemperature();
// get temperature as F
int fahrenheit = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(celsius) || isnan(fahrenheit)) {
lcd.print("DHT sensor Fail!");
Serial.print("DHT sensor Fail!");
return;
}
// print results
//set humidity in the first row
lcd.setCursor(0,0);
// prints values to serial comm and the lcd
lcd.print("Humidity:");lcd.print(humidity);
Serial.print("Humidity: "); Serial.print(humidity);
//set Fahrenheit in the second row
lcd.setCursor(0,2);
lcd.print("F:");lcd.print(fahrenheit);lcd.print((char)223);
Serial.print(" Fahrenheit: "); Serial.print(fahrenheit);
lcd.print(" C:");lcd.print(celsius);lcd.print((char)223);
Serial.print(" Celsius: "); Serial.println(celsius);}
}
}