#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define DHT_PIN 19 // Pin where your DHT22 is connected (change if needed)
#define DHT_TYPE DHT22 // Define the sensor type (DHT22)
// Initialize the DHT sensor
DHT dht(DHT_PIN, DHT_TYPE);
// Create an OLED display object connected to I2C
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
void setup()
{
Serial.begin(115200); // Initialize serial communication at a higher baud rate
// Initialize the DHT sensor
dht.begin();
// Initialize OLED display with I2C address 0x3C
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C))
{
Serial.println(F("Failed to start SSD1306 OLED"));
while (1); // Infinite loop to halt execution
}
delay(2000); // Wait two seconds for initializing
oled.clearDisplay(); // Clear display
}
void loop()
{
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Check if the data was successfully read from the sensor
if (!isnan(temperature) && !isnan(humidity)) {
// Clear the display
oled.clearDisplay();
// Display temperature and humidity on OLED
oled.setTextSize(1); // Set text size
oled.setTextColor(WHITE); // Set text color
oled.setCursor(21, 0); // Set position to display (x, y)
oled.print("Weather Station");
oled.setCursor(0, 20); // Set position to display (x, y)
oled.print("Temperature: ");
oled.setCursor(100, 20);
oled.print(temperature);
oled.print(" C");
oled.setCursor(0, 45); // Set position to display (x, y)
oled.print("Humidity: ");
oled.setCursor(100, 45);
oled.print(humidity);
oled.print(" %");
// Draw lines for separation
oled.drawLine(0, 15, 128, 15, WHITE); // Horizontal line
oled.drawLine(0, 35, 128, 35, WHITE); // Horizontal line
oled.drawLine(70, 16, 70, 64, WHITE); // Vertical line
oled.display(); // Update OLED display
// Print temperature and humidity values to the serial monitor
Serial.print("Temperature (°C): ");
Serial.println(temperature);
Serial.print("Humidity (%): ");
Serial.println(humidity);
} else {
// If there was an error reading data from the sensor, print an error message
Serial.println("Error reading from DHT sensor");
}
// Delay for a few seconds before taking the next reading
delay(2000);
}