#include <LiquidCrystal_I2C.h>
#include <DHT.h>
// LCD settings
LiquidCrystal_I2C lcd(0x27, 16, 2); // LCD address and dimensions
// DHT sensor settings (upgrade to DHT22 for wider range)
#define DHTPIN 11 // Pin where the DHT is connected
#define DHTTYPE DHT22 // Use DHT22 for real-life weather station, supports negative values
DHT dht(DHTPIN, DHTTYPE);
// Custom degree symbol
byte degree_symbol[8] = {
0b00111,
0b00101,
0b00111,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};
// Calibration offsets (adjust these if you have calibration data)
float tempCalibrationOffset = 0.0; // Temperature offset (for sensor calibration)
float humCalibrationOffset = 0.0; // Humidity offset
void setup()
{
lcd.init(); // Initialize the LCD
lcd.backlight();
lcd.print("Temp = ");
lcd.setCursor(0, 1);
lcd.print("Humidity = ");
lcd.createChar(1, degree_symbol); // Create degree symbol
lcd.setCursor(9, 0);
lcd.write(1); // Display degree symbol
lcd.print("C");
lcd.setCursor(13, 1);
lcd.print("%");
dht.begin(); // Initialize the DHT sensor
}
void loop()
{
// DHT11 needs a 2-second interval between readings
delay(2000);
const int numReadings = 5; // Number of readings to average
float tempSum = 0;
float humSum = 0;
int validReadings = 0;
// Take multiple readings for better accuracy
for (int i = 0; i < numReadings; i++) {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Check if readings are valid
if (!isnan(temperature) && !isnan(humidity)) {
tempSum += temperature;
humSum += humidity;
validReadings++;
}
delay(1000); // Wait 1 second between readings
}
if (validReadings > 0) {
// Calculate average and apply calibration offsets
float avgTemp = (tempSum / validReadings) + tempCalibrationOffset;
float avgHum = (humSum / validReadings) + humCalibrationOffset;
// Ensure values are within sensor's range
avgTemp = constrain(avgTemp, -40.0, 80.0); // Adjust as needed for your sensor
avgHum = constrain(avgHum, 0.0, 100.0);
// Clear previous temperature value
lcd.setCursor(7, 0);
lcd.print(" "); // Clear four characters
lcd.setCursor(7, 0);
lcd.print(avgTemp, 1); // Display temperature with 1 decimal, supports negative values
// Clear previous humidity value
lcd.setCursor(11, 1);
lcd.print(" "); // Clear four characters
lcd.setCursor(11, 1);
lcd.print(avgHum, 1); // Display humidity with 1 decimal
} else {
// Display error if readings are invalid
lcd.setCursor(7, 0);
lcd.print("Err ");
lcd.setCursor(11, 1);
lcd.print("Err ");
}
}