Using an ESP32 MCU with Voltage and Current Sensors
To continuously monitor energy consumption in his home, and store and communicate the data wirelessly, Gamal built a 3-phase energy meter, using a single ESP32 MCU with dual-core architecture, and voltage and current sensors. In his novel design, one core senses voltage and current and calculates consumed energy, while the other, long-forgotten core handles the user’s web requests, logs measurements on an SD card, and displays current, voltage, and cumulative power consumption.
Understanding the energy consumption pattern of home appliances and gadgets is important for owners to optimize and to minimize their electricity bills. Keeping track of the official energy meter to identify our daily consumption may prove impractical, especially if the meter is installed outside the premises. I needed an inexpensive solution to adjust my electricity consumption and to estimate future bills.
I came across many energy meter projects based on microcontrollers (MCUs) and sensor modules, but they mostly focused on single-phase mains power supplies. Since I have 3-phase mains, I would then require three homemade meters and offline analysis of their readings to manage my consumption. In this project, I consolidate the mains supply monitoring for my home into a single MCU-based meter for which I can embed all analysis code once, and control it within my home Internet of Things.
I chose the ESP32 MCU for this project for several reasons. It supports Wi-Fi and Bluetooth for remote access. It supports many analog GPIOs required by the voltage and current sensors. And above all, it has dual core architecture, a feature rarely found in its price range. It looks like embedded systems designers overlooked the duality-of-core feature and kept using 50% of the MCU processing capabilities, at least for energy meter projects.
I considered the duality of cores a prerequisite for a 3-phase meter, since processing voltage and current data is triple that of the regular workload of a single-phase meter. Furthermore, serving user’s queries and commands would interrupt the energy measurement process, so it requires a separate core to guarantee consistency. The ESP32 provides an abundance of memory that enables it to run multimedia and AI applications. This makes it a good fit for this project which is rather large in code size. It takes around 80% of the ESP32’s 1.25MB program memory, indicated in the Arduino IDE compilation output for the project’s sketch as indicated:
Sketch uses 1,063,197 bytes (81%) of program storage space. Maximum is 1,310,720 bytes.
Global variables use 50,516 bytes (15%) of dynamic memory, leaving 277164 bytes for local variables. Maximum is 327,680 bytes.
HARDWARE
The meter project is housed in a waterproof plastic box 15cm×11cm×8cm and is built around the ESP32-WROOM-32U development board, alongside three ZMPT101B [1] voltage sensing modules [2], an SD Card module, and three 7-segment 8-digit display blocks [3] (Figure 1). There are also three SCT-013 60A/1V AC current sensors [4] external to the meter and hooked to the mains power supply feeding cables (Figure 2). A sample display per phase for the cumulative consumed power (in one-hundredth accuracy), the instant AC voltage and current (in one-tenth accuracy) is shown in Figure 3.

The exterior structure of the project. Top: three 7-segment 8-digit modules, each of which is allocated to a specific mains supply phase. Mid-right: an MCU reset red button, a yellow push button to display button. Mid-bottom: five LED indicators (from right)—Blink, Wi-Fi connectivity, 5V power supply, Activity, and External MCU power source (for example, Laptop’s USB port). Bottom right: DC 5V jack, MCU power source selector switch, Continuous Display switch.

The ZMPT101B voltage sensor module (left) and SCT-013 60A/1V current sensor transformer (right).

The three 7-segment display blocks—one block per mains power phase. The top line shows the consumed energy in kilowatt hours (kWh), the middle is for voltage (V), and the bottom shows the current in Amperes (A).
Figure 4 depicts the peripherals wiring to the MCU. Their VCC is fed directly from the external 5V DC adapter, except for the current sensing bridge, which is powered from the MCU’s onboard 3.3V regulator. Figure 5 illustrates the wiring of the project sensors to my home electrical switching panel, which became a little bit cluttered following some modifications to balance the load distribution on the 3-phase supply. I used a clamp-type current meter to help me tune and verify the driving sketch code of my current sensors.

Wiring the display and voltage and current sensing modules to the MCU. The 3.3V feed to the current sensing bridge (10kΩ, 10μF) is fed from the MCU development board. The LEDs are wifiSTAT (green), ACTIVITY (red), and BLINK (blue), and they use 220Ω resistors. The selector switch forces continuous display (segON in code), and the push button enables on-demand display for a specified duration (segSW in code).

