Hey guy! I'm new to the world of programming and arduinos. I made an automatic relay switch that turns on my space heater when the temperature is at certain level. It also displays the temp and humidity on a 16x2 LCD screen. I've managed to patch together some code and it works, but i'm wondering how I could improve a few things. Mainly the fact that when I unplug the sensor it changes the text on screen and then when I plug it back in the text is all jumbled because I can't just clear the screen to reset it or else I will lose what i've set into the setup().
Example:
#include "DHT.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Defines LCD variable
#define DHTPIN 2 // DHT22 is connected to D2 pin
#define DHTTYPE DHT22 // DHT 22 (AM2302)
#define relaytwo 7 //Relay pin IN2 is connected to D7
#define relayone 5 //Relay pin IN1 is connected to D5
//Control Points
#define TEMPHIGH 76 // Turn off if higher than 79
#define TEMPLOW 73 // Turn on if lower than 74
DHT dht(DHTPIN, DHTTYPE);
void setup() {
pinMode(relaytwo, OUTPUT);
digitalWrite(relaytwo, true);
pinMode(relayone, OUTPUT);
digitalWrite(relayone, true);
lcd.begin(16,2);
dht.begin();
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Temp: ");
lcd.setCursor(0,1);
lcd.print("Humidity: ");
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature(true); //true means farenheit
// Check if h or t is-not-a-number, if its not then print error
if (isnan(h) || isnan(t)) {
digitalWrite(relayone, HIGH); // Sets relay to off if no input detected
lcd.setCursor(0,0);
lcd.print("Failed to read");
lcd.setCursor(0,1);
lcd.print("from DHT sensor!");
return;
}
//Move cursor to end of word Temp: and print reading to 2 decimals
lcd.setCursor(6,0);
lcd.print(t,2);
//Move cursor to end of word Humidity: and print to 2 decimals
lcd.setCursor(10,1);
lcd.print(h,2);
if(t > TEMPHIGH) {
digitalWrite(relayone, HIGH);
}
else
{
if(t < TEMPLOW)
digitalWrite(relayone, LOW);
}
}
As you can see in the loop it checks if the h or t variable is not a number. If it's not a number then it displays an error. The problem is when it becomes a number again (plugging the sensor back in) it doesn't reset the screen back to the way it was. So it puts this on screen "Failed to72read from40sensor"
If I were to just clear the screen then it would skip the part of the setup function where it prints Temp: and Humidity:.
I'm just not sure what to do with the logic in order to get it to clear the error from the screen and go back to displaying "Temp:72 Humidity:40" if I were to unplug the sensor and plug it back in.
I hope this made sense.
Thank you!