Implementing Energy Calculation and Data Logging on ESP32 for IoT kWh Monitoring

After completing the hardware architecture of the single-socket IoT energy meter, the next critical stage was implementing reliable energy calculation and data handling on the ESP32.

Unlike simple voltage or current monitoring, a kWh system must continuously compute power and accumulate energy over time. This requires careful handling of sampling intervals, communication reliability, and data persistence.

image.png

Reading Electrical Parameters

The system uses the PZEM-004T module to obtain:

  • Voltage (V)
  • Current (A)
  • Active Power (W)
  • Energy (kWh)
  • Frequency (Hz)

Communication between ESP32 and PZEM is handled via UART.

image.png

A periodic polling method is implemented to read data every defined interval (typically 1–2 seconds).

To avoid unstable readings:

  • Invalid responses are filtered
  • Communication timeout is monitored
  • Re-read attempts are implemented if data is corrupted

This ensures stable long-term monitoring.

Energy Accumulation Strategy

Although the PZEM module provides accumulated energy internally, I implemented additional logic on the ESP32 for:

  • Energy reset functionality
  • Session-based energy tracking
  • Cost calculation (based on Rp/kWh tariff)

Energy cost is calculated using:

Cost = Energy (kWh) × Tariff (Rp/kWh)

image.png

The tariff value can be configured remotely depending on the electricity pricing scheme.

WiFi Connectivity Handling

Because the device operates in real environments, WiFi stability cannot be assumed.

The firmware includes:

  • Auto-reconnect routine
  • Offline detection (fallback to local LCD monitoring)
  • Timeout-based retry logic

If WiFi is unavailable for a defined period, the system continues measuring locally and resumes cloud synchronization once the connection is restored.

Data Logging Architecture

image.png

All measurement data is transmitted to Firebase Realtime Database using HTTPS-based secure communication.

The structured data tree includes:

  • voltage
  • current
  • power
  • energy
  • cost
  • alert
  • timestamp

Each measurement cycle updates the corresponding fields in the database. Separating measurement logic from communication logic ensures modular firmware design.

This architecture allows:

  • Real-time remote monitoring
  • Historical data visualization
  • Cloud-based alert evaluation
  • Scalability for multiple devices

By isolating the Firebase client functions from core measurement routines, the firmware remains adaptable for future platform expansion without modifying the energy calculation engine.

Relay Control Logic (Threshold-Based Warning System)

Instead, a threshold-based warning mechanism is implemented.

When:

Energy ≥ Configured Limit

image.png

The system will:

· Set an alert flag in Firebase

· Display warning information on the LCD

· Trigger remote notification via the cloud layer

The load remains active unless manually switched OFF.

This design choice improves safety and avoids unintended service interruption while still providing preventive energy monitoring.

Design Lessons

Accurate kWh monitoring is not only about measuring voltage and current. It requires:

  • Stable communication
  • Robust error handling
  • Persistent data logic
  • Proper integration between measurement and cloud layer

This firmware architecture became the backbone for the multi-socket and advanced IoT versions developed afterward.

#Embedded# #ESP32# #iot# #internet of things# #firebase# #kwh meter#

IoT Project
Hardware Architecture of My IoT-Based Single-Socket kWh Energy Monitoring System

Monitoring electrical energy consumption at the socket level provides valuable insight into real-time power usage, cost estimation, and load behavior. In this project, I designed a single-socket IoT-based kWh monitoring system capable of measuring voltage, current, power, and accumulated energy, while transmitting data over WiFi for remote monitoring.

This first version focuses on a compact single-output architecture using ESP32 and a PZEM-based energy measurement module.

image.png

System Overview

The hardware consists of the following main blocks:

  • ESP32 microcontroller (main controller with WiFi)
  • PZEM-004T energy measurement module
  • AC-DC power supply (220VAC to 5VDC)
  • High-power relay for load control
  • LCD 16x2 display for local monitoring
  • Terminal block for AC input/output

The internal board layout and power separation can be seen in the device assembly documentation:

image.png

Energy Measurement Module

