#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <RTClib.h> // Include the RTC library
#define DHTPIN 2 // DHT22 data pin is connected to digital pin 2
#define DHTTYPE DHT22 // DHT type is DHT22
#define NUM_BARS 5 // Number of bars for graphical representation
DHT dht(DHTPIN, DHTTYPE);
// Set the LCD address to 0x27 for a 20 chars and 4 line display
LiquidCrystal_I2C lcd(0x27, 20, 4);
RTC_DS1307 rtc; // Create an instance of the RTC DS1307 object
unsigned long previousMillis = 0;
const long interval = 1000; // Interval between updates in milliseconds (5 seconds)
float lastTemperature = 0.0;
float lastHumidity = 0.0;
void setup() {
Serial.begin(9600);
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the backlight
dht.begin();
Wire.begin(); // Initialize I2C communication
rtc.begin(); // Initialize RTC
// If the RTC isn't running, set it to the time of compilation
if (!rtc.isrunning()) {
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
}
void loop() {
unsigned long currentMillis = millis(); // Current time
// Check if it's time to update
if (currentMillis - previousMillis >= interval) {
// Update previousMillis to current time
previousMillis = currentMillis;
// Read temperature and humidity
float temperature = dht.readTemperature(); // Read temperature in Celsius
float humidity = dht.readHumidity(); // Read humidity
// Convert temperature from Celsius to Fahrenheit
temperature = (temperature * 9 / 5) + 32;
// Read current time from RTC
DateTime now = rtc.now();
// Check if temperature or humidity has changed
if (temperature != lastTemperature || humidity != lastHumidity) {
// Update last temperature and humidity
lastTemperature = temperature;
lastHumidity = humidity;
// Clear and update temperature
lcd.setCursor(0, 0);
lcd.print(" "); // Clear the line
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print("F"); // Display temperature in Fahrenheit
// Clear and update humidity
lcd.setCursor(0, 1);
lcd.print(" "); // Clear the line
lcd.setCursor(0, 1);
lcd.print("Humidity: ");
lcd.print(humidity);
lcd.print("%");
}
// Clear and update current time
lcd.setCursor(0, 3);
lcd.print(" "); // Clear the line
lcd.setCursor(0, 3);
lcd.print("Time: ");
lcd.print(now.hour());
lcd.print(":");
if (now.minute() < 10) {
lcd.print("0");
}
lcd.print(now.minute());
lcd.print(":");
if (now.second() < 10) {
lcd.print("0");
}
lcd.print(now.second());
}
}