#define BLYNK_TEMPLATE_ID "TMPL3rXG5L_ba"
#define BLYNK_TEMPLATE_NAME "HOME AUTOMATION"
#define BLYNK_AUTH_TOKEN "vYyLSr9-kG-2-fY_KNSaekWV_i38m8m5"
#define BLYNK_PRINT Serial
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
// Replace with your WiFi credentials
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
const int relayPin1 = 23;
const int relayPin2 = 22;
const int switchPin1 = 19;
const int switchPin2 = 18;
bool switchState1 = LOW;
bool switchState2 = LOW;
bool relayState1 = LOW;
bool relayState2 = LOW;
BlynkTimer timer;
// Function to check the state of physical switches
void checkPhysicalSwitch() {
bool currentSwitchState1 = digitalRead(switchPin1) == LOW; // Switch connected to GND with INPUT_PULLUP
bool currentSwitchState2 = digitalRead(switchPin2) == LOW; // Switch connected to GND with INPUT_PULLUP
if (currentSwitchState1 != switchState1) {
switchState1 = currentSwitchState1;
Serial.print("Switch 1 state changed to: ");
Serial.println(switchState1);
relayState1 = switchState1; // Set relay state to match switch state
digitalWrite(relayPin1, relayState1);
Blynk.virtualWrite(V1, relayState1); // Update Blynk app
Serial.print("Relay 1 state: ");
Serial.println(relayState1);
}
if (currentSwitchState2 != switchState2) {
switchState2 = currentSwitchState2;
Serial.print("Switch 2 state changed to: ");
Serial.println(switchState2);
relayState2 = switchState2; // Set relay state to match switch state
digitalWrite(relayPin2, relayState2);
Blynk.virtualWrite(V2, relayState2); // Update Blynk app
Serial.print("Relay 2 state: ");
Serial.println(relayState2);
}
}
// Blynk write functions to handle virtual button presses from the app
BLYNK_WRITE(V1) {
relayState1 = param.asInt();
digitalWrite(relayPin1, relayState1);
Serial.print("Blynk V1 state: ");
Serial.println(relayState1);
}
BLYNK_WRITE(V2) {
relayState2 = param.asInt();
digitalWrite(relayPin2, relayState2);
Serial.print("Blynk V2 state: ");
Serial.println(relayState2);
}
void setup() {
Serial.begin(115200);
Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
pinMode(relayPin1, OUTPUT);
pinMode(relayPin2, OUTPUT);
pinMode(switchPin1, INPUT_PULLUP);
pinMode(switchPin2, INPUT_PULLUP);
digitalWrite(relayPin1, relayState1);
digitalWrite(relayPin2, relayState2);
timer.setInterval(100L, checkPhysicalSwitch); // Check the physical switch state every 100ms
}
void loop() {
Blynk.run();
timer.run(); // Run the Blynk timer to check the physical switches
}