Smart Switch
An offline-first 4-channel 230V mains automation controller engineered with an ESP32-WROOM-32, optocoupler galvanic isolation, boot-state brownout protection, and a local captive portal web interface.

The complete Smart Switch hardware system: Laptop with PlatformIO serial logs, mobile control dashboard, 4-gang modular switchboard, and ESP32 relay controller.
Controls standard Indian household ceiling fans, room lighting, and immersion pumps.
EL817 optocouplers providing complete optical isolation between 3.3V logic and 230V coils.
Embedded HTTP web server and captive portal running entirely on local ESP32 chip.
Real-time UART serial telemetry monitoring FreeRTOS task ticks and relay states.
Executive Overview
What It Is
Smart Switch is a custom-engineered 4-channel home automation controller built on an ESP32-WROOM-32 microcontroller. It interfaces physical 4-gang Indian modular wall switches with 230V mains relays while providing local, zero-cloud Wi-Fi smartphone control.
Why It Exists
Commercial smart switches (Tuya, Sonoff) are designed for Western electrical environments with stable grids and ubiquitous high-speed broadband. In Teghra, Bihar, daily realities include sudden voltage fluctuations (180V–260V), frequent brownouts, high summer humidity, and periodic internet outages. When cloud servers go down or Wi-Fi disconnects, commercial switches fail completely—often leaving users unable to turn off a room light manually.
Who It Serves
Indian households requiring reliable electrical automation that preserves existing manual toggle switch operation, survives frequent power outages without flickering, and operates 100% offline without remote cloud subscriptions.
The Engineering Core
Addresses hardware-level edge cases: defensive boot-state initialization that prevents active-LOW relay clicking during 3 AM power restorations, non-blocking software debouncing with dual-state synchronization, and an on-chip captive portal serving compressed web UI assets from LittleFS flash.
✨ Key Architecture Takeaways:
- ✓Solves the "3 AM relay click" brownout problem through hardware pull-ups and defensive pin initialization.
- ✓Synchronizes physical wall rocker switches with wireless commands without mechanical overrides.
- ✓Zero-cloud offline architecture: ESP32 serves its own responsive web dashboard at 192.168.4.1/dash.
Problem & Ground Motivation
Why Off-The-Shelf Smart Switches Fail in Regional India
Living in Teghra, power quality is an engineering challenge. Voltage fluctuates wildly between 180V and 260V depending on agricultural pump loads on the rural feeder transformer. Power cuts occur multiple times a week, followed by rapid restoration spikes.
When Javed tested commercial commercial smart switches, they failed in three fundamental ways:
First: Cloud Vulnerability. Most commercial switches route all commands through proprietary cloud servers in distant data centers. When the local internet cable or cellular router drops, the smart switch becomes completely unresponsive. Family members could not even turn on a ceiling fan using their smartphones.
Second: The "3 AM Relay Click" Nightmare. Commercial active-LOW relay modules pull pins low on boot. When mains power restored in the middle of the night after an outage, the switchboard would violently click all relays ON for 200 milliseconds before discovering Wi-Fi, turning on bedroom lights and waking up the entire house.
Third: Mechanical Incompatibility. Commercial switches either replace physical wall switches with cheap capacitive touch glass that breaks when touched with damp hands, or they disconnect the wall switch entirely. Indian families demand that elderly grandparents can flip a normal physical switch on the wall at any time.
⚠️ Real-World Ground Constraints:
- ▪Hazardous electrical environment: Handling live 230V AC mains at 50Hz carries severe shock and fire risk if isolation barriers fail.
- ▪Inductive load transients: Switching heavy inductive loads (ceiling fan motors, water pumps) produces massive back-EMF spikes that can reset microcontrollers.
- ▪Space constraint: Control circuitry, step-down SMPS, relays, and microcontroller must eventually fit behind a standard Indian 4-module wall switchboard.
This case study documents custom embedded hardware interfacing with 230V AC mains. Live mains voltage is lethal. Proper galvanic isolation, creepage distance, and fuse protection are mandatory before connecting any microcontroller to wall power.
Goals & Engineering Constraints
🎯 Functional Goals
- •Control 4 independent 230V AC electrical channels (lighting, ceiling fan, porch, water pump).
- •Preserve manual physical wall switch functionality with instantaneous state synchronization.
- •Provide a zero-cloud mobile web control interface accessible over local Wi-Fi and direct Access Point.
- •Persist relay states across sudden power cuts into non-volatile flash memory (NVS).
✨ UX & Ergonomics
- •Instant response time (<10ms) when flipping physical wall switches.
- •Responsive, modern mobile web dashboard accessible by typing smartswitch.local or 192.168.4.1/dash.
- •Clear tactile feedback and visible status LEDs for network connectivity and relay states.
⚡ Performance Budgets
- •Microsecond-level FreeRTOS task scheduling to prevent web server requests from delaying physical switch debouncing.
- •Total power consumption under 1.5 Watts in idle state to minimize standby energy drain.
- •Non-blocking C++ code utilizing millis() rather than delay() calls.
🛡️ Security & Hardware Guardrails
- •Optocoupler isolation (PC817 / EL817) with at least 5mm physical PCB creepage between 3.3V DC and 230V AC.
- •Snubber circuits and 1N4007 flyback diodes across relay coils to clamp inductive voltage spikes.
- •Defensive boot-pin configuration ensuring relays remain firmly OFF during chip startup.
Architecture & System Design
The architecture pairs dual-core ESP32 32-bit hardware with modular C++ firmware running on FreeRTOS. Core 0 handles Wi-Fi networking, DNS captive portal, and HTTP web server routines; Core 1 handles real-time GPIO polling, switch debouncing, and relay actuation.
+--------------------------------------------------------------------------+
| 230V AC INDIAN MAINS POWER INPUT |
| |
| +------------------------------------+ |
| | Isolated 230V AC -> 5V DC SMPS | |
| +-----------------+------------------+ |
+-------------------------|------------------------------------------------+
| 5V DC Clean Logic Power
v
+-------------------------+------------------------------------------------+
| ESP32-WROOM-32 CONTROLLER (FREERTOS) |
| |
| [ CORE 0: NETWORKING & WEB ] [ CORE 1: REAL-TIME HARDWARE ] |
| - ESPAsyncWebServer (Port 80) - Non-blocking millis() Debounce |
| - DNS Captive Portal Server - Edge Detection on GPIO Inputs |
| - mDNS: smartswitch.local - State Machine & NVS Flash Sync |
| - LittleFS Static UI Delivery - Active-LOW Defensive Boot Pin |
+------------+-----------------------------------------+-------------------+
| |
| Wi-Fi / AP (192.168.4.1) | GPIO 25, 26, 27, 14
v v
+------------+-------------+ +-------------+-------------------+
| MOBILE WEB DASHBOARD | | 4-CHANNEL OPTOCOUPLER ISOLATION |
| - Responsive UI Tiles | | - 4x EL817 Optocouplers (5kV) |
| - Real-Time Switch Sync | | - S8050 NPN Relay Coil Drivers |
| - Fast LittleFS Cached | | - 1N4007 Flyback Damping Diodes |
+--------------------------+ +-------------+-------------------+
|
v
+------------------------------------------------------+-------------------+
| 4x SONGLE 5V RELAYS (10A 250V AC) & 4-GANG WALL SWITCHES |
| - Relay 1: Room Light 1 (GPIO 25) <-> Physical Switch 1 (GPIO 32) |
| - Relay 2: Ceiling Fan (GPIO 26) <-> Physical Switch 2 (GPIO 33) |
| - Relay 3: Room Light 2 (GPIO 27) <-> Physical Switch 3 (GPIO 18) |
| - Relay 4: Water Pump (GPIO 14) <-> Physical Switch 4 (GPIO 19) |
+--------------------------------------------------------------------------+Subsystem Layer Breakdown
High-Voltage Power & Load Layer
230V AC / 10ARole: 230V AC Mains Switching
4× Songle SRD-05VDC-SL-C electromechanical relays switching up to 10A at 250V AC. Directly drives household lighting, fans, and appliances.
Galvanic Optical Barrier Layer
Optocoupler EL817Role: 5000V RMS Optical Isolation
EL817 optocouplers completely separate the low-voltage 3.3V ESP32 microcontroller logic ground from the relay driver ground, preventing mains surges from frying the processor.
Microcontroller Logic Layer
ESP32 FreeRTOSRole: ESP32-WROOM-32 Dual-Core Engine
Xtensa 32-bit LX6 running at 240MHz. Executes hardware debouncing state machine, non-volatile storage (NVS) state saving, and FreeRTOS task scheduling.
Local Network & Web Layer
Offline Captive PortalRole: Zero-Cloud Web Server & Captive Portal
Runs ESPAsyncWebServer, LittleFS flash filesystem, and DNSServer. Serves a responsive mobile control dashboard at 192.168.4.1/dash and smartswitch.local.
Step-by-Step Execution Sequence
- 1User flips physical wall switch: GPIO input pin detects voltage edge transition.
- 2Software state machine debounces mechanical bounce over a 50ms window using non-blocking millis().
- 3ESP32 inverts target relay state, pulls active-LOW relay pin LOW, and writes new state to NVS flash memory.
- 4Relay coil energizes via optocoupler and transistor driver, closing relay contacts and turning appliance ON/OFF.
- 5Connected smartphone on local Wi-Fi receives state broadcast via SSE (Server-Sent Events) and updates UI tile in <25ms.
Technical Stack & Architectural Rationale
Every tool and library was chosen under strict engineering constraints of latency, memory limits, and physical execution reality.
ESP32-WROOM-32
Embedded/HardwareRole: Primary Microcontroller
Why Chosen: Dual-core 240MHz architecture provides separate cores for real-time GPIO handling and asynchronous Wi-Fi/HTTP networking.
PlatformIO & C++ (Arduino Framework)
ToolingRole: Firmware Build & Dependency Environment
Why Chosen: Provides modern dependency management, compilation optimization, and reproducible embedded builds over standard Arduino IDE.
Songle SRD-05VDC-SL-C Relays
Embedded/HardwareRole: High-Voltage AC Electromechanical Actuators
Why Chosen: Reliable 10A 250V AC rated relay contacts capable of switching inductive and resistive Indian household electrical loads.
EL817 Optocouplers
Embedded/HardwareRole: Galvanic Optical Isolation Barriers
Why Chosen: Provides 5000V RMS galvanic isolation, preventing dangerous mains surges and back-EMF spikes from reaching microcontroller silicon.
ESPAsyncWebServer & LittleFS
BackendRole: Embedded High-Concurrency HTTP Engine
Why Chosen: Serves static HTML/CSS/JS dashboard assets directly from flash memory with zero-cloud dependencies and non-blocking asynchronous event handling.
ESP32 Non-Volatile Storage (NVS)
Storage/DBRole: Persistent Flash State Memory
Why Chosen: Saves appliance on/off states with wear leveling so that appliance states are accurately restored after unexpected power outages.
Chronological Development Journey
From initial field investigations in Teghra to bench prototypes, hardware revisions, and production releases.
Initial Circuit Assembly on Solderless Breadboard
Javed assembled the first prototype using an ESP32 development board, jumper wires, a single 5V relay module, and pushbuttons. Verified basic 3.3V logic level shifting and validated that the ESP32 could trigger the relay coil without voltage sag.

