#include <DHTesp.h>
#include <WiFi.h>
#include <ThingSpeak.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ThingSpeak settings
const char* thingSpeakApiKey = "BMAIUFPJQVJEQ8O6";
const int channelNumber = 2506733;
// Define the pin connections for the OLED display.
#define OLED_RESET -1 // Reset pin (or -1 if not used)
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Create an instance of the SSD1306 OLED display class.
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
WiFiClient client;
// Create an instance of the DHT sensor class.
// Connect the sensor to Digital I/O Pin 14.
DHTesp dht;
void setup() {
// Initialize serial communication for debugging and data readout.
Serial.begin(9600);
// Initialize the Wire library for I2C communication.
Wire.begin();
// Connect to WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
// Initialize the ThingSpeak library
ThingSpeak.begin(client);
// Initialize the OLED display with the default I2C address (0x3C).
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // Don't proceed, loop indefinitely
}
display.setTextSize(2);
// Initialize DHT sensor
dht.setup(14, DHTesp::DHT22);
}
void loop() {
float temperature = 0.0;
float humidity = 0.0;
// Attempt to read the temperature and humidity values from the DHT sensor.
TempAndHumidity sensorData = dht.getTempAndHumidity();
temperature = sensorData.temperature;
humidity = sensorData.humidity;
// Check the results of the readings.
// If the reading is successful, print the temperature and humidity values on the OLED display.
// If there are errors, print the appropriate error messages.
if (!isnan(temperature) && !isnan(humidity)) {
// Clear the display buffer.
display.clearDisplay();
// Print temperature and humidity values on the OLED display.
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("Temperature: ");
display.print(temperature);
display.println(" C");
display.setCursor(0, 10);
display.print("Humidity: ");
display.print(humidity);
display.println(" %");
// Display the content of the display buffer.
display.display();
// Print temperature and humidity values to serial monitor.
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C\tHumidity: ");
Serial.print(humidity);
Serial.println(" %");
// Send data to ThingSpeak
ThingSpeak.setField(1, temperature);
ThingSpeak.setField(2, humidity);
ThingSpeak.writeFields(channelNumber, thingSpeakApiKey);
} else {
// Print error message if reading failed
Serial.println("Failed to read from DHT sensor");
}
// Delay for a short period between readings.
delay(1000);
}