Build a 3-Channel Solar and Battery DC Monitor with ESPHome and INA3221

Build a 3-channel DC power monitor using an ESP8266 and INA3221 to track solar generation, battery flow, and load consumption in Home Assistant via ESPHome.

Illustration for: Build a 3-Channel Solar and Battery DC Monitor with ESPHome and INA3221
AI-generated illustration
Difficulty: IntermediateTime: about 2 to 3 hoursTested on my setup

Tested on: Tested on an ESP8266 D1 Mini paired with an INA3221 sensor, a 3S6P 18650 12V lithium-ion battery pack, a PWM solar charge controller, and a <=20W solar panel.

Before you start

Small off-grid DC power systems often operate in the dark. Standard, low-cost solar charge controllers typically display basic battery voltages, lack detailed current instrumentation, and offer no native network integration to track your power balance over time.

In this tutorial, you will build a dedicated three-channel DC energy monitor using an ESP8266 and an INA3221 I2C sensor. Running ESPHome, this device monitors solar panel production, net battery charging or discharging, and DC load consumption simultaneously, publishing accurate data to Home Assistant.

What you need

  • ESP8266 development board (D1 Mini)
  • INA3221 3-channel I2C current and voltage sensor module (0.1 ohm shunts)
  • 12V DC battery pack (e.g., 3S 18650 lithium battery pack; check your sensor voltage limits)
  • Solar panel (tested with <=20W)
  • PWM solar charge controller
  • DC-DC step-down (buck) converter (12V to 5V, 3A rated)
  • Inline fuse holder and fuses (e.g., 2A fuse for buck converter/microcontroller)
  • Jumper wires, screw terminals, and prototyping board
  • ESPHome and Home Assistant running on your local network

Step 1 · Understand the 3-Channel High-Side Monitoring Topology

Before assembling wires, it is critical to understand where current is measured. The INA3221 is a triple-channel high-side current and bus voltage sensor. High-side sensing means the sensor's shunt resistors must sit in line along the positive (+) voltage rail, not the negative ground rail.

To capture the complete power balance of your solar setup, each channel breaks the positive line at a specific stage: - Channel 1 (Solar Panel): Breaks the positive lead between the solar panel and the charge controller's PV+ input. This measures the raw energy harvested from the panel. - Channel 2 (Load): Breaks the positive lead between the charge controller's LOAD+ output and your DC loads (including the buck converter feeding the microcontroller). This measures actual power consumption. - Channel 3 (Battery): Breaks the positive lead between the charge controller's BATT+ output and the battery's positive terminal. When solar generation exceeds consumption, current flows into the battery (positive current). When loads draw power without sufficient solar output, current flows out of the battery (negative current).

Channel Routing Plan
Channel 1: Solar Panel(+)  -> IN1+ | IN1- -> Charge Controller PV(+)
Channel 2: Controller LOAD(+) -> IN2+ | IN2- -> DC Loads (+)
Channel 3: Controller BATT(+) -> IN3+ | IN3- -> Battery (+)

Step 2 · Wire the INA3221 to the ESP8266 I2C Bus

Connect the INA3221 sensor module to the ESP8266 D1 Mini using the I2C bus.

We select GPIO4 for SDA and GPIO5 for SCL. On the D1 Mini silkscreen, these correspond to pins D2 and D1. These pins are specifically chosen because they are not strapping pins used by the ESP8266 during boot (such as GPIO0, GPIO2, or GPIO15), preventing bootloader hangs or flashing issues.

Connect VCC on the INA3221 to the 3V3 or 5V pin on the D1 Mini (ensure your breakout board supports your chosen logic level), and connect GND to the D1 Mini's GND.

I2C Pin Connections
INA3221 Pin   ->   ESP8266 D1 Mini Pin
VCC           ->   3V3 (or 5V)
GND           ->   GND
SDA           ->   D2 (GPIO4)
SCL           ->   D1 (GPIO5)

Step 3 · Power the Microcontroller from the Controller's LOAD Port

