#include "DHT.h"
#include "LiquidCrystal.h"
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal LCD(12, 8, A5, A4, A3, A2);
float temp;
float humidity;
float oldTemp = NAN;
float oldHumidity = NAN;
unsigned long lastRead = 0;
const unsigned long interval = 2000;
void setup() {
Serial.begin(9600);
dht.begin();
LCD.begin(16, 2);
LCD.print("DHT22 Monitor");
delay(1000);
LCD.clear();
// Colon aligned to column 8
LCD.setCursor(0, 0);
LCD.print("Temp :"); // Temp + 4 spaces + :
LCD.setCursor(0, 1);
LCD.print("Humidity:"); // Already ends at colon in col 8
}
void loop() {
if (millis() - lastRead >= interval) {
lastRead = millis();
readSensor();
displayData();
}
}
void readSensor() {
temp = dht.readTemperature();
humidity = dht.readHumidity();
if (isnan(temp) || isnan(humidity)) {
LCD.clear();
LCD.setCursor(0, 0);
LCD.print("Sensor Error!");
}
}
void displayData() {
if (temp != oldTemp) {
LCD.setCursor(10, 0);
char buf[8];
dtostrf(temp, 5, 1, buf); // width 5, 1 decimal
LCD.print(buf); // aligned on decimal
LCD.write(223);
LCD.print("C");
oldTemp = temp;
}
if (humidity != oldHumidity) {
LCD.setCursor(10, 1);
char buf[8];
dtostrf(humidity, 5, 1, buf); // width 5, 1 decimal
LCD.print(buf); // aligned on decimal
LCD.print("%");
oldHumidity = humidity;
}
}