Two-Way Light Switch Wiring (3-Way) + Smart ESP32 Upgrade

Advertisement

A two-way light circuit lets you switch one lamp from two places, such as both ends of a hallway or a staircase. In the US it is called a 3-way switch; in France and much of Europe it is a va-et-vient. This guide shows the classic wiring first, then a safe way to make the same lamp controllable from Home Assistant with an ESP32 while the wall switches keep working.

The smart part is optional. If you only need the standard installation, the first half of the article is all you need.

Two-Way Light Switch Wiring (3-Way) + Smart ESP32 Upgrade

Key terms

TermMeaning
Common (C or L)The terminal that carries the live in or the switched live out.
Travelers (T1, T2)Two wires linking the two switches. They carry mains voltage, alternately.
Switched liveThe wire from the second switch to the lamp. It is live only when the switches line up.
Permanent liveA live conductor that is always energized, regardless of switch position.

Safety first

Warning: mains voltage can kill. Wiring rules and who may do the work differ by country (for example NF C 15-100 in France, BS 7671 in the UK, NEC in the US). If you are not qualified, hire a licensed electrician.

  • Switch off the circuit breaker and prove the circuit is dead with a voltage tester. Do not trust the wall switch to isolate the circuit.
  • Use correctly rated cable, usually 1.5 mm² for lighting circuits in Europe, and respect the breaker rating required locally.
  • Keep live, neutral and earth conductors in the colors your country requires. Colors vary: France commonly uses red, brown or black for live, blue for neutral and green/yellow for earth; the UK uses brown, blue and green/yellow; the US uses black, white and green.
  • Close all junction boxes and switch plates before restoring power.

Part 1: Classic two-way switch wiring

What you need

  • Two two-way switches (3 terminals each: one common and two travelers)
  • Lighting cable with live, neutral and earth conductors
  • Junction box and connectors suitable for your wire size
  • A voltage tester

How it works

Each two-way switch connects its common terminal to one of two traveler terminals. The two travelers run between the switches. Flipping either switch changes which traveler carries the live, so the lamp toggles from either position.

Step by step

  1. Live: connect the live coming from the breaker to the common terminal of switch 1.
  2. Travelers: connect T1 of switch 1 to T1 of switch 2, and T2 of switch 1 to T2 of switch 2. Use two separate conductors of the same size.
  3. Switched live: connect the common terminal of switch 2 to the lamp live terminal.
  4. Neutral: run the neutral directly from the panel to the lamp. It never goes through a switch.
  5. Earth: connect the earth conductors to the lamp (if it has an earth terminal) and to metal switch boxes where applicable.
  6. Restore power and test both switches in every combination: all four positions should alternate the lamp on and off.

Common mistakes

SymptomLikely cause
Lamp works from one switch onlyA traveler is on a common terminal, or a traveler is disconnected.
Breaker trips when a switch is flippedLive and neutral are mixed up, or travelers are touching a neutral.
Lamp is always on or always offLive feed and switched live are swapped between the common terminals.
Switch gets warmLoose terminal or undersized conductor. Switch the breaker off and retighten.

Part 2: Make it smart with an ESP32 (the safe way)

Never connect the traveler wires to ESP32 pins. The travelers carry 230 V (or 120 V). Connecting them to a GPIO instantly destroys the board and creates a serious shock and fire hazard. The design below uses an isolated AC detector and a relay instead.

Option A: use a certified smart relay (recommended for most people)

If you are not completely comfortable with mains wiring, buy a certified smart relay module designed for two-way circuits and follow its manual. It is safer, tested and compliant. Many such modules support Home Assistant natively.

Option B: DIY node with an isolated AC detector

This design lets the lamp be toggled from Home Assistant and from either wall switch, with no change to the wall switches:

  • A mains-rated, opto-isolated AC detector watches the switched live wire. It tells the ESP32 whether the wall switches are currently in the "on" alignment.
  • A relay fed from the permanent live powers the lamp.
  • Every time the detector state changes (someone flipped a wall switch), the ESP32 toggles the relay. Home Assistant can also set the relay directly.

Because the lamp is powered by the relay and not by the switched live, the wall switches only act as "toggle" signals, exactly like a normal two-way circuit.

Requirements before you start

  • You need permanent live and neutral at the place where you install the node (the lamp junction box or a deep back box). If they are not present there, use Option A or have an electrician add a conductor.
  • All mains parts must be inside a closed, insulated enclosure with proper clearances between mains and low-voltage parts.
  • Choose a relay rated for your lamp load. LED drivers have high inrush current, so use a relay with a contact rating well above the lamp power.

Parts

PartNotes
ESP32 development boardAny ESP32 DevKit.
Relay moduleOpto-isolated input, contacts rated at least 10 A, with a proper mains-side layout.
Isolated AC detector moduleMains-rated input (L and N), opto-isolated output to the ESP32.
Isolated 5 V supplyAn enclosed, certified module (for example a HLK-PM01 inside a box) or a certified USB charger.
Small fuse (about 1 A)On the supply feed of the node.
Insulated enclosure and connectorsSuitable for mains wiring.

