Skip to content
You Start with one site
Amounts in Start with one site
Build · Power and batteries

The battery and power monitor: see what your battery goes through every night, before it fails early.

A solar battery bank or a UPS battery was meant to last eight years. It dies in three. It was drained too deep, night after night, or it never reached full charge, or the generator ran while the battery could still carry the load. Nobody saw the pattern, because nobody measured it. The same happens to a device on batteries that goes dead a month early.

Build a small monitor for that battery. It measures the current in and out every second, keeps the count of what is left, and warns the right person in time. It also gives you the record you need to choose: the depth of every night, the energy in and out each day, and the cycles the battery has used.

About KSh 5,512USD 42 in parts Printing: 6 to 8 hours Building: a weekend
Found this useful?
The box from the model, and the shunt on the right with its cover. The shunt goes in the battery's negative cable; the box only reads it.

What you end with

A battery that reports its voltage, its current and its state of charge every minute, and sends an alert when the voltage is low, when a night went too deep, when it is not charging by noon, and when the monitor itself goes quiet. The record shows the energy in and out each day, the depth of every night, any charge put in at night, and the cycles used so far.

Currentboth ways, to 54 A
Banks12, 24 or 48 V
Countedevery second
Kept offline12 hours
Charge countset at each full
Load cuton the board
Battery work is for qualified people. A battery can drive thousands of amperes into a short circuit, and direct current does not put out its own arc. Large banks, and anything on the mains side of an inverter, need a qualified person and the maker's instructions. Fuse every positive lead, right at the battery. This monitor measures; it never disconnects a load by itself. The optional cut works only through a properly rated contactor or battery protector with its own fuse, and the protection that keeps the battery alive (its BMS, the charge controller's low-voltage cut-out) works on its own, with no network.

What you need

Rough prices for single parts bought online, in

Get the parts wherever suits you: a local electronics shop, or online. Pick a shop and each Find it link searches there.

#PartQtyAbout
1ESP32 DevKitAny 30 or 38 pin boardFind it1KSh 650USD 5.00
2INA226 moduleUp to 36 V: for 12 and 24 V banks. For 48 V, an INA228 module instead (about USD 10)Find it1KSh 325USD 2.50
3Shunt, 50 A 75 mVOr 100 A 75 mV if the current stays above 33 A for longFind it1KSh 650USD 5.00
4Main fuse and holderRated for your cable and your battery; at the battery positiveFind it1KSh 1,040USD 8.00
5Inline fuse holders, 1 AOne for the voltage lead, one for the buck converterFind it2KSh 390USD 3.00
6Buck converter, 5 V outInput up to 60 V, so it survives a 48 V bank chargingFind it1KSh 390USD 3.00
7Battery cable and lugs30 cm of cable the size of your battery cable, two M8 lugsFind it1KSh 520USD 4.00
8WireA twisted pair for the shunt, red and black 0.75 mm² for the restFind it3 mKSh 390USD 3.00
9Terminal strip, 6-way5.08 mm screw terminals: the field wires land hereFind it1KSh 104USD 0.80
10PG7 cable glandsFor 3 to 6.5 mm cablesFind it3KSh 195USD 1.50
11Relay module (optional)Only for the load cut, and only to drive a contactor coilFind it1KSh 195USD 1.50
12Jumper wiresFemale to femaleFind it15KSh 195USD 1.50
13Screws4 x M3 x 10, 2 for the box, 2 for the shunt coverFind it10KSh 130USD 1.00
14PETG or ASAPLA softens near a warm inverterFind it130 gKSh 338USD 2.60
TotalKSh 5,512USD 42

Also: a 3D printer, a multimeter, a clamp meter for DC if you have one, a crimp tool for the lugs, a 12 V bench supply or a small 12 V battery for the desk test, and an account on siliconwit.io (free).