Wiring the project box to the mains power supply fuse panel (left). Wiring the blue current sensors (middle). Verifying current measurement using AC current multimeter (right).
WORKING WITH THE ESP32’S DUAL CORE ARCHITECTURE
This MCU has two identical cores—Core-0 and Core-1—sharing its program memory and RAM. They both have equal access to the device’s GPIOs and thus to its connected peripherals. The default core used in single core applications is Core-1. To utilize both cores, we need to code the device using the real-time operating system (RTOS) supplied by the MCU manufacturer, and that one is already built into the ESP32 hardware core for the Arduino IDE v.2.3.2. So, instead of building a traditional sketch composed of a setup() and a loop() section, we need to forget about putting any code in the latter section, and just declare two special functions (called “tasks” in RTOS terminology) in the setup() section. Each task configures the resources allocated to a specific core. The implementation of those functions in the sketch contains all the code we need to set up the hardware under the control of the relevant core at MCU startup, and also the code that will continue to run by the core throughout the uptime of the MCU.
I always maintain modularity when writing complex project code, since it helps debugging and reusability. This explains why the structure of the project sketch is composed of six files, alongside the main ino file, in which we declare the two tasks that will run on the MCU cores. Each file contains declarations and functions relevant to a specific peripheral. I identified the peripherals as the SD card module (SD_Functions.h), the MCU built-in Wi-Fi module (Wlan.h), the display modules (Display.h), and the clock module (Clock.h), in addition to the two cores (task0.ino and task1.ino).
Referring to Listing 1, we see the invocation of RTOS by declaring the two tasks of class type TaskHandle_t, then in the setup() section we emphasize their configuration in xTaskCreatePinnedToCore() functions. A task configuration includes the name of the relevant task implementation (for example, Task0code and Task1code), which will be detailed in separate ino sketch files, the task name (for example, Task0 and Task1), the task’s core ID (for example, 0 and 1), the task’s priority on its assigned core, and the task’s stack size. I did some trial and error work for setting up the latter two configuration settings. The highest priority is set to 1, while increasing its value may cause some activities to break—such as wireless LAN setup, which fails at priority 100. As for the stack size, I found that 100,000 bytes is the achievable maximum beyond which the core fails to work, whereas 10,000 bytes is an operable setting for this project.
LISTING 1
The setup() section of the sketch declaring the shared GPIOs between cores and the RTOS task assigned to each core. The implementation of those tasks is detailed in two separate header files within the sketch.
TaskHandle_t Task0;TaskHandle_t Task1;void setup() { analogReadResolution(10); pinMode(segSW, INPUT_PULLUP); // toggle switch 7-segments display ON/OFF pinMode(segON, INPUT_PULLUP); // selector switch 7-segments display ON pinMode(wifiSTAT, OUTPUT); // state of wiFi connection pinMode(ACTIVITY, OUTPUT); // ACTIVITY in sensing pinMode(BLINK, OUTPUT); // blink periodically delay(200); digitalWrite(wifiSTAT, LOW); digitalWrite(ACTIVITY, LOW); digitalWrite(BLINK, HIGH); Serial.begin(115200); xTaskCreatePinnedToCore( Task0code, /* Task function. */ “Task0”, /* name of task. */ 10000, /* Stack size of task */ NULL, /* parameter of the task */ 1, /* priority of the task */ &Task0, /* Task handle to keep track of created task */ 0); /* pin task to core 0 */ delay(500); xTaskCreatePinnedToCore( Task1code, /* Task function. */ “Task1”, /* name of task. */ 10000, /* Stack size of task */ NULL, /* parameter of the task */ 1, /* priority of the task */ // when priority was set to 100 then network scan would not complete &Task1, /* Task handle to keep track of created task */ 1); /* pin task to core 1 */ delay(500);}
TASK#0 RUNNING ON CORE-0
Looking into the implementation of each task, refer to Listing 2, which illustrates the setup section of the task#0 for handling the SD card module, the wireless LAN, the Web application server, the NTP service, and the 7-segment display. The SD card module is hooked to VS-SPI of the MCU and is used to keep a log file of periodically sensed measurements (for example, every 15 minutes), and a summary file for the accumulated power consumption per mains supply phase. Wi-Fi is required to link the meter to the Internet for adjusting local timestamps of logged data by synching with a global NTP server, and for maintaining a Web server to serve the user’s requests.
LISTING 2
The setup section of Task#0 for the SD card, the wireless LAN, the 7-segment display, and the Web application.
void Task0code(void* pvParameters) { Serial.print(“++++++++++++++++++++++ Task0 running on core “); Serial.println(xPortGetCoreID()); sd_setup(); checkFiles(); wlan_setup(); web_setup(); show_time(); initialise(); // initialize 7-segments displays delay(2000);
The server handles a set of client requests, such as listing logged data, listing accumulated power consumption per phase, resetting its calculation to zero, and erasing log file (that is, recycling the file). Figure 6 illustrates some Web client queries to the energy meter, using its IP address (in my case it is “192.168.1.182”), or its DNS host name (in my case it is “energy-3p.local”). The Web server responds to a few keywords in the client’s URL queries such as “sum” to show the accumulated power consumption in kWh per phase from the summary file, “list” to display the log file records, “clear” to erase the summary file, and “erase” to erase the log file.
Listing 3 shows the loop section of Task#0 marked by the for(;;) statement, by which Core-0 continuously checks for Web client requests to serve, and periodically logs sensed data into the SD card, and displays sensed data on the 7-segment display.
LISTING 3
The loop section of Task#0 for continuous handling of the 7-segment displays and the sensed data files stored on an SD card, and user access via the Web application.
for (;;) { server.handleClient(); if (digitalRead(segSW) == 0 && digitalRead(segON) == 1) { initialise(); show_Data(); } ++show_timer0; if (show_timer0 >= SHOWCNT) { digitalWrite(ACTIVITY, !digitalRead(ACTIVITY)); digitalWrite(BLINK, !digitalRead(BLINK)); show_timer0 = 0; if (digitalRead(segON) == 0) { initialise(); show_Data(); } if (digitalRead(segSW) == 1 && digitalRead(segON) == 1) initialise(); } process_logfile(); // invokes processing log and summary files // ================================================== }}
The benefit of dedicating a MCU core to run those activities can be demonstrated simply when the user requests a list of thousands of logged data records from the SD card without disrupting the current and voltage sensing activity, thus power consumption calculations become credible.
Activating the 7-segment display is designed to work in two modes: continuously showing logged data by turning on the designated selector switch (shown in Figure 1 and Figure 4), which is wired to GPIO16 (for example, the segON in Listing 3) of the MCU, or manually by pressing the yellow push-button (Figure 1), which is wired to GPIO17 (for example, segSW). I coded the Blink and the Activity LEDs to fluctuate interchangeably to give the feeling of system alive, while fluctuation is suspended during the serving of Web client requests and resumes afterward.
Note that working with multicore architecture required re-initializing the 7-segment display blocks prior to showing any data for each round of the loop section of the task.
TASK#1 RUNNING ON CORE-1
Task#1 is responsible for continuously sensing AC current and voltage, and for calculating the power consumption. Monitoring the AC current using the SCT-013 sensor is based on the Emonlib library [5]. I emulated the Simply Explained blog [6] that dealt with a single phase mains supply, and I modified their code to fit my objective of handling a 3-phase source (see Listing 4). I faced some difficulty adjusting the resistor bridge to get AC current readings matching those of the clamped multimeter. I settled on a resistor value of 10kΩ for the voltage divider circuit, but still got some current reading of few hundred milliamps at no load condition. I worked around this by ignoring readings below 500mA and rounding whatever was above that to 1.0A. I put this statement in the code to do that:
if (Irms < 1.0) Irms = round(Irms);
LISTING 4
Task#1 runs on Core-1 for sensing voltage and current of each mains supply phase, and for calculating the corresponding consumed energy per second. The hourly consumed power is then calculated by scaling the per-second calculation to per-hour. Irms, RMSPower, and kilos for phases 2 and 3 are replicates of the shown phase 1 calculations.
void Task1code(void* pvParameters) { Serial.print(“====================== Task1 running on core “); Serial.println(xPortGetCoreID()); analogReadResolution(10); emon1.current(iPORT1, 60); // Current: input pin, calibration emon2.current(iPORT2, 60); // Current: input pin, calibration emon3.current(iPORT3, 60); // Current: input pin, calibration RunningStatistics inputStats1; RunningStatistics inputStats2; RunningStatistics inputStats3; inputStats1.setWindowSecs(windowLength); inputStats2.setWindowSecs(windowLength); inputStats3.setWindowSecs(windowLength); for (;;) { Serial.print(“====================== Task1 running on core “); Serial.println(xPortGetCoreID()); while (true) { Sensor = analogRead(vPORT1); // read the analog in value: inputStats1.input(Sensor); // log to Stats function Sensor = analogRead(vPORT2); // read the analog in value: inputStats2.input(Sensor); // log to Stats function Sensor = analogRead(vPORT3); // read the analog in value: inputStats3.input(Sensor); // log to Stats function if ((unsigned long)(millis() - previousMillis) >= printPeriod) { Serial.print(“====================== Task1 running on core “); Serial.println(xPortGetCoreID()); previousMillis = millis(); // update time every second current_Volts1 = intercept + slope * inputStats1.sigma(); //Calibartions for offset and amplitude current_Volts1 = current_Volts1 * (48); //Further calibrations for the amplitude current_Volts2 = intercept + slope * inputStats2.sigma(); //Calibartions for offset and amplitude current_Volts2 = current_Volts2 * (48); //Further calibrations for the amplitude current_Volts3 = intercept + slope * inputStats3.sigma(); //Calibartions for offset and amplitude current_Volts3 = current_Volts3 * (48); //Further calibrations for the amplitude Irms1 = emon1.calcIrms(1480); // Calculate Irms only if (Irms1 < 1.0) Irms1 = round(Irms1); // ignore small loads RMSPower1 = current_Volts1 * Irms1; //Calculates RMS if (RMSPower1 > peakPower1) peakPower1 = RMSPower1; kilos1 = kilos1 + (RMSPower1 * (2.05 / 60 / 60 / 1000)); //Calculate kilowatt hours used
I assume such an approximation does not affect the legitimacy of my energy meter project, since my concern is tracking heavy loads that bring bulky bills. Furthermore, I discovered some facts about my appliances’ consumption of energy, and this led me to pay attention to economizing their usage. For example, the microwave and 1hp water pump are rated at [5.0A ≈ 1hp Air Conditioner], whereas the solar water heater (in winter) and an electric kettle require 10.0A.
As for AC voltage measurement using the ZMPT101B voltage sensor module, the calculations are based on the Filters library [7]. I followed the example of the SURTR TECHNOLOGY blog [8], but still also tailored their code to fit the 3-phase power source. Coarse calibration of the voltage module can be done using its built-in potentiometer, and this is necessary for each phase; then fine tuning the readings should be done by adjusting the value in this statement in Listing 4:
current_Volts1 = current_Volts1 * (48);
You might notice fluctuations in the voltage readings of each phase, even though they are almost identical. I assume this case is somehow an exaggeration of what you see in digital multimeters that show minor reading fluctuations. Furthermore, I came across some energy meter projects in which the mains voltage is fixed to some value (such as 230V) to simplify the design.
A printout on the Arduino IDE serial monitor for the meter in action is shown in Figure 7, in which the MCU startup and run for Core-0 and Core-1 activities are shown. Task#0 shows its preliminary check of SD Card files, then at some point, it confirms serving a Web client request, and later on it appends a log record to the log file. Task#1 shows its acquired measurements for instant voltage, current, energy, kWh per-second, and maximum recorded energy.
This project draws a high current of more than 4A due to the nature of the ESP32 itself, and for the extensive peripherals I put into it, including the 7-segment displays, the SD card module, and the voltage-sensing modules. Smaller DC current source will disable the operation of the SD Card module and dim the 7-segment display.
CLOSING REMARKS
A 3-phase energy meter design is presented in a novel way, utilizing the dual-core architecture of the ESP32 MCU. One core is dedicated to continuous sensing of AC current and voltage. The other core handles the user’s web requests, and manages logging measurements on an SD card and displaying instant AC current and voltage on the 7-segment display alongside cumulative power consumption.
REFERENCES
[1] https://5nrorwxhmqqijik.leadongcdn.com/ZMPT101B+specification-aidijBqoKomRilSqqokpjkp.pdf
[2] https://www.electroschematics.com/voltage-sensor/
[3] https://fares-pcb.com/product/332-digits-56-7-segment-display-module-red-color-56d332/
[4] https://bcrobotics.com/datasheets/yhdc.pdf?srsltid=AfmBOoqkTs0ms3bt2v_trOm9ViT9D3KVHDA_P7ISxzT2nxTJgsZ23LrU
[5] https://github.com/Savjee/EmonLib-esp32
[6] https://simplyexplained.com/blog/Home-Energy-Monitor-ESP32-CT-Sensor-Emonlib/
[7] https://github.com/JonHub/Filters
[8] https://surtrtech.com/2019/01/21/easy-measure-of-ac-voltage-using-arduino-and-zmpt101b/
RESOURCES
Fares PCB | www.fares-pcb.com
PUBLISHED IN CIRCUIT CELLAR MAGAZINE • MAY 2025 #418 – Get a PDF of the issue
Sponsor this Article