Wiring the node

FromTo
Permanent live (through the 1 A fuse)5 V supply input, and relay common (COM)
Neutral5 V supply input, the AC detector N input, and the lamp neutral
Switched live (wire that used to go to the lamp)AC detector L input only
Relay normally-open (NO)Lamp live
AC detector outputESP32 GPIO27 (and GND)
ESP32 GPIO26Relay module input (plus 5 V and GND)

The wall switches, travelers and switched live stay as in Part 1. Only the end of the switched live changes: it now goes to the detector instead of the lamp.

ESP32 code

Install the PubSubClient library, edit the settings at the top, and upload. Check whether your relay board is active-high or active-low and set RELAY_ACTIVE_HIGH accordingly.

/*
  Smart two-way (3-way) light control with ESP32 + MQTT + Home Assistant
  - Wall switches stay in place and keep working, even without Wi-Fi.
  - The ESP32 only SENSES the switched line through an isolated AC detector
    and drives a relay fed from the permanent live. It never touches
    the traveler wires directly.
  Library: PubSubClient (Nick O'Leary)
*/
#include <WiFi.h>
#include <PubSubClient.h>

// ---------- User settings ----------
const char* WIFI_SSID     = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
const char* MQTT_HOST     = "192.168.1.100";
const uint16_t MQTT_PORT  = 1883;
const char* MQTT_USER     = "esp32_light";
const char* MQTT_PASS     = "YOUR_MQTT_PASSWORD";

const char* NODE_ID = "hallway_light";

const int  RELAY_PIN         = 26;     // relay module input
const bool RELAY_ACTIVE_HIGH = true;   // set to false for active-LOW relay boards
const int  DETECT_PIN        = 27;     // output of the isolated AC detector module

const unsigned long AC_PRESENT_TIMEOUT_MS = 40;   // AC "present" if an edge was seen this recently
const unsigned long DEBOUNCE_MS           = 60;   // a new wall-switch state must stay stable this long
const unsigned long BOOT_SETTLE_MS        = 3000; // wait before reading the wall switch at power-up

WiFiClient wifiClient;
PubSubClient mqtt(wifiClient);

String stateTopic, cmdTopic, availTopic;

volatile unsigned long lastEdgeMs = 0;
void IRAM_ATTR onDetectEdge() { lastEdgeMs = millis(); }

bool lampOn = false;               // what the relay is doing
bool lastSwitchState = false;      // last stable wall-switch state
bool candidateState = false;
unsigned long candidateSince = 0;
bool initialized = false;
unsigned long bootMs = 0;
unsigned long lastMqttAttempt = 0;
unsigned long lastWifiAttempt = 0;

bool acPresent() { return (millis() - lastEdgeMs) < AC_PRESENT_TIMEOUT_MS; }

void publishState() {
  if (mqtt.connected()) mqtt.publish(stateTopic.c_str(), lampOn ? "ON" : "OFF", true);
}

void applyLamp(bool on) {
  lampOn = on;
  digitalWrite(RELAY_PIN, (on == RELAY_ACTIVE_HIGH) ? HIGH : LOW);
  publishState();
}

// Runs every loop, with or without network: the wall switches must always work.
void handleWallSwitch() {
  if (!initialized) {
    if (millis() - bootMs < BOOT_SETTLE_MS) return;
    lastSwitchState = candidateState = acPresent();
    candidateSince = millis();
    applyLamp(lastSwitchState);          // lamp follows the wall switches after a power cut
    initialized = true;
    return;
  }

  bool now = acPresent();
  if (now != candidateState) {           // state changed, start debounce timer
    candidateState = now;
    candidateSince = millis();
  }
  if (candidateState != lastSwitchState && millis() - candidateSince >= DEBOUNCE_MS) {
    lastSwitchState = candidateState;
    applyLamp(!lampOn);                  // any wall-switch flip toggles the lamp, like a real 2-way circuit
  }
}

void onMqttMessage(char* topic, byte* payload, unsigned int length) {
  String msg;
  for (unsigned int i = 0; i < length; i++) msg += (char)payload[i];
  if (msg == "ON")       applyLamp(true);
  else if (msg == "OFF") applyLamp(false);
}

void publishDiscovery() {
  String topic = String("homeassistant/light/") + NODE_ID + "/config";
  String json = "{";
  json += "\"name\":\"Hallway light\",";
  json += "\"unique_id\":\"" + String(NODE_ID) + "\",";
  json += "\"command_topic\":\"" + cmdTopic + "\",";
  json += "\"state_topic\":\"" + stateTopic + "\",";
  json += "\"availability_topic\":\"" + availTopic + "\",";
  json += "\"payload_on\":\"ON\",\"payload_off\":\"OFF\",";
  json += "\"device\":{\"identifiers\":[\"" + String(NODE_ID) + "\"],";
  json += "\"name\":\"Smart two-way light\",\"manufacturer\":\"DIY\",\"model\":\"ESP32 relay + AC detector\"}}";
  mqtt.publish(topic.c_str(), json.c_str(), true);
}