Rigging the Electrical Test Bench with Multimeters and 230V AC Load
Moved the setup to a dedicated wooden testing bench. Instrumented the system with a digital multimeter to measure coil current draw (approx. 72mA per active relay coil) and monitored 5V power supply rail stability under 4-channel simultaneous activation.

Wiring 4-Channel Relay Board to Standard 4-Gang Indian Switchboard
Connected the optocoupler-isolated 4-channel relay board to a genuine 4-gang Indian modular toggle switchboard. Wired mechanical rocker switches as low-voltage inputs to ESP32 GPIOs 32, 33, 18, and 19.

Debugging Brownouts & PlatformIO Serial Telemetry at 115200 Baud
Connected the system to PlatformIO serial monitor at 115200 baud. Analyzed FreeRTOS boot logs, resolved active-LOW boot clicking, tuned debouncing timers to 50ms, and implemented the DNS captive portal engine.

Engineering Challenges & Technical Solutions
Real failure modes encountered on live devices, breadboards, and regional networks, complete with root-cause analysis and code-level resolutions.
Challenge #1: Eliminating the "3 AM Relay Click" During Power Restoration
● ResolvedThe Problem Context
Active-LOW relay boards trigger when their input pin is pulled to GND. When mains power restores after a power outage at 3 AM, ESP32 GPIO pins default to high-impedance/input mode with weak internal pull-downs for ~150ms before user code executes. This caused all 4 relays to momentarily energize, violently clicking and turning on bedroom lights.
Investigation & Root Cause Analysis
Probing the relay input headers with an oscilloscope revealed a 150ms LOW pulse during ESP32 bootloader initialization before setup() was reached.
The Actual Engineering Resolution
Added physical 10kΩ pull-up resistors to the 3.3V rail on each relay control line to keep the inputs pulled firmly HIGH during hardware reset. In software, initialized the pins in the very first machine instructions of setup():
// Defensive boot initialization: configure pins HIGH before setting OUTPUT mode
void setup() {
// CRITICAL: Prevent 3 AM relay click by asserting HIGH before OUTPUT mode
digitalWrite(RELAY_1_PIN, HIGH);
digitalWrite(RELAY_2_PIN, HIGH);
digitalWrite(RELAY_3_PIN, HIGH);
digitalWrite(RELAY_4_PIN, HIGH);
pinMode(RELAY_1_PIN, OUTPUT);
pinMode(RELAY_2_PIN, OUTPUT);
pinMode(RELAY_3_PIN, OUTPUT);
pinMode(RELAY_4_PIN, OUTPUT);
Serial.begin(115200);
Serial.println("[SYSTEM] Defensive relay boot state initialized: RELAYS OFF");
}Challenge #2: Mechanical Switch Contact Bounce in Humid Environments
● ResolvedThe Problem Context
Indian modular rocker switches exhibit mechanical contact bounce lasting 10ms to 25ms. In high-humidity monsoon conditions, micro-arcing caused the microcontroller to interpret a single physical switch toggle as 3 to 5 rapid transitions, causing the relay to oscillate furiously.
Investigation & Root Cause Analysis
Serial logs showed multiple edge interrupts firing within a 30ms window whenever a physical wall switch was operated.
The Actual Engineering Resolution
Replaced simple edge interrupts with a non-blocking software state machine using millis() timestamps. When an input edge transition is detected, the firmware locks the channel for a 50ms debounce window and verifies that the new switch state remains stable before toggling the relay state.
// Non-blocking switch debouncing state machine
void checkWallSwitches() {
unsigned long now = millis();
for (int i = 0; i < 4; i++) {
int reading = digitalRead(switchPins[i]);
if (reading != lastSwitchState[i]) {
lastDebounceTime[i] = now;
lastSwitchState[i] = reading;
}
if ((now - lastDebounceTime[i]) > 50) { // 50ms debounce window
if (reading != stableSwitchState[i]) {
stableSwitchState[i] = reading;
toggleRelay(i); // Flip relay state and sync NVS
}
}
}
}Features & User Experience Walkthrough
A deep architectural inspection of shipped interfaces, physical control panels, and protocol telemetry.
Integrated ESP32 & Modular Switchboard Setup
Complete operational setup showing the 4-gang Indian switchboard, optocoupler relay module, ESP32 microchip, and real-time serial telemetry.

