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

CHIP_INA228 to 1.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.

Build it
Each step links to the lesson section that teaches it. Open one only when you need it.
Tick each step as you finish it. Your place is kept, so you can stop and come back.
Kept on this device. Sign in to keep it on every device.Kept with your account.
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.
- 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_SIGNto -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.
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 agesconst 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 longconst 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 chargeconst int NIGHT_FROM_H = 18, NIGHT_TO_H = 8; // the night, local timeconst int NOON_H = 12; // a solar battery should be charging by then; -1 for a UPS on the gridconst long UTC_OFFSET_S = 0; // your time zone in seconds, for "today" and the night (UTC+3: 3 * 3600)| 12 V battery | Full at | Charge kept | Deep night | Cut, back on |
|---|---|---|---|---|
| LiFePO4, 4 cells | 14.0 V | 0.99 | over 80 % | 12.0 V, 13.0 V |
| Lead-acid, 6 cells | 13.2 V | 0.90 | over 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 milliohmconst 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 GNDconst int SDA_PIN = 21, SCL_PIN = 22;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 AINA226 config 0x4B2F: 256 averages, 823 ms of each secondINA228, same shunt: 0.5 mA step, SHUNT_CAL 9830day: 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 againdrift: 0.2 A of error for 10 days adds 48 Ah; only a full charge sets it rightnight: 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 cyclesoverflow: 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 cutThe 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.
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.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.
| Part | Lay it |
|---|---|
| Box | On its back, open side up. 101 x 151 mm with its ears. |
| Lid | Front face down, skirt up. |
| Shunt cover | Closed 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.
Fit it at the battery
For a large bank, have a qualified person do this step. With every load and charger switched off:
- Take the negative cable off the battery first. Insulate its end.
- 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.
- 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.
- 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.
- 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.
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 TLSconst char* DEVICE_ID = "SWD-XXXXXX"; // client ID, username, and the topic nameconst 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 certificateOne 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.
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.
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:
v 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.
Read the record
- The depth of each night.
night_dodis 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 %. SetUTC_OFFSET_Sso the night is your night. - Charge at night.
night_in_ahabove zero means the generator or the grid charged the battery in the night. If that happens whilesocis still at 70 %, the generator starts too early: the battery could have carried the load, and the fuel was spent for nothing. - The drift.
driftis 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 whilesocstill says 40 %, it holds less than you set: lowercapacity_ah. - Energy in and out.
wh_inandwh_outreset 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.
cyclesis 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,
syncreads 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
- Build sheet: parts, wiring and the steps on two A4 pagesbattery-power-monitor-build-sheet.pdf · 100 KB
- Firmware: Arduino sketch, logic, testsbattery-power-monitor-firmware.zip · 25 KB
- Print files (STL) and print notesbattery-power-monitor-stl.zip · 68 KB
- Drawings: the assembly, then the box, the lid and the shunt cover, with every size in mm (4 A3 sheets, 1:1)battery-power-monitor-drawings.pdf · 139 KB
- FreeCAD 1.1 model, with the spreadsheetBatteryPowerMonitor.FCStd · 57 KB
- STEP, every part and moduleBatteryPowerMonitor.step · 360 KB
- Wiring drawingbattery-power-monitor-wiring.svg · 22 KB
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
- Batteries: State of Charge and Cycle Life: counting charge, why voltage is a poor gauge, and what wears a battery.
- Hybrid Systems: Solar with a Generator or the Grid: when the generator should run, and what it costs.
- Monitoring, Faults, Soiling and Degradation: alarm rules that do not cry at every cloud.
- INA226 data sheet: a shunt step of 2.5 µV (81.92 mV full scale), a bus step of 1.25 mV, 36 V at most, and CAL = 0.00512 / (current step x shunt ohms).
- INA228 data sheet: 20 bits, inputs from -0.3 V to 85 V, and SHUNT_CAL = 13107.2 x 10⁶ x current step x shunt ohms.
- Build: the live sensor node: the same firmware family, with one sensor.
Ways to take this build
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 siteKSh 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 supervisorOpen to all
Every step, the firmware and the printable files. Tick the steps as you go.
Start step 1Priced 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 groupPlus 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.



My notes on this page
Kept on this device. To have them on every device, turn on keeping in My notes.
Tip: select words in the lesson, or tap a figure or an equation, to put a note right there.
Notes on earlier wording
The lesson has changed and these words are no longer in it. Your notes are kept, with the words you chose.