bool connectMqtt() {
  String clientId = String("esp32-") + NODE_ID + "-" + String((uint32_t)ESP.getEfuseMac(), HEX);
  if (!mqtt.connect(clientId.c_str(), MQTT_USER, MQTT_PASS,
                    availTopic.c_str(), 0, true, "offline")) {
    Serial.printf("MQTT connect failed, rc=%d\n", mqtt.state());
    return false;
  }
  mqtt.subscribe(cmdTopic.c_str());
  mqtt.publish(availTopic.c_str(), "online", true);
  publishDiscovery();
  publishState();
  Serial.println("MQTT connected.");
  return true;
}

void handleNetwork() {
  if (WiFi.status() != WL_CONNECTED) {
    if (millis() - lastWifiAttempt > 10000) {
      lastWifiAttempt = millis();
      WiFi.disconnect();
      WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    }
    return;
  }
  if (!mqtt.connected()) {
    if (millis() - lastMqttAttempt > 5000) {
      lastMqttAttempt = millis();
      connectMqtt();
    }
  } else {
    mqtt.loop();
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(RELAY_PIN, OUTPUT);
  digitalWrite(RELAY_PIN, RELAY_ACTIVE_HIGH ? LOW : HIGH);   // lamp OFF until the wall switch is read
  pinMode(DETECT_PIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(DETECT_PIN), onDetectEdge, CHANGE);

  stateTopic = String(NODE_ID) + "/state";
  cmdTopic   = String(NODE_ID) + "/set";
  availTopic = String(NODE_ID) + "/status";

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  mqtt.setServer(MQTT_HOST, MQTT_PORT);
  mqtt.setBufferSize(1024);
  mqtt.setCallback(onMqttMessage);
  bootMs = millis();
}

void loop() {
  handleWallSwitch();   // always first: local control never depends on the network
  handleNetwork();
}

How the code works

  • Local control first: the wall-switch logic runs before any network code, so the lamp still toggles if Wi-Fi or Home Assistant is down.
  • AC detection: the detector output pulses with the mains cycle. The sketch treats the line as live if an edge was seen in the last 40 ms, then debounces the change for 60 ms.
  • Toggle logic: each stable change of the wall-switch state flips the lamp, just like a real two-way circuit.
  • After a power cut: the lamp follows the current position of the wall switches once the system has settled.
  • Home Assistant: the node publishes an MQTT discovery message and appears as a light entity with availability status.
Two-Way Light Switch Wiring (3-Way) + Smart ESP32 Upgrade

Home Assistant setup

You need a Mosquitto broker and an MQTT user. If you have not set them up yet, follow the broker steps in our ESP32 energy monitor guide. After the first connection, Smart two-way light appears under Settings → Devices & Services → MQTT.

Test procedure

  1. With the power off, check every connection and make sure the enclosure is closed.
  2. Power on and watch the Serial Monitor at 115200 baud.
  3. Flip each wall switch: the lamp should toggle every time.
  4. Toggle the light from Home Assistant, then flip a wall switch: the lamp should toggle again.
  5. Disconnect the Wi-Fi router: wall switches must still work.

Troubleshooting

SymptomLikely cause and fix
Lamp toggles twice per switch flipDetector output is noisy. Increase DEBOUNCE_MS or add a small capacitor on the detector output.
Lamp is inverted at bootRelay board is active-low. Set RELAY_ACTIVE_HIGH to false.
Wall switch does nothingDetector not seeing the switched live, or the output pin is wrong. Check GPIO27 with the Serial Monitor.
Does not appear in Home AssistantCheck the broker IP, MQTT credentials and that the MQTT integration is configured.
LED lamp flickers when offLeakage through the detector circuit. Use a detector with a higher input impedance or a different model.

Frequently asked questions

Can I use this with three or more switches?

A circuit with more than two switches uses an intermediate (4-way) switch in the middle. The detector principle is the same, because it only senses the switched live, but test it carefully.

Does it work with dimmers?

No. This design switches the lamp fully on or off. Dimming needs a different circuit and a compatible dimmer module.

Why not connect the travelers to the ESP32 with resistors?

Resistors alone cannot make mains voltage safe for a GPIO. Without proper isolation, a fault can put mains voltage on the whole board and USB connection. Always use a mains-rated, isolated detector.

Can I use an ESP8266 instead?

Yes, the logic is the same, but the pin numbers and interrupt syntax differ slightly. The ESP32 is recommended for new builds.

What to build next

More projects: ESP32 Smart Home projects.

Conclusion

A two-way light circuit is simple once you understand commons and travelers. If you want it smart, sense the switched live through an isolated detector and drive a relay from a permanent live, instead of touching the traveler wires. Questions about the wiring or the code? Leave a comment below, and mention your country so the answer can follow your local rules.

No comments