Powering the monitor directly from the raw battery terminals presents two major drawbacks: if your battery lacks a built-in low-voltage disconnect BMS, the monitor could slowly over-discharge the pack; second, the monitor's own power consumption would bypass measurement.

Instead, feed a 12V to 5V (3A) buck converter from the charge controller's LOAD terminals. Install an inline 2A fuse on the positive lead close to the LOAD+ connection. The 5V output of the buck converter then powers the D1 Mini (via the 5V pin) and any connected 5V peripherals.

Connecting through the charge controller's LOAD port provides automatic low-voltage cutoff (typically around 10.5V on 12V lithium settings), protecting your battery cells. Furthermore, the energy consumed by the ESP8266 is correctly accounted for under Channel 2.

Power Supply Wiring
Charge Controller LOAD(+) -> Inline 2A Fuse -> IN2+ -> IN2- -> Buck Converter (12V IN+)
Charge Controller LOAD(-) -----------------------------------> Buck Converter (12V IN-)
Buck Converter 5V OUT(+) ------------------------------------> ESP8266 5V Pin
Buck Converter 5V OUT(-) ------------------------------------> ESP8266 GND Pin

Step 4 · Wire the High-Side Shunts in Series

Now wire the high-side sensing channels. Remember: each channel must be placed strictly in series along the positive wire.

1. Solar Panel Channel (CH1): Route the positive wire from your solar panel directly into IN1+. From IN1-, connect a wire to the PV+ input terminal of the charge controller. 2. Load Channel (CH2): Route a wire from the charge controller's LOAD+ terminal into IN2+. Connect IN2- to your fused DC loads and the step-down converter. 3. Battery Channel (CH3): Route a wire from the charge controller's BATT+ terminal into IN3+. Connect IN3- directly to the battery's positive terminal (with an inline fuse).

If the polarity on Channel 2 or Channel 3 is reversed, current readings will report negative numbers. While this can be corrected in software, wiring IN+ towards the power source and IN- towards the destination maintains intuitive conventions.

Shunt Wiring Reference
Solar Panel(+)  -> IN1+  |  IN1- -> Charge Controller PV(+)
Controller LOAD(+) -> IN2+  |  IN2- -> Loads (+) (Buck Converter)
Controller BATT(+) -> IN3+  |  IN3- -> Battery (+) (via Fuse)

Step 5 · Isolate the Solar Panel Negative Return

In typical low-voltage DC electronics, all grounds share a single return bus. However, with standard PWM solar charge controllers, this rule does NOT apply to the solar panel.

Most budget PWM controllers switch the low side (PV-) to regulate charging, while leaving the positive line internally tied (PV+ to BATT+). If you attach the solar panel's negative lead (PV-) to the common system ground, you create an external bypass around the controller's internal switching circuit. When this happens, the controller cannot stop charging, and the battery will be pushed past its maximum safe voltage limit.

Connect the solar panel's negative lead exclusively to the charge controller's PV- terminal. Do not connect any branch from PV- to the system ground. The Battery (-), Load (-), buck converter (-), and INA3221 GND lines continue to share the common ground return as normal.

Grounding Scheme
Solar Panel (-)  --------> Charge Controller PV(-) ONLY (ISOLATED)
Battery (-)      --------> Charge Controller BATT(-)
Load (-)         --------> Charge Controller LOAD(-)
System Common Return ---> Tied between Battery(-), Load(-), and INA3221 GND

Step 6 · Configure ESPHome with I2C Auto-Detection

Create the ESPHome configuration file. To make the firmware resilient against hardware revisions or variations in the INA3221 A0 address pin state, we include an on_boot lambda.

This boot routine scans addresses 0x40, 0x41, 0x42, and 0x43. When it detects an active I2C response using write_readv(), it dynamically updates the sensor's runtime address and logs the result. We also add a watchdog interval that checks whether the INA3221 has reported a reading in the last 10 minutes, automatically executing a safe reboot if communication locks up.

