Skip to content
Advanced 5 hours

ESP32 Smart Home Switch with MQTT and Home Assistant

By Amit1379
July 13, 2026

This project replaces a conventional light switch with a smart one that integrates directly into a Home Assistant instance running on a Raspberry Pi or other server. The ESP32 connects to your MQTT broker, publishes power state, and subscribes to command topics. Physical button still works as a fallback. Power monitoring via a current transformer gives you real-time watt readings. OTA updates mean you never need to physically plug in the ESP32 again after first flash.

What You’ll Need

  • ESP32 DevKit
  • 5 V relay module (optocoupler-isolated)
  • SCT-013 non-invasive current transformer (for power monitoring)
  • 10 Ω burden resistor + 100 kΩ × 2 biasing resistors (for CT sensor)
  • Momentary push button
  • Home Assistant instance on local network
  • Mosquitto MQTT broker (installed on HA or separate Pi)
  • 5 V / 1 A USB power supply

Step-by-Step Instructions

  1. Install libraries: PubSubClient (MQTT), ArduinoOTA, EmonLib (energy monitoring), WiFi.
  2. Wire the relay: Relay IN pin → ESP32 GPIO 26. Relay VCC → 5 V, GND → GND. The relay’s NO/COM contacts switch the load (lamp).
  3. Wire current transformer: SCT-013 clamps around one load wire. Two burden resistor ends go to GPIO 34 (ADC) and GND, with two 100 kΩ resistors biasing the midpoint to VCC/2 for AC signal capture.
  4. MQTT topics: Publish to: cmnd/switch1/POWER (relay state). Subscribe to: stat/switch1/POWER (receive commands). Publish to: tele/switch1/SENSOR (energy data JSON every 60 s).
  5. Home Assistant MQTT config: In HA configuration.yaml, add an mqtt switch entity referencing your topics and a sensor entity for the power reading.
  6. OTA updates: In setup(), call ArduinoOTA.begin(). In loop(), call ArduinoOTA.handle(). Now flash new firmware wirelessly via Arduino IDE (select the ESP32’s IP as the port).
  7. Physical button: Interrupt on GPIO 0. Toggle relay and immediately publish new state to MQTT so HA stays in sync.

Safety Notes

  • This project involves mains voltage in the relay load circuit — if installing on a real light switch, this work must be done by a qualified electrician in most jurisdictions.
  • Never work on the relay load circuit while it is connected to mains supply.
  • Use an optocoupler-isolated relay module to prevent mains voltage from reaching the ESP32 in a fault condition.

Tips & Troubleshooting

  • If MQTT disconnects frequently, add a reconnect loop with exponential backoff in your code.
  • Use a static IP (WiFi.config()) so HA’s MQTT device configuration doesn’t break when the router reassigns the IP.
  • Add a retained MQTT publish on startup so HA knows the switch state immediately after ESP32 reboot.

Leave a Comment

Your email address will not be published. Required fields are marked *