For accurate measurement of voltage, current, power, and accumulated energy (kWh), I used the PZEM-004T module. This module simplifies high-voltage measurement because it provides built-in isolation between the AC line and the low-voltage microcontroller side.

Key specifications include:

  • Voltage measurement up to 260VAC
  • Current measurement up to 100A (using CT)
  • Frequency range 45–65Hz

Using a dedicated metering module reduces ADC complexity and improves reliability compared to raw analog sensing.

Power Supply and Isolation

The system operates from a 220VAC input. A compact AC-DC converter module steps down the voltage to 5VDC, which powers the ESP32, relay driver, and LCD.

Important hardware considerations:

  • Clear separation between high-voltage AC section and low-voltage logic section
  • Proper terminal block insulation
  • Short wiring between PSU and ESP32
  • Adequate spacing to reduce electrical noise

Even in prototype form (matrix board), I ensured physical separation between AC terminals and control circuitry to minimize risk and interference.

Load Control Section

A high-power relay is used to control the socket output. The relay allows:

  • Remote ON/OFF switching
  • Automatic cut-off based on energy limit
  • Integration with IoT platforms for smart control

The relay driver circuit includes proper transistor switching and flyback protection to ensure ESP32 safety.

Local Monitoring Interface

A 16x2 LCD is used to display:

  • Voltage (V)
  • Current (A)
  • Power (W)
  • Energy (kWh)

image.png

This ensures the device remains functional even without internet connectivity.

Design Lessons

Designing an AC-powered IoT device requires careful attention to isolation, grounding, and layout discipline. Even small wiring mistakes can introduce noise into measurement readings.

Although this version was built as a prototype, migrating to a properly manufactured PCB would significantly improve safety, signal integrity, and long-term reliability.

This single-socket design became the foundation for more advanced multi-socket and cloud-integrated versions developed later.

#Embedded# #ESP32# #PZEM# #Energy Monitor#

IoT Project
Designing an IoT-Based RFID Inventory Management System Using ESP Module and RC522

image.png

This project presents the development of an IoT-based RFID Inventory Management System designed for real-time inbound, outbound, and stock checking processes. The system integrates an ESP32 microcontroller with an MFRC522 RFID reader module and communicates directly with a web-based inventory platform via WiFi.

System Architecture

The core controller is the ESP32, selected for its built-in WiFi capability, dual-core processing, and stable SPI communication. The MFRC522 RFID module operates at 13.56 MHz and communicates with the ESP8266/ESP32 through SPI (SDA, SCK, MOSI, MISO, RST).

Additional peripherals include:

  • 16x2 LCD with I2C interface
  • Push button for mode selection
  • Buzzer for audio feedback
  • 5V regulated power supply

image.png

The wiring configuration where RFID, LCD, Button, and Buzzer are clearly mapped to the ESP board pins.

Operating Modes

The device supports three main modes selectable via a single push button:

  1. Inbound Mode – Register new tagged items into the system
  2. Outbound Mode – Record item removal from inventory
  3. Check Item Mode – Display item details without modifying stock

The LCD interface provides clear status feedback such as INBOUND, OUTBOUND, and CHECK ITEM, while the buzzer confirms successful tag detection.

Web Integration & Database

Home_web_Screenshot 2023-07-29 171357.png

The system connects to a local or cloud-based web server. The backend can be deployed using XAMPP with Apache and MySQL.

Data flow sequence:

  1. RFID tag scanned
  2. UID captured by ESP
  3. HTTP request sent to server (with device ID & token)
  4. Database updated in real-time
  5. Web dashboard displays transaction log

The web interface allows:

  • Device configuration
  • Item group management
  • Real-time inbound/outbound logs
  • Report export to Excel

Hardware Implementation

After successful breadboard prototyping, the circuit was assembled onto a perforated PCB and enclosed in a custom black panel box. The enclosure integrates:

  • Front LCD window
  • RFID scan area
  • Rear 5V adapter input
  • Power switch

The final device is compact, stable, and ready for industrial or laboratory environments.

#ESP32# #Embedded# #RFID# #inventory# #warehouse#