The box open on the wall, and the shunt beside it with its cover off, each part marked with its number from the parts list. In the box: 1, the ESP32 DevKit, on the left; 2, the purple INA226 module, at the top in the middle; 6, the buck converter, below it; 11, the relay module, on the right; 9, the terminal strip, at the bottom left; 10, the three cable-gland nuts on the floor. On the right: 3, the shunt, with its brass end blocks; 7, a battery cable and its lug bolted to each end.
Where each part goes, numbered as in the list above. The shunt (3) sits in the battery's negative cable, on a board beside the battery, under its printed cover. The fuses (4, 5) go at the battery positive, and every cable comes into the box from below, through a gland (10).
Why the INA226. It reads the shunt in steps of 2.5 µV and the voltage in steps of 1.25 mV, 16 bits each, and it costs a few dollars. On a 1.5 milliohm shunt that is a current step of under 2 mA. The INA219 is cheaper but stops at 26 V, too low for a 24 V bank on charge (about 29 V), and its steps are four times coarser. The INA226 stops at 36 V: for a 48 V bank use the INA228, which reads to 85 V with 20 bits. Set CHIP_INA228 to 1.
The shunt. A 50 A, 75 mV shunt is 1.5 milliohm. At 50 A it drops 75 mV, inside the INA226's 81.92 mV, and makes 3.75 W of heat. Shunts are made to run at about two thirds of their rating, so this one suits currents up to about 33 A for long periods. If yours stay higher, fit a 100 A, 75 mV shunt (0.75 milliohm): the steps double, still under 4 mA.
The shunt goes on the negative lead. All the current of the battery passes through it, so the cables to it are battery cables, bolted with lugs. Its two small screws carry only the sense pair. Everything else (loads, charger, inverter, and the monitor itself) joins on the load side, or the shunt cannot count it. On the negative lead the INA226's inputs sit a few tens of millivolts either side of its ground: inside its absolute limits, just below the 0 V where its data sheet starts. The INA228 is specified down to -0.3 V, if you want the data sheet to cover that too.

The design, in 3D and on paper

Turn it, open Parts to hide the lid or the shunt cover, and use Section to cut through the box and the cover. The parts carry the numbers of the parts list.

The battery and power monitor: the box, the lid, the shunt cover, the shunt and its cables, and the parts inside. Drag to turn, pinch or scroll to zoom. Open in the full viewer.
A3 assembly drawing, first angle, 1 to 1. The front view of the box with the lid taken off shows the ESP32 DevKit and the terminal strip on the left, the INA226 module and the buck converter in the middle, the relay module on the right and the gland nuts on the floor. To its right, the view from the left and section A-A through the middle gland hole and both ears, hatched, with the lid's skirt hanging over the walls. Below, the shunt and its cover from the cable end and section B-B through the shunt's axis: the cover over the studs, nuts and lugs. Sizes 100.8 by 150.8 by 40.8 mm, the cover 100.8 by 64.8 by 41.4 mm. Balloons match the item list: 1, 2, 3, 6, 7, 9, 10 and 11, then 15 to 17 for the box, the lid and the shunt cover.
The A3 assembly drawing (click for the PDF). Sheets 2 to 4 give every size of the box, the lid and the shunt cover.

Build it

Each step links to the lesson section that teaches it. Open one only when you need it.

Build track
Follow this build, one step at a time

Tick each step as you finish it. Your place is kept, so you can stop and come back.

1

Wire it on the desk

Wire it on the desk first, with a 12 V bench supply or a small 12 V battery, a 1 A fuse, and a car bulb as the load. Go near the real battery only when this works.

