Home automation with manual control and feedback

Hey guys,

so i am working on a home automation project which lets you control light from the blynk app as well as manually and the state of the switch is shown in the app. I have got everything working but am having an issue with the switch as the switch is reversed everytime i use the app. For example i turn on the light using the switch the light turns on and the switch remains on and then i switch off the light using the phone but when i turn the switch off the light turns back on again. i have attached the code below so that you can take a look and help me fix the switch.

#define BLYNK_PRINT Serial


#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

BlynkTimer timer;     //Make a simple timer

void checkSwitch();

int relayState = LOW;
int switchState = HIGH;


// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "BxVoOl0SiO3BHhHXvJt9SWd1bxNhO3YD";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "D-Link_DIR-600M";
char pass[] = "Aventador";

#define RELAY_PIN 5  //D1
#define SWITCH 2     //D4
#define VPIN V2

BLYNK_CONNECTED()
{
  Blynk.syncVirtual(VPIN);  //Syncing state from server
}

BLYNK_WRITE(VPIN)
{
  relayState = param.asInt();
  digitalWrite(RELAY_PIN, relayState);   //When app button is used reflect the state
}

void checkSwitch()
{
  if (digitalRead(SWITCH) == LOW)
  {
    if (switchState != LOW)
    {
      relayState = !relayState;
      digitalWrite(RELAY_PIN, relayState);   //Changing relay state
      Blynk.virtualWrite(VPIN, relayState);  //update widget in blynk
    }
    switchState = LOW;
  }
  else if (digitalRead(SWITCH) == HIGH)
  {
    if (switchState != HIGH)
    {
      relayState = !relayState;
      digitalWrite(RELAY_PIN, relayState);
      Blynk.virtualWrite(VPIN, relayState);
    }
    switchState = HIGH;
  }
}

void setup()
{
  // Debug console
  Serial.begin(9600);

  Blynk.begin(auth, ssid, pass);

  pinMode(RELAY_PIN, OUTPUT);
  pinMode(SWITCH, INPUT_PULLUP);
  digitalWrite(RELAY_PIN, relayState);

  timer.setInterval(500L, checkSwitch);
}

void loop()
{
  Blynk.run();
  timer.run();
}

Is your switch a low voltage switch connected to your hardware?

If it is the regular on/off wall switch you will need to wire something in to test if there is current an update your code every physical change.

1 Like

I’d agree that some info on the type of switch, and how it’s wired would be useful.

Personally, I’d start by adding plenty of serial print statements to indicate the program flow and variable values. That way you’ll soon get to the bottom of the issue.

Pete.