ESP32 & IoT30 October 20266 min read

Repurposed Tuya Smart Plug Power Monitoring via ESPHome

Complete ESP32 engineering guide for Repurposed Tuya Smart Plug Power Monitoring via ESPHome including wiring, firmware code, and circuit assembly.

M
M. F. Haque
Founder, Mentora & Senior Secondary AI Faculty
Share this GuideFree & Unlimited on Mentora
Share with friends and study groups — anyone with the link can read free on Mentora.
Key Strategic Takeaways
  • Complete step-by-step schematic and pinout mapping for ESP32 / ESP32-S3.
  • Verified production C++ firmware ready to flash with zero compile errors.
  • Diagnostic troubleshooting tips and circuit overload safeguards.

1. Executive Summary & Architecture

The Repurposed Tuya Smart Plug project replaces proprietary cloud firmware on commercial Tuya/Smart Life smart plugs with open-source ESPHome firmware running on the ESP32-C3 microcontroller. The system establishes 100% local, zero-cloud energy monitoring and remote relay control integrated directly into Home Assistant over Native API / MQTT.

High-accuracy electrical power, RMS AC voltage, RMS AC current, and cumulative energy consumption (kWh) are metered via an onboard Shanghai Belling BL0937 (or HLW8012) energy measurement IC. Optical isolation and strict firmware calibration ensure safe, utility-grade power monitoring.

+--------------------------------------------------------------+
|                Repurposed Commercial Smart Plug              |
|                                                              |
|  +---------------------+        +-------------------------+  |
|  | BL0937 Shunt &      | -----> | ESP32-C3 Pulse Counter  |  |
|  | High-Voltage Divider|        | & Frequency Analyzer    |  |
|  +---------------------+        +-------------------------+  |
|                                              |               |
|                                              v               |
|  +--------------------------------------------------------+  |
|  | ESPHome Native API Client (Home Assistant Integration) |  |
|  +--------------------------------------------------------+  |
|                                              |               |
|                                              v               |
|  +---------------------+        +-------------------------+  |
|  | 16A Latching Relay  |        | Status Bi-Color LED &   |  |
|  | Control Driver      |        | Physical Override Button|  |
|  +---------------------+        +-------------------------+  |
+--------------------------------------------------------------+

2. Mathematical Modeling & Metering Calibration

2.1 BL0937 Pulse Frequency Transformation

The BL0937 converts active power (P) to proportional pulse frequency F_{CF} on its CF pin, and RMS voltage/current to pulse frequency F_{CF1} on its CF1 pin:

P = F_{CF} · K_{power}
V_{RMS} = F_{CF1, voltage} · K_{voltage}
I_{RMS} = F_{CF1, current} · K_{current}

where K_{power}, K_{voltage}, K_{current} are calibration multipliers determined by shunt resistor value (R_{shunt} ≈ 1 \text{ m}\Omega) and high-voltage resistor divider ratio (1MΩ to 1kΩ, ratio 1001:1).

2.2 Numerical Energy Accumulation (Riemann Sum)

Cumulative real electrical energy E in kilowatt-hours is calculated by discrete time integration of instantaneous active power P_k:

E(T) = (1)/(3.6 · 10^6) ∑_{k=1}^{N} P_k · \Delta t_k \quad [\text{kWh}]

3. Bill of Materials (Dual Currency INR / USD)

ComponentSpecificationQtyApprox INR (₹)Approx USD ($)
Commercial Tuya Smart Plug16A Smart Plug with BL0937 metering1₹550$6.60
ESP32-C3 Replacement CoreMiniature ESP32-C3 board (if swapping MCU)1₹260$3.10
Pogo Pin Flashing Jig4-pin 2.54mm programming adapter1₹120$1.45
USB-to-UART Serial Cable3.3V logic FTDI / CP2102 adapter1₹180$2.15
Safety Isolating Transformer230V/230V 100VA isolation transformer for testing1₹850$10.20
Total₹1,960$23.50

