#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
// LCD setup
#define I2C_ADDR 0x27
#define LCD_COLUMNS 20
#define LCD_LINES 4
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
// DHT22 setup
#define DHTPIN1 2 // Pin for the first DHT22 sensor
#define DHTPIN2 3 // Pin for the second DHT22 sensor
#define DHTTYPE DHT22
DHT dht1(DHTPIN1, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);
// Timing variables
unsigned long lastUpdateTime = 0; // Store the last update time
const unsigned long updateInterval = 500; // Update every 500 ms (0.5 seconds)
void setup() {
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Initializing...");
// Initialize DHT sensors
dht1.begin();
dht2.begin();
delay(2000); // Allow sensors to stabilize
lcd.clear();
}
void loop() {
// Check if it's time to update the display
if (millis() - lastUpdateTime >= updateInterval) {
lastUpdateTime = millis(); // Reset the timer
// Read data from DHT1
float temp1 = dht1.readTemperature(true); // Fahrenheit
float hum1 = dht1.readHumidity();
// Read data from DHT2
float temp2 = dht2.readTemperature(true); // Fahrenheit
float hum2 = dht2.readHumidity();
// Check for read errors
if (isnan(temp1) || isnan(hum1) || isnan(temp2) || isnan(hum2)) {
lcd.setCursor(0, 0);
lcd.print("Sensor error! ");
return;
}
// Update LCD without flickering
lcd.setCursor(0, 0);
lcd.print("S1: ");
lcd.print(temp1, 1);
lcd.print("F ");
lcd.print(hum1, 1);
lcd.print("% "); // Ensure to overwrite any leftover characters
lcd.setCursor(0, 1);
lcd.print("S2: ");
lcd.print(temp2, 1);
lcd.print("F ");
lcd.print(hum2, 1);
lcd.print("% "); // Overwrite leftover characters
lcd.setCursor(0, 2);
lcd.print("Avg Temp: ");
float avgTemp = (temp1 + temp2) / 2;
lcd.print(avgTemp, 1);
lcd.print("F ");
lcd.setCursor(0, 3);
lcd.print("Avg Hum: ");
float avgHum = (hum1 + hum2) / 2;
lcd.print(avgHum, 1);
lcd.print("% ");
}
// You can add other non-blocking code here
}