/**
ESP32 + DHT22 + SSD1306 OLED Example for Wokwi
https://wokwi.com/arduino/projects/322410731508073042
*/
#include "DHTesp.h"
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// DHT22 settings
const int DHT_PIN = 15; // DHT22 is connected to GPIO 15
DHTesp dhtSensor;
//LED GPIO Pins
const int RED_LED = 16; // Red LED on GPIO 16
const int GREEN_LED = 17; // Green LED on GPIO 17
const int BLUE_LED = 18; // Blue LED on GPIO 18
// OLED settings
#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)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Initialize DHT sensor
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
// Initialize the OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // Don't proceed, loop forever
}
// Clear the buffer
display.clearDisplay();
display.setTextSize(2); // Set text size to normal 1:1 pixel scale
display.setTextColor(SSD1306_WHITE); // Set text color to white
display.setCursor(3, 5); // Start at top-left corner
display.print("DHT22 Sensor");
display.display(); // Display initial message
delay(5000); // Wait for 2 seconds
// Initialize LEDs as outputs
pinMode(RED_LED, OUTPUT);
pinMode(GREEN_LED, OUTPUT);
pinMode(BLUE_LED, OUTPUT);
}
void loop() {
// Read temperature and humidity from the DHT22 sensor
TempAndHumidity data = dhtSensor.getTempAndHumidity();
// Print the values to the Serial Monitor
Serial.println("Temp: " + String(data.temperature, 2) + "°C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%");
Serial.println("---");
// Display the values on the OLED display
display.clearDisplay(); // Clear the display buffer
display.setCursor(0, 0); // Start at top-left corner
display.setTextSize(1); // Set text size to normal
// Display temperature
display.print("Temp: ");
display.print(data.temperature, 2); // Show temperature with 2 decimal places
display.println(" C");
// Display humidity
display.print("Humidity: ");
display.print(data.humidity, 1); // Show humidity with 1 decimal place
display.println(" %");
// Update the display with new data
display.display();
// Wait 2 seconds before the next update
delay(2000);
if (data.temperature < 18.0) {
digitalWrite(BLUE_LED, HIGH); // Turn on blue LED
} else {
digitalWrite(BLUE_LED, LOW); // Turn off blue LED
}
if (data.temperature > 22.0) {
digitalWrite(RED_LED, HIGH); // Turn on red LED
} else {
digitalWrite(RED_LED, LOW); // Turn off red LED
}
if (data.humidity < 40.0 || data.humidity > 50.0) {
digitalWrite(GREEN_LED, HIGH); // Turn on green LED
} else {
digitalWrite(GREEN_LED, LOW); // Turn off green LED
}
}