Hardware & Embedded Systems · ESP32 & Mains IoT📍 Teghra, Bihar, India🗓️ 2024–2026● Operational Bench Prototype & Field Deployment

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.

Smart Switch full hardware system: PlatformIO serial monitor, phone dashboard, 4-gang Indian switchboard, ESP32, and relay board

The complete Smart Switch hardware system: Laptop with PlatformIO serial logs, mobile control dashboard, 4-gang modular switchboard, and ESP32 relay controller.

Mains Rating230V AC / 10A

Controls standard Indian household ceiling fans, room lighting, and immersion pumps.

Isolation Barrier5000V RMS

EL817 optocouplers providing complete optical isolation between 3.3V logic and 230V coils.

Cloud Dependency0% Standalone

Embedded HTTP web server and captive portal running entirely on local ESP32 chip.

Baud Rate115200 Baud

Real-time UART serial telemetry monitoring FreeRTOS task ticks and relay states.

System Section 01Executive Summary

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.
System Section 02Origin & Ground Reality

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.
📌Electrical Safety Warning

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.

System Section 03Specifications

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.
System Section 04Topology & Pipeline

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.

Topology & Data Pipeline Schema
+--------------------------------------------------------------------------+
|                  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 / 10A

Role: 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 EL817

Role: 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 FreeRTOS

Role: 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 Portal

Role: 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

  1. 1User flips physical wall switch: GPIO input pin detects voltage edge transition.
  2. 2Software state machine debounces mechanical bounce over a 50ms window using non-blocking millis().
  3. 3ESP32 inverts target relay state, pulls active-LOW relay pin LOW, and writes new state to NVS flash memory.
  4. 4Relay coil energizes via optocoupler and transistor driver, closing relay contacts and turning appliance ON/OFF.
  5. 5Connected smartphone on local Wi-Fi receives state broadcast via SSE (Server-Sent Events) and updates UI tile in <25ms.
System Section 05Engineering Primitives

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/Hardware

Role: 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)

Tooling

Role: 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/Hardware

Role: 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/Hardware

Role: 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

Backend

Role: 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/DB

Role: 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.

System Section 07Engineering Timeline

Chronological Development Journey

From initial field investigations in Teghra to bench prototypes, hardware revisions, and production releases.

Stage 1: Breadboard Prototyping & GPIO Verification🗓️ 2024

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.

Early breadboard prototype with jumper wires and single relay
Early Breadboard Stage: Validating GPIO pinouts, 3.3V to 5V transistor logic switching, and basic trigger code.
Stage 2: Bench Testing & Electrical Instrumentation🗓️ Late 2024

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.

Bench setup with multimeters, breadboards, and AC wiring
Electrical Test Bench: Monitoring DC rail current draw, ripple voltage, and thermal behavior under full 4-channel load.
Stage 3: High-Voltage Relay Wiring & Switchboard Integration🗓️ 2025

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.

Close-up high-voltage wiring of relay board and screw terminals
High-Voltage Wiring: Relay screw terminals wired to 230V mains, with optocoupler signals routed to ESP32 GPIO headers.
Stage 4: Firmware Hardening & Serial Telemetry Debugging🗓️ 2025–2026

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.

PlatformIO serial monitor showing boot logs and telemetry at 115200 baud
PlatformIO Serial Debugging: Monitoring 115200 baud telemetry for Wi-Fi reconnection, relay toggles, and NVS flash writes.
System Section 06Debugging & Post-Mortems

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

● Resolved

The 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():

src/main.cpp
// 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");
}
💡 Key Takeaway:Hardware default states must be secured physically with pull-ups; relying solely on software execution leaves dangerous reset-window vulnerabilities.

Challenge #2: Mechanical Switch Contact Bounce in Humid Environments

● Resolved

The 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.

src/debouncer.cpp
// 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
      }
    }
  }
}
💡 Key Takeaway:Embedded inputs interfacing with physical mechanical contacts must always be conditioned with deterministic software debouncing.
System Section 08Production Surface

Features & User Experience Walkthrough

A deep architectural inspection of shipped interfaces, physical control panels, and protocol telemetry.

Feature 01

Integrated ESP32 & Modular Switchboard Setup

● Implemented

Complete operational setup showing the 4-gang Indian switchboard, optocoupler relay module, ESP32 microchip, and real-time serial telemetry.

Full hardware setup showing laptop serial monitor, phone, and switchboard
Complete System: Serial monitor tracking firmware state, mobile web UI, and physical 4-gang switchboard.

⚡ 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.
Feature 02

Zero-Cloud Mobile Captive Portal Dashboard

● Implemented

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.

Mobile web captive portal dashboard showing switch toggle cards
Mobile Dashboard: Responsive control tiles for Lights, Fan, Porch, and Pump served from ESP32 LittleFS.

⚡ 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.
Feature 03

Electrical Test Bench & Multimeter Profiling

● Implemented

Monitoring current draw, ground rail potential, and thermal dissipation under prolonged 4-channel active relay operation.

Test bench with digital multimeters and breadboards
Test Bench: Validating power supply ripple and relay coil current under simultaneous 4-channel activation.

⚡ 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.
Feature 04

High-Voltage Screw Terminals & Optocoupler Trace Isolation

● Implemented

Detailed inspection of relay screw terminal blocks, mains cable routing, and optocoupler isolation barrier on the relay module.

High-voltage relay screw terminal blocks and PCB traces
Relay Wiring Detail: 230V mains connected via heavy-gauge screw terminals with physical optical separation.

⚡ 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.
Feature 05

PlatformIO 115200 Baud Serial Telemetry

● Implemented

Serial monitor logging device boot sequence, Wi-Fi connection handshake, mDNS initialization, and real-time state changes.

Serial monitor console output showing 115200 baud boot messages
Serial Telemetry: Real-time logs verifying FreeRTOS task ticks, Wi-Fi IP assignment, and NVS flash commits.

⚡ 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.
System Section 09Verification & Metrics

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.
System Section 10Reflective Analysis

Lessons Learned & Engineering Reflections

First-principles insights gathered while building, testing, and debugging directly in Indian field conditions.

01

In IoT hardware, the software is only as dependable as the underlying physical electrical design; ignoring brownout pin states leads to catastrophic midnight bugs.

02

Offline-first architecture is not a luxury in emerging markets—it is a mandatory baseline requirement.

03

Mechanical physical controls must remain first-class citizens alongside wireless smartphone dashboards; smart homes must never become hostage to smartphone battery life.

System Section 11Horizon Planning

Future Roadmap

Clear distinction between verified accomplishments and prospective architectural exploration.

🟢 Completed
  • ✓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.
🟡 In Progress
  • •KiCad schematic design for integrated single-board PCB.
  • •Thermal logging of relay coils under continuous 12-hour activation.
🔵 Planned
  • ◦Custom PCB fabrication with onboard fuse and MOV surge protection.
  • ◦3D-printed flame-retardant ABS switchboard enclosure.
  • ◦Current sensor integration for appliance power monitoring.
🟣 Exploratory
  • ?ESP-NOW peer-to-peer mesh linking multiple room switchboards without Wi-Fi router dependency.