#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define DHTPIN 2 // Pin where the DHT22 is connected
#define DHTTYPE DHT22 // DHT 22
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// initialize with the I2C addr 0x3C (for the 128x64)
if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.display(); // Clear the buffer
display.setTextColor(SSD1306_WHITE); // Draw white text
display.setTextSize(1); // Draw 1X-scale text
display.setCursor(0,0); // Start at top-left corner
display.display();
delay(2000);
dht.begin();
}
void loop() {
// Read humidity and temperature
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature)) {
display.clearDisplay();
display.setCursor(0, 0);
display.println("Failed to read");
display.println("from DHT sensor!");
display.display();
delay(2000);
return;
}
// Print the data on the OLED display
display.clearDisplay();
display.setCursor(0, 0);
display.print("Temp: ");
display.print(temperature);
display.print(" C");
display.setCursor(0, 16);
display.print("Humidity: ");
display.print(humidity);
display.print(" %");
display.display();
delay(2000); // Delay between readings
}