⚡ Engineering Highlights:
- ✓4-channel active-LOW relay driver with optocoupler isolation.
- ✓Physical 4-gang Indian modular wall switch integration.
- ✓Real-time PlatformIO serial monitoring at 115200 baud.
Zero-Cloud Mobile Captive Portal Dashboard
Responsive web interface served directly by the ESP32 chip over local Wi-Fi. Access at smartswitch.local or 192.168.4.1/dash with zero internet connection.

⚡ Engineering Highlights:
- ✓Standalone captive portal: broadcasts SmartSwitch-Local AP if router is offline.
- ✓Zero cloud latency: sub-25ms response time on local Wi-Fi.
- ✓Tile layout with visual on/off state icons and responsive touch feedback.
Electrical Test Bench & Multimeter Profiling
Monitoring current draw, ground rail potential, and thermal dissipation under prolonged 4-channel active relay operation.

⚡ Engineering Highlights:
- ✓Precise 5V and 3.3V power rail monitoring under active load.
- ✓Thermal observation of isolated step-down SMPS module.
- ✓Validation of optocoupler barrier isolation integrity.
High-Voltage Screw Terminals & Optocoupler Trace Isolation
Detailed inspection of relay screw terminal blocks, mains cable routing, and optocoupler isolation barrier on the relay module.