solar-dc-monitor.yaml excerpt
esphome:
  name: solar-dc-monitor
  friendly_name: "Solar DC Monitor"
  on_boot:
    priority: 800
    then:
      - lambda: |-
          const uint8_t possible_addrs[] = {0x40, 0x41, 0x42, 0x43};
          bool found = false;
          for (uint8_t addr : possible_addrs) {
            if (id(bus_i2c)->write_readv(addr, nullptr, 0, nullptr, 0) == esphome::i2c::ERROR_OK) {
              id(ina)->set_i2c_address(addr);
              id(ina_addr) = addr;
              ESP_LOGW("ina3221", "Detected INA3221 at 0x%02X", addr);
              found = true;
              break;
            }
          }
          if (!found) {
            id(ina)->set_i2c_address(0x40);
            ESP_LOGE("ina3221", "No INA3221 detected in 0x40..0x43, defaulting to 0x40");
          }

esp8266:
  board: d1_mini

i2c:
  id: bus_i2c
  sda: GPIO4
  scl: GPIO5
  scan: true

Step 7 · Flash the Firmware and Validate Sensor Channels

Connect the D1 Mini to your computer via USB and compile the firmware using the ESPHome dashboard or CLI: esphome run solar-dc-monitor.yaml.

Once flashed and booted, inspect the logs: 1. Verify that the INA3221 is detected on the I2C bus (e.g., at 0x40 or 0x41). 2. Inspect Channel 1 (Solar): Voltage should match your panel's open-circuit or operating voltage. Current will show positive amperes under sunlight. 3. Inspect Channel 2 (Load): Turn on a connected DC device. The current should read positive. If it reads negative (e.g., -0.032 A), the IN2+ and IN2- wires are reversed. You can either swap the wires physically or apply an abs() filter in Home Assistant template sensors. 4. Inspect Channel 3 (Battery): Verify the resting battery voltage. Under bright sun, current will show positive as the battery charges; under load with low sun, current will read negative as the battery discharges.

ESPHome Log Check
esphome logs solar-dc-monitor.yaml

Troubleshooting

All three channels read a fixed current of approximately 1.64A simultaneously.

Check your shunt wiring immediately. This symptom indicates that IN+ and IN- were wired in parallel across power rails (like a voltmeter) rather than breaking the positive line in series. The 0.1-ohm shunt created a direct short circuit, saturating the internal ADC. Disconnect power and rewire each channel strictly in series along the positive conductor.

The battery continues charging past its maximum safe cutoff voltage (e.g., exceeding 12.6V on a 3S pack).

Check the solar panel negative wiring. On most low-cost PWM controllers, the negative terminal (PV-) is switched internally. If you tied the solar panel negative lead to the common system ground, you bypassed the internal switch. Route the solar panel negative lead exclusively to the charge controller's PV- terminal.

Load current reads zero in Home Assistant despite active loads running.

The wiring polarity on Channel 2 is reversed (IN2+ and IN2- swapped), producing a negative reading (e.g., -0.032A). If your Home Assistant template sensor uses max(0, x) to filter noise, it will clamp the actual negative reading to 0. Either physically swap IN2+ and IN2- or update the template sensor to use abs(x).

Sensor shows 'No response' or fails to communicate over I2C.

Confirm your wiring matches the configured pins: SDA to D2 (GPIO4) and SCL to D1 (GPIO5). Ensure VCC has reliable 3.3V or 5V power and GND is common with the ESP8266. The on_boot scanning lambda tests 0x40 through 0x43; verify that your sensor's A0 address pin is firmly grounded or tied according to your desired address.

Solar panel current peaks and plateaus at ~1.64A during peak midday sun.

The 0.1-ohm shunt resistors installed on standard INA3221 breakout boards reach their ADC measurement ceiling at roughly 1.638A. If your solar panel exceeds this capacity, swap to an INA3221 module equipped with smaller shunts (e.g., 0.01 ohm, extending capacity to ~16A) and adjust shunt_resistance in the YAML configuration.