Wiring drawing. The battery positive goes through the main fuse at the terminal to the system positive. The battery negative goes through the 50 A, 75 mV shunt to the system negative. The INA226 module's IN+ goes to the battery side of the shunt and IN- to the load side, as a twisted pair; its VBUS goes to the battery positive through a 1 A fuse. A buck converter takes the battery positive through its own 1 A fuse and gives 5 V to the ESP32. The INA226's VCC, GND, SDA and SCL go to the ESP32's 3V3, GND, GPIO 21 and GPIO 22. An optional relay module on GPIO 26. Every ground is the load side of the shunt.
Open the drawing full size. The heavy lines carry the battery's own current; every other wire carries almost nothing.
  • Take the small 0.1 ohm resistor (marked R100) off the INA226 module with a soldering iron. The external shunt replaces it; left in place, it would carry part of the current.
  • IN+ to the battery side of the shunt, IN- to the load side. Then charging reads plus and discharging reads minus. If yours reads the other way, set SHUNT_SIGN to -1.
  • The monitor's ground is the load side of the shunt. The bus input then reads the battery plus the shunt's drop, up to 75 mV; the firmware takes the drop off again.
  • The ESP32 takes 5 V from the buck converter on its 5V pin (VIN on some boards). Set the converter to 5.0 V with a multimeter before you connect the board.
2

Set your battery

At the top of the sketch: the capacity you rely on, the voltage at which the battery counts as full, and your night. The values shown are for a 12 V LiFePO4 battery:

// --- your battery (a 12 V LiFePO4 shown; times 2 for 24 V, times 4 for 48 V; lead-acid in the README) ---
const float CAPACITY_AH = 100; // the capacity you rely on; lower it as the battery ages
const float FULL_V = 14.0; // a little below the charger's absorption voltage (LiFePO4 14.0, lead-acid 13.2)
const float TAIL_PCT = 4; // full when the charge current falls below this share of the capacity ...
const int FULL_HOLD_S = 180; // ... with the voltage above FULL_V, both held this long
const float CHARGE_EFF = 0.99; // of each Ah put in, the share stored (LiFePO4 0.99, lead-acid about 0.90)
const float DEEP_PCT = 80; // a night deeper than this is flagged (LiFePO4 80, lead-acid 50)
const float START_SOC = 50; // the guess at the first start, until the first full charge
const int NIGHT_FROM_H = 18, NIGHT_TO_H = 8; // the night, local time
const int NOON_H = 12; // a solar battery should be charging by then; -1 for a UPS on the grid
const long UTC_OFFSET_S = 0; // your time zone in seconds, for "today" and the night (UTC+3: 3 * 3600)
12 V batteryFull atCharge keptDeep nightCut, back on
LiFePO4, 4 cells14.0 V0.99over 80 %12.0 V, 13.0 V
Lead-acid, 6 cells13.2 V0.90over 50 %11.8 V, 12.8 V

Times 2 for 24 V, times 4 for 48 V. A starting point only: your battery's data sheet and your charger's settings decide.

  • FULL_V sits a little below the charger's absorption voltage, so a good day reaches it. The battery counts as full when the voltage is above it and the charge current has fallen below 4 % of the capacity, both for 3 minutes.
  • The shunt and the chip: set them from the shunt's label. The sketch works out the calibration register itself.
// --- the shunt and the chip ---
#define CHIP_INA228 0 // 0: INA226 (12 and 24 V banks; never over 36 V). 1: INA228 (up to 85 V: 48 V banks)
const float SHUNT_A = 50, SHUNT_MV = 75; // the shunt's rating, from its label: 50 A at 75 mV is 1.5 milliohm
const int SHUNT_SIGN = 1; // -1 if charging reads negative (the two sense wires are the other way round)
const uint8_t INA_ADDR = 0x40; // A0 and A1 to GND
const int SDA_PIN = 21, SCL_PIN = 22;
3

Flash and check on the desk

Open battery_monitor/battery_monitor.ino in the Arduino IDE, choose ESP32 Dev Module, install PubSubClient and ArduinoJson (version 7), and upload. No library is needed for the INA226 or the INA228: the sketch talks to them over Wire. Compiled for the ESP32 with the esp32 core 4.0.0: 1.12 MB of flash (85 % of the default app space) and 64 KB of RAM for global data, with no warnings, for the INA226, the INA228, with the load cut, and without TLS.

