#include "U8glib.h" // OLED library
#include "DHT.h" // DHT sensor library
#define DHTPIN 2 // Pin connected to DHT22
#define DHTTYPE DHT22 // DHT22 sensor type
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);
// Initialize OLED
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE);
float temperature = 0.0;
float humidity = 0.0;
void setup() {
dht.begin(); // Start DHT sensor
u8g.setFont(u8g_font_6x10); // Set smaller font
}
void loop() {
// Read temperature and humidity
float temp = dht.readTemperature();
float hum = dht.readHumidity();
// Check if readings are valid
if (isnan(temp) || isnan(hum)) {
temperature = 0.0;
humidity = 0.0;
} else {
temperature = temp;
humidity = hum;
}
// Display data on OLED
u8g.firstPage();
do {
// Title
u8g.drawStr(8, 10, "Temp & Humidity");
// Display Temperature
u8g.drawStr(5, 30, "Temp:");
u8g.drawFrame(50, 20, 70, 10);
// Map temp (-40 to 80°C) to bar width (0 to 70)
u8g.drawBox(40, 20, map(temperature, -40, 80, 0, 70), 10);
u8g.setPrintPos(125, 30);
u8g.print(temperature, 1);
u8g.print("C");
// Display Humidity
u8g.drawStr(5, 50, "Humid:");
u8g.drawFrame(50, 40, 70, 10);
// Map humidity (0 to 100%) to bar width (0 to 70)
u8g.drawBox(50, 40, map(humidity, 0, 100, 0, 70), 10);
u8g.setPrintPos(125, 50);
u8g.print(humidity, 1);
u8g.print("%");
} while (u8g.nextPage());
delay(1000); // Wait 1 second before refreshing
}