/ #esp32 #home assistant 

Turn ESP32 Into a Smart Energy Meter with Home Assistant Integration

I’ve always been a bit obsessed with data, especially when it comes to understanding my home’s energy consumption. After getting hit with a surprisingly high electricity bill last winter, I decided it was time to stop guessing and start measuring. Commercial smart plugs with energy monitoring are great, but what if you want to monitor a whole circuit, like your kitchen or workshop? That’s when I decided to turn an ESP32 into a smart energy meter.

This project will guide you through building your own open-source, highly accurate energy monitor that integrates seamlessly with Home Assistant. We’ll use inexpensive current sensors and the fantastic ESPHome platform, which makes the software side a breeze. Let’s get shocked by the data, not the bill!

What You’ll Need

Before we dive in, let’s gather the components. I’ve tried to keep this budget-friendly and accessible.

Hardware Components

  • ESP32 Development Board: The brains of the operation. Its built-in analog-to-digital converter (ADC) is key. I used a generic ESP32 DevKit C1.
  • ACS712 Current Sensor (30A variant): This is a hall-effect-based sensor that safely measures AC and DC current. Alternatively, for a more robust and accurate solution, consider the SCT-013-030 (a non-invasive current transformer clamp) paired with a burden resistor.
  • Breadboard and Jumper Wires: For prototyping without soldering.
  • Micro-USB Cable: To power the ESP32.
  • AC Power Cord & Plug: (ADVANCED - USE WITH EXTREME CAUTION) To create a safe enclosure for a plug-in monitor. Warning: This involves working with mains voltage, which is dangerous if not handled properly.

Tools & Software

  • Home Assistant: Your home automation hub, already set up.
  • ESPHome Add-on: The magic tool that will compile and flash our firmware.
  • A Computer: To configure and flash the ESP32.
⚠️ Safety First! This project involves working with or near mains electricity. If you are not confident or experienced in dealing with high voltage, please use an pre-made enclosure for the AC cord parts or consider a project that uses pre-assembled smart plugs. You are responsible for your own safety.

Step 1: Understanding the Hardware Setup

The core principle is simple: the current sensor measures the flow of electricity, the ESP32 reads this measurement, and ESPHome translates it into useful data for Home Assistant.

I started with the ACS712 because it’s easy to wire, but I later upgraded to the SCT-013 for better accuracy and safety, as it doesn’t require direct contact with the live wire. For this tutorial, I’ll show the wiring for both.

Wiring the ACS712 Sensor

The ACS712 has three pins:

  • VCC: Connect to the ESP32’s 5V pin.
  • OUT: Connect to an analog pin on the ESP32 (e.g., GPIO 34).
  • GND: Connect to the ESP32’s GND.

The sensor is placed in series with the load (the appliance you’re measuring). This means you have to break the live wire and run it through the sensor, which can be a bit fiddly.

The SCT-013 is a current transformer (CT clamp). It clamps around the live wire, making it completely non-invasive and much safer.

  • The output wires of the SCT-013 connect to a burden resistor (typically 22-50Ω) across its terminals.
  • The point between the resistor and one of the wires is then connected to an analog pin (e.g., GPIO 34) and a GND pin on the ESP32.

Here’s a simple diagram for the SCT-013 setup:

SCT-013 Clamp ---> Burden Resistor
                     |
                     +--- GPIO 34 (Analog Input)
                     |
                     +--- GND

Step 2: Flashing the ESP32 with ESPHome

Now for the software part, which is surprisingly simple thanks to ESPHome.

  1. In your Home Assistant instance, go to Settings > Add-ons.
  2. If you haven’t already, install the ESPHome add-on and start it. I also recommend enabling “Start on boot” and “Watchdog”.
  3. Open the ESPHome dashboard and click the + button to create a new device.
  4. Give your device a name, like smart-energy-meter, and select your ESP32 board type.
  5. ESPHome will generate a basic configuration file. Now, we need to customize it heavily for our energy monitor.

Step 3: The ESPHome Configuration Magic

This YAML configuration is the heart of the project. It tells the ESP32 how to read the sensor and what data to send to Home Assistant. I’ve commented the code extensively to explain what each section does.

Replace the entire contents of your new device’s YAML file with the following. This example uses the SCT-013 sensor.

substitutions:
  devicename: smart-energy-meter
  friendly_name: Smart Energy Meter

esphome:
  name: $devicename
  friendly_name: $friendly_name

esp32:
  board: nodemcu-32s
  framework:
    type: arduino

# Enable logging and the Home Assistant API
logger:
api:
ota:
wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password

  # Optional: Add a fallback hotspot
  ap:
    ssid: "${friendly_name} Fallback Hotspot"
    password: !secret fallback_password

captive_portal:

