Smart Alternative Switch with ESP8266 for ioBroker via MQTT

We can make our home lighting smarter with this ESP8266 circuit while keeping the conventional wall switch usable even if Wi-Fi is unavailable or the ioBroker server stops working.

Difficulty: Advanced

Reviewed: October 2026

This project uses an ESP8266 NodeMCU, but another microcontroller, such as an ESP32, could also be used. In that case, pay attention to the pin assignments and voltage levels when building the circuit. The Arduino sketch must also use the appropriate pins and libraries for the chosen microcontroller.

Smart two-way lighting switch using ESP8266, ioBroker and MQTT
Smart two-way lighting switch using ESP8266, ioBroker and MQTT

Parts used in this project:

  • ESP8266 NodeMCU
  • SFH620A phototransistor optocoupler
  • Two 100 kΩ, 1 W resistors
  • 47 kΩ, 0.25 W resistor
  • 230 V AC to 5 V DC switching power supply
  • 5 V relay module with an optocoupler

Warning!

This project involves parts that may be connected to mains voltage. Mains electricity can cause serious injury, fatal electric shock or fire.

Always disconnect the circuit from the mains before working on it. Take particular care to prevent contact with live wiring and terminals.

Mains-voltage parts must be housed in a suitable closed electrical enclosure. Use appropriately rated, insulated cables, wires, switches, lamp holders and plugs.

Only work with mains voltage if you have the necessary knowledge and skills. If you are unsure, ask a qualified electrician for help. The author cannot accept responsibility for damage or injury.

How does a two-way switch work?

A two-way switch has three terminals. Its common terminal, often marked “COM” or “L”, is connected to one of the other two terminals at any given time. Moving the switch connects it to the other terminal. An ordinary on/off switch is not suitable for this circuit.

As the diagram below shows, a conventional two-way lighting circuit uses two two-way switches. The live conductor is connected to the COM or L terminal of the first switch, while the lamp is connected to the COM or L terminal of the second. The two remaining terminals of each switch are connected by two traveller wires. Depending on the position of the first switch, one of these wires carries the live supply towards the second switch.

In this arrangement, moving either switch changes the state of the lamp. The animation below illustrates the operating principle and the path through the circuit.

How a two-way lighting switch works.

This basic arrangement uses two two-way switches. If we want to control the lamp from additional locations, we can place intermediate switches between them. The two-way switches remain at the beginning and end of the switching arrangement, with the intermediate switches installed between their traveller connections.

The following animation shows how this works and how the current path changes.

Two-way switches with an additional intermediate switch.

Creating a smart two-way switch

In the circuit described above, one of the two-way switches can be replaced with a relay module that has a changeover contact. The relay must provide all three contact terminals: NO, COM and NC.

Warning!

The solder joints connected to the relay’s mains-voltage contacts on the relay module’s circuit board may be live.

Touching these parts can be fatal.

For protection against electric shock, place the relay module in a suitable closed enclosure before energising the circuit.

The diagram below shows the COM or L terminal of the wall switch connected to the live conductor of the 230 V mains supply. Its two remaining terminals connect to the relay module’s changeover contacts. The relay’s COM terminal connects to the lamp, while the other side of the lamp connects to the neutral conductor.

Schematic overview of the smart two-way lighting switch
Smart two-way lighting switch – schematic overview

The SFH620A is an optocoupler with an AC input and a phototransistor output. It provides galvanic separation between its mains-sensing input and the microcontroller-side output. With appropriately rated series resistors, it can be used to detect voltage across the lamp.

The relay module used in the tested circuit also contains an optocoupler. However, its presence alone does not guarantee galvanic separation between the NodeMCU and the relay module’s control circuit. Whether the module can be driven reliably from a 3.3 V GPIO also depends on the particular module and its wiring.

The black block at the bottom of the diagram represents a 230 V AC to 5 V DC switching power supply. It powers the low-voltage part of the circuit.

