Professional-grade AC power monitoring system for home and industrial applications. Monitor voltage, current, power consumption, and energy usage with real-time web interface and historical analytics.
π Real-time Power Monitoring
- Live voltage, current, power, energy, frequency, and power factor readings
- Interactive charts showing consumption trends over time
- Day/night energy consumption tracking with separate statistics
π Smart Web Interface
- Fully responsive design - works on mobile, tablet, and desktop
- WebSocket-based real-time updates (no page refreshing needed)
- WiFi setup portal with automatic fallback to Access Point mode
- Real-time system logs
πΎ Intelligent Data Management
- Automatic CSV data logging with configurable intervals
- Configurable data retention periods to manage storage
- Energy statistics export for day/night consumption analysis
- FTP server for bulk file operations and remote access
π§ Advanced System Features
- Over-the-air (OTA) firmware updates without USB cable
- Automatic NTP time synchronization with timezone support
- Dual WiFi mode operation (Access Point + Station)
- System reliability with watchdog protection and auto-restart
β
Industrial Accuracy - 0.5% measurement precision with PZEM sensors
β
Real-time Monitoring - Live data streaming with interactive charts
β
Smart Data Management - Automatic CSV logging with configurable retention
β
Mobile-First Design - Responsive web interface works on any device
β
Professional Features - OTA updates, FTP access, advanced analytics
β
Easy Setup - WiFi portal setup, automatic network recovery
β
Reliable Operation - 24-hour auto-restart, memory monitoring, error recovery
β
Developer Friendly - Full API, WebSocket support, modular architecture
β οΈ Safety & Prerequisites- π οΈ Hardware Requirements
- π Quick Start
- π± Detailed Setup
- π Web Interface Guide
- π API Reference
- π Project Structure
- π§ Troubleshooting
Working with AC Power
This project measures AC mains voltage. While the PZEM sensors provide isolation, basic electrical safety is important. Turn off power when making connections and double-check your wiring.
Basic Safety Steps:
- β‘ Turn off circuit breaker when connecting wires
- π Use proper wire connections (no loose wires)
- π¦ Keep electronics in a suitable enclosure
- π Double-check connections before powering on
Coding Experience:
- None required! Just follow the setup instructions
- Copy and paste - the code is ready to use
- Basic computer skills (downloading, uploading files)
Basic Electronics:
- Connecting wires (positive, negative, data lines)
- Using a USB cable to program the ESP8266
- Basic understanding that electricity can be dangerous
- Hardware assembly: 1-2 hours (simple wire connections)
- Software setup: 15-30 minutes (mostly downloading and uploading)
- Getting it working: Usually works right away if wired correctly
- I'll turn off power when connecting wires
- I'll double-check connections before turning power back on
- I understand this involves electrical work (but it's manageable)
- I'll ask for help if I'm unsure about anything
ESP8266 Development Board
- Any ESP8266 board with accessible GPIO pins
- Examples: NodeMCU, Wemos D1 Mini, ESP-01 (with adapter), etc.
- Must have 3.3V and 5V power available
- USB programming interface recommended for easy setup
Power Monitoring Sensor:
Model | Max Current | Best For |
---|---|---|
PZEM-014 | 10A | Household circuits, small appliances |
PZEM-016 | 100A | Main panels, large loads (needs external CT) |
π Detailed specifications: See PZEM-014/016 Technical Manual for complete electrical specifications and communication protocol details.
Note: This project is specifically designed for PZEM-014/016 sensors due to their Modbus RTU communication protocol. Other power sensors would require code modifications.
- Jumper wires (male-to-female, 4 pieces minimum)
- 5V Power supply (USB phone charger works fine)
- Project enclosure (optional but recommended for permanent installation)
Choose PZEM-014 if:
- β Monitoring individual appliances or circuits under 10A
- β Want simpler installation (built-in current measurement)
- β Most household applications (lights, outlets, small appliances)
Choose PZEM-016 if:
- β Monitoring main electrical panel or large loads
- β Need to measure over 10A (up to 100A)
- β Already have or can install current transformer (CT)
ESP8266 PZEM-014/016
================== ============
5V or VIN --> VCC (+5V)
GND --> GND
GPIO13 (D7)* --> TX (Data out from PZEM)
GPIO15 (D8)* --> RX (Data in to PZEM)
*Pin numbers may vary by board - check your specific ESP8266 board pinout
β‘ IMPORTANT: Turn off circuit breaker before making these connections!
For PZEM-014:
- Connect L (Live/Hot) wire through the device
- Connect N (Neutral) wire through the device
- Built-in current sensing - no external wires needed
For PZEM-016:
- Connect L and N for voltage sensing
- Install current transformer (CT) around the main wire
- CT connects to designated terminals on PZEM-016
π Detailed wiring diagrams: See figures 4.1 and 4.2 in the PZEM Technical Manual for complete wiring instructions and safety guidelines.
- Project enclosure: Protect electronics (DIN rail mount available)
- Heat shrink tubing: Professional wire connections
- Terminal blocks: Easier wire connections
- Current transformer: Required for PZEM-016 (usually included)
For experienced users - Get running in 30 minutes. Need more detail? Jump to Detailed Setup.
Prerequisites: PlatformIO installed (VS Code extension or CLI)
ESP8266 β PZEM-014/016
5V/VIN β VCC
GND β GND
GPIO13 β TX
GPIO15 β RX
Connect PZEM to your AC circuit (β‘ power off first). See PZEM Technical Manual for detailed wiring instructions.
git clone https://github.com/tsaplia/energy-controller-refactored.git
cd energy-controller-refactored
platformio run --target upload # Upload firmware via USB
platformio run --target uploadfs # Upload web interface files
Or use VS Code PlatformIO extension buttons
- ESP creates AP
ESP8266-Sensor
(password:password
) - Connect and enter your WiFi credentials
- Device connects to your network and shows IP address
- AP automatically disconnects - reconnect to your home WiFi network
- Access web interface using the displayed IP address
- Find ESP IP address (router admin or serial monitor)
- Open
http://ESP_IP_ADDRESS
in browser - Start monitoring power consumption!
- No sensor data? β Check wiring, verify PZEM power
- Can't connect to WiFi? β Reset and try AP mode again
- Upload failed? β Check USB cable, try different port
- Web interface not loading (Error 404)? β Verify filesystem upload completed
π Need help? See Detailed Setup or Troubleshooting sections.
Step-by-step guide for beginners - No prior experience needed!
- Download VS Code: Go to code.visualstudio.com and install
- Install PlatformIO extension:
- Open VS Code
- Click Extensions icon (left sidebar)
- Search "PlatformIO IDE"
- Click Install on the official extension
- Wait for PlatformIO Core to download and install (this may take several minutes)
- Restart VS Code when prompted
β οΈ Important: Wait for PlatformIO to fully initialize before opening projects. If you encounter project configuration issues, try: View β Command Palette β "PlatformIO: Rebuild IntelliSense Index"
- Install Python (if not already installed)
- Install PlatformIO Core:
pip install platformio
git clone https://github.com/tsaplia/energy-controller-refactored.git
cd energy-controller-refactored
- Go to the project's GitHub page
- Click green "Code" button β "Download ZIP"
- Extract ZIP file to a folder
- Remember the folder location
- ESP8266 board (any model with GPIO pins)
- PZEM-014 or PZEM-016 sensor
- 4 jumper wires (male-to-female)
- USB cable for ESP8266
β‘ IMPORTANT: Do this with power OFF!
-
Connect ESP8266 to PZEM:
ESP8266 Pin β PZEM Pin ============ ========= 5V or VIN β VCC GND β GND GPIO13 (D7)* β TX GPIO15 (D8)* β RX
*Pin labels may vary - check your board's pinout
-
Connect PZEM to AC Power (β‘ Turn off circuit breaker first!):
- PZEM-014: Connect Live and Neutral wires through the device
- PZEM-016: Connect L/N for voltage, install CT for current
- See PZEM Technical Manual for detailed wiring diagrams
-
Double-check all connections before powering on
- VS Code: File β Open Folder β Select your project folder
- CLI: Navigate to project folder in terminal
Using VS Code:
- Click PlatformIO icon in left sidebar
- Under "PROJECT TASKS" β "nodemcuv3" β "General"
- Click "Upload" (this compiles and uploads firmware)
- Wait for "SUCCESS" message
Using CLI:
platformio run --target upload
Using VS Code:
- Same location as above
- Click "Upload Filesystem Image"
- Wait for completion
Using CLI:
platformio run --target uploadfs
- ESP8266 starts and creates its own WiFi network
- Network name:
ESP8266-Sensor
(password:password
) - Connection process:
- Connect your phone/computer to ESP8266's WiFi
- Open any webpage - it will redirect to setup page
- Enter your home WiFi name and password
- Device connects to your network and displays IP address on the page
- AP automatically disconnects - you must reconnect to your home WiFi network to access the web interface
Method 1 - Router Admin:
- Log into your router (usually 192.168.1.1 or 192.168.0.1)
- Look for new device in connected devices list
Method 2 - Serial Monitor:
- Keep USB cable connected
- Open serial monitor in PlatformIO (9600 baud)
- Device will print its IP address
- Open browser and go to:
http://YOUR_ESP_IP_ADDRESS
- You should see the energy monitoring dashboard
- If sensor is connected properly, you'll see live voltage/current/power readings
- Dashboard: View real-time power consumption
- Settings: Configure data intervals, timezones, export your energy data, etc.
- Logs: Monitor system operation
No sensor data showing?
- Check wiring connections
- Verify PZEM has power (AC connected)
- Try different GPIO pins if needed
Can't connect to WiFi?
- Reset ESP8266 (power cycle)
- Try connecting to AP again
- Check WiFi password
Upload failed?
- Check USB cable connection
- Try different USB port
- Make sure ESP8266 drivers are installed
Still stuck? Check the Troubleshooting section below!
Once your device is connected to WiFi, open its IP address in your browser to access the monitoring interface.
The main dashboard provides real-time monitoring with:
- Real-time sensor readings updated via WebSocket connection
- Voltage, current, power, energy consumption metrics
- Frequency and power factor measurements
- Interactive charts showing voltage and power trends over time
- π± Fully responsive design β works perfectly on mobile phones, tablets, and desktop
- π Auto-updating data β no need to refresh the page
- π Visual charts β easily spot power consumption patterns
Access the settings page at /settings
to configure your controller:
- Data Save Interval: How often to record sensor data (default: 30 seconds)
- Data Retention: How long to keep historical data (default: 1 day)
- Timezone Offset: Set your local timezone for accurate timestamps
- Day Phase Start: When "day" energy tracking begins (default: 7:00 AM)
- Night Phase Start: When "night" energy tracking begins (default: 11:00 PM)
- Automatically calculates separate day and night energy consumption
- Log Level: Control detail level of system logs (DEBUG, INFO, WARNING, ERROR)
- WiFi Credentials: Update network connection settings
- Energy Reset: Reset energy counter to start fresh measurements
- Download sensor data: Export CSV with all recorded measurements
- Download energy stats: Export day/night energy consumption summaries
β οΈ WiFi Changes: After updating WiFi credentials, the device will disconnect and connect to the new network. You'll need to find the new IP address to access the interface again.
The logs page at /logs
provides:
- Live log stream via WebSocket connection
- Historical logs from device storage
- Timestamp information for troubleshooting
- DEBUG: Detailed technical information
- INFO: General operational messages
- WARNING: Important notices and state changes
- ERROR: Problems that need attention
The controller provides a comprehensive HTTP API for automation and integration with other systems.
Route | Method | Description | Response |
---|---|---|---|
/api/restart |
GET | Restart the ESP8266 controller | {"detail": "Restarting..."} |
/api/pause |
GET | Pause data collection and processing | {"detail": "Pausing..."} |
/api/resume |
GET | Resume normal operation | {"detail": "Resuming..."} |
/api/system-info |
GET | Get detailed system information | JSON with chip, memory, filesystem data |
/api/clear-old |
GET | Remove old data based on retention settings | {"detail": "Cleared old data"} |
Route | Method | Description | Body | Response |
---|---|---|---|---|
/api/settings |
GET | Get current configuration | - | JSON with all settings |
/api/settings |
POST | Update configuration | JSON with settings to change | {"detail": "OK"} |
/api/reset-energy |
PUT | Reset energy measurement baseline | - | {"detail": "OK"} |
/api/connect-wifi |
POST | Update WiFi credentials | {"ssid": "...", "password": "..."} |
{"ip": "192.168.x.x"} |
Socket Path | Purpose | Message Format |
---|---|---|
/ws/data |
Real-time sensor data | {"type": "data", "data": {...}} |
/ws/logs |
Live system logs | {"type": "log", "data": "log message"} |
Sensor Data Messages:
{
"type": "data",
"data": {
"time": 1640995200,
"voltage": 230.5,
"current": 2.150,
"power": 495.6,
"energy": "12.5",
"frequency": 50.0,
"pf": 0.95
}
}
Log Messages:
{
"type": "log",
"data": "2024-01-01 12:00:00 [INFO] WiFi connected on IP: 192.168.1.100"
}
Route | Description |
---|---|
/sensor-data.csv |
Raw sensor measurements |
/energy-stats.csv |
Day/night energy summaries |
/configs.json |
Current device configuration |
/logs.txt |
System log file |
Files can also be accessed via FTP for bulk operations:
- Host: ESP8266 IP address
- User:
esp
- Password:
password
- Port: 21 (standard FTP)
Understanding the project layout helps you navigate the codebase and customize functionality as needed.
energy-consumption-controller/
βββ π .vscode/ # VS Code configuration
βββ π data/ # Web interface files (uploaded to ESP8266)
βββ π docs/ # Documentation and images
βββ π external-data/ # Stores large external resources not kept on the ESP8266
βββ π include/ # C++ header files
βββ π lib/FTPClientServer-master/ # FTP server library
βββ π src/ # C++ source code
βββ π .gitignore # Git ignore rules
βββ π LICENSE # Project license
βββ π README.md # This file
βββ π platformio.ini # PlatformIO configuration
These files are uploaded to the ESP8266's filesystem and served by the web server:
data/
βββ π auth.html # WiFi setup page (AP mode)
βββ π data.js # WebSocket data handling
βββ π index.html # Main dashboard page
βββ π logs.html # System logs viewer
βββ π logs.js # Log WebSocket handling
βββ π settings.html # Configuration page
βββ π settings.js # Settings management
βββ π shared.js # Common JavaScript functions
βββ π style.css # All page styling
external-data/
βββ π bootstrap.min.css # Bootstrap styling, loaded via GitHub CDN instead of controller storage
Main application logic organized by functionality:
src/
βββ π main.cpp # Application entry point & setup
βββ π configs.cpp # Configuration management
βββ π globals.cpp # Global variables initialization
βββ π logger.cpp # Logging system implementation
βββ π loop-handlers.cpp # Main loop logic handlers
βββ π sensor.cpp # PZEM sensor communication
βββ π utils.cpp # Utility functions (time, files, etc.)
βββ π wifi-tools.cpp # WiFi management (AP/STA modes)
βββ π web/ # Web server components
βββ π api-handlers.cpp # HTTP API endpoint handlers
βββ π web-server.cpp # Web server setup & routing
βββ π web-utils.cpp # Web utility functions
Interface definitions and constants:
include/
βββ π configs.h # Configuration class definition
βββ π constants.h # System constants and defaults
βββ π globals.h # Global variable declarations
βββ π logger.h # Logging system interface
βββ π loop-handlers.h # Loop handler function declarations
βββ π sensor.h # Sensor data structures & functions
βββ π utils.h # Utility function declarations
βββ π wifi-tools.h # WiFi management interface
βββ π web/ # Web server headers
βββ π api-handlers.h # API handler declarations
βββ π web-server.h # Web server declarations
βββ π web-utils.h # Web utility declarations
platformio.ini
- Build configuration, board settings, librariesmain.cpp
- Add new sensors or modify startup behaviorconstants.h
- Modify default settings, intervals, passwordsstyle.css
- Customize web interface appearance
logger.cpp
- Understand logging systemwifi-tools.cpp
- WiFi connection issuessensor.cpp
- PZEM communication problems
api-handlers.cpp
- Add new API endpointsweb-server.cpp
- Modify routing or WebSocket behavior
When running, the controller creates these files in its filesystem:
ESP8266 Filesystem:
βββ π /configs.json # Saved configuration
βββ π /sensor-data.csv # Historical sensor readings
βββ π /energy-stats.csv # Daily/nightly energy summaries
βββ π /logs.txt # System log history
Pages loading slowly or not fully:
- Try reloading the page (Ctrl+F5 or Cmd+Shift+R)
- Wait a few seconds between page requests - ESP8266 has limited resources
Charts not loading properly:
- Slow internet connection may prevent all data from loading
- Reduce data retention in settings to keep less historical data
- Check your router for connection issues
- Try accessing
/api/restart
to restart the ESP8266 controller
Extension not working properly:
- Wait for PlatformIO Core to fully download and install
- Project configuration errors: Go to View β Command Palette β "PlatformIO: Rebuild IntelliSense Index"
- Build issues: Try PlatformIO: Clean then PlatformIO: Build
- Still having problems: Restart VS Code and wait for initialization
No sensor data showing:
- Check wiring connections between ESP8266 and PZEM
- Verify PZEM has AC power connected
- Try different GPIO pins if needed
- Check serial monitor for sensor communication errors
Can't connect to WiFi:
- Reset ESP8266 (power cycle)
- Try connecting to AP mode again
- Check WiFi password spelling
- Ensure WiFi network is 2.4GHz (ESP8266 doesn't support 5GHz)
Upload failed:
- Check USB cable connection
- Try different USB port
- Check platformio.ini configuration: "board = nodemcuv2" or "[env:nodemcuv3]" must match your actual board
- Ensure ESP8266 drivers are installed
- Press and hold FLASH button during upload if needed