DIY ESP32 AC Power Meter (with Home Assistant/Automation Integration)

**The Power Meter Project: Measuring Electrical Energy Consumption with ESP32**

As you probably know, we use electric power pretty much all the time during our daily life. We use it to create light, cook a meal, print documents, watch TV and so on. That is why it is no wonder that the average electrical energy consumption is pretty high nowadays. I have the goal of lowering mine though, and what better way to do so than by being constantly exposed to my power consumption which will hopefully remind me that having one light bulb is enough.

In this video, I will show you how to use the ESP32 and some complementary components in order to create a proper power meter that can spit out pretty much all important power values. At the end, I will then show you how to integrate this meter into my home assistant system which I presented you in one of my previous videos.

This way, I can see my power consumption at any time and make informed decisions about my energy usage.

**Understanding the ESP32 Power Meter**

To create a power meter using an ESP32 board, we need to understand how it works. The ESP32 has an analog-to-digital converter (ADC) that can read the voltage from a current transformer (CT). A CT is used to measure the current flowing through a wire, and its output is proportional to the current.

In this project, I used an ESP32 board with an ADC range of 3.3V. However, the voltage from the CT was too high for the microcontroller, so we need to reduce it using a voltage divider circuit.

The current transformer has a ratio of 1000:1, which means that if there is 5A flowing through the primary side, the output on the secondary side will be 5mA. This low-voltage signal can then be read by the ESP32's ADC.

**Calibrating the Power Meter**

To get accurate readings from the power meter, we need to calibrate it using a known power source. In this case, I used my laptop charger as a reference. By adjusting the calibration variables in the code, I was able to get the power meter to read close to the actual value.

The accuracy of the power meter is not as good as that of a commercial energy meter, but it is still acceptable for monitoring purposes. With some tweaking and adjustments, we can get the readings to match closely with those from an energy multimeter.

**Integrating the Power Meter into Home Assistant**

To integrate the power meter into my home assistant setup, I had to create a custom sensor using ESPHome. This involved uploading the EmonLib library files and creating a new .h file with the necessary code.

After compiling and uploading the code, I was able to add the power values to my overview board, which still works fine.

**Conclusion**

In this project, we created a simple power meter using an ESP32 board and some complementary components. We learned how to calibrate it using a known power source and integrate it into our home assistant setup.

While the accuracy of the power meter is not as good as that of a commercial energy meter, it can still be used for monitoring purposes. With some tweaking and adjustments, we can get the readings to match closely with those from an energy multimeter.

I hope you enjoyed watching this project! Don't forget to like, share, subscribe, and hit the notification bell. Stay creative and I will see you next time!

