#define BLYNK_TEMPLATE_ID "TMPL6kp6d_svR"
#define BLYNK_TEMPLATE_NAME "Test2"
#define BLYNK_AUTH_TOKEN "FmWQiEgPbmjbU_QMVEquvZQQik-DfTCw"
#define WIFI_SSID "newan"
#define WIFI_PASS "newaniscooking88"
#include <BlynkSimpleEsp32.h>
// ---------------- CONFIG ----------------
#define RELAY1 5
#define MOTION_PIN 14
#define TEMP_VPIN V2
#define BUTTON_VPIN V1
#define AUTO_MODE_BTN V3
#define NOTIFY_VPIN V4 // Notification virtual pin
#define NOTIFY_MIN_INTERVAL 5 * 60 * 1000UL
bool autoMode = true;
bool relayState = false;
float currentTemp = 22.0;
unsigned long lastMotionNotifyAt = 0;
unsigned long lastMotionAt = 0;
// --- AUTO TEMP SETTINGS ---
const float TEMP_TARGET = 22.0;
const float TEMP_HYSTERESIS = 0.5;
// --- MOTION SETTINGS ---
const unsigned long MOTION_TIMEOUT = 30000; // 30 sec
// ---------------- UTILS ----------------
void setRelay(bool on) {
digitalWrite(RELAY1, on ? LOW : HIGH);
relayState = on;
Blynk.virtualWrite(V10, on ? 1 : 0);
}
// ---------------- BLYNK HANDLERS ----------------
BLYNK_WRITE(BUTTON_VPIN) {
int value = param.asInt();
setRelay(value);
autoMode = false; // manual override
}
BLYNK_WRITE(AUTO_MODE_BTN) {
int value = param.asInt();
autoMode = (value == 1); // re-enable auto
}
BLYNK_WRITE(TEMP_VPIN) {
currentTemp = param.asFloat();
}
// ---------------- AUTO CONTROL ----------------
void checkAuto() {
if (!autoMode) return; // skip auto if manual
// Motion-based control
if (digitalRead(MOTION_PIN) == HIGH) {
lastMotionAt = millis();
if (!relayState) setRelay(true);
if (millis() - lastMotionNotifyAt > NOTIFY_MIN_INTERVAL) {
Blynk.virtualWrite(NOTIFY_VPIN, "Motion detected!"); // send notification via V4
lastMotionNotifyAt = millis();
}
}
if (relayState && millis() - lastMotionAt > MOTION_TIMEOUT) {
setRelay(false);
}
// Temperature-based control
if (currentTemp < (TEMP_TARGET - TEMP_HYSTERESIS)) {
if (!relayState) setRelay(true);
} else if (currentTemp > (TEMP_TARGET + TEMP_HYSTERESIS)) {
if (relayState) setRelay(false);
}
}
// ---------------- SETUP & LOOP ----------------
void setup() {
pinMode(RELAY1, OUTPUT);
pinMode(MOTION_PIN, INPUT);
setRelay(false);
Blynk.begin(BLYNK_AUTH_TOKEN, WIFI_SSID, WIFI_PASS);
}
void loop() {
Blynk.run();
checkAuto();
delay(500);
}