#define BLYNK_TEMPLATE_ID "TMPL6hNmpcu6z"
#define BLYNK_TEMPLATE_NAME "Smart Home"
#define BLYNK_PRINT Serial
#define BLYNK_AUTH_TOKEN "WnBwXYS1F1eTrfk_qzLX1bF3SSeJT6nY"
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
#include "DHT.h" // Include DHT sensor library
#include <ESP32Servo.h>
const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
#define RELAY_PIN 5
#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT22
DHT dht(DHTPIN, DHTTYPE);
Servo myServo;
BLYNK_WRITE(V0) {
digitalWrite(RELAY_PIN, param.asInt());
}
void setup() {
Serial.begin(115200);
myServo.attach(18);
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW);
Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
dht.begin(); // Initialize DHT sensor
}
void loop() {
Blynk.run();
static unsigned long lastMillis = 0;
unsigned long currentMillis = millis();
if (currentMillis - lastMillis >= 2000) { // Read sensor every 2 seconds.
lastMillis = currentMillis;
float h = dht.readHumidity();
float t = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Blynk.virtualWrite(V1, t); // Send temperature to virtual pin V1
Blynk.virtualWrite(V2, h); // Send humidity to virtual pin V2
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C");
// Control servo based on temperature and humidity
if ((h < 35) && (t > 40)) {
myServo.write(90); // Move to 90 degrees
Serial.println("Servo moved to 90 degrees");
} else {
myServo.write(180); // Move to 180 degrees
Serial.println("Servo moved to 180 degrees");
}
}
}