#include <WiFi.h>
#include <WiFiClient.h>
#include <DHT.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// BLYNK ---
#define BLYNK_FIRMWARE_VERSION "0.1.0"
#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPL6RdFFtTmM"
#define BLYNK_TEMPLATE_NAME "Hoang Hao"
#define BLYNK_AUTH_TOKEN "xHlLoFqGwTT-LD7dXN80vS0G-1Buoc5M"
#include <BlynkSimpleEsp32.h>
BlynkTimer timer;
// DHT22 ---
#define DHTPIN 15
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// LED ---
#define LED 5
WidgetLED LED_CONNECT(V5);
void setup() {
Serial.begin(115200);
pinMode(LED, OUTPUT);
// Blynk setup
Blynk.begin(BLYNK_AUTH_TOKEN, WIFI_SSID, WIFI_PASSWORD);
// DHT sensor setup
dht.begin();
// Setup a timer to send data every 2 seconds
timer.setInterval(2000L, sendData);
}
void loop() {
Blynk.run();
timer.run();
}
BLYNK_CONNECTED() {
Blynk.syncVirtual(V0); // Sync the LED control status on V0 when connected
}
BLYNK_WRITE(V0) {
int value = param.asInt(); // Read value from virtual pin V0
if (value) {
digitalWrite(LED, HIGH); // Turn on LED
} else {
digitalWrite(LED, LOW); // Turn off LED
}
}
void sendData() {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Send data to Blynk
Blynk.virtualWrite(V1, t); // Send temperature to Virtual Pin V1
Blynk.virtualWrite(V2, h); // Send humidity to Virtual Pin V2
Serial.print("Temperature: ");
Serial.print(t);
Serial.print("°C, Humidity: ");
Serial.print(h);
Serial.println("%");
// Update LED widget to show WiFi connection status
if (WiFi.status() == WL_CONNECTED) {
LED_CONNECT.on();
} else {
LED_CONNECT.off();
}
}