What I learned

  • Standard common-ground assumptions fail on PWM charge controllers: Low-cost PWM controllers regulate charging by disconnecting the negative line (PV-). Tying PV- to a common return bypassed the switch and allowed a 3S battery to overcharge to 12.7V.
  • Shunt sensors must strictly break the positive line in series: Accidentally connecting IN+ and IN- across battery poles in parallel placed a dead short across the 0.1-ohm shunt, pegged ADC readings at 1.64A, and damaged a development board.
  • Powering the monitor from the charge controller's LOAD port provides essential battery undervoltage protection (10.5V cutoff) when the battery lacks an internal low-voltage disconnect BMS, while also capturing the monitor's own power consumption.
  • Polarity mismatches can be compensated in software: When inverted load shunt wiring produced negative current readings (-0.032A), adapting the template sensor to use abs() resolved the issue cleanly without rewiring hardware.

Next steps

  • Configure Home Assistant alerts: Set up automated notifications when battery voltage drops below 11.0V to take action before the controller's 10.5V low-voltage disconnect triggers.
  • Track daily energy statistics: Create Riemann sum integral sensors and Home Assistant Utility Meters to calculate daily solar energy harvested (Wh) versus daily load consumed.
  • Upgrade current range for larger panels: If expanding beyond a 20W solar panel, replace the 0.1-ohm shunts with 0.01-ohm resistors to increase current handling from 1.64A up to ~16A.

Get the code

Complete ESPHome firmware configuration, secrets template, and documentation for a 3-channel solar, battery, and load DC power monitor.

View the code on GitHub →

Files in the repository (3)

README.md

README.md
# 3-Channel Solar and Battery DC Power Monitor