# Sensor configuration for the SCT-013
sensor:
  - platform: adc
    pin: GPIO34
    id: sct013_raw
    name: "Raw Current Value"
    internal: true # We don't need to see this in HA, it's for calibration
    update_interval: 1s
    filters:
      - lambda: return (x / 4095.0) * 3.3; # Convert ADC reading to voltage
      - calibrate_linear:
          # Map the input voltage to the measured current.
          # This is the most important calibration step!
          # You MUST calibrate this for your specific setup.
          # The formula is: Voltage = (Current / Sensor Range) * Vcc
          # For SCT-013-030 (30A) with a 33Ω burden resistor and 3.3V Vcc:
          # 0A -> Vcc/2 = 1.65V
          # 30A -> ~2.88V, -30A -> ~0.42V
          - 0.42 -> -30.0
          - 1.65 -> 0.0
          - 2.88 -> 30.0

  - platform: template
    name: "${friendly_name} Current"
    id: current_sensor
    unit_of_measurement: "A"
    accuracy_decimals: 2
    icon: "mdi:current-ac"
    # Calculate RMS current from the raw sensor
    lambda: |-
      static float filtered_value = 0.0;
      // Simple low-pass filter to smooth the readings
      filtered_value = filtered_value * 0.9 + id(sct013_raw).state * 0.1;
      // For AC, we should calculate RMS, but for simplicity and with calibration,
      // the absolute value is often sufficient for home monitoring.
      return abs(filtered_value);      
    update_interval: 1s

  - platform: template
    name: "${friendly_name} Power"
    id: power_sensor
    unit_of_measurement: "W"
    accuracy_decimals: 1
    icon: "mdi:flash"
    # Power (W) = Current (A) * Voltage (V) * Power Factor
    # We assume a constant voltage (e.g., 230V) and a power factor of 1 for resistive loads (like heaters, incandescent bulbs).
    # For more accuracy, you could integrate a voltage sensor as well.
    lambda: |-
            return id(current_sensor).state * 230.0;
    update_measurement: current_sensor # Update this sensor whenever the current updates

  - platform: total_daily_energy
    name: "${friendly_name} Daily Energy"
    power_id: power_sensor
    unit_of_measurement: "kWh"
    accuracy_decimals: 3
    icon: "mdi:chart-line"
    filters:
      - multiply: 0.001 # Convert from Wh to kWh
💡 Pro Tip: Calibration is Key! The calibrate_linear section in the code is the most critical part for accuracy. The values I provided are a starting point for a 30A SCT-013 with a 33Ω burden resistor. The best way to calibrate is to compare your sensor's reading with a known, reliable device (like a commercial smart plug) under a consistent load (e.g., a 100W bulb).

After pasting this code, click Save and then Install. Choose the “Plug into the computer running ESPHome Dashboard” method and follow the on-screen instructions to flash your ESP32.

Step 4: Integrating with Home Assistant

If all went well, this is the easiest step. Once the ESP32 boots and connects to your WiFi, it should automatically appear in your Home Assistant Settings > Devices & Services under the ESPHome integration.

You should see your three new sensors:

  • sensor.smart_energy_meter_current
  • sensor.smart_energy_meter_power
  • sensor.smart_energy_meter_daily_energy

You can now add these to your dashboard! I like to use a glance card to show all three at once.

type: glance
entities:
  - entity: sensor.smart_energy_meter_power
  - entity: sensor.smart_energy_meter_current
  - entity: sensor.smart_energy_meter_daily_energy
title: Workshop Power

Troubleshooting and Common Pitfalls

I ran into a few issues myself, so here’s how to solve them:

  • Sensor reads zero or a constant value: Double-check your wiring. For the SCT-013, ensure the clamp is only around the live wire, not the neutral or both. For the ACS712, ensure the load is connected and powered on.
  • Readings are jumpy or noisy: The ESP32’s ADC can be noisy. The low-pass filter in the Lambda function (filtered_value) helps a lot. You can also try adding a small capacitor (e.g., 0.1µF) between the analog input pin and GND.
  • Readings are inaccurate: This is almost always a calibration issue. Revisit the calibrate_linear section in the YAML. Use a known load to fine-tune the values.
  • Device doesn’t connect to Home Assistant: Check your WiFi credentials in the ESPHome secrets file. Ensure your ESP32 is close enough to your router.

Where to Go From Here

Congratulations! You now have a fully functional smart energy meter. But why stop there?

  • Monitor Multiple Circuits: Use an ESP32 with multiple analog pins and several SCT-013 clamps to monitor your entire breaker panel.
  • Add Voltage Sensing: For true, high-accuracy power measurement (especially for reactive loads like motors), you’ll need to measure voltage as well. This requires a separate, safe voltage sensor circuit.
  • Create Energy Dashboards: Use the data in Home Assistant to create beautiful energy dashboards with Grafana, just like I did in my guide to Grafana alerting.
  • Set Up Automations: Get an alert when your workshop saw has been left on for too long, or automatically turn off a space heater when a certain energy threshold is reached.

Frequently Asked Questions (FAQ)

Q: Is it safe to use the SCT-013 sensor? A: Yes, the SCT-013 is one of the safest options because it’s non-invasive. It clamps around the wire without requiring any direct electrical connection to the mains voltage.

Q: Can I use this to monitor my whole house’s energy consumption? A: Absolutely. You can place a SCT-013 clamp around the main live wire coming into your electrical panel. Just be extremely careful and consider hiring an electrician if you’re not comfortable working inside the panel.

Q: Why is my power reading slightly off compared to my electricity meter? A: Our setup assumes a constant voltage (230V/110V) and a power factor of 1. Real-world power factor and voltage fluctuations can cause small discrepancies. For most household monitoring, it’s perfectly adequate.

Q: Can I use an ESP8266 instead of an ESP32? A: You can, but the ESP32 has a superior ADC (Analog-to-Digital Converter) which generally provides more stable and reliable readings for analog sensors like this.

I hope this guide empowers you to take control of your energy usage. It’s a deeply satisfying project that blends hardware tinkering with software smarts. If you run into any issues, the ESPHome and Home Assistant communities are incredibly helpful. Happy building