#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#include <DHT.h>
// OLED display width and height, change if using a different model
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// DHT22 configuration
#define DHTPIN 2 // Pin connected to the DHT22 data pin
#define DHTTYPE DHT22 // Using DHT22 sensor
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// Start serial communication
Serial.begin(9600);
// Initialize the DHT sensor
dht.begin();
// Initialize the OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // 0x3C is the I2C address for the OLED
Serial.println(F("SSD1306 allocation failed"));
while (true); // Don't proceed, loop forever
}
// Clear the display buffer
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
}
void loop() {
// Read the humidity and temperature from the DHT22 sensor
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again)
if (isnan(humidity) || isnan(temperature)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Print values to Serial for debugging
Serial.print(F("Humidity: "));
Serial.print(humidity);
Serial.print(F("% Temperature: "));
Serial.print(temperature);
Serial.println(F("°C"));
// Display temperature and humidity on the OLED
display.clearDisplay(); // Clear the display
display.setCursor(0, 0); // Set cursor at top-left corner
display.setTextSize(2); // Set text size to 2 for larger text
display.print("Temp: ");
display.print(temperature);
display.println(" C");
display.print("Hum: ");
display.print(humidity);
display.println(" %");
display.display(); // Update the OLED display
delay(2000); // Wait 2 seconds between readings
}