Part of the DIY projects collection on [erness.dev](https://erness.dev) ("Life is a DIY Project").

This project provides a complete ESPHome firmware configuration for monitoring a low-voltage DC solar power setup using an **ESP8266 D1 Mini** and a 3-channel **INA3221** I2C current and bus voltage sensor.

## Monitored Channels

1. **Solar Panel (CH1)**: Measures raw solar generation (voltage, current, power) from a small solar panel (<=20W).
2. **Load (CH2)**: Measures energy drawn by DC loads and step-down converters connected to the charge controller's `LOAD` terminal.
3. **Battery (CH3)**: Measures battery terminal voltage and net current flow (positive when charging, negative when discharging).

## Hardware Requirements

- **Microcontroller**: ESP8266 D1 Mini
- **Sensor**: INA3221 3-channel I2C power monitor module (0.1 ohm shunts)
- **Power Source**: 12V DC battery pack (e.g. 3S 18650 lithium-ion pack)
- **Solar Panel**: Small 12V solar panel (<=20W tested)
- **Charge Controller**: Standard PWM solar charge controller
- **Voltage Regulator**: DC-DC buck converter (12V to 5V, 3A rated) with inline 2A fuse

## Critical Wiring and Safety Rules

1. **High-Side Series Measurement**: Every channel on the INA3221 must break the **positive lead in series** (`IN+` in, `IN-` out). Never connect `IN+` and `IN-` in parallel across positive and negative rails; doing so dead-shorts the 0.1-ohm shunt resistor across your power source.
2. **Isolated Solar Negative (PV-)**: Most PWM charge controllers regulate charging by switching the **negative** side (`PV-`). The solar panel's negative wire must connect **strictly to the charge controller's PV- terminal**. Do not connect the solar panel negative to common ground, or you will bypass the charging regulator and overcharge the battery.
3. **Common System Ground**: Battery (-), Load (-), buck converter (-), and INA3221 GND connect to the shared return bus.
4. **Power from LOAD Output**: Power the buck converter from the charge controller's `LOAD` terminal. This ensures low-voltage cutoff protection (10.5V) covers the monitor and accounts for the monitor's power draw under Channel 2.

## Pin Connections

| INA3221 Pin | ESP8266 D1 Mini Pin | Notes |
|---|---|---|
| VCC | 3V3 (or 5V) | Module power |
| GND | GND | Ground reference |
| SDA | D2 (GPIO4) | I2C Data (non-strapping pin) |
| SCL | D1 (GPIO5) | I2C Clock (non-strapping pin) |

## Quick Start

1. Copy `secrets.yaml.example` to `secrets.yaml` and configure your WiFi credentials and encryption keys.
2. Install ESPHome: `pip install esphome`
3. Validate the configuration:
   ```bash
   esphome config solar-dc-monitor.yaml
   ```
4. Flash to your ESP8266:
   ```bash
   esphome run solar-dc-monitor.yaml
   ```
5. Open Home Assistant. The device will be auto-discovered via the ESPHome integration.

solar-dc-monitor.yaml

solar-dc-monitor.yaml
esphome:
  name: solar-dc-monitor
  friendly_name: "Solar DC Monitor"
  on_boot:
    priority: 800
    then:
      - lambda: |-
          const uint8_t possible_addrs[] = {0x40, 0x41, 0x42, 0x43};
          bool found = false;
          for (uint8_t addr : possible_addrs) {
            if (id(bus_i2c)->write_readv(addr, nullptr, 0, nullptr, 0) == esphome::i2c::ERROR_OK) {
              id(ina)->set_i2c_address(addr);
              id(ina_addr) = addr;
              ESP_LOGW("ina3221", "Detected INA3221 at 0x%02X", addr);
              found = true;
              break;
            }
          }
          if (!found) {
            id(ina)->set_i2c_address(0x40);
            ESP_LOGE("ina3221", "No INA3221 detected in 0x40..0x43, defaulting to 0x40");
          }

esp8266:
  board: d1_mini

logger:

api:
  encryption:
    key: !secret api_encryption_key

ota:
  - platform: esphome
    password: !secret ota_password

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  ap:
    ssid: "Solar DC Monitor Fallback Hotspot"
    password: !secret wifi_ap_password

i2c:
  id: bus_i2c
  sda: GPIO4
  scl: GPIO5
  scan: true

sensor:
  - platform: ina3221
    id: ina
    address: 0x40
    channel_1:
      shunt_resistance: 0.1 ohm
      bus_voltage:
        name: "Solar Panel Voltage"
      current:
        name: "Solar Panel Current"
      power:
        name: "Solar Panel Power"
    channel_2:
      shunt_resistance: 0.1 ohm
      bus_voltage:
        name: "Load Voltage"
      current:
        name: "Load Current"
      power:
        name: "Load Power"
    channel_3:
      shunt_resistance: 0.1 ohm
      bus_voltage:
        name: "Battery Voltage"
        id: battery_voltage
        on_value:
          then:
            - lambda: |-
                id(last_read) = millis();
      current:
        name: "Battery Current"
        id: battery_current
        on_value:
          then:
            - lambda: |-
                id(last_read) = millis();
      power:
        name: "Battery Power"
    update_interval: 30s

  - platform: uptime
    name: "Solar DC Monitor Uptime"
    update_interval: 60s

  - platform: wifi_signal
    name: "Solar DC Monitor WiFi Signal"
    update_interval: 60s

button:
  - platform: restart
    name: "Solar DC Monitor Restart"

globals:
  - id: ina_addr
    type: uint8_t
    restore_value: no
    initial_value: '0'
  - id: last_read
    type: uint32_t
    restore_value: no
    initial_value: '0'

interval:
  - interval: 5min
    then:
      - lambda: |-
          if (millis() > 900000 && (millis() - id(last_read)) > 600000) {
            ESP_LOGW("watchdog", "No readings from INA3221 for 10 min: rebooting");
            App.safe_reboot();
          }

text_sensor:
  - platform: template
    name: "Solar DC Monitor INA3221 Address"
    update_interval: 60s
    lambda: |-
      char b[16];
      if (id(ina_addr) == 0) return std::string("No response");
      snprintf(b, sizeof(b), "0x%02X", id(ina_addr));
      return std::string(b);

secrets.yaml.example

secrets.yaml.example
# secrets.yaml.example
# Copy this file to secrets.yaml and populate with your network credentials

wifi_ssid: "YOUR_WIFI_SSID"
wifi_password: "YOUR_WIFI_PASSWORD"
wifi_ap_password: "YOUR_FALLBACK_AP_PASSWORD"

api_encryption_key: "GENERATE_OR_PASTE_ESPHOME_ENCRYPTION_KEY_HERE="
ota_password: "YOUR_OTA_PASSWORD"