The chip is read once a second by a task of its own, so a slow connection never stops the count. It averages 256 readings over 823 ms of each second, so short peaks (a pump starting, an inverter surge) are counted too. The logic was tested on a laptop first; these lines come from those tests:

INA226, 50 A 75 mV shunt: current step 2 mA, CAL 1707, 3.75 W in the shunt at 50 A
INA226 config 0x4B2F: 256 averages, 823 ms of each second
INA228, same shunt: 0.5 mA step, SHUNT_CAL 9830
day: night took 42.0 Ah, lowest 58.0 %, depth 42.0 %; full seen with the count at -0.40 %
full: needs 14.0 V and under 4.0 A held 180 s; a cloud starts the wait again
drift: 0.2 A of error for 10 days adds 48 Ah; only a full charge sets it right
night: 142 Ah out, 40 Ah in from a generator at 03:00, depth 72.0 % (deep)
cycles: 10 nights of 42 Ah on 100 Ah = 4.20 equivalent full cycles
overflow: 10 mA for a day is 0.2400 Ah counted (a float total moved 0.0000 Ah)
guard: cut after 10 s below the cut-off; a 5 s dip does not cut

The count is kept in whole micro-coulombs in 64 bits. A float would stop counting small currents: on a 100 Ah total, 10 mA for a whole day does not move it at all.

Put the bulb on and read its current with a clamp meter or a multimeter in series. Check: a on the Serial Monitor agrees within 2 %, minus while it draws. Turn the supply up past FULL_V with no load: it reads a small plus.
4

Print the box and the shunt cover

PETG or ASA. 0.2 mm layers, 4 walls, 20 % infill, no supports. About 130 g in all.

PartLay it
BoxOn its back, open side up. 101 x 151 mm with its ears.
LidFront face down, skirt up.
Shunt coverClosed top down.

Every cable enters the box from below, through a gland, and lands on the terminal strip. The cover screws to the board over the shunt, so a dropped spanner cannot bridge its studs; the battery cables leave through slots at its ends. It fits a shunt 90 x 26 mm on its base and 36 mm tall: measure yours, and set ShuntL, ShuntW and ShuntH in the model if it differs.

5

Fit it at the battery

For a large bank, have a qualified person do this step. With every load and charger switched off:

  1. Take the negative cable off the battery first. Insulate its end.
  2. Screw the shunt to a board beside the battery. Bolt a new short cable from the battery minus to one end, and the old negative cable to the other. Nothing else goes on the battery minus.
  3. Fit the main fuse on the battery positive, as close to the terminal as it can go, rated for the cable. Fit the two 1 A fuses where the thin leads leave the positive.
  4. The sense pair, twisted, from the shunt's two small screws to the box. Then the voltage lead and the buck converter lead, each through its own fuse.
  5. Screw the cover over the shunt. Mount the box on the wall, every cable through a gland from below. Put the negative cable on the battery last.

Checked in FreeCAD 1.1: every module fits the box with 9 mm to spare under the lid, the gland nuts clear the parts, and the cover clears the shunt, its studs, its nuts and both cable lugs.

Switch on one known load. Check: the current reads minus and about right. Then let the charger run: it reads plus.
6

Connect it

On siliconwit.io, our monitoring service: Add Device, then Define my own device, with the fields of the reading below. Set the data interval to 60 seconds. To look around first, with no sign-up, siliconwit.io/try gives you a device for about 30 minutes. Copy the Device ID and Access Token into these lines, with your Wi-Fi above them, and upload again:

const char* MQTT_HOST = "mqtt.siliconwit.io";
const int MQTT_PORT = 8883; // MQTT over TLS
const char* DEVICE_ID = "SWD-XXXXXX"; // client ID, username, and the topic name
const char* MQTT_PASS = "your-access-token"; // the Access Token
#define USE_TLS 1 // 0 only for a test broker on your own network: then port 1883, and no certificate

One reading a minute, on d/<device-id>/t:

{"v":13.18,"a":-3.42,"w":-45.1,"soc":71.6,"sync":1,"sensor":1,"ah_in":43.2,"ah_out":38.9,
"wh_in":588,"wh_out":507,"cycles":41.27,"drift":-0.4,"night_dod":42.0,"night_out_ah":42.0,
"night_in_ah":0.0,"deep":0,"no_charge":0,"ts":1795000630}

The link is MQTT over TLS on port 8883, with the ISRG Root X1 certificate in the sketch. After a failed connect it waits 5, 10, 20, 40, then 60 seconds. While the network is down it keeps up to 12 hours of readings and sends them later, each with its own time, and it saves the count to flash every 15 minutes so a restart does not lose it. A watchdog restarts the board if the code ever gets stuck. Your own Mosquitto broker works the same: change the broker lines, as on the live sensor node.

7

Make it act

Commands change the settings from the device page, and each gets a reply. When the battery ages, lower capacity_ah; when you have seen it full yourself, send reset_soc:

d/SWD-XXXXXX/c {"command":"capacity_ah","value":90,"session":"a1"}
d/SWD-XXXXXX/k/a1 {"status":"ok"}
d/SWD-XXXXXX/c {"command":"reset_soc","session":"a2"} (you saw it full)
d/SWD-XXXXXX/k/a2 {"status":"ok"}
d/SWD-XXXXXX/c {"command":"cutoff_v","value":13.8,"session":"a3"}
d/SWD-XXXXXX/k/a3 {"status":"error","message":"cutoff_v must be above 0 and well below full_v"}
// a command on d/<id>/c: run it, then reply on d/<id>/k/<session>
void onCommand(char* t, byte* data, unsigned int len) {
JsonDocument msg;
if (deserializeJson(msg, data, len)) return; // not JSON: ignore it
const char* session = msg["session"] | "";
const char* error = nullptr;
JsonVariant v = msg["value"];
float n = v | -1.0f;
xSemaphoreTake(lock, portMAX_DELAY);
if (msg["command"] == "capacity_ah") { // keeps the percentage, rescales the Ah
if (n >= 1 && n <= 5000) { float s = batt.rawSoc(); batt.capacityAh = n; batt.tailA = n * TAIL_PCT / 100; batt.setSoc(s); }
else error = "capacity_ah must be 1 to 5000";
} else if (msg["command"] == "full_v") {
if (n >= 5 && n <= 70 && n > guard.reconnectV) batt.fullV = n;
else error = "full_v must be 5 to 70 V and above the reconnect voltage";
} else if (msg["command"] == "reset_soc") { // no value: you saw it full, so 100
float s = v.isNull() ? 100.0f : n;
if (s >= 0 && s <= 100) { batt.setSoc(s); batt.synced = (s == 100); }
else error = "reset_soc must be 0 to 100";
} else if (msg["command"] == "cutoff_v") {
if (!(n < batt.fullV - 0.5f) || !guard.setCutoff(n)) error = "cutoff_v must be above 0 and well below full_v";
} else if (msg["command"] == "load") {
#if HAS_LOAD_CUT
bool want = v.is<bool>() ? v.as<bool>() : (v == "on" || v == 1);
if (!guard.command(want)) error = "voltage at or below cutoff_v";
digitalWrite(CUT_PIN, guard.on ? LOW : HIGH);
#else
error = "no load cut fitted";
#endif
} else {
error = "unknown command";
}
if (!error) save();
xSemaphoreGive(lock);
if (*session) {
char reply[128];
if (error) snprintf(reply, sizeof(reply), "{\"status\":\"error\",\"message\":\"%s\"}", error);
else snprintf(reply, sizeof(reply), "{\"status\":\"ok\"}");
mqtt.publish((topic("k/") + session).c_str(), reply);
}
}

The optional load cut (HAS_LOAD_CUT 1) runs on the board, with no network. It cuts when the voltage stays below the cut-off for 10 seconds, so a motor starting does not trip it, and connects again only after a minute above the reconnect voltage. When the board is off or restarting, the load stays as it is wired.