IoT Project
From Prototype to Production: PWM Generator & Servo Driver for Non-PWM PLC

image.png

In many industrial systems, not all PLC models provide native PWM output. When PWM expansion modules are available, they are often expensive and unnecessary for simple positioning tasks.

I needed to control a low-voltage servo (MG996R, 5–6V) using a standard 24V PLC digital output. Since the PLC did not support PWM, I decided to design a dedicated PWM Generator & Servo Driver board as a cost-effective solution.

Prototype Phase

image.png

The first version was built using a perforated prototype PCB.

The goal was to validate:

  • 12V/24V PLC signal compatibility
  • Servo movement stability

After several adjustments, the prototype worked reliably. The servo response was smooth and consistent under normal load conditions. Once the concept was proven, I decided to redesign the circuit into a proper PCB.

PCB Design & Fabrication

image.png

The circuit was redesigned into a 2-layer PCB for:

  • Cleaner routing
  • Better power distribution
  • Reduced noise
  • More professional mechanical structure

The PCB was fabricated using JLCPCB. The board quality was excellent, with accurate drilling, clean copper traces, and clear silkscreen. The compact layout also improved reliability compared to the prototype version.

Small Batch Production

image.png

After testing the first PCB batch, I proceeded with small-scale production of 30 units. These boards were used for real application testing and market validation.

image.png

The system successfully enables standard PLC digital outputs (12V/24V) to control low-voltage servo motors without needing an expensive PLC PWM module.

Technical Overview

System flow:

PLC 12V/24V Digital Output

→ Signal Conditioning

→ PWM Generator

→ 5–6V Servo Driver

→ MG996R Servo

image.png

Main features:

  • 12V/24V PLC compatible input
  • Stable 50Hz servo PWM
  • 1–2ms adjustable pulse width
  • Compact 2-layer PCB

This project started from a simple prototype on a perforated board and evolved into a small production run using JLCPCB.

It demonstrates how custom PCB design can provide a practical and economical solution for PLC systems without built-in PWM functionality.

#PCB# #Module# #PWM# #PCBDesign# #SERVO# #PLC#

Build with JLCPCB
Comparing PCB Etching Techniques

【What is PCB Etching?】

In short, etching is the chemical or physical process of removing unwanted copper from a substrate to reveal your designed circuit pattern. It’s the "make or break" step in PCB manufacturing.

【Top 3 Etching Techniques Compared】

  1. Wet Etching (The Industry Standard) 🧪
    • How it works: Uses chemical solutions (Acidic or Alkaline) to dissolve excess copper.
    • Pros: Cost-effective, high speed, perfect for mass production.
    • Cons: Risks "undercutting" (sideways etching), which can limit fine-line precision.
    • Best for: Standard boards and inner layer circuits.
  2. Dry / Plasma Etching (The Precision Play)
    • How it works: Uses plasma gases in a vacuum to bombard the surface.
    • Pros: Exceptional precision with zero liquid waste; no "undercutting" issues.
    • Cons: Expensive equipment and slower throughput.
    • Best for: High-density interconnect (HDI) boards and ultra-fine designs.
  3. Laser Etching (The Clean Alternative) 🎯
    • How it works: A high-energy laser beam "evaporates" copper directly.
    • Pros: No chemicals needed; highly flexible for rapid prototyping.
    • Cons: Not suitable for large-scale production due to cost and time.

【3 Tips for Engineers to Avoid Failure】

  • Mind the Undercut: Account for "Etch Factor" in your design to ensure your trace width remains accurate after chemical processing.
  • Surface Preparation: Even a fingerprint can cause etching defects—cleanliness is key!
  • Post-Etch Care: Ensure thorough rinsing and immediate surface finishing (like HASL or ENIG) to prevent copper oxidation.

Join the Conversation:

When designing high-speed circuits, which factor do you prioritize more: production cost or trace edge precision? Let’s discuss in the comments!

#PCBDesign #ElectronicsEngineering #HardwareDesign #JLCPCB #Manufacturing #TechTips

#PCB##JLCPCB#

PCB