In this circuit, pins 1 and 2 of the SFH620A AC input are connected across the lamp’s live and neutral terminals, each through a 100 kΩ, 1 W series resistor. The phototransistor’s collector, pin 4, connects to D2 on the ESP8266 NodeMCU. A 47 kΩ resistor pulls this input up to 3.3 V. The phototransistor’s emitter, pin 3, connects to the NodeMCU’s GND. This signal lets the program monitor whether voltage is present at the lamp.

The following diagram shows the connection between the SFH620A and the ESP8266 NodeMCU. It also shows the two oppositely oriented LEDs and the phototransistor inside the optocoupler.

Circuit diagram of the SFH620A and ESP8266 NodeMCU
Connecting the SFH620A to the ESP8266 NodeMCU

Interpreting the SFH620A signal

Because the mains supply is alternating current, the output of the AC-input SFH620A changes around each voltage zero crossing. We examined this behaviour with a test circuit based on the diagram below.

Warning!
Parts of this test circuit are connected to the 230 V mains supply. Protect against accidental contact and assemble the mains-voltage parts in a suitable closed enclosure.

SFH620A test circuit used for the oscilloscope measurement

The oscilloscope clearly shows the effect of the mains half-cycles: a repeating 100 Hz signal on the optocoupler’s output.

Oscilloscope display showing the 100 Hz pulses

Even while the lamp is on, the microcontroller could mistake the brief signal changes at the zero crossings for an off state. The Arduino sketch accounts for these gaps in software.

Arduino sketch for the smart two-way switch

To run the circuit, upload the sketch below to the ESP8266. Open the Arduino IDE and paste in the code. If necessary, install the ESP8266 board package and the PubSubClient library first.

Replace the Wi-Fi SSID and password with your own, and enter the IP address of your MQTT server. Then upload the sketch to the ESP8266.

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

constexpr char ssid[] = "ssid";
constexpr char password[] = "password";
constexpr char mqttServer[] = "192.168.1.23";
constexpr char clientId[] = "ESP8266-SmartAlternativeSwitch";

constexpr uint16_t relayPin = 5;          // GPIO5 -> D1
constexpr uint16_t lightControllPin = 4;  // GPIO4 -> D2

unsigned long lastFlagRestore = 0;
unsigned long lastReconnectAttempt = 0;
unsigned long lastWifiReconnectAttempt = 0;

volatile unsigned long lastPulseTime = 0;
constexpr unsigned long acTimeout = 40;

bool relayState = true;
bool lightControllFlag = false;
bool switchState = false;
bool switchFlag = false;

WiFiClient espClient;
PubSubClient client(espClient);


void IRAM_ATTR lightPulseISR()
{
  lastPulseTime = millis(); 
}

void setupWifi()
{
  Serial.println(F("Connecting to the wifi network..."));
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  int counter = 0;
  while(WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.print(F("."));
    counter++;
    if(counter > 60)
    {
      ESP.restart();
    }
  }
  Serial.println();
  Serial.println(F("Wifi is connected!"));
}

