Energy monitor¶
A PZEM-004T v3 meter measures voltage, current, power and energy; the board stores a reading every 10 seconds in SQL Server. SQL queries turn them into daily and monthly consumption, the cost, the power use by hour of the day, and the standby load at night.
Mains voltage
The PZEM-004T's measuring side connects to mains voltage. Wire it only if you're qualified to, with the power off, in a closed enclosure, and as your local rules require. The current is measured with a clamp (current transformer) around one wire; nothing has to be cut.
Parts and wiring¶
- ESP32 or ESP8266 board
- PZEM-004T v3 with its current transformer. The v3 uses Modbus; older versions need another library.
The TTL side, at 5 V:
| PZEM-004T | ESP32 | ESP8266 |
|---|---|---|
| 5V | 5V (VIN) | 5V (VIN) |
| GND | GND | GND |
| TX | GPIO16 (Serial2 RX) | D5 (SoftwareSerial RX) |
| RX | GPIO17 (Serial2 TX) | D6 (SoftwareSerial TX) |
Set up the database¶
Run setup.sql in your database:
CREATE TABLE dbo.energy (
id BIGINT IDENTITY PRIMARY KEY,
meter VARCHAR(32) NOT NULL,
voltage REAL NOT NULL,
current_a REAL NOT NULL,
power_w REAL NOT NULL,
energy_wh INT NOT NULL, -- the meter's counter, in Wh
frequency REAL NOT NULL,
power_factor REAL NOT NULL,
recorded_at DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME()
);
CREATE INDEX ix_energy_meter ON dbo.energy (meter, recorded_at);
GO
CREATE PROCEDURE dbo.add_energy
@meter VARCHAR(32),
@voltage REAL,
@current_a REAL,
@power_w REAL,
@energy_wh INT,
@frequency REAL,
@power_factor REAL
AS
INSERT INTO dbo.energy (meter, voltage, current_a, power_w, energy_wh, frequency, power_factor)
VALUES (@meter, @voltage, @current_a, @power_w, @energy_wh, @frequency, @power_factor);
GO
-- The monitor may only add readings. Run CREATE LOGIN in master.
CREATE LOGIN energy WITH PASSWORD = '<a long random password>';
CREATE USER energy FOR LOGIN energy;
GRANT EXECUTE ON dbo.add_energy TO energy;
GO
Configure the sketch¶
Install the PZEM-004T-v30 library (by Jakub Mandula), open energy_monitor.ino, and fill in the settings at the top. With PlatformIO:
How it works¶
The meter is on a serial port: a hardware one on the ESP32, a software one on the ESP8266:
#if defined(ESP32)
static PZEM004Tv30 meter{Serial2, 16, 17};
#else
static SoftwareSerial meter_serial{D5, D6}; // RX, TX
static PZEM004Tv30 meter{meter_serial};
#endif
The parameters are bound once; each reading sets their values and calls the
procedure. The energy counter goes into an int, in Wh: tdslite has no
8-byte float parameter, and a 4-byte float loses precision on a large
kWh counter.
// Bound once; set the values before each call
static tdsl::sql_parameter_varchar p_meter{meter_name};
static tdsl::sql_parameter_float4 p_voltage{}, p_current{}, p_power{}, p_frequency{}, p_pf{};
static tdsl::sql_parameter_int p_energy_wh{};
static tdsl::sql_parameter_binding params []{p_meter, p_voltage, p_current, p_power,
p_energy_wh, p_frequency, p_pf};
static bool store_reading() {
for (int attempt = 0; attempt < 2; attempt++) {
const auto result = driver.execute_rpc(
tdsl::string_view{"EXEC dbo.add_energy @meter = @p0, @voltage = @p1, "
"@current_a = @p2, @power_w = @p3, @energy_wh = @p4, "
"@frequency = @p5, @power_factor = @p6"},
params);
if (result) {
return true;
}
if (not(result.error() == tdsl::detail::e_rpc_error_code::network_error) ||
not connect_to_db()) {
return false;
}
}
return false;
}
The meter answers with NaN when it can't measure, e.g. without mains power. Those readings are skipped:
void loop() {
static unsigned long last = 0;
if (last != 0 && millis() - last < interval_ms) {
return;
}
last = millis();
const float voltage = meter.voltage();
const float energy = meter.energy(); // kWh since the meter's last reset
if (isnan(voltage) || isnan(energy)) {
// No answer: wiring, or the meter has no mains power
Serial.println("No reading from the PZEM-004T");
return;
}
p_voltage = voltage;
p_current = meter.current();
p_power = meter.power();
p_energy_wh = static_cast<tdsl::int32_t>(energy * 1000.0f + 0.5f);
p_frequency = meter.frequency();
p_pf = meter.pf();
Serial.printf("%.1f V, %.0f W, %.3f kWh -> %s\n", voltage, static_cast<float>(p_power),
energy, store_reading() ? "stored" : "not stored");
}
At one reading every 10 seconds, the table grows by about 8,600 rows a day,
which SQL Server handles easily. Raise interval_ms if you don't need that
detail.
Reports¶
From queries.sql. The meter's counter only goes up, unless it's reset; the reports add up the increases between readings, so a reset doesn't count as negative use.
Daily consumption:
-- Daily consumption in kWh, over the last 30 days
WITH steps AS (
SELECT meter, recorded_at,
energy_wh - LAG(energy_wh) OVER (PARTITION BY meter ORDER BY recorded_at, id) AS step_wh
FROM dbo.energy
WHERE recorded_at > DATEADD(DAY, -31, SYSUTCDATETIME())
)
SELECT meter,
CAST(recorded_at AS DATE) AS day,
SUM(CASE WHEN step_wh > 0 THEN step_wh ELSE 0 END) / 1000.0 AS kwh
FROM steps
WHERE recorded_at > DATEADD(DAY, -30, SYSUTCDATETIME())
GROUP BY meter, CAST(recorded_at AS DATE)
ORDER BY meter, day;
Monthly consumption and cost:
-- Monthly consumption and cost; set your price per kWh
DECLARE @price_per_kwh DECIMAL(6, 4) = 0.30;
WITH steps AS (
SELECT meter, recorded_at,
energy_wh - LAG(energy_wh) OVER (PARTITION BY meter ORDER BY recorded_at, id) AS step_wh
FROM dbo.energy
)
SELECT meter,
DATEFROMPARTS(YEAR(recorded_at), MONTH(recorded_at), 1) AS month,
SUM(CASE WHEN step_wh > 0 THEN step_wh ELSE 0 END) / 1000.0 AS kwh,
SUM(CASE WHEN step_wh > 0 THEN step_wh ELSE 0 END) / 1000.0 * @price_per_kwh AS cost
FROM steps
GROUP BY meter, DATEFROMPARTS(YEAR(recorded_at), MONTH(recorded_at), 1)
ORDER BY meter, month;
Power use by hour of the day (UTC):
-- Average power by hour of the day, over the last 7 days: when
-- the house uses the most
SELECT meter,
DATEPART(HOUR, recorded_at) AS hour_utc,
AVG(power_w) AS avg_power_w,
MAX(power_w) AS peak_power_w
FROM dbo.energy
WHERE recorded_at > DATEADD(DAY, -7, SYSUTCDATETIME())
GROUP BY meter, DATEPART(HOUR, recorded_at)
ORDER BY meter, hour_utc;
The standby load: what the house draws when everything should be off:
-- Standby load: the lowest 5-minute average power of each night
-- (00:00 - 05:00 UTC), over the last 7 nights
SELECT meter, CAST(slot AS DATE) AS night, MIN(avg_w) AS standby_w
FROM (
SELECT meter,
DATEADD(MINUTE, DATEDIFF(MINUTE, 0, recorded_at) / 5 * 5, 0) AS slot,
AVG(power_w) AS avg_w
FROM dbo.energy
WHERE recorded_at > DATEADD(DAY, -7, SYSUTCDATETIME())
AND DATEPART(HOUR, recorded_at) < 5
GROUP BY meter, DATEADD(MINUTE, DATEDIFF(MINUTE, 0, recorded_at) / 5 * 5, 0)
) AS s
GROUP BY meter, CAST(slot AS DATE)
ORDER BY meter, night;
The complete sketch¶
energy_monitor.ino
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#else
#error "This sketch is for the ESP32 and the ESP8266"
#endif
#if defined(ESP8266)
#include <SoftwareSerial.h>
#endif
#include <PZEM004Tv30.h>
#include <tdslite.h>
static const char * wifi_ssid = "<your Wi-Fi name>";
static const char * wifi_password = "<your Wi-Fi password>";
static const char db_server [] = "192.168.1.10";
static const char db_name [] = "home";
static const char db_user [] = "energy";
static const char db_password [] = "<password>";
static const char meter_name [] = "main";
static constexpr unsigned long interval_ms = 10000;
static tdsl::uint8_t net_buf [2048] = {};
static tdsl::arduino_driver<WiFiClient> driver{net_buf};
#if defined(ESP32)
static PZEM004Tv30 meter{Serial2, 16, 17};
#else
static SoftwareSerial meter_serial{D5, D6}; // RX, TX
static PZEM004Tv30 meter{meter_serial};
#endif
static void print_message(void *, const tdsl::tds_info_token & token) noexcept {
if (not token.is_error()) {
return;
}
Serial.print("SQL Server error: ");
for (const char16_t c : token.msgtext) {
Serial.print(static_cast<char>(c));
}
Serial.println();
}
static bool connect_to_db() {
decltype(driver)::connection_parameters params;
params.server_name = db_server;
params.db_name = db_name;
params.user_name = db_user;
params.password = db_password;
params.app_name = meter_name;
params.packet_size = 1024;
return driver.connect(params) == decltype(driver)::e_driver_error_code::success;
}
// Bound once; set the values before each call
static tdsl::sql_parameter_varchar p_meter{meter_name};
static tdsl::sql_parameter_float4 p_voltage{}, p_current{}, p_power{}, p_frequency{}, p_pf{};
static tdsl::sql_parameter_int p_energy_wh{};
static tdsl::sql_parameter_binding params []{p_meter, p_voltage, p_current, p_power,
p_energy_wh, p_frequency, p_pf};
static bool store_reading() {
for (int attempt = 0; attempt < 2; attempt++) {
const auto result = driver.execute_rpc(
tdsl::string_view{"EXEC dbo.add_energy @meter = @p0, @voltage = @p1, "
"@current_a = @p2, @power_w = @p3, @energy_wh = @p4, "
"@frequency = @p5, @power_factor = @p6"},
params);
if (result) {
return true;
}
if (not(result.error() == tdsl::detail::e_rpc_error_code::network_error) ||
not connect_to_db()) {
return false;
}
}
return false;
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
driver.set_info_callback(print_message);
while (not connect_to_db()) {
Serial.println("SQL Server: connect failed, retrying");
delay(5000);
}
}
void loop() {
static unsigned long last = 0;
if (last != 0 && millis() - last < interval_ms) {
return;
}
last = millis();
const float voltage = meter.voltage();
const float energy = meter.energy(); // kWh since the meter's last reset
if (isnan(voltage) || isnan(energy)) {
// No answer: wiring, or the meter has no mains power
Serial.println("No reading from the PZEM-004T");
return;
}
p_voltage = voltage;
p_current = meter.current();
p_power = meter.power();
p_energy_wh = static_cast<tdsl::int32_t>(energy * 1000.0f + 0.5f);
p_frequency = meter.frequency();
p_pf = meter.pf();
Serial.printf("%.1f V, %.0f W, %.3f kWh -> %s\n", voltage, static_cast<float>(p_power),
energy, store_reading() ? "stored" : "not stored");
}
Going further¶
- Several circuits: several PZEM-004T meters can share one serial port
with different Modbus addresses; give each its own
metername. - Local time: the reports group by UTC. On SQL Server 2016 and later,
recorded_at AT TIME ZONE 'UTC' AT TIME ZONE 'W. Europe Standard Time'converts to a local time zone.
Related¶
- Log sensor readings
- Run parameterized queries: the parameter types