#include <EEPROM.h>
#include "DHT.h"
#define DHTPIN 4
#define DHTTYPE DHT22
#define EEPROM_SIZE 512
DHT dht(DHTPIN, DHTTYPE);
int logCount = 0;
float prevTemp = -100;
float prevHum = -100;
// Display all logs
void displayLogs() {
Serial.println("----- COMPLETE LOG -----");
int count = EEPROM.read(0);
for(int i=0;i<count;i++) {
int base = 1 + i*4;
int16_t tempStored;
int16_t humStored;
EEPROM.get(base, tempStored);
EEPROM.get(base+2, humStored);
float temp = tempStored / 10.0;
float hum = humStored / 10.0;
Serial.print("Log ");
Serial.print(i+1);
Serial.print(" → Temp: ");
Serial.print(temp,1);
Serial.print(" C Humidity: ");
Serial.print(hum,1);
Serial.println(" %");
}
Serial.println("------------------------");
}
void setup() {
Serial.begin(115200);
EEPROM.begin(EEPROM_SIZE);
dht.begin();
Serial.println("ESP32 Sensor Logging Started");
delay(5000);
// Reset logs
EEPROM.write(0,0);
EEPROM.commit();
logCount = 0;
}
void loop() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if(isnan(temperature) || isnan(humidity)) {
Serial.println("DHT Read Failed");
delay(2000);
return;
}
Serial.print("Temperature: ");
Serial.print(temperature,1);
Serial.print(" C Humidity: ");
Serial.print(humidity,1);
Serial.println(" %");
// Log only if value changes
if(temperature != prevTemp || humidity != prevHum) {
Serial.println("Change detected → Logging data");
int16_t tempStore = temperature * 10;
int16_t humStore = humidity * 10;
int base = 1 + logCount * 4;
EEPROM.put(base, tempStore);
EEPROM.put(base+2, humStore);
logCount++;
EEPROM.write(0, logCount);
EEPROM.commit();
prevTemp = temperature;
prevHum = humidity;
Serial.print("Total Logs = ");
Serial.println(logCount);
}
else {
Serial.println("No change → Log skipped");
}
// Show logs if user types L
if(Serial.available()) {
char c = Serial.read();
if(c=='L' || c=='l') {
displayLogs();
}
}
delay(3000);
}