0% found this document useful (0 votes)
72 views25 pages

Elektor ESP32 Energy Meter en

The document outlines the development of an ESP32-based energy meter, detailing the project's goals, design requirements, and progress updates. It emphasizes real-time power monitoring, safety considerations, and the integration of various technologies to create a user-friendly device. Future enhancements and community support for the ESP32 chip are also highlighted, indicating ongoing improvements and updates to the project.

Uploaded by

fagundesbr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views25 pages

Elektor ESP32 Energy Meter en

The document outlines the development of an ESP32-based energy meter, detailing the project's goals, design requirements, and progress updates. It emphasizes real-time power monitoring, safety considerations, and the integration of various technologies to create a user-friendly device. Future enhancements and community support for the ESP32 chip are also highlighted, indicating ongoing improvements and updates to the project.

Uploaded by

fagundesbr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

www.elektormagazine.

com

SPECIAL

SPECIAL
ab • Elek
or l
kt t

or
Ele
Elektor ESP32

lab
ORIGINA
L

Ele

b
or

Energy Meter

kt
or

la
la b
• Ele k t

IN THIS
EDITION
project

Prototyping an
ESP32-Based En
ergy Meter
By Saad Imtiaz (Elektor
)
This article presents
the journey of devel
an energy meter using oping
emphasizing real-t an Espressif ESP32
ime ,
monitoring and safety power consumption
. It highlights the initia
steps, requiremen l
project • Elektor ts, and
lab la
take place when emba considerations that
rking on an embedded

or

b
Elekt
IN A
L project. As the projec
t progresses, future
Figure 1: Test rendering
O R IG achievements will

b
of how our Single-Ph
be shared in upcom

r la
ase Energy Meter
ek might look.
editions of Elektor ing

to
El t or le k
la b E • Mag.
In the field of engineer

ate:
ing, combining the

Project Upd ed
to significant advance right technologies
ments. This project can lead designs provides
meter using the Espress aims to develop an flexibility during the
if ESP32 microco energy cost-effectivenes engineering phase.
ATM90E32AS energy ntroller and Microch s makes it an attractiv Second, its
metering IC. In this ip’s e choice for a prototyp

s
aims to balance perform

a
project’s journey is article, the beginnin e that

-B
g of this ance and budget.

2
briefly shared, from Third, the compati

ESP3
component selection with a wide range
ing. The goal is straightfo to prototyp- of sensors and ICs bility
rward: to create a Lastly, the extensiv offers significant
energy measurement reliable system for e community support advantages.
from your home or accurate for ESP32 chip augmen

ter
workshop’s main circuit suitability for this
This meter will enable project. Figure 2 highligh ts its

e
box.

M
users to track their ts the ESP32-D0WD-V3

y
time, offering insights power consumption ’s

e rg
that can lead to more in real

