#include <ESP32Servo.h>
#include <DHT.h>
#include <WiFi.h> // Use the "WiFi" library for ESP32
#include <ThingSpeak.h>
#define DHTPIN 2 // Define the pin to which the DHT11 sensor is connected
#define DHTTYPE DHT22 // Set the type of DHT sensor you are using
#define SERVO_PIN 4 // Define the pin to which the servo motor is connected
#define TEMP_THRESHOLD 30.0 // Set the temperature threshold in Celsius
DHT dht(DHTPIN, DHTTYPE);
Servo servo;
const char* ssid = "Wokwi-GUEST"; // Your network SSID (name)
const char* password = ""; // Your network password
const unsigned long channelID = 2454872; // Your ThingSpeak Channel ID
const char* writeAPIKey = "XWPM92OI8Z2KNU2W"; // Your ThingSpeak Write API Key
void setup() {
dht.begin();
servo.attach(SERVO_PIN);
Serial.begin(9600);
servo.write(0); // Close the vent initially (position at 0 degrees)
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
delay(2000); // Wait a few seconds between temperature readings
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
int pos = 0;
if (!isnan(temperature) && !isnan(humidity)) {
Serial.print("Temperature: ");
Serial.println(temperature);
Serial.print("Humidity: ");
Serial.println(humidity);
// Create a separate WiFiClient instance for ThingSpeak
WiFiClient client;
// Send data to ThingSpeak
ThingSpeak.begin(client);
ThingSpeak.setField(1, temperature);
ThingSpeak.setField(2, humidity);
int x = ThingSpeak.writeFields(channelID, writeAPIKey);
if (x == 200) {
Serial.println("Data sent to ThingSpeak");
} else {
Serial.println("Problem updating ThingSpeak. HTTP error code " + String(x));
}
if (temperature > TEMP_THRESHOLD) {
Serial.println("Ventilation ON");
// Temperature exceeds threshold, open the vent
for (pos = 0; pos <= 180; pos += 1) {
servo.write(pos);
delay(15);
}
for (pos = 180; pos >= 0; pos -= 1) {
servo.write(pos);
delay(15);
}
} else {
// Temperature is below threshold, close the vent
servo.write(0);
Serial.println("Ventilation OFF");
}
} else {
Serial.println("Failed to read temperature or humidity from DHT sensor!");
}
}