The relay module switches a signal, never the load. GPIO 26 drives a relay whose contacts switch the coil of a contactor rated for the load current, or the remote input of a battery protector, with its own fuse. The battery's BMS and the charge controller's low-voltage cut-out stay in place as the protection that matters.
8

Set the alerts

This is where the battery stops failing in silence. Email alerts come with the free account (up to 10 rules); SMS with the Business plan. Send each one to the person who can act on it:

Low voltagev below 12.0 (lead-acid 11.8), held for 5 minutes Running lowsoc below 30, held for 10 minutes Deep nightdeep equal to 1 Not chargingno_charge equal to 1 Sensor faultsensor equal to 0, held for 5 minutes Not reportingthe device silent for 10 minutes

"Not charging by noon" catches a tripped breaker, a dirty or shaded array, or a failed charge controller on the first morning, not after a week of drained nights. The last alert matters most: a monitor that has lost its power or its network cannot say so itself; only the service can notice the silence.

9

Read the record

  • The depth of each night. night_dod is 100 minus the lowest state of charge between 18:00 and 08:00. Deeper nights use the battery up faster: a lead-acid battery taken to 80 % every night lasts a fraction of one taken to 50 %. Set UTC_OFFSET_S so the night is your night.
  • Charge at night. night_in_ah above zero means the generator or the grid charged the battery in the night. If that happens while soc is still at 70 %, the generator starts too early: the battery could have carried the load, and the fuel was spent for nothing.
  • The drift. drift is what the count said when the battery last reached full, minus 100. A few per cent is normal. If the battery reaches its low-voltage limit while soc still says 40 %, it holds less than you set: lower capacity_ah.
  • Energy in and out. wh_in and wh_out reset at midnight; the last values of a day are its totals. Over a few days that end where they started, out divided by in is the round-trip efficiency: above 0.9 for LiFePO4, about 0.8 for lead-acid. Lower than that, the battery is hot or old.
  • Cycles. cycles is all the Ah taken out, divided by the capacity. Set it against the cycle life on the data sheet.

The free account keeps 7 days of history, enough to see the pattern of the nights. Share the device with up to 2 people, for example the technician who looks after the system.

You are done when

  • The current on the device page agrees with a clamp meter within a few per cent, minus while the battery discharges and plus while it charges.
  • After the first full charge, sync reads 1.
  • On the desk, with the Wi-Fi off, the load cut (if fitted) clicks after 10 seconds below the cut-off, and not on a short dip.
  • An alert reaches your phone when you pull the monitor's own 1 A fuse for ten minutes.
  • After a night, the reading carries night_dod, and you know whether that depth suits your battery.

Downloads

Checked: the firmware compiles for the ESP32 with no warnings in all its variants (INA226 or INA228, with or without the load cut and TLS). Its logic (the register maths of both chips, the count over a whole synthetic day, the full-charge reset, the nights, the totals, the cycles, overflow, the millis() wrap and the load cut) passes 83 checks on a laptop, with the address and undefined-behaviour checkers on. The parts were checked in FreeCAD 1.1 with every module in place. A build on a real battery bank is next: if yours needs a change, tell us in the discussion below.

References

Ways to take this build

Have it done for your site

Fitted and watched by us

Our engineers fit the sensors, watch the readings and send a monthly record of what it found and saved.

Start with one site
Supervised, with an engineer

KSh 15,000USD 150 for the build

Four video meetings over about six weeks: plan it, show progress, show it working. Ends in a project record anyone can check.

Build it with a supervisor
On your own

Open to all

Every step, the firmware and the printable files. Tick the steps as you go.

Start step 1
For a team or a class

Priced for the group

Your staff or students build the battery and power monitor together, with reviews and a record for each person.

Ask for a group

Plus opens the worked answers in the lessons each step links to: see Plus.

Made by

Engineers who build what they teach, and answer for it.