⚡ Engineering Highlights:
- ✓Heavy-gauge screw terminal connections for phase and load lines.
- ✓Flyback diodes suppressing inductive kickback from fan coils.
- ✓Visual LED indicators for individual relay actuation.
PlatformIO 115200 Baud Serial Telemetry
Serial monitor logging device boot sequence, Wi-Fi connection handshake, mDNS initialization, and real-time state changes.

⚡ Engineering Highlights:
- ✓Live serial monitoring of Wi-Fi RSSI signal strength and IP assignment.
- ✓Immediate verification of physical switch edge detection interrupts.
- ✓NVS flash commit confirmation on every state transition.
Results & Honest Current Status
Smart Switch is an operational bench prototype that has been validated under real 230V AC mains electrical loads in Teghra. The system reliably controls 4 electrical channels both physically and wirelessly without internet connectivity.
✅ Verified Implemented Functionality
- •ESP32-WROOM-32 dual-core firmware running on FreeRTOS.
- •Optocoupler-isolated 4-channel active-LOW relay actuation.
- •Defensive boot state configuration eliminating 3 AM brownout clicking.
- •Non-blocking 50ms software debouncing for physical 4-gang Indian wall switches.
- •Zero-cloud local captive portal web server serving dashboard from LittleFS.
- •mDNS local hostname resolution (smartswitch.local) and AP fallback (192.168.4.1).
- •State persistence across power outages using ESP32 NVS flash memory.
⚠️ Known Limitations & Ground Reality
- •Current build is an engineered bench prototype with discrete modules on a mounting board; a custom etched all-in-one PCB is required for compact in-wall flush mounting.
- •No hardware electrical power metering IC (e.g. ADE7758 / HLW8032) is included in this revision; power consumption is calculated rather than measured in real-time.
- •Not commercially safety-certified (e.g. BIS or CE certified); operates as a custom experimental prototype for personal domestic testing.
➔ Immediate Engineering Next Steps:
- ➔Design a custom 2-layer PCB in KiCad with integrated HLK-PM01 SMPS, fuse protection, and varistors.
- ➔Fabricate custom 3D-printed enclosure matching standard Indian 4-module concealed metal box dimensions.
- ➔Integrate current transformer (CT) coil for live kilowatt-hour power consumption monitoring.
Lessons Learned & Engineering Reflections
First-principles insights gathered while building, testing, and debugging directly in Indian field conditions.
In IoT hardware, the software is only as dependable as the underlying physical electrical design; ignoring brownout pin states leads to catastrophic midnight bugs.
Offline-first architecture is not a luxury in emerging markets—it is a mandatory baseline requirement.
Mechanical physical controls must remain first-class citizens alongside wireless smartphone dashboards; smart homes must never become hostage to smartphone battery life.
Future Roadmap
Clear distinction between verified accomplishments and prospective architectural exploration.
- ✓Breadboard prototype and GPIO validation.
- ✓Optocoupler 4-channel relay integration with 230V mains load.
- ✓Defensive boot state pull-up configuration.
- ✓Non-blocking switch debouncing state machine.
- ✓Local captive portal and LittleFS web dashboard.
- •KiCad schematic design for integrated single-board PCB.
- •Thermal logging of relay coils under continuous 12-hour activation.
- ◦Custom PCB fabrication with onboard fuse and MOV surge protection.
- ◦3D-printed flame-retardant ABS switchboard enclosure.
- ◦Current sensor integration for appliance power monitoring.
- ?ESP-NOW peer-to-peer mesh linking multiple room switchboards without Wi-Fi router dependency.