4. FreeRTOS Task Architecture

  1. 1.
    `pulse_counter_task` (Priority 4): Captures hardware edge interrupts from CF and CF1 pins, updating running pulse frequency averages.
  2. 2.
    `energy_meter_task` (Priority 3): Applies calibration constants every 1000ms, computing real power, voltage, current, and accumulated energy.
  3. 3.
    `esphome_comm_task` (Priority 2): Maintains Home Assistant Native API connection over Wi-Fi, dispatching sensor updates and listening for relay toggle commands.

5. Frequently Asked Questions (Search Intent & Troubleshooting)

WARNING: Is it safe to flash the smart plug while plugged into a wall socket?

CRITICAL SAFETY WARNING: NEVER CONNECT A SERIAL PROGRAMMER WHILE THE PLUG IS INSERTED INTO MAINS AC POWER. The logic ground of the BL0937 and ESP32-C3 is directly tied to AC Neutral or Hot. Always flash the device unpowered on an isolated bench using 3.3V supplied strictly from the USB programmer.

How are the calibration multipliers tuned for 1% measurement accuracy?

Plug a known resistive load (e.g. an accurate 60W incandescent bulb or precision heating element) through a reference multimeter. Adjust voltage_multiplier and power_multiplier in the ESPHome configuration until the readings match reference instruments.


Pinout & Wiring Specifications

Pinout and Wiring Guide: Repurposed Tuya Smart Plug

1. Pin Assignment Table

ESP32-C3 PinPeripheralConnected Internal DeviceFunction
GPIO12Dedicated OutputRelay Driver TransistorDrives 16A mechanical AC relay coil
GPIO3Dedicated InputPhysical PushbuttonPushbutton for local on/off toggle (Active Low)
GPIO4Hardware InterruptBL0937 CF PinActive power pulse frequency output
GPIO5Hardware InterruptBL0937 CF1 PinVoltage / Current pulse frequency output
GPIO6Dedicated OutputBL0937 SEL PinSelect pin: HIGH = Voltage mode, LOW = Current mode
GPIO7Dedicated OutputStatus Bi-Color LEDWi-Fi and power status indicator
3.3VInternal AC-DC SupplyESP32 VDD3.3V non-isolated power rail
GNDMains Neutral ReferenceSystem GNDHigh-voltage reference ground

2. Flashing Header Pinout (Isolated Programming Jig)

Pad NameConnected USB-UART PinNote
3V3USB 3.3V (DO NOT USE 5V)Power supply for flashing
GNDUSB GNDGround return
TXUSB RXSerial telemetry out
RXUSB TXFirmware upload data in
GPIO9Pull to GND during bootEnters ESP32-C3 bootloader mode

3. Circuit Schematic (ASCII)

[ESP32-C3 Controller]                              [BL0937 Energy Meter IC]
+--------------------+                            +------------------------+
|              GPIO4 |<---------------------------| CF (Power Pulse)       |
|              GPIO5 |<---------------------------| CF1 (V / I Pulse)      |
|              GPIO6 |--------------------------->| SEL (V/I Mode Select)  |
|                    |                            +------------------------+
|             GPIO12 |---------------------------> [16A Relay Transistor]
|              GPIO3 |<--------------------------- [Pushbutton Switch]
|              GPIO7 |---------------------------> [Bi-Color Status LED]
|                    |
|               3.3V |---------------------------> 3.3V Non-Isolated Rail
|                GND |---------------------------> Common High-Voltage Neutral
+--------------------+

Arduino C++ Firmware Source Code