WEBVTTKind: captionsLanguage: enAs you probably know we use electric powerpretty much all the time during our dailylife.We use it to create light, cook a meal, printdocuments, watch TV and so on.That is why it is no wonder that the averageelectrical energy consumption is pretty highnowadays.I have the goal of lowering mine though andwhat better way to do so than by being constantlyexposed to my power consumption which willhopefully remind me that having one lightone is enough.So in this video I will show you how to usethe ESP32 and some complementary componentsin order to create a proper power meter thatcan spit out pretty much all important powervalues and at the end I will then show youhow to integrate this meter into my home assistantsystem which I presented you in one of myprevious videos.This way I can see my power consumption atall times on my smartphone which is prettyhandy and shocking at the same time.And with that being said let’s get started!This video is sponsored by JLCPCB, who currentlyoffer a variety of promotions.Not only can you get 4 Layer PCBs for a priceof just 2$ but you can also visit their virtualonline exhibition at which you have a 100%chance of winning prices.So have a look for yourself.First off how can we use a microcontrollerin order to measure/calculate power?Well before giving you a basic overview Iwould recommend you to watch my basics videoabout true, reactive, apparent and deformedpower in order to get a true understandingof the subject.And with that being said let’s just simplyget an old school light bulb and hook it upto the power grid while having a look at itscurrent flow and its used voltage.As you can see the voltage features the typicalsinusoidal shape with a top value of 326V,an RMS value of 231V and a frequency of 50Hz,so all normal values here in Germany.If we now observe the current, we can seethat the waveform is also sinusoidal and itfollows the voltage waveform.That means our load is resistive which meansit is the simplest load we can deal with.If we would hook up an inductive load likea motor then the current waveform would belagging and if we would hook up a capacitiveload then the current waveform would be leading.And if we got the most difficult load to workwith like a laptop power supply then the currentcan look something like this with currentspikes near the voltage peaks.Now you might be surprised but it is actuallynot that difficult to calculate the real powerof those 4 voltage and current waveforms butlet’s start with the simplest one.The formula for calculating real power lookssomething like this which might seem a bitscary but by using the math function of myoscilloscope I can partly visualize the formulaon screen.The newly shown waveform is the multiplicationof the voltage and current values in eachsampled point and it represents the real powerconsumption over time.And if we would add up all of the area underneaththis waveform then we would get the averagereal power consumption.But let’s make it a bit more difficult byhaving a look at an inductive load.As you can see we still got mostly positivepower values but this time also some negativepower values.Those values are not real power since thispower form only oscillates between the powersource and load.So by subtracting this negative area fromthe positive one, we once again get the averagereal power we are looking for.Similar negative power areas appear for capacitiveloads and also for our laptop charger loadbut you should now understand how to calculatethe real power consumption of them as well.Now to sample the voltage and current withour microcontroller we will need a safetytransformer for the voltage and a currenttransformer for obviously the current.What the microcontroller will do is samplethe current and voltage waveform a specifiedamount of times per half wave.Then it will multiply the values with oneanother, sum them up and divide them by theamount of samples and just like that we getan average real power measurement.Along the way the microcontroller will alsocalculate the RMS Voltage and RMS currentand use it to calculate the apparent powerand then finally the power factor but if youwant to learn more about those terms thendefinitely have a look at the openenergymonitor.orgwebsite which has tons of great informationand I will also be using their EmonLib libraryin order to make programming easier for me.But anyway with the theory out of the wayhow exactly do we have to hook up the twotransformers to the microcontroller.To find that out I connected my safety transformerto mains voltage but let me tell you thatworking with mains voltage can be lethal ifnot handled correctly, you have been warned.After then adding wire bridges to its outputterminals, like its shown on its label toget 12V AC, I hooked up my oscilloscope probesin order to find out that I was getting 39Vpeak to peak which is of course a way toohigh for my 3.3V microcontroller.To safely use it, we not only have to reducethe voltage but also let it swing around anoffset of for example half the supply voltageso that the microcontroller can properly samplethe waveform with its Analog to Digital Converter.So what we need is basically such a circuit.After adding all of the components to themicrocontroller and the transformer we cansee how the voltage is now definitely suitablefor our task which brings me to the currenttransformer.I got this one from EBay for pretty cheapand it can handle a maximum current of 5Aand comes with a Ratio of 1000:1.That means as soon as we pass a live wirethrough its core and power a load so thatcurrent flows through it, the created magneticfield of the primary side will create a currentthrough the secondary side which will be 1000times lower.So at for example 5A we would get a currentflow of 5mA which will create a voltage dropof 1V since the current transformer uses aburden resistor of 200 ohms.Now to make this 1V current signal suitablefor the microcontroller I will using thissimple circuit which just adds an offset.After building it up, we can see on the oscilloscopethat all values are now in the desired rangeso it was time to hook up the voltage andcurrent signal wires to pin 34 and 35 of theESP32 respectively.For the software side I already told you thatI will be using an ESP32 version of the EmonLiblibrary but what I haven’t told you yetis that you should definitely browse throughtheir included .cpp file in order to see somebeautiful well explained math on how to calculateall the values.But anyway after uploading the given examplecode and connecting my energy multimeter tothe load in order to check whether the calculatedvalues are all correct, I noticed that prettymuch nothing was correct yet.The problem was that the current and voltagecalibration variables were not adjusted yet,but after fiddling around with them for quitea while I reached a sweet spot.As you can see we can measure pretty similarpower values with my complicated laptop chargerbut also with more high power loads like mytoaster.Of course there are accuracy differences betweenmy 1000€ energy meter and this 30€ ESP32meter but overall I was rather impressed withthis build.So time to integrate it into my home assistantsetup but sadly I quickly noticed that theEmonLib library is not supported by ESPHome.That is why I browsed through the availabletutorials in order to learn how to createa custom sensor.To do that all I had to do was to upload theemonlib.h and emonlib.cpp file to the esphomefolder and then create a new .h file intowhich I more or less copied the example Arduinocode.After then altering the code of my new ESP32node, it compiled and uploaded without anyproblems.That means it was time for me to add all thepower values to my overview board and as youcan see everything still seems to work justfine, awesome.So as a last step I soldered my ESP32 to aperfboard and added proper wiring to my complementarycomponents in order to add them to my homedistribution box for a test.And I am only doing a test here because Icurrently do not have the space inside myhome distribution box to permanently mountall of the components there so I will haveto come up with a solution for that in thefuture.But nevertheless the power meter still worksperfectly fine and I hope you enjoyed watchingthis project.If so don’t forget to like, share, subscribeand hit the notification bell.Stay creative and I will see you next time!