void reconnect()
{
  Serial.println(F("Connecting to the MQTT server..."));
  if(!client.connected()) 
  {
    if(client.connect(clientId))
    {
      Serial.println(F("MQTT server is connected!"));
      client.subscribe("test/lighting");
      
      client.publish("test/lighting", lightControllFlag ? "true" : "false");
      switchState = lightControllFlag;
    } 
    else 
    {
      Serial.print(F("MQTT connection failed, retrying in 5 seconds"));
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length)
{
  if(strcmp(topic, "test/lighting") == 0 && switchFlag == false)
  {
    bool targetState = false;
    if(strncmp((char*)payload, "true", length) == 0 && length == 4)
    {
      targetState = true;
      if(targetState != lightControllFlag)
      {
        relayState = !relayState;
        digitalWrite(relayPin, relayState ? HIGH : LOW);
        
        switchFlag = true;
        lastFlagRestore = millis();
        
        Serial.println(F("Relay toggled via MQTT to match target state."));
      }
    }
    else if(strncmp((char*)payload, "false", length) == 0 && length == 5)
    {
      targetState = false;
      if(targetState != lightControllFlag)
      {
        relayState = !relayState;
        digitalWrite(relayPin, relayState ? HIGH : LOW);
        
        switchFlag = true;
        lastFlagRestore = millis();
        
        Serial.println(F("Relay toggled via MQTT to match target state."));
      }
    }
  }
}

void setup()
{
  pinMode(lightControllPin, INPUT); 
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, HIGH);

  attachInterrupt(digitalPinToInterrupt(lightControllPin), lightPulseISR, FALLING);

  Serial.begin(115200);
  delay(500);
  Serial.println();

  setupWifi();

  client.setServer(mqttServer, 1883);
  client.setCallback(callback);
}

void loop()
{
  unsigned long now = millis();

  if(now - lastPulseTime < acTimeout) 
  {
    lightControllFlag = true;
  } 
  else 
  {
    lightControllFlag = false;
  }

  if(switchFlag && (now - lastFlagRestore > 500))
  {
    switchFlag = false;
  }

  if(WiFi.status() != WL_CONNECTED)
  {
    if(now - lastWifiReconnectAttempt > 5000)
    {
      lastWifiReconnectAttempt = now;
      Serial.println(F("WiFi connection lost! Reconnecting..."));
      WiFi.disconnect();
      setupWifi();
    }
  }
  else if(!client.connected()) 
  {
    if(now - lastReconnectAttempt > 5000)
    {
      lastReconnectAttempt = now;
      reconnect();
    }
  }
  else
  {
    client.loop();

    if(lightControllFlag != switchState)
    {
      switchState = lightControllFlag;
      switchFlag = true;
      lastFlagRestore = now;
      
      if(lightControllFlag)
      {
        client.publish("test/lighting", "true");
        Serial.println(F("Light turned on manually!"));
      }
      else
      {
        client.publish("test/lighting", "false");
        Serial.println(F("Light turned off manually!"));
      }
    }
  }
}

How does the Arduino sketch work?

The program has two main jobs. It checks whether voltage is present at the lamp and, when requested through MQTT, changes the relay position according to the lamp’s current state. The relay acts as a two-way switch alongside the conventional wall switch. For this reason, the relay position alone does not tell us whether the lamp is on. The SFH620A optocoupler provides the signal used to determine the lamp’s actual state.

The optocoupler’s output changes briefly around each zero crossing of the AC mains voltage. During our measurement, we observed a 100 Hz series of pulses, arriving approximately every 10 milliseconds. An interrupt on D2, which is GPIO4, records the time of each falling edge. The interrupt handler only updates this timestamp; the main program interprets the signal.

The main loop checks how much time has passed since the most recent pulse. If less than 40 milliseconds have passed, it treats the lamp as on. If no new pulse arrives within that time, it treats the lamp as off. This 40-millisecond window bridges the short gaps around the mains zero crossings. It is a software interpretation of the repeating signal, not an electrical smoothing of the optocoupler output.

At startup, the sketch configures the relay output and the interrupt on the lamp-monitoring input, then connects to Wi-Fi and the MQTT server. When the MQTT connection is established, it subscribes to test/lighting and publishes the measured lamp state on the same topic. If it cannot establish a Wi-Fi connection at startup, it restarts the ESP8266 after approximately 30 seconds of attempts. If the MQTT connection is lost, it tries to reconnect later.

In an MQTT message, true requests an on lamp state and false requests an off state. The program compares the requested state with the measured one. If the lamp is already in the requested state, it leaves the relay alone. Otherwise, it changes the relay position through D1, which is GPIO5. There is no fixed relay position that always means “on” or “off”; changing the relay position changes the lamp’s state.

Using the wall switch can also change the lamp’s state without any command to the relay. The program detects this through the optocoupler signal and publishes the new state to test/lighting, allowing the change to appear in ioBroker. The switchFlag briefly prevents an MQTT message echoed back from the server from immediately changing the relay again.

If Wi-Fi or the MQTT server is unavailable, remote control and state reporting stop. The conventional wall switch can still operate the lamp.

The tested circuit and sketch demonstrate the operating principle. They are not a finished smart switch suitable for installation in a wall box.


← More ioBroker articles

← More Arduino and ESP examples and projects