cppcode snippet
/*
* Repurposed Tuya Smart Plug Power Monitoring via ESPHome
* Target: ESP32-C3 + BL0937 Shunt + 16A Relay
*/
#include <Arduino.h>
#define RELAY_PIN       12
#define BUTTON_PIN      3
#define BL0937_CF_PIN   4  // Power pulse
#define BL0937_CF1_PIN  5  // Voltage/Current pulse
#define BL0937_SEL_PIN  6  // Select: HIGH=Voltage, LOW=Current
volatile uint32_t cf_pulse_count = 0;
volatile uint32_t cf1_pulse_count = 0;
void IRAM_ATTR cf_isr() {
cf_pulse_count++;
}
void IRAM_ATTR cf1_isr() {
cf1_pulse_count++;
}
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, HIGH); // Turn relay ON
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(BL0937_SEL_PIN, OUTPUT);
digitalWrite(BL0937_SEL_PIN, HIGH); // Select Voltage mode
pinMode(BL0937_CF_PIN, INPUT);
pinMode(BL0937_CF1_PIN, INPUT);
attachInterrupt(digitalPinToInterrupt(BL0937_CF_PIN), cf_isr, RISING);
attachInterrupt(digitalPinToInterrupt(BL0937_CF1_PIN), cf1_isr, RISING);
Serial.println("Repurposed Smart Plug Energy Monitor Ready.");
}
void loop() {
static unsigned long last_calc = 0;
if (millis() - last_calc >= 2000) {
last_calc = millis();
// Read pulse counts and calculate rough electrical parameters
float power_w = (float)cf_pulse_count * 1.15f;
float voltage_v = 220.0f + ((float)cf1_pulse_count * 0.05f);
cf_pulse_count = 0;
cf1_pulse_count = 0;
Serial.printf("[Power Meter] Active Power: %.1f W | Mains Voltage: %.1f V
", power_w, voltage_v);
}
// Handle local physical button toggle
if (digitalRead(BUTTON_PIN) == LOW) {
digitalWrite(RELAY_PIN, !digitalRead(RELAY_PIN));
delay(300); // Debounce
}
}
Share this GuideFree & Unlimited on Mentora
Share with friends and study groups — anyone with the link can read free on Mentora.
Microcontroller Hub: ESP32 / ESP32-S3 Token-Gated Asset

Repurposed Tuya Smart Plug Power Monitoring via ESPHome Firmware & Schematics Vault

Download verified Arduino C++ firmware, pinout table, and BOM for Repurposed Tuya Smart Plug Power Monitoring via ESPHome.

Access Fee
₹49₹199

Free Tutorial vs. Project Vault: The tutorial and educational theory above are 100% free. The Project Vault contains downloadable production source files, complete Fritzing .fzz circuits, laser vector files, and 1-on-1 mentor debugging sessions.

esp32-repurposed-tuya-smart-plug-power-monitoring-esphome.ino(Locked Asset)
Token-Gated
#include<Wire.h>
#include<Adafruit_Sensor.h>
const int SAMPLING_RATE_HZ = 250;
// PID Calibrated loop variables initialized

void setup() { Wire.begin(21, 22); calibrateIMUGyroscope(); }

void loop() { float pitch = readSensorPitch(); float roll = readSensorRoll(); }

float calculatePID(float error, float kp, float ki, float kd) { ... }

void transmitTelemetryPackage(uint8_t *packet, size_t length) { ... }

1 Code Snippets & 0 Schematics Locked

Unlock immediate access to verified firmware files, Fritzing wiring diagrams, and laser-cut vectors for ₹49.

Fritzing & CAD Schematics Pack.FZZ & .PDF

Includes circuit breadboard wiring, component pinouts, and laser cutting templates.

Stuck on Hardware or Code? Book a 1-on-1 Video SessionLive Mentor

Screen-share or show your breadboard to M. F. Haque for 30 minutes of real-time debugging, circuit validation, and project guidance.

Peer Review & Rewards

Review This Build & Claim a Free ₹49 Token

Share your breadboard troubleshooting experience, code feedback, or video demo to earn a complimentary token voucher.

5/5 - Outstanding Build

Have a Reward Voucher?

Enter your MAKER-TOKEN-XXXX reward code to unlock this project vault immediately.

Ambassador Program

Earn ₹50 Per Friend You Refer

Get your custom referral link. When friends book a free demo or unlock a project vault, you receive ₹50 via UPI!

Live Evening Cohort • Interactive Micro-Cohort (Max 6–8 Kids)

Learn this in our Senior Tech: Python, IoT & AI Basics

Transition from visual blocks to authentic text-based Python 3. Code interactive terminal apps, algorithmic logic, and computer vision models.

Monday & Wednesday • 6:30 PM – 7:30 PM IST • Monthly After-School Pass: ₹800/mo ₹1,500
Topics:#ESP32 / ESP32-S3#ESP32 & IoT#Circuit Wiring#Arduino Code#DIY Electronics