#include <SPI.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#include <DHT.h>
#define DHT22_PIN 33 // ESP32 pin GPIO21(33) connected to DHT22 sensor
DHT dht22(DHT22_PIN, DHT22);
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
void setup() {
// initialize the DHT22 sensor
Serial.begin(9600);
dht22.begin();
// initialize OLED display with address 0x3C for 128x64
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
while (true);
}
delay(1000);
oled.clearDisplay();
oled.setTextSize(2);
oled.setTextColor(WHITE);
oled.setCursor(45, 20);
oled.println("Test");
oled.display();
delay(1000);
oled.clearDisplay();
oled.drawCircle(64, 32, 15, WHITE);
oled.display();
delay(1000);
oled.clearDisplay();
}
void loop() {
// read humidity
float humi = dht22.readHumidity();
// read temperature in Celsius
float tempC = dht22.readTemperature();
// read temperature in Fahrenheit
float tempF = dht22.readTemperature(true);
// check whether the reading is successful or not
if ( isnan(tempC) || isnan(tempF) || isnan(humi)) {
Serial.println("Failed to read from DHT22 sensor!");
} else {
Serial.print("Humidity: ");
Serial.print(humi);
Serial.print("%");
Serial.print(" | ");
Serial.print("Temperature: ");
Serial.print(tempC);
Serial.print("°C ~ ");
Serial.print(tempF);
Serial.println("°F");
}
oled.setTextSize(1);
oled.setTextColor(WHITE);
oled.setCursor(0, 7);
oled.println("Temp: ");
oled.setCursor(30, 7);
oled.println(tempC);
oled.drawCircle(65, 7, 2, WHITE);
oled.setCursor(70, 7);
oled.println("C");
oled.setCursor(0, 50);
oled.println("Humidity: ");
oled.setCursor(55, 50);
oled.println(humi);
oled.setCursor(85, 50);
oled.println("%");
oled.setTextSize(2);
oled.setCursor(0, 25);
oled.println("CO: ");
oled.setCursor(40, 25);
oled.println("2000");
oled.setCursor(90, 25);
oled.println("PPM");
oled.display();
}