En
efficient energy use. .
r Energy Meter
Design and Requir ering of the Elekto
ements Figure 1: Rend
The project has
clear goals and
design requirem
totyping
monitor single-phase ents: real-time
power using three
in Pro current transform
Next Steps
keep it affordable,
and make it user-frie ers (CTs), ly energy
ATM90E32AS IC compon ndly. The choice of user-friend
ESP32 and a reliable, ll-
ents was guided by
proje these aims, offeringnboth devloping previous insta
cost-effectivenes
s and reliable perform ct journey of oller. In our
bega our microcontr we discussed
keep the size smaller ance. AnotherWe target was aging the ESP32 y Meter” [1], ng
thantor)
100×80×30 mm (L×W×H meter lever to sed Energ plan for starti
it can be accomm ESP32-Ba am and the
z (Elek ) to ensure otyping an . The
By Saad Imtiaodated in a circuit breaker box. To ment , “Prot that nts, block diagr it, let’s have a recap
experien enhance the luser n requireme
ce, a mobile interface
is of
ment included for remotethe initia desig an upda telaon
b • Elek in Figur e 1.
firs install
as well as an tOLED also give r t ring
monitori ct. Before we to in the orende
In thealso display with buttons this projeng, n is shown
d the for direct interacti
loresoftware eptual desig
k

design r la
we exp
Ele

allows for on. The r conc on


utilityseri
this es, future
Ele kto r , ensuringenerg
updates y mete
g, with an
emphasis
b
for the consumer. Inof the
ign Figure 1, the renderin long-ter m O r R I
moni G I N
torin A L ent preci se, we
al des ment, g of the current on real-time
powe
measurem
foundation e isIn
type enclosur
shown. tall focus was
Our proto- the energy y monitoring
IC
ins
ter. this
y. To make energ
Ele

ab

affordabilit t a polyphase o and will


rgy Me se in the safety and 90E32AS,or la the mains
rl

EneMicroc
k

ontrollernex
the Select t pha ion opted for the
Atmel ATM b • Ege
ase volta
t
l e kfrom
y. The main
ll loo
The
we’analysis k ofatthe ter pro ject, the single-ph ure the current safel

Project Update #2:


choice IC will get in Wi-Fi
energy me
ESP32 microcon [2]. This to meas built-
its d
troller has
s,
was predicated on ers ESP32 as it
ESP 32-bofase capabilit
d sch em
ies. The chip excels atic a detailed
use split coil
transform
selected was MCUs. In
Figure 2,
detaile
success of this project. in several areas contr oller other
focusing on n stra
crucial to the to
key application
micro compared
tegies, and on into varied and
First, its ease of integrati
effective when

ESP32-Based
atio very cost-
circuit
circuit isol ancements.
Figure 2: Main features
and advantages of the
ESP32.
enh

Energy Meter
96 L N
www.elek tormagaz
ine.com
ELECTRICAL
ISOLATION
BOUNDARY AC/DC
L ISOLATED
N Y
POWER SUPPL
AC/DC
ISOLATED Y
POWER SUPPL

Som e Enhancements GND VCC

VREF
GND VCC
Figure 1: New enclosure
design rendering
I1P ESP32 AY of the ESP32 Energy
I1N OLED DISPL Meter.
CS
E32AS
By Saad
ATM90 Imtiaz ADuM3151
(Elektor
CLK
CS
) SDI
WI-FI TO
In the previous instal
CLK
E
MOBILE DEVIC
SDO

lment
SDI
the size of the prototyp
series, we discussed lab • Ele of this
APPLICATION NET
SDO
PROCESSOR
AND INTER
e PCB was 100×100
components were mm. After testing,
project the TO PC

and circuit isolation to schem


removed some
r kto
atics, hence the size for
USB COMMand the layout
this version is reduced
of the PCB was optimize
d,
strategies of the
k

r la

to 79.5×79.5 mm
Ele

about 20% less from


ESP32 Energy Meter last time. In Figure — that’s
b

.ORIGI
V1P
Now let’s NAL discuss new version of PCB 1, the new enclosur
e for the
further enhanceme is shown. Along with
V1N

Energy Meter safer that, to make the


nts, a PCB design, to use, instead of ESP32
Ele

powering the PCB


la b

the mains voltage, directly with


and moreor.la b • Ele ktor now a 220 V-to-12
kt

required for voltage V Step Down Transfor


sampling and also mer is
Figure 2: a transformer does powering the circuit.

Project Update #3:


am of the have some drawbac Adding
Block Diagr but safety first! Since ks in terms of phase
y Meter. In 2023, we started we are not looking delays,
Elektor Energ with the goal of creating to measure voltage
fast sags or surges, spikes, or
energy meter using a reliable, user-frie but energy, this shouldn’
an Espressif ESP32 ndly t hurt our measure

ESP32-Based
article, “Project Update: microcontroller. In ment.
ESP32-Based Energy our last The Updated Schem
the block diagram zine.com
, the schematics, circuit
Meter” [1], we went
over atic Design
elektormaga isolation strategy, We made some upgrades
ary andwww.
2024 project strategy. Let’s start features, , and now, rather than
ry & Febru with a small recap is on board. This also the ESP32, the ESP32-S

Energy
6 Janua the next update. before we get into unlocks more potential 3
ESP32-S3 offers significa for the Energy Meter.
nt enhancements The
improved process over the ESP32, including
The main idea revolved ing power, AI and
around developing more memory, and signal processing
energy meter leveragi a precise and efficient better security features capabilities,
ng the capabilities further improves . The updated schemat
microcontroller and of the Espressif the capability of the ic
the ATM90E32AS ESP32 functionality. The design Energy Meter along
The project aimed IC for energy measure references guides with more
to enhance user experien ment. useful internet resource from Espressif [2]
meticulous schemat ce and reliability through s [3…6] were used and other
ic design and circuit into the project. In to integrate the ESP32-S
isolation using the Figure 2, the schemat

Meter
to provide safe commun ADuM3151 3
ication between ESP32 ic of the project is
by Atmel (now Microch and the ATM90E32AS shown.
ip). It emphasized The circuit board
incorporating noise safety and efficienc layout has been optimize
reduction techniqu y by usability, its OLED
with and display and live d to improve the
ments, and protectiv es, signal integrityESP32 Energy Meter efficacy of the ESP32-S3. We’ve safety,
e mechanisms such 1: The assemble d enhance- ments made
focus on future-re Figureas fuses by lowering the PCB substant ial adjust-
proje and MOVs. With a size for a more compact
ady features status indicators .
monitoring and data ct , the plan included integrating remote
to transformer-based footprint , moving
power for increase
analysis tools for improve with single and three-ph d safety, and adding
and efficiency insights. d energy manage ase compatibility. versatility
ment efficient AP63203 The utilization of
WU-7 buck converte a more
along with voltage sampling
foraddition r in place of Hi-Link
In this article, our Transformerthe modules,
main goals remain using a 230-V-to-12-V Step Downconnector improves safety of user-frie
while ndly features such Elekat
have been made to the same, and This significantlyand a Qwiic connect lab •as oUSB-C
make the project and runningplenty
ng of theofsystem.
changes or for expandability, or r

Integration and Testi


safer to use, reduce to the advance
and three-ph mentase installations. all contributed
tion cost, and reduce for both single- of the project. These
kt

its produc-
lab

its size. As mention ing flexibility improve


Ele

ESP32-S ments

Project Update #4
maintain 3’s capabilities, focusing build on the
t ed in the previous

with Home Assistan


article, a more efficient on providing a practical INAL
included
and integrat
the safer energyion ofmonitori
ng calibra-
solution. ORIG , adaptab le,
Other improvements the PCB more modular,
ab

converter, making not


Ele

ESP32-Based
WU-7 buck more. This
rl

AP63203 g circuit, and to


r la b Ele k t
o
transformer samplin
k

tion of the current functionality, but •


102 May & June performance and
tormagazine.com optimizes the energy meter’s
2024 www.elek
only
) cost and size.
By Saad Imtiaz (Elektor also reduces both

Energy Meter
meter
taken to get this energy
t update, you discuss the steps
In the previous projec In this article, we will to the
from the lab bench
the journey it took
cements to the ESP32 up and running and also discuss how
to set it up,
learned about enhan atic design and circuit breaker box.
Furthermore, we will
with Home Assistan
t with
how to integrate it
Energy Meter’s schem on the practical calibrate it, and finally, the collected data from the energy
es Ener
monitor
PCB. This article focus
Home to show and Meter project
integration of the
new ESP gy Monitoring with
a vivid snapshot of
the ESP32 Energy

implementation and step-by-step guide


meter. In Figure 1,
in action is captured
, encased in a 3D-print MQT T
ed enclosure with
rs that
an OLED
seamles sly
a indicato
version. It provides with ESPHome
display. The image
highlights live status
real-time power consump
tion.
on setting up the meter Saad Imtiaz track and display
By
(Elektor
energ y)
for effective
and Home Assistant Previo we dealusly,with the Assembly
we focus compact and straightf
orward
ermore, edThe
onnew settin designed to be more
monitoring. Furth Based
ation.Energy Meter and
g up
PCB was the ESP32 e spacing for each component
the layout had adequat-
device’s calibr Assistant. We also integr
to solder andating
it with Home
soldering process of it. To facilitate
project
discu ssed accommodated the professionals alike,
the
of leveraging theto the replicatio
which
the futuretions
n and modifica
by enthusiasts and While production
poten tial
ESP32 format, and the the AI/ML integratio
functon enhance ments -S3 chip of Materials
complete Bill for
(BOM) in Mouser
AI and MLLab GitHub reposito extensive
n is still in progress
— given the
In our previous article
[1], we focused ionali
Meter,ty to
with predic
improve -
t
ry [2]. data preparation
involved — this minor
and PCB of the ESP32 Energy energ
and identiget into the next files y usage patterns
are shared on the Elektor’s focuses on a crucial interim update
schematic design features. Before we fy devices. In this updat real-tim terminal development: enabling
screw type
e energy
ments in modular
ity and safety
forwa e, we take a stepconnecti ons, monitoring using
have a brief overview rd by introducing firmw
. current sampling blocks MQTT. MQTT is
For the voltage and lightwei
these terminal
ght messag a
project update, let’s are that used, the quality of commun ing protocol designe
time energy moni by CUI Devices enables real-
were seen
blocks Refer
terminal ication.
d for efficient
the ESP32 Energy toring blocks
Meter project, using MQTT
better ,than the cheap blue coloredfor moreVoltages and to the textbox “What Is MQTT?”
for
of
advan much pavin
es. on most sensor modules. Asgwe
AC informat
In the most recent
advance ments
ced featur
introduc ing enhance d were theareway
dealing with ion.
ESP32-S 3 microcontroller, and reliable connections.
we upgraded to the lity. The new design
slimmed it is vital to have secure Custom Firmware
and broader functiona energy metering, and MQTT
processing power er-based power system, In this article, we will
incorporated a transform discuss the next phase
down the PCB and — leveraging MQTT of the project
We previously discusse and the Arduino
d the entire journey real-time energy IDE to enable
Energy meter from of the ESP32 monitoring. This
firmware developm update will cover
the lab bench to ent that allows the the
box, which started the circuit breaker ESP32 to commu-
by assembling compon nicate with an MQTT
up the energy meter ents, setting broker, sending energy data
tormagazine.com with ESPHome and Home Assistant to a
2024 www.elek server or any other
12 July & August tant, calibration and Home Assis- MQTT-c
testing, and finally platform. ompatible
the circuit breaker installing it into
box. In the last update
foundation by integratin [1], we laid the
g the meter with Home The advantage of
with the ambitiou Assistant, using MQTT with
s goal of adding AI over ESPHome is an individual firmware
to predict energy and ML capabilities that the individual
usage patterns and greater flexibility firmware offers much
based on their energy identify devices in terms of integrati
tion. With a custom on and customiza-
signatures. firmware, you have
how the data is collected full control over
, processed, and
transmitted,
What Is MQTT ?
MQTT is a lightweig
ht messaging protocol
IoT environments. designed for efficient
Central to this system communication between
The broker receives is the MQTT broker, devices, especially
messages from devices, a server that acts in
known as subscrib known as publishe as a hub for message
ers, based on a system rs, and routes them exchange.
of topics. to the appropriate
recipients,
A topic in MQTT is
a string that categori
a subscriber is a device zes messages, acting
or application that as a channel where
smart home setup, listens to specific information is publishe
a topic like home/en topics to receive those d, while
ing to this topic would ergy/voltage messages. For example
receive and display might carry voltage , in a
those readings in readings, and a dashboa
real-time. rd subscrib-
The broker ensures
that messages are
applications, the MQTT delivered efficientl
broker is crucial for y and securely, even
(which are the MQTT managing data exchang over unreliable network
clients), enabling e between sensors, s. In IoT
real-time monitori devices, and systems
ng, control, and automat
ion.
62 November &
Decembe r 2024 www.elek
tormagaz ine.com
project

Prototyping an
ESP32-Based Energy Meter
By Saad Imtiaz (Elektor)

This article presents the journey of developing


an energy meter using an Espressif ESP32,
emphasizing real-time power consumption
monitoring and safety. It highlights the initial
steps, requirements, and considerations that
take place when embarking on an embedded
project. As the project progresses, future
achievements will be shared in upcoming
Figure 1: Test rendering of how our Single-Phase Energy Meter might look. editions of Elektor Mag.

In the field of engineering, combining the right technologies can lead designs provides flexibility during the engineering phase. Second, its
to significant advancements. This project aims to develop an energy cost-effectiveness makes it an attractive choice for a prototype that
meter using the Espressif ESP32 microcontroller and Microchip’s aims to balance performance and budget. Third, the compatibility
ATM90E32AS energy metering IC. In this article, the beginning of this with a wide range of sensors and ICs offers significant advantages.
project’s journey is briefly shared, from component selection to prototyp- Lastly, the extensive community support for ESP32 chip augments its
ing. The goal is straightforward: to create a reliable system for accurate suitability for this project. Figure 2 highlights the ESP32-D0WD-V3’s
energy measurement from your home or workshop’s main circuit box.
This meter will enable users to track their power consumption in real
time, offering insights that can lead to more efficient energy use.

Design and Requirements


The project has clear goals and design requirements: real-time
monitor single-phase power using three current transformers (CTs),
keep it affordable, and make it user-friendly. The choice of ESP32 and
ATM90E32AS IC components was guided by these aims, offering both
cost-effectiveness and reliable performance. Another target was to
keep the size smaller than 100×80×30 mm (L×W×H) to ensure that
it can be accommodated in a circuit breaker box. To enhance the user
experience, a mobile interface is also included for remote monitoring,
as well as an OLED display with buttons for direct interaction. The
design also allows for future software updates, ensuring long-term
utility for the consumer. In Figure 1, the rendering of the current proto-
type enclosure is shown.

Microcontroller Selection
The choice of the ESP32 microcontroller was predicated on a detailed
analysis of its capabilities. The chip excels in several areas crucial to the
success of this project. First, its ease of integration into varied circuit Figure 2: Main features and advantages of the ESP32.

2 www.elektormagazine.com
Figure 3: The energy meter is based on an application note by Atmel [2]. Here, you can see the circuitry around the metering IC.

main features and advantages resulting in its being selected for this Design Phase and Electrical Safety Standards
project. The design phase is indeed a pivotal part of the engineering process,
particularly when safety is an indispensable consideration. In a device
Metering IC Integration designed to interact with mains AC voltages, meticulous attention
The ATM90E32AS IC from Microchip was integrated according to the must be paid to conformance with established safety standards. In
manufacturer’s application note; the document served as a cornerstone Figure 4, the project’s block diagram is shown.
in ensuring that the energy metering IC communicated seamlessly
with the ESP32 microcontroller. However, this phase was not devoid of To ensure safety, several specialized electrical components were
challenges. The procurement of the correct components within budget integrated into the design. Metal oxide varistors (MOVs) were used
constraints required meticulous planning, given the constraints on for transient voltage suppression to protect the circuitry from voltage
availability. In Figure 3, the application note provided by Atmel (now spikes. Furthermore, fuse components were included as an essential
Microchip) in shown. failsafe to prevent overcurrent conditions.

Guest edited by 3
Figure 4: Block diagram of our Energy Meter project.

Beyond component selection, circuit design also focused on layout this magazine — we’re still in the process of getting the prototype
considerations that would abide by safety norms. Adequate creepage made, tested, and working, on the software that will run it. There’s
and clearance distances were maintained between the conductive more to come, so stay tuned for updates on this project. We will near
elements on the PCB to prevent electrical arcing. Trace widths for AC completion and share updates in the January/February 2024 edition
voltage lines were calculated carefully to handle the current ratings, of Elektor, which is dedicated to the topic of Power & Energy.
adhering to IPC-2221 standards [1]. This was critical in ensuring the 230646-01
thermal performance of the board under full-load conditions. To ensure
ground integrity, a solid ground plane was used. Special attention was
given to the design of differential pairs for signal integrity, making sure Questions or Comments?
that the routing followed precise geometry to minimize electromag- If you have questions about this article, feel free to email the Elektor
netic interference. editorial team at editor@elektor.com.

Manufacturing Selection: Opting for JLC PCB


After scrutinizing various PCB assembly services, JLC PCB was
selected. The principal reason for this choice was the balance of
cost-effectiveness and reliability that they offer. This decision was
important in keeping the project within budget without compromis-
ing on the quality of the assembled board. Currently, the prototype
schematic and PCB designs are being finalized, and they will soon
be sent for production.
Related Products
Reflecting on the Journey and Looking Forward
In retrospect, this project shows what can be achieved when careful > ESP32-DevKitC-32E
www.elektor.com/20518
planning meets good engineering. The hurdles we faced helped us
improve our design. As we move from making a prototype to possibly > ESP32-C3-DevKitM-1
mass-producing it, we expect it to make a real difference in how people www.elektor.com/20324
manage energy. This project will be detailed in upcoming editions of

4 www.elektormagazine.com
project

• Elekto
lab r
or

lab
t
Elek
AL
ORIGIN

la b
El e
kt

or
or l kt
a b • Ele

Project Update:
ESP32-Based
Energy Meter Figure 1: Rendering of the Elektor Energy Meter.
Next Steps in Prototyping

By Saad Imtiaz (Elektor) We began our journey of devloping a reliable, user-friendly energy
meter leveraging the ESP32 microcontroller. In our previous install-
In the first installment of ment, “Prototyping an ESP32-Based Energy Meter” [1], we discussed
this series, we explored the the initial design requirements, block diagram and the plan for starting
this project. Before we give an update on it, let’s have a recap. The
foundational design of the Elektor energy meter conceptual design is shown in the rendering in Figure 1.
Energy Meter. In this installment,
we’ll look at the next phase in the Our focus was on real-time power monitoring, with an emphasis on
safety and affordability. To make the energy measurement precise, we
ESP32-based energy meter project, opted for the Atmel ATM90E32AS, a polyphase energy monitoring IC
focusing on detailed schematics, [2]. This IC will get the single-phase voltage from the mains and will
circuit isolation strategies, and key use split coil transformers to measure the current safely. The main
application microcontroller selected was ESP32 as it has built-in Wi-Fi
enhancements. and very cost-effective when compared to other MCUs. In Figure 2,

N L ELECTRICAL L N
ISOLATION
BOUNDARY

ISOLATED AC/DC ISOLATED AC/DC


POWER SUPPLY POWER SUPPLY

GND VCC VREF GND VCC

I1P
I1N

ATM90E32AS ESP32
CS CS
ADuM3151 OLED DISPLAY
CLK CLK
SDI SDI
SDO SDO

APPLICATION
WI-FI TO
PROCESSOR MOBILE DEVICE
AND INTERNET
V1P
V1N USB COMM TO PC

Figure 2:
Block Diagram of the
Elektor Energy Meter.

6 January & February 2024 www.elektormagazine.com


January & February 2024 7
AMS1117-3.3 +3.3V AMS1117-3.3 +3.3V A
IC3 IC4
ACDC1 ACDC2
HLK-5M05 R12 HLK-5M05 R23
R21a +3V3 +3.3V A
100Ω LINE LINE
C15 1 4 1 4
K1 AC/L +Vout JP1 AC/L +Vout
1k

1k
C18 C19 C21 C22
R R20
330n 2 3 LED1 2 3 LED2
T AC/N –Vout 10µ 10µ AC/N –Vout 10µ 10µ
22Ω

S C16
NEUT NEUT
CP1-2503A-ND R21b 330n
100Ω A
R21c
100Ω +3.3V +3V3 +3V3
C13
K2
R R19 +3.3V
R14
330n R22 D1
T
22Ω

S C14
10k

BAT760-7

10k
CP1-2503A-ND R21d K7
330n 1
100Ω C11 C12 C6 C7
C20 42 2
VDD18 SW2 C24 C25
R17 43 10µ 10µ 3
VDD18 100n 100n
100Ω 100n 1 4
C8 41 AVDD 100n 100n
K3 /RESET 48 5
R R16 DVDD
11 A 6
330n 3 VREF
T I1P MOD1 A
22Ω

S C9 4
I1N 22 ESP32-WROOM-32
5 ZX0 C1 C3
CP1-2503A-ND R18 I2P 23
330n 6 ZX1
100Ω I2N 24 +3V3
ZX2 10µ 100n +3.3V +3V3
7
I3P IC2
8 IC1 ADuM3151
I3N 25 1 38
CF1 GND GND
ATM90E32AS 26 1 20 2 37 +3V3
13 CF2 VDD1 VDD2 3V3 IO23
V1P -AU-R 27 2 19 3 36
14 CF3 GND1 GND2 EN IO22 K5
R7 V1N 28 3 18 A 4 35 1
15 CF4 MCLK SCLK SENSOR_VP TXD0
240k

V2P 4 17 5 34 2
16 MO SI SENSOR_VN RXD0
V2N 29 5 16 6 33 3
17 WARNOUT MI SO IO34 IO21
R6 V3P 6 15 7 32 4
18 /MSS /SSS IO35 NC
240k

V3N 30 7 14 8 31 A
IRQ0 VIA VOA IO32 IO19
31 8 13 9 30
R9 R10 R11 R8 33 IRQ1 VIB VOB IO33 IO18
R5 C2 C4 C10 C17 PM0 9 12 10 29
34 VOC VIC IO25 IO5
240k

PM1 20 X1 10 11 11 28
OSCI GND1 GND2 IO26 IO17
1k

1k

1k

1k
18n 18n 18n 18n 21 12 27
37 OSCO A IO27 IO16
R4 /CS 13 26
38 IO14 IO4
240k

SCLK 9 16.384MHz 14 25
IO12 IO0

GND
IO13

IO15
IC

SD2
SD3

CLK
SD0
SD1
39
SDO 10 GND IO2
IC 3 5 SW1
40 C23
R3 SDI 36
IC
IC5

15
16
17
18
19
20
21
22
23
24
240k

32
100n

Figure 3: Schematic diagram of the project.


35 TEST A
NC 19 PS2501
+3.3V 45 DGND
R2 NC 44 A
46 DGND
240k

NC 47 6 4
DGND
12 R13
AGND

510Ω
R1 R15a R15b R15c R15d 2
AGND
240k
A

10k

10k

10k

10k
F1 LINE
K4
C5
RV1
AC
100n 240V

1
2
3
4
5
6
7
8
K6
230709-003
NEUT
where the SCT013 by YHDC will be connected, which is a split core
type CT, shown in Figure 4. The reason for selecting CT was that it is
cost-effective easy to use, and non-invasive.

The energy metered is powered by two Hi-Link HLK-5M05 modules


ACDC1/2, to ensure galvanic isolation between the MCU and energy
meter circuitry, protecting against high-voltage risks. AMS1117-3.3
regulators provide stable 3.3 V power, essential for the ESP32 and
other low-voltage parts. Safety is further bolstered by fuses (F1) for
overcurrent protection and a metal oxide varistor (MOV) (R23) against
Figure 4: The YHDC SCT013 . (Source: YHDC) voltage spikes. For diagnostics, LED1 and LED2 indicate power and
operational status. Connector K6 connects to all the outputs for the
MCU for debugging operations.

the project’s updated block is shown. The planned size of the final Circuit Isolation
energy meter is 100×80×30 mm (L×W×H), but, for the prototype, In the schematic, you might have noticed two DC grounds, GND and
our PCB is 100×100 mm. Our goal of this prototype is as proof-of- GNDA. The ground terminal (GND) is connected to IC1 and is also
concept and, subsequently, if we’re successful in it, we’ll scale the connected to the AC mains neutral. GNDA is an isolated ground termi-
size down to 100×80 mm or even less for the final version. The main nal that is connected to the ESP32-WROOM-32D, which is MOD1. To
purpose of making this energy meter was to make an IoT-enabled, ensure safety, it is imperative to isolate the ESP32 from the AC mains
budget-friendly device that can make accurate energy measurements neutral. As the IC1 lacks galvanic isolation, it is imperative to isolate
and provide real-time energy data to the user via a mobile device, so these components from each other. Now, the question arises as to
the user can track their power consumption in real time and become how the SPI between these two chips will be communicated. Here is
more energy efficient. when IC2, an Analog Devices ADuM3151, comes into play.

In this article, we dive deeper into the project’s evolution, highlighting The ADuM3151 is pivotal in ensuring safe communication between
the schematic design, the implementation of circuit isolation, and the IC1 and the ESP32-WROOM-32D, providing galvanic isolation for SPI
key improvements we’ve integrated since our initial concept. lines. In Figure 5, you can see the functional block diagram of IC2
[3]. It uses inductive couplers to transfer digital signals across an
Schematic Design isolation barrier, effectively shielding the computer-connected ESP32
The heart of our project lies in its schematic design. The ESP32 micro-
controller remains central to our architecture, interfacing seamlessly
with the ATM90E32AS for energy measurement. Our updated schematic
reflects a more streamlined approach, reducing noise and enhancing
signal integrity, circuit isolation, and more. In Figure 3, you can see
the complete schematic of the project.

IC1 is the ATM90E32AS which is the brain of this entire project, it


connects the mains voltage with series seven 240 k resistors (R1…R7)
to pins V1P, V2P, and V3P. For keeping things simple, all these pins will
be given a single-phase voltage from the mains. You might ask, why
not use a transformer instead of these series of resistors? Because as
we have size and cost constraints due to the approach we chose. Apart
the small size benefit of using resistors there is another benefit, that is
less Phase Delay. Transformers can introduce a phase delay between
the primary and secondary windings, which could affect the timing and
accuracy of voltage readings in energy measurements. When using
resistors, this phase delay is significantly reduced, potentially leading
to more accurate real-time voltage readings. But, using these series
resistors has a major disadvantage, i.e., no galvanic isolation. We will
talk about this later in the article.

Now moving to the current measurement: For that we will be using Figure 5: ADuM3151 SPIsolator functional block diagram. (Source: Analog
coil transformers (CTs). Connectors K1-K3 are audio jack connectors Devices [3])

8 January & February 2024 www.elektormagazine.com


from the AC mains’ high-voltage transients. This choice is crucial for We are committed to continuous improvement and innovation, with a
preventing damage during coding and debugging, while its capability focus on user feedback to guide future enhancements. The goal is to
of supporting multiple isolated channels ensures reliable and secure not only provide a reliable energy monitoring tool, but also to empower
SPI communication, maintaining data integrity and aligning with the users with insights into their energy usage, fostering awareness and
project’s safety and performance goals. efficiency.
230709-01
User Interface and Interaction
The user interface of the ESP32 Energy Meter project is designed
to be informative and user-friendly. An OLED Display, connected to Questions or Comments?
connector K5, which is interfacing with the I2C pins of the ESP32, If you have questions about this article, feel free to email the
will serve as the primary display medium. This display will show all author at saad.imtiaz@elektor.com or the Elektor editorial team
relevant data to the user in real-time, including energy consumption at editor@elektor.com.
metrics and system status. The choice of OLED technology ensures
clear visibility and a responsive interface.

In addition to the hardware display, the project incorporates a web


server hosted on the ESP32. This web interface will mirror the data
displayed on the OLED screen, offering users an alternative way to About the Author
monitor their energy usage. The development team is dedicated to Saad Imtiaz (Senior Engineer, Elektor) is a mechatronics engineer
creating a web UI and UX that is both user-friendly and detailed, with five years of experience in embedded systems, mechatronic
ensuring accessibility and comprehensiveness in data presentation. systems, and product development. He has collaborated with numer-
This dual-interface approach allows users to interact with the energy ous companies, ranging from startups to enterprises globally, on
meter both physically and remotely, enhancing the overall usability product prototyping and development. Saad has also spent time
of the system. in the aviation industry and has led a technology startup company.
Recently, he joined Elektor and drives project development in both
Next Steps and Future Plans software and hardware.
As the project moves forward, the initial PCB design has been sent
off for manufacture. Upon its return, the focus will shift to the firmware
side of the project. The firmware development will involve program-
ming the ESP32 to accurately process and display energy consump-
tion data, manage the web server, and ensure smooth communication Related Products
between all components. > LILYGO T-Display-S3 ESP32-S3 Development Board
www.elektor.com/20299
Looking ahead, there are plans to integrate additional features to
enhance the energy meter’s functionality. These may include: > ESP-C3-12F-Kit Development Board (4 MB Flash)
www.elektor.com/19855
> Remote monitoring capabilities: Allowing users to check their > Joy-IT NodeMCU ESP32
energy consumption data from anywhere via the web interface. www.elektor.com/19973
> Alerts and notifications: Implementing a system to alert users
about unusual energy consumption patterns or potential system
issues.
> Data analysis tools: Incorporating analytical tools in the web
interface to help users understand their energy usage trends and
identify areas for efficiency improvements.

WEB LINKS
[1] Saad Imtiaz, “Prototyping an ESP32-Based Energy Meter,” Elektor Guest Edition 2023: http://www.elektormagazine.com/230646-01
[2] ATM90E32AS Poly-Phase Energy Metering IC: https://www.microchip.com/en-us/product/atm90e32as
[3] Analog Devices Inc. ADuM3151 SPIsolator™ Digital Isolators: https://eu.mouser.com/new/analog-devices/adi-adum3151-isolators

January & February 2024 9


project

lab • Elektor
or

kt

lab
Ele
O R IG IN A L

ab
Ele

rl
to
r la b k to

k
• Ele

Project Update #2:


ESP32-Based
Energy Meter
Some Enhancements
Figure 1: New enclosure design rendering of the ESP32 Energy Meter.

By Saad Imtiaz (Elektor)


the size of the prototype PCB was 100×100 mm. After testing, some
In the previous installment of this components were removed and the layout of the PCB was optimized,
series, we discussed the schematics, hence the size for this version is reduced to 79.5×79.5 mm — that’s
about 20% less from last time. In Figure 1, the new enclosure for the
and circuit isolation strategies of the new version of PCB is shown. Along with that, to make the ESP32
ESP32 Energy Meter. Now let’s discuss Energy Meter safer to use, instead of powering the PCB directly with
further enhancements, a PCB design, the mains voltage, now a 220 V-to-12 V Step Down Transformer is
required for voltage sampling and also powering the circuit. Adding
and more. a transformer does have some drawbacks in terms of phase delays,
but safety first! Since we are not looking to measure voltage spikes, or
fast sags or surges, but energy, this shouldn’t hurt our measurement.
In 2023, we started with the goal of creating a reliable, user-friendly
energy meter using an Espressif ESP32 microcontroller. In our last The Updated Schematic Design
article, “Project Update: ESP32-Based Energy Meter” [1], we went over We made some upgrades, and now, rather than the ESP32, the ESP32-S3
the block diagram, the schematics, circuit isolation strategy, features, is on board. This also unlocks more potential for the Energy Meter. The
and project strategy. Let’s start with a small recap before we get into ESP32-S3 offers significant enhancements over the ESP32, including
the next update. improved processing power, AI and signal processing capabilities,
more memory, and better security features. The updated schematic
The main idea revolved around developing a precise and efficient further improves the capability of the Energy Meter along with more
energy meter leveraging the capabilities of the Espressif ESP32 functionality. The design references guides from Espressif [2] and other
microcontroller and the ATM90E32AS IC for energy measurement. useful internet resources [3…6] were used to integrate the ESP32-S3
The project aimed to enhance user experience and reliability through into the project. In Figure 2, the schematic of the project is shown.
meticulous schematic design and circuit isolation using the ADuM3151
to provide safe communication between ESP32 and the ATM90E32AS The circuit board layout has been optimized to improve the safety,
by Atmel (now Microchip). It emphasized safety and efficiency by usability, and efficacy of the ESP32-S3. We’ve made substantial adjust-
incorporating noise reduction techniques, signal integrity enhance- ments by lowering the PCB size for a more compact footprint, moving
ments, and protective mechanisms such as fuses and MOVs. With a to transformer-based power for increased safety, and adding versatility
focus on future-ready features, the plan included integrating remote with single and three-phase compatibility. The utilization of a more
monitoring and data analysis tools for improved energy management efficient AP63203WU-7 buck converter in place of Hi-Link modules,
and efficiency insights. along with the addition of user-friendly features such as a USB-C
connector and a Qwiic connector for expandability, all contributed
In this article, our main goals remain the same, and plenty of changes to the advancement of the project. These improvements build on the
have been made to make the project safer to use, reduce its produc- ESP32-S3’s capabilities, focusing on providing a practical, adaptable,
tion cost, and reduce its size. As mentioned in the previous article, and safer energy monitoring solution.

10 May & June 2024 www.elektormagazine.com


+3V3
GND
+5V
+5VA GND_B

WARNOUT

PM0
PM1
CF4
CF3
CF2
CF1
CS

ZX0
ZX1
ZX2
SDI
SDO
IRQ1
IRQ0

CLK
JP7 D2
VBUS_B
JP5 JP6 1 2 3
+3V3 +5VA 4k7 CC2
+5VA IC2 +3V3-U 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1N5819HW-7-F
R31 SBU1
NJM2882F33-TE1
PM1 DP2
1 5 K2
IN OUT +3V3 DN1

Figure 2: Project schematic.


DP1 GSB1C41110SSHR
+3V3 DN2

GND
CONTROL
NOISE
D4 D5 D3 CC1
R38 PM2 4k7
2 3 4

80Ω
R37 R32 SBU2

R20
R21
R19
R18
100k VBUS_A

C26 C27 C25 LED7 GND_A

10k
10k
10k
10k
3 x SZSMF4l5.0AT3G
22µ 10n 22µ

+3V3
R22

10k
42
R2 R3 R6 R7 R10 R11 VDD18
C2 C3 C4 C6 C9 C11 C24 43 +3V3
VDD18

2Ω4
2Ω4
2Ω4
2Ω4
2Ω4
2Ω4
1 C1
41 AVDD
18n 18n 18n 18n 18n 18n 100n /RESET 48
K1 DVDD
11 100n 1 40
6 R1 3 VREF +3V3-U GND GND
I1P 1k I1P 2 39
5 R4 4 C12 C13 C8 C10 C5 C7 3V3 IO2
I1N 1k I1N 22 3 38
4 R5 5 ZX0 EN IO2
I2P 1k I2P 23 4 37
R8 6 ZX1 100n 10µ 100n 100n 100n 10µ IO4 TXD0
3
I2N 1k I2N 24 5 36
2 R9 7 ZX2 IO5 RXD0
I3P 1k I3P 6 MOD1 35
1 R12 8 IO6 IO42
I3N 1k I3N 25 7 34
IC1 CF1 IO7 ESP32-S3-WROOM-1 IO41
26 8 33
+12V 13 CF2 IO15 IO40
V1P 27 9 32
14 CF3 IO16 IO39
V1N 28 10 31
D6 D7 15 CF4 IO17 IO38
V2P 11 30
16 ABM8G R33 R34 R35 R36 IO18 IO37
2 x B140HW-7 V2N 29 16.384MHz B4Y-T 12 29
K4 17 WARNOUT IO8 IO36
80Ω
80Ω
80Ω
80Ω

V3P 2 X1 4 13 28
6 R30 18 GND GND IO19 IO35
UC 100k V3N 30 14 27
R28 IRQ0 IO20 IO0 +3V3-U
5 LED3 LED4 LED5 LED6
IO9
IO10
IO12
IO13
IO14

IO11

IO46
IO21
IO47
IO48

UB 100k 31 IO3 IO45


4 R29 33 IRQ1
UA 100k PM0 1 3
XIN XOUT R16
15
16
17
18
19
20
21
22
23
24
25
26

3 34
GND R24 C22 R23 C21 R25 C23 R15 C16 R14 C15 R13 C14 PM1 20
2 OSCI
GND 21

1k
1k
1k
1k
1k
1k
10k

1 37 OSCO
DC IN /CS
38
18n 18n 18n 18n 18n 18n SCLK 9
39 IC

ATM90E32AS-AU-R
SDO 10 K3 C19 C18
40 IC 1 +3V3-U R27 R26
EN1

JP8 SDI 36 +3V3 GND


IC 2
80Ω
80Ω

32 3V3 S1 S2 100n 100n


35 TEST Qwiic 3
NC 19 SDA
45 DGND C20 4 LED2 LED1
NC 44 SCL
AP63203WU-7 46 DGND +3V3 +3V3-U
C28 NC 47
1 6 DGND 100n JP3 JP4
FB BST 12 JP1 1 1 GREEN RED
AGND GND 3V3
+12V IC3 100n L1 R39
+3V3 2 2 2
2 5 AGND 3V3 GND C17
EN SW 0Ω 3 3
SCL SCL
BOOT1

SRN6028C-3R9M D1
4 4
3 4 R40 SCA SCA 100n
VIN GND +3V3-U

80Ω
BAT760-7
1 2 3 4 5 6
C32 C30 C29 C31 LED8
JP2
100n 220µ 220µ 100n
TX
D0

RX
EN
GND

3V3-U

240093-001

May & June 2024 11


Figure 3: Overall wiring of a three-phase voltage system and coil
transformers with the ESP32 Energy meter.

Refined Voltage and Current Sampling


IC1 remains the same ATM90E32AS, but the change is that it now
requires a 220 VAC-to-12 VAC step-down transformer, between it and
the mains. This change has been made to make the project more safe
to test and use, as the transformers provide galvanic isolation. In my
testing there was no notable difference in doing so.

Figure 4:
Thus, for each of IC1’s voltage sampling inputs, there is now only one The front and
100 kΩ resistor (R27 to R29). Last time we combined all the phase back of the
voltages into one input, and a lot of feedback was given by the readers PCB layout.
to have the option to use it with either three-phase or single-phase
power if needed. We thought about it, and now we can use it with
both. By default, three-phase mode is configured, but if one wants provided on terminal JP5 and JP6. This enables the energy meter
to make it single-phase, jumper JP8 needs to be shorted. Figure 3 to be used as a module as well with another MCU if the onboard
shows the general wiring illustration for a three-phase system. Note ESP32-S3 is not required.
that the phase wires are connected after the step-down to 12 VAC
from a transformer — using a 12 VAC doorbell transformer can be The ESP32-S3 has the USB feature built in, so it’s really convenient to
useful in this case. program the MCU this way, which is why we added USB-C connector
K2. For troubleshooting, terminal JP2 has been added. Status LEDs
For current sampling and measurement, instead of using the headphone LED1 and LED2, which can be controlled by the ESP32-S3, and push
jack as the connector, a 5.08 mm pitch screw terminal block is used, buttons S1 and S2 are added for interacting with the OLED screen,
i.e., K1. This adds to the overall ruggedness of the energy meter. For which can be connected to JP3 and JP4. Why two connection points?
current coil sensors, the YHDC SCT013 100 A : 50 mA is selected Some I2C OLED screens have ground as the first pin and some have
and the resistors R1 to R12 for all three current sensing inputs are 3V3 supply instead. This way, both types of OLED pinout variants can
calibrated accordingly. be worked with.

Power Supply Optimization Finally, the Qwiic connector at K3 has also been added to enhance
The energy meter is now powered with buck switching regulator IC3, the functionality of the Energy Meter, in case one wishes to add some
i.e., the AP63203WU-7 by Diodes Incorporated. Previously, Hi-Link additional sensors or modules to this project.
HLK5M05 modules were used, but they are much bulkier and more
expensive than this buck converter. This is done as buck converters The PCB Layout
are more efficient than these Hi-Link modules, they cost less, and The PCB layout has been meticulously optimized for compactness,
their size is much smaller. Using IC3 also lets us power the circuit with and easy soldering, shown in Figure 4. At the top, voltage and current
12 VDC at K4 for development purposes and also from the UA, i.e., sampling connections are strategically positioned in one place for DIN
voltage phase 1 of from the same connector, K4, for normal operation. rail format integration. On the right side, connections for any external
microcontroller (MCU) are facilitated through 2.54 mm pitch headers,
Interactive and Modular Features ensuring ease of access and modularity. Centrally located is the connec-
For active, reactive, apparent, active fundamental, and harmonic tion for the OLED screen, flanked by push buttons for intuitive inter-
energy pulse outputs CF1 to CF4, LEDs have been added [7][8]. For action. Adjacent to the OLED display, power and status LEDs provide
the power mode selection of IC1, jumpers PM1 and PM2 are added. immediate visual feedback, while energy pulse output LEDs are conve-
In this version, all the output pins of IC1 ATM90E32AS for MCU are niently situated near the MCU output terminals for direct monitoring.

12 May & June 2024 www.elektormagazine.com


Figure 5: 3D model of the assembled PCB.

At the foundation of the design, the USB-C port and the ESP32-S3
module are positioned away from the AC voltage areas to improve
safety. A ceramic capacitor, placed adjacent to the 3 V input of the
ESP32-S3, serves to decouple and significantly reduce any potential
noise. Additionally, electrolytic capacitors are incorporated into the
design, further stabilizing the power supply and ensuring the circuit’s
reliability and performance. This layout streamlines the assembly
process and enhances functionality and user experience by provid-
ing a clear and logical component arrangement. In Figure 5, you can
see the rendering of the assembled PCB. Questions or Comments?
If you have questions about this article, feel free to email the
This design requires the use of mains-powered author at saad.imtiaz@elektor.com or the Elektor editorial team
transformers. People inexperienced with mains at editor@elektor.com.
voltages should not attempt this project or should ask
someone with experience who can help them with this
project!

Next Steps and Prospects


Following the prototype phase with the original schematic, we’ve made
several enhancements to increase the reliability of the ESP32 Energy About the Author
Meter. Currently, we are also focusing on the further development of Saad Imtiaz (Senior Engineer, Elektor) is a mechatronics engineer
its firmware. with experience in embedded systems, mechatronic systems, and
product development. He has collaborated with numerous compa-
The latest PCB design has been dispatched for production, and we nies, ranging from startups to enterprises globally, on prototyping
anticipate conducting extensive tests upon its receipt to ensure system and development. Saad has also spent time in the aviation industry
reliability. Concurrently, software development is progressing, aimed and has led a technology startup company. At Elektor, he drives
at maximizing the capabilities of the ESP32-S3 module within our project development in both software and hardware.
energy meter.

Looking forward, we plan to integrate the ESP32 Energy Meter with


Home Assistant, aiming for simplified user engagement. Neverthe- Related Products
less, we are equally committed to developing bespoke firmware to
fully utilize the device’s potential. > Qoitech Otii Arc - Power Supply, Power Meter and Data
Acquisition
www.elektor.com/19270
In summary, the project is moving forward with both hardware improve-
ments and software advancements. Our goal remains to provide a > ESP Terminal
dependable and efficient energy metering solution. This project is www.elektor.com/20526
also on the Elektor Labs platform [9], so feel free to comment and
contribute there!
> Arduino Nano ESP32
www.elektor.com/20562
240093-01

WEB LINKS
[1] Saad Imtiaz, “Project Update: ESP32-Based Energy Meter,” Elektor 1/2024: https://elektormagazine.com/magazine/elektor-324/62641
[2] ESP32 S3 DevKit-C Schematic: https://dl.espressif.com/dl/schematics/SCH_ESP32-S3-DevKitC-1_V1.1_20221130.pdf
[3] ESP32 S3 Pinout Help Guide: https://luisllamas.es/en/which-pins-can-i-use-on-esp32-s3
[4] SCH_ESP32-S3-USB-Bridge-MB_V2.1 Schematic: https://tinyurl.com/usbbridgeschematic
[5] ESP32-S3 Pin Reference: http://wiki.fluidnc.com/en/hardware/ESP32-S3_Pin_Reference
[6] ESP32-S3: Which Pins Should I Use?: https://atomic14.com/2023/11/21/esp32-s3-pins.html
[7] Application Note Poly-Phase Energy Metering IC M90E32AS: https://tinyurl.com/polyphasemetering
[8] Atmel M90E32AS | Datasheet: https://eu.mouser.com/datasheet/2/268/Atmel_46003_SE_M90E32AS_Datasheet-1368788.pdf
[9] ESP32 Energy Meter | Elektor Labs:
https://elektormagazine.com/labs/esp32-energy-meter-an-open-source-solution-for-real-time-energy-monitoring

May & June 2024 13


project
ab • Elek
or l
kt t

or
Ele

lab
ORIGINA
L

Ele

b
or

kt
or

la
la b
• Ele k t

Project Update #3:


ESP32-Based

Energy
Meter Integration and Testing
Figure 1: The assembled ESP32 Energy Meter with its OLED display and live
status indicators.

using a 230-V-to-12-V Step Down Transformer for voltage sampling


and running of the system. This significantly improves safety while
with Home Assistant maintaining flexibility for both single- and three-phase installations.

Other improvements included the integration of a more efficient


AP63203WU-7 buck converter, making the PCB more modular, calibra-
tion of the current transformer sampling circuit, and more. This not
By Saad Imtiaz (Elektor) only optimizes the energy meter’s performance and functionality, but
also reduces both cost and size.
In the previous project update, you
learned about enhancements to the ESP32 In this article, we will discuss the steps taken to get this energy meter
up and running and the journey it took from the lab bench to the
Energy Meter’s schematic design and circuit breaker box. Furthermore, we will also discuss how to set it up,
PCB. This article focuses on the practical calibrate it, and finally, how to integrate it with Home Assistant with
implementation and integration of the new ESP Home to show and monitor the collected data from the energy
meter. In Figure 1, a vivid snapshot of the ESP32 Energy Meter project
version. It provides a step-by-step guide in action is captured, encased in a 3D-printed enclosure with an OLED
on setting up the meter with ESPHome display. The image highlights live status indicators that seamlessly
and Home Assistant for effective energy track and display real-time power consumption.

monitoring. Furthermore, we deal with the Assembly


device’s calibration. The new PCB was designed to be more compact and straightforward
to solder and the layout had adequate spacing for each component
which accommodated the soldering process of it. To facilitate project
In our previous article [1], we focused on enhancements to the replication and modifications by enthusiasts and professionals alike, the
schematic design and PCB of the ESP32 Energy Meter, with improve- complete Bill of Materials (BOM) in Mouser format, and the production
ments in modularity and safety features. Before we get into the next files are shared on the Elektor’s Lab GitHub repository [2].
project update, let’s have a brief overview.
For the voltage and current sampling connections, screw type terminal
In the most recent advancements of the ESP32 Energy Meter project, blocks by CUI Devices were used, the quality of these terminal blocks
we upgraded to the ESP32-S3 microcontroller, introducing enhanced were much better than the cheap blue colored terminal blocks seen
processing power and broader functionality. The new design slimmed on most sensor modules. As we are dealing with AC Voltages and
down the PCB and incorporated a transformer-based power system, energy metering, it is vital to have secure and reliable connections.

14 July & August 2024 www.elektormagazine.com


Noise reduction is a critical aspect of the PCB design, addressed
by integrating both electrolytic and ceramic capacitors around the
ATM90E32S energy metering chip. This arrangement helps to filter
out both low- and high-frequency noise, ensuring more accurate and
stable energy measurement. The board is depicted in Figure 2.

As mentioned earlier, we decided to use a step-down transformer for


voltage sampling and the main source of powering the entire system. Figure 2: PCB of the fully assembled ESP32 Energy Meter.
Finding such a transformer is easy and cheap, but most of these step
down transformers take up a lot of space when used in a custom
enclosure, as shown in Figure 3. So, it is best that DIN Rail Bell trans-
formers are used in this case to make the setup more clean and safe;
such transformers can easily be found online. Moreover, the accuracy
of voltage measurements depends on the characteristics of the trans-
formers, including their voltage ratio accuracy, phase shift, and linearity.

You might have noticed in the images that there is only one trans-
former attached to the energy meter. As the energy meter was config-
ured to be used in Single Phase mode, by sorting the jumper JP8 on
the back side of the PCB, as seen in Figure 4. To operate the energy
meter in three-phase mode or to sample voltage from each phase in
a three-phase system using three step-down transformers, you must
connect the primary sides of three transformers to the respective
phases (L1, L2, L3). On the secondary side, connect one end of each
transformer’s winding to a common neutral point, forming a star (Y)
configuration. The free ends of the secondary windings (V1, V2, V3)
will then provide the voltage outputs (UA, UB and UC) on the PCB
for each phase. Key considerations include ensuring the transformers
are properly rated for the system’s voltage and current, maintaining
strict isolation between primary and secondary circuits for safety, and
securing a stable and well-balanced neutral connection to prevent
measurement inaccuracies.

Setting up with ESPHome and Home Assistant


As part of the development plan, a specific firmware is being created Figure 3: 220 V to 12 V Step-down transformer setup within a
to leverage the capabilities of the energy metering chip and the custom enclosure.
advanced AI features of the ESP32-S3. Although developing such
tailored firmware requires a significant amount of time and is still under-
way, this does not restrict the usability of the energy meter. The device
can be fully functional with existing platforms like Home Assistant,
providing an immediate solution for energy monitoring. Therefore, in
this article, the focus is on the integration of the ESP32 Energy Meter
with Home Assistant [3] and ESPHome [4]. This section will guide
you through setting up the energy meter within the Home Assistant
environment to utilize its complete functionality.

To set up the ESP32 Energy Meter with the ESPHome firmware and
integrate it into Home Assistant, you should start by installing Home
Assistant. (See a comprehensive guide in an article by my colleague
Clemens Valens [5].) After that, add the ESPHome integration from the
Add-on Store; then create a new project in ESPHome for your ESP32
device. This automatically generates a basic YAML configuration file
(such a YAML file specifies a distinct ESPHome project with all the
sensors used and many other options). You have to download this Figure 4: Single-phase jumper configuration on the ESP32 Energy
default file, before taking the next steps. Meter’s PCB.

July & August 2024 15


Connect your ESP32 to your computer and select the correct COM
Port for the ESP32-S3. In the ESPHome dashboard, click Install and
choose the .bin file to flash the firmware. Once the firmware is success-
fully uploaded, and your ESP32 Energy Meter is recognized by Home
Assistant, proceed to edit the initial YAML configuration. To do this,
open the ESPHome dashboard in Home Assistant, find your device,
and click on the Edit option on the energy meter’s card. Replace the
existing configuration with the YAML content provided in the GitHub
repository [2]. Make sure to properly configure your API, OTA, and
WiFi credentials in this new YAML setup.

Install the new configuration wirelessly onto your ESP32 Energy Meter.
Once this is done, the device will be active and connected. To display
the energy meter data on your Home Assistant dashboard, simply
assign the ESPHome device to a specific area in Home Assistant. This
helps organize your dashboard by grouping devices according to their
physical or logical location in your home. For a visual representation of
what you can achieve, refer to the Figure 5, which displays the energy
meter data on the Home Assistant dashboard.

Integrating the ESP32 Energy Meter with Home Assistant not only
simplifies the process of monitoring energy usage but also unlocks
a suite of powerful features provided by the platform. Home Assis-
tant offers an intuitive interface for real-time data visualization, control
automation, and seamless integration with other smart devices in your
home. This integration allows for the creation of detailed history graphs
and analytics within Home Assistant, providing an in-depth look at
power consumption patterns over time, as shown in Figure 6. These
insights enable users to make informed decisions about their energy use, Figure 5: Home Assistant dashboard displaying real-time
identify potential savings, and optimize their home’s energy efficiency. energy data from the ESP32 Energy Meter.

Figure 6: Detailed history graphs of energy consumption in Home Assistant.

16 July & August 2024 www.elektormagazine.com


By following the setup process described above, users can take full
advantage of these capabilities, turning the ESP32 Energy Meter into
a central component of their smart home ecosystem. This integra-
tion not only enhances the functionality of the energy meter but also
enriches the overall smart home experience with comprehensive energy
monitoring and management tools.

YAML Configuration
The provided YAML configuration sets up the ESP32 Energy Meter with
ESPHome, enabling the monitoring of essential electrical parameters
like voltage, current, power across all three phases. It leverages the
capabilities of the ATM90E32 sensor, with detailed definitions for SPI
communication and individual sensors for each phase. This setup not
only measures but also calculates total consumption metrics, integrat-
ing a daily energy counter for kWh and an OLED display for real-time
data visualization. These configurations are made according to the
instructions on the ESPHome page for the ATM90E32 sensor [6].

For ensuring the accuracy of the data reported by the ESP32 Energy
Meter, calibration is a crucial step. The specifics of how to adjust the
gain settings for current transformers and voltage inputs will be detailed
in the upcoming section.
Figure 8: Clamp meter setup for calibration.
Test Setup and Calibration
The test setup employed a multi-step heat and speed hair dryer as
the load, covering a range from 0.7 A to 8 A. The power cord of an
extension power strip was stripped to allow placement of the split coil This level of precision is adequate for most projects, but is slightly less
transformers on the live or neutral wire, facilitating direct monitoring precise than professional-grade meters.
under various conditions as shown in Figure 7.
During the calibration, a comparison of current readings was observed:
I conducted the current and voltage calibration of the ESP32 Energy the clamp meter reading was 1.692 A shown in Figure 8, while the
Meter using my UT201+ multimeter. This offers a resolution of 0.001 A readings calculated by the energy meter displayed 1.70 to 1.73 A after
and an accuracy specification of ±4% +10 digits for current and a calibration, as shown in Figure 9. Given the specifications of the UT201+
resolution of 0.001 V with accuracy of ±1% +5 digits for voltage. and the SCT-013-000, a Class 1 split core transformer which guarantees
an accuracy within 1% of the actual value, this small discrepancy falls
within the expected error margin. However, for even greater accuracy,
a more precise clamp meter could be used.

To fine-tune the ESP32 Energy Meter’s accuracy further, adjustments


were made to the gain settings for both voltage and current measure-
ments. For voltage, the sensor was calibrated using the formula:

New gain_voltage = (your voltage reading /


ESPHome voltage reading) * existing gain_voltage value

Similarly, for current adjustments:

New gain_ct = (your current reading /


ESPHome current reading) * existing gain_ct value

These new gain values were then updated in the ESPHome YAML
configuration file, followed by recompiling and uploading the firmware.
This process can be repeated as necessary to ensure optimal accuracy.
Figure 7: Setup for testing and calibrating the ESP32 Energy Meter using a These calibrated values help refine the measurements and are crucial
variable load. for accurate reporting and analysis in any energy monitoring setup.

July & August 2024 17


WARNING: Working inside a circuit breaker box
carries inherent risks, including the potential for
electrical shock or fire. It is vital to turn off all power before
starting the installation. In most countries, this work may
only be carried out by a qualified electrician!

Breaker Box Installation for the ESP32 Meter


Installing the ESP32 Energy Meter into my circuit breaker box proved
to be a manageable task that required meticulous attention to detail to
ensure both safety and functionality. I started by selecting a circuit with
the lowest amp limit. This choice was strategic, as it provided a safety
buffer; the circuit breaker would trip in the event of any unexpected
surges or transformer failures, thus protecting the system.

Using split core current transformers was particularly beneficial due to


their ease of installation. These transformers can be quickly clamped
onto any load, but it was crucial to pay attention to the direction of
current flow to guarantee accurate readings. It’s important to note
that if the direction of the current and the orientation of the current
transformer are not aligned correctly, the power readings will appear
negative, which indicates incorrect installation.

For a visual demonstration of the ESP32 Energy Meter in action within


the circuit breaker panel, refer to Figure 10. This image shows the
energy meter displaying real-time current, voltage measurements,
and the corresponding load in kilowatts, illustrating its functionality
in a live setting.
Figure 9: Final calibration results showing improved measurement
accuracy.

Figure 10: ESP32 Energy


Meter installed in a
circuit breaker panel,
monitoring real-time
power consumption.

18 July & August 2024 www.elektormagazine.com


Development and Prospects
While the current software configuration runs on ESPHome, there is
ongoing development to expand the capabilities of the ESP32 Energy
Meter. The project is looking forward to being integrated with a new
firmware specifically designed to harness the full potential of the ESP32-
S3 chip. This future firmware is expected to include advanced features
such as detailed energy analytics and potentially groundbreaking AI/
ML functionalities that could predict energy usage patterns and identify
the device according to its load footprint. About the Author
Saad Imtiaz (Senior Engineer, Elektor) is a mechatronics engineer
Although the core design and operational aspects of the project have with experience in embedded systems, mechatronic systems, and
been completed, the development of these sophisticated features is product development. He has collaborated with numerous compa-
a complex and time-consuming endeavor. I am excited about the nies, ranging from startups to enterprises globally, on prototyping
possibilities and committed to pushing the boundaries of what this and development. Saad has also spent time in the aviation industry
energy meter can achieve. and has led a technology startup company. At Elektor, he drives
project development in both software and hardware.
The ESP32 Energy Meter project is continuously evolving, incorporat-
ing more features with each update. Community members who are
interested in the upcoming AI and ML functionalities, or those who
would like to contribute to the development, are encouraged to get
involved. Collaboration will help accelerate progress and result in a
more robust and feature-rich energy monitoring solution. Keep an eye Related Products
out for further advancements as the project aims to refine and elevate
this versatile energy management tool to new heights. > PeakTech 4350 Clamp Meter
www.elektor.com/18161
240244-01
> Siglent SDM3045X Multimeter
www.elektor.com/17892
Questions or Comments?
If you have questions about this article, feel free to email the
author at saad.imtiaz@elektor.com or the Elektor editorial team
at editor@elektor.com.

WEB LINKS
[1] Saad Imtiaz, “Project Update #2: ESP32-Based Energy Meter”, Elektor 5-6/2024 :
https://www.elektormagazine.com/magazine/elektor-341/62892
[2] ESP32 Energy Meter Github Repository: https://github.com/ElektorLabs/esp32-energymeter
[3] Home Assistant: https://home-assistant.io/
[4] ESPHome: http://esphome.io
[5] Clemens Valens, “Home Automation Made Easy,” Elektor Magazine 9-10/2020 : https://www.elektormagazine.com/200019-01
[6] ATM90E32 Power Sensor: https://esphome.io/components/sensor/atm90e32.html

July & August 2024 19


project
• Elekto
lab r
or

lab
t
Elek
AL
ORIGIN

la b
Project Update #4

El e
kt

or
or l kt
a b • Ele

ESP32-Based
Energy Meter
Energy Monitoring with MQTT

By Saad Imtiaz (Elektor)

Previously, we focused on setting up the ESP32-


Based Energy Meter and integrating it with Home
While the AI/ML integration is still in progress — given the
Assistant. We also discussed the future potential extensive data preparation involved — this minor update
of leveraging the ESP32-S3 chip for AI and ML focuses on a crucial interim development: enabling
functionality to predict energy usage patterns real-time energy monitoring using MQTT. MQTT is a
lightweight messaging protocol designed for efficient
and identify devices. In this update, we take a step
communication. Refer to the textbox “What Is MQTT?”
forward by introducing firmware that enables real- for more information.
time energy monitoring using MQTT, paving the way
for advanced features. Custom Firmware and MQTT
In this article, we will discuss the next phase of the project
— leveraging MQTT and the Arduino IDE to enable
real-time energy monitoring. This update will cover the
We previously discussed the entire journey of the ESP32 firmware development that allows the ESP32 to commu-
Energy meter from the lab bench to the circuit breaker nicate with an MQTT broker, sending energy data to a
box, which started by assembling components, setting Home Assistant server or any other MQTT-compatible
up the energy meter with ESPHome and Home Assis- platform.
tant, calibration and testing, and finally installing it into
the circuit breaker box. In the last update [1], we laid the The advantage of using MQTT with an individual firmware
foundation by integrating the meter with Home Assistant, over ESPHome is that the individual firmware offers much
with the ambitious goal of adding AI and ML capabilities greater flexibility in terms of integration and customiza-
to predict energy usage patterns and identify devices tion. With a custom firmware, you have full control over
based on their energy signatures. how the data is collected, processed, and transmitted,

What Is MQTT ?
MQTT is a lightweight messaging protocol designed for efficient communication between devices, especially in
IoT environments. Central to this system is the MQTT broker, a server that acts as a hub for message exchange.
The broker receives messages from devices, known as publishers, and routes them to the appropriate recipients,
known as subscribers, based on a system of topics.

A topic in MQTT is a string that categorizes messages, acting as a channel where information is published, while
a subscriber is a device or application that listens to specific topics to receive those messages. For example, in a
smart home setup, a topic like home/energy/voltage might carry voltage readings, and a dashboard subscrib-
ing to this topic would receive and display those readings in real-time.

The broker ensures that messages are delivered efficiently and securely, even over unreliable networks. In IoT
applications, the MQTT broker is crucial for managing data exchange between sensors, devices, and systems
(which are the MQTT clients), enabling real-time monitoring, control, and automation.

20 November & December 2024 www.elektormagazine.com


Listing 1: The firmware (excerpt).
#include <WiFi.h>
#include <SPI.h>
#include <ATM90E32.h>
#include <MQTTPubSubClient.h>
#include <config.ino> // Include configuration file for WiFi and MQTT details

// WiFi Credentials
const char* ssid = WIFISSID; // Your WiFi SSID
const char* pass = WIFIPASSWORD; // Your WiFi Password

WiFiClient client;
MQTTPubSubClient mqtt;

ATM90E32 energymeter{};

void setup() {

...

/* Initialize the ATM90E32 energy meter with the specified parameters */


energymeter.begin(CS_PIN, LINEFREQ, PGA_GAIN, VOLTAGE_GAIN, GAIN_CT_A, GAIN_CT_B, GAIN_CT_C);

...

/* Begin the WiFi connection using the provided SSID and password */
WiFi.begin(ssid, pass);

/* Initialize the MQTT client */


mqtt.begin(client);

/* Connect to WiFi, MQTT broker, and Home Assistant */


connect();

...
}

void loop() {
/* Keep the MQTT client updated */
mqtt.update();

/* Reconnect to the MQTT broker if the connection is lost */


if (!mqtt.isConnected()) {
connect();
}

/* Check and send energy data to Home Assistant every 3 seconds */


static uint32_t prev_ms = millis();
if (millis() > prev_ms + 3000) {
prev_ms = millis();
getEnergyData(); // Retrieve energy data and send via MQTT
}
}

void getEnergyData() {

// Retrieve system status from the ATM90E32


unsigned short sys0 = energymeter.GetSysStatus0(); //EMMState0
unsigned short sys1 = energymeter.GetSysStatus1(); //EMMState1
unsigned short en0 = energymeter.GetMeterStatus0(); //EMMIntState0
unsigned short en1 = energymeter.GetMeterStatus1(); //EMMIntState1

// Print system and meter status for debugging


Serial.println("Sys Status: S0:0x" + String(sys0, HEX) + " S1:0x" + String(sys1, HEX));
Serial.println("Meter Status: E0:0x" + String(en0, HEX) + " E1:0x" + String(en1, HEX));
delay(10);

// Check if the MCU is not receiving data from the energy meter
if (sys0 == 65535 || sys0 == 0) Serial.println("Error: Not receiving data
f
       ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ ​​​​​​​ rom energy meter - check your connections");

// Retrieve all parameters from the ATM90E32


f
 ​​​​​​​ ​​​​​​​ loat lineVoltageA = energymeter.GetLineVoltageA();
f  ​​​​​​​ ​​​​​​​ loat lineVoltageB = energymeter.GetLineVoltageB();
f  ​​​​​​​ ​​​​​​​ loat lineVoltageC = energymeter.GetLineVoltageC();
...

// Send all the collected energy data via MQTT to Home Assistant
mqtt.publish("esp32energymeter/lineCurrentA", String(lineCurrentA).c_str());
mqtt.publish("esp32energymeter/lineCurrentB", String(lineCurrentB).c_str());
mqtt.publish("esp32energymeter/lineCurrentC", String(lineCurrentC).c_str());
mqtt.publish("esp32energymeter/totalCurrent", String(totalCurrent).c_str());

...
}

November & December 2024 21


allowing you to tailor the system to meet specific project
requirements. This level of control is particularly benefi-
cial for complex applications where you need to optimize
performance, integrate with non-standard hardware, or
implement advanced features like AI and machine learn-
ing algorithms.

Additionally, custom firmware allows for easier integration


with a wide range of platforms beyond just Home Assis-
tant, such as cloud-based services, custom dashboards,
and other IoT systems. You can also implement more
granular security measures, such as custom encryption
protocols or advanced authentication mechanisms, ensur-
ing that your data is secure across the network. Further-
more, individual firmware can be optimized for specific
use cases, reducing overhead and improving system
efficiency, which is especially important in resource-con-
strained environments.

The Software
The firmware is written to connect the ESP32 to a Wi-Fi
network and utilize MQTT for communication, allowing
the energy data to be sent to a Home Assistant server for
monitoring and automation purposes. In Listing 1, you
 can see an excerpt version of the code, as the entire code
and all hardware files can be accessed on the GitHub
Figure 1: Configuration repository of this project [2].
options for the MQTT
broker in Home
Assistant, including the The project relies on two key libraries: the ATM90E32
Start on boot option to library, provided by CircuitSetup [3], which handles
ensure automatic startup. the communication with the energy metering IC, and
the MQTTPubSubClient library [4], which manages the
communication as an MQTT client. The ATM90E32 library
is essential for collecting data from the energy meter
chip, including metrics like voltage, current, and power.
During the development process, a significant challenge
was encountered when integrating MQTT with username
and password authentication. While many MQTT libraries
can handle basic tasks, MQTTPubSubClient stood out
as one of the few that was compatible with the ESP32
and supported the necessary authentication features.

The software begins by including the necessary


libraries for network connectivity, SPI communication,
interfacing with the energy meter IC, and managing
MQTT communication. Configuration details for Wi-Fi
and MQTT are stored in a separate configuration file. The
setup() function initializes the serial port for debugging,
sets up the ATM90E32 energy meter with the specified
parameters, and establishes connections to the Wi-Fi
Figure 2: Setting up network and MQTT broker. This initial setup ensures that
MQTT integration in the ESP32 is ready to communicate with Home Assistant
Home Assistant with the
and other MQTT-compatible platforms.
IP address, port, and
user credentials.
In the main loop(), the MQTT client is continuously
 updated to maintain the connection with the broker. If

22 November & December 2024 www.elektormagazine.com


Defining the MQTT Data as Sensors in Home Assistant
To monitor the data sent by your ESP32 Energy Meter via MQTT, you need to define these data points as
sensors in Home Assistant. Follow these steps:

Access the Configuration File:


Open your Home Assistant configuration file (configuration.yaml) using the File Editor or any text editor.

Define MQTT Sensors:


In the configuration.yaml file, add the following configuration to define your MQTT sensors:

mqtt:
sensor:
- name: Line Voltage A
unique_id: esp32_voltage_a
state_topic: "esp32energymeter/lineVoltageA"
unit_of_measurement: "V"

- name: Line Current A


unique_id: esp32_current_a
state_topic: "esp32energymeter/lineCurrentA"
unit_of_measurement: "A"

Customize Your Sensors:


Replace Line Voltage A, Line Current A, etc., with names that suit your needs.
Ensure the state_topic matches the topic used in your ESP32 firmware for publishing the data. The
unique_id should be a unique identifier for each sensor, allowing Home Assistant to track and manage them
properly.

Save and Restart Home Assistant:


After adding the sensor definitions, save the configuration.yaml file and restart Home Assistant to apply the
changes.

View Your Sensors:


Once Home Assistant restarts, your MQTT sensors should appear in the dashboard, allowing you to monitor
the energy data in real-time.

the connection is lost at any point, the code automati- nection process if either the Wi-Fi or MQTT connection
cally attempts to reconnect. Additionally, the software is is lost. Debugging messages provide real-time feedback
programmed to retrieve energy data from the ATM90E32 on the connection status, and an LED is used to indicate
chip and send this data to the MQTT broker. This setup successful connections visually.
enables Home Assistant to monitor the energy consump-
tion in near real-time, providing valuable insights for home Setting Up an MQTT Broker on Home
automation. Assistant
To enable the ESP32 Energy Meter to use MQTT proto-
The getEnergyData() function plays a crucial role in col to send the meter reading, you’ll need to first set up
the software by collecting various energy metrics from an MQTT broker. An MQTT broker can be set up on
the ATM90E32 chip. These metrics include line voltage, almost any computer connected to your home network. It
current, power (active, reactive, and apparent), power can be configured on your PC using a Docker container,
factor, phase angle, frequency, and temperature. The installed directly on a Raspberry Pi, or even hosted on a
collected data is then published to specific MQTT topics, cloud server for remote access. However, to keep things
making it accessible for monitoring and analysis within simple and integrate seamlessly with your smart home
Home Assistant. For developers and users who enable setup, we’re going to set it up on Home Assistant.
debugging, the energy data is also printed to the Serial
Monitor, allowing for easy troubleshooting and valida- To install the MQTT Add-on in Home Assistant, start by
tion of the data. accessing your Home Assistant dashboard by navigat-
ing to the URL where your instance is running. From
To ensure that the ESP32 maintains a stable connection the sidebar, go to Settings, then Add-ons, and open the
to the network and the MQTT broker, the connect() Add-on Store. Search for MQTT, where you should find
function is included. This function handles the recon- the official Mosquitto broker in the results. Click on it

November & December 2024 23


Figure 3: Testing the
MQTT connection by and then select Install; the installation may take a few
subscribing to all topics
moments. Once installed, you can configure the MQTT
to ensure messages are
being received by Home broker by editing the configuration options — typically,
Assistant. the default settings are sufficient, but you can and should
set up a specific username and password. After configu-
 ration, click the Start button to activate the MQTT broker,
and enable the Start on boot option to ensure it starts
automatically whenever Home Assistant restarts, as
shown in Figure 1.

Next, you’ll need to configure MQTT integration within


Home Assistant. Go to Settings, then Devices & Services,
and select Integrations. Click on Add Integration, search
Figure 4: Custom for MQTT, and select it. Home Assistant will automatically
dashboard in Home detect the running MQTT broker. If prompted, configure
Assistant, visualizing the MQTT settings, such as the IP address of the broker
real-time energy data — usually localhost if it’s running on the same device as
from the ESP32 Energy
Home Assistant (you can also enter core-mosquito to
Meter.
get the same result). For the port, keep it default 1833,
 and for the username as password, make sure that user
credentials are of a current user in Home Assistant as
shown in Figure 2. You can also make a separate user
in Home Assistant just for MQTT in this case.

Now, we have to ensure Home Assistant is set up to


receive messages from your ESP32 Energy Meter. You
can test the connection by subscribing to a topic “#” to
receive all the messages sent to your MQTT broker, as
shown in Figure 3. This page is accessible by clicking
Configure in Integration entities in the MQTT integra-
tion menu item.

With the MQTT broker running on Home Assistant,


you can now connect your ESP32 Energy Meter.
In the config.ino file of your ESP32 firmware, set the
HOMEASSISTANT_IP to the IP address of your Home
Assistant instance. Then configure the DEVICE_NAME,
USER_ID, and PASSWORD if you have set up authentica-
tion on the MQTT broker. After configuring these settings,
flash the ESP32 with the firmware and ensure it connects
to the MQTT broker successfully. Once connected, the
ESP32 Energy Meter will begin publishing energy data
to the MQTT broker, which you can monitor in Home
Assistant by subscribing to the appropriate MQTT topics.

Finally, to visualize energy data in Home Assistant, the


MQTT entities will be automatically created for each topic
your ESP32 Energy Meter publishes. If not, what can
happen sometimes, you will have to define the MQTT
entities in the configurations.yaml file in Home Assis-
tant. You can follow the instructions mentioned in the
text box Defining the MQTT Data as Sensors in Home
Assistant.
Figure 5: Example of graphs created in Home Assistant to monitor energy consumption in
the History dashboard.

24 November & December 2024 www.elektormagazine.com


After that, you can find the sensor entities under Settings
in Home Assistant, then Devices & Services, and Entities.
Use these entities to create custom dashboards in Home
Assistant, allowing you to visualize real-time energy data,
to create graphs, and to set up alerts based on consump-
tion thresholds as shown in Figure 4 and Figure 5. With
MQTT and Home Assistant, you can also automate
actions based on energy data as shown in Figure 6,
integrate with other smart devices, and gain valuable
insights into your home’s energy usage.

For beginners, I recommend checking out the Getting


Started Guide by Home Assistant [5], which provides
a comprehensive introduction to setting up and using
Home Assistant. Additionally, you can explore the Home 
Assistant MQTT Integration Documentation [6][7] for
Figure 6: Automated
detailed instructions on configuring MQTT and integrating
actions in Home
your devices effectively. These resources will help you get Assistant based on
up and running with Home Assistant and MQTT, making energy data received
your smart home setup more efficient and user-friendly. Visit our Power
IoT & Sensors
Electronics
page from the ESP32 Energy
240349-01 forEnergy
& page
articles, projects,
for articles,
news, and Meter via MQTT.
videos. news, and videos.
projects,
www.elektormagazine.com/
power-energy
iot-sensors
About the Author
Saad Imtiaz, Senior Engineer at Elektor, is a mecha-
tronics engineer with extensive experience in embed-
ded systems and product development. His journey
has seen him collaborate with a diverse array of
companies, from innovative startups to established
global enterprises, driving forward-thinking prototyp-
ing and development projects. With a rich background
that includes a stint in the aviation industry and leader-
ship of a technology startup, Saad brings a unique
blend of technical expertise and entrepreneurial spirit
to his role at Elektor. Here, he contributes to project
development in both software and hardware.
Related Products
Questions or Comments? > Home Assistant Green
If you have questions about this article, feel free to www.elektor.com/20725
email the author at saad.imtiaz@elektor.com or the
Elektor editorial team at editor@elektor.com.
> Raspberry Pi 5 (2 GB RAM)
www.elektor.com/20951

WEB LINKS
[1] Saad Imtiaz, “Project Update #3: ESP32-Based Energy Meter,” Elektor 7-8/2024:
https://elektormagazine.com/240244-01
[2] ESP32 Energy Meter Github Repository: https://github.com/ElektorLabs/esp32-energymeter
[3] ATM90E32 Arduino Library by CircuitSetup: https://github.com/CircuitSetup/ATM90E32
[4] MQTTPubSubClient Library by hideakitai: https://github.com/hideakitai/MQTTPubSubClient
[5] Getting started, Home Assistant: https://www.home-assistant.io/getting-started/
[6] MQTT Integration, Home Assistant: https://www.home-assistant.io/integrations/mqtt/
[7] MQTT Sensor, Home Assistant : https://www.home-assistant.io/integrations/sensor.mqtt/

November & December 2024 25

You might also like