#define BLYNK_TEMPLATE_ID "TMPL3DyCpFLbf"
#define BLYNK_TEMPLATE_NAME "smart home"
#define BLYNK_AUTH_TOKEN "FrKQOMmZUF08kvGfPuts3DFg_3WBZVCB"
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
// Pins
#define LIGHT_PIN 2
#define FAN_PIN 18
#define PIR_PIN 5
#define DHT_PIN 4
#define DHT_TYPE DHT22
DHT dht(DHT_PIN, DHT_TYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Variables
bool autoMode = false; // 🔥 start in MANUAL (important)
BlynkTimer timer;
unsigned long lastMotionTime = 0;
const int motionDelay = 10000;
bool blinkState = false;
bool shouldBlink = false;
int fanSpeed = 0;
// 🔘 MODE
BLYNK_WRITE(V0) {
autoMode = param.asInt();
if (!autoMode) {
shouldBlink = false;
}
}
// 💡 LIGHT
BLYNK_WRITE(V1) {
if (!autoMode) {
shouldBlink = false;
digitalWrite(LIGHT_PIN, param.asInt());
}
}
// 🌬️ FAN (PWM)
BLYNK_WRITE(V2) {
if (!autoMode) {
fanSpeed = param.asInt();
analogWrite(FAN_PIN, fanSpeed);
}
}
// 🔁 BLINK
void blinkLight() {
if (autoMode && shouldBlink) {
blinkState = !blinkState;
digitalWrite(LIGHT_PIN, blinkState);
}
}
// 📡 MAIN
void sendData() {
float temp = dht.readTemperature();
int motion = digitalRead(PIR_PIN);
if (isnan(temp)) {
Serial.println("DHT ERROR");
return;
}
Serial.print("Temp: ");
Serial.print(temp);
Serial.print(" | Motion: ");
Serial.println(motion);
// AUTO MODE
if (autoMode) {
if (motion == HIGH) {
shouldBlink = true;
lastMotionTime = millis();
}
if (millis() - lastMotionTime > motionDelay) {
shouldBlink = false;
digitalWrite(LIGHT_PIN, HIGH);
}
if (temp > 30) {
fanSpeed = map(temp, 30, 50, 100, 255);
} else {
fanSpeed = 0;
}
analogWrite(FAN_PIN, fanSpeed);
}
// 🔥 CRITICAL: Sync everything to Blynk
Blynk.virtualWrite(V0, autoMode);
Blynk.virtualWrite(V1, digitalRead(LIGHT_PIN));
Blynk.virtualWrite(V2, fanSpeed);
Blynk.virtualWrite(V3, temp);
// LCD
lcd.setCursor(0, 0);
lcd.print(" ");
lcd.setCursor(0, 0);
lcd.print("T:");
lcd.print(temp);
lcd.print(autoMode ? " A" : " M");
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print("L:");
lcd.print(digitalRead(LIGHT_PIN) ? "ON " : "OFF");
lcd.print("F:");
lcd.print(fanSpeed > 0 ? "ON" : "OFF");
}
// 🔧 SETUP
void setup() {
Serial.begin(115200);
pinMode(LIGHT_PIN, OUTPUT);
pinMode(FAN_PIN, OUTPUT);
pinMode(PIR_PIN, INPUT);
dht.begin();
lcd.init();
lcd.backlight();
lcd.print("Connecting...");
Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
lcd.clear();
// 🔥 IMPORTANT SYNC
Blynk.syncVirtual(V0);
Blynk.syncVirtual(V1);
Blynk.syncVirtual(V2);
timer.setInterval(1000L, sendData);
timer.setInterval(500L, blinkLight);
}
// 🔁 LOOP
void loop() {
Blynk.run();
timer.run();
}