Skip to content

INA226 Battery Monitor

sonoaltercocker edited this page Nov 14, 2026 · 9 revisions

Scott Sheppard, KJ4ZZB — Version 1.1 — November 2026

This guide adds battery monitoring to a Raspberry Pi 3B+ that runs from a 12 V LiFePO4 battery. When you are done, the Pi will:

  • measure battery voltage and current (charging and discharging) every 2 seconds
  • track the battery's state of charge (SoC) in percent and amp-hours
  • shut itself down cleanly before the battery runs flat, protecting the SD card
  • log a reading every minute to a CSV file
  • optionally send the battery status as APRS telemetry, which aprs.fi graphs automatically

It works on any Raspberry Pi OS install, including DigiPi. Notes specific to DigiPi's read-only filesystem are marked DigiPi:.


Parts

Part Notes
INA226 voltage/current module, 0–36 V, 20 A Must have the R002 (0.002 Ω) shunt resistor. See Step 1.
12 V LiFePO4 battery Any size; you enter the capacity in the software
Inline fuse or DC breaker Sized to the battery's BMS limit (for example 10 A for a 10 A BMS)
12 V → 5 V buck converter, 5 A Powers the Pi from the battery. Set it to 5.1–5.2 V; a 3 A converter can brown out the Pi under load
4 female-to-female jumper wires For the INA226 → Pi I2C connection
Hook-up wire, 16 AWG For the battery and load wiring
Crimp ferrules or ring terminals Strongly recommended for screw terminals (see the rules)

Software: battery_monitor.py (version 1.6 or later) and, optionally, aprs-send-telemetry.py (version 1.3 or later). Both are in the ina226 folder of the Scott-weewx-aprs repository on GitHub.


Before you start

You'll need:

  • a Raspberry Pi 3B+ running Raspberry Pi OS or DigiPi, connected to your network
  • Optional: an RTC (real-time clock) module on header pins 1–9. The wiring in this guide leaves those pins free for it. Installing it will be covered in a future wiki article.
  • a way to type commands on the Pi. This guide uses SSH from another computer, described next. A keyboard and monitor plugged into the Pi also work, as does DigiPi's built-in web terminal (under shell).

Connecting to the Pi with SSH (Mac)

1. Turn on SSH on the Pi (skip this if you can already connect):

  • Raspberry Pi OS: on the Pi, run sudo raspi-config, then choose Interface Options → SSH → Yes. Or, when writing the SD card with Raspberry Pi Imager, turn on SSH in its OS customisation settings.
  • DigiPi: SSH is normally already on.

2. Find the Pi's address. On the Pi, hostname -I shows it (for example 192.168.1.224). It's also in your router's list of connected devices. On many networks the name digipi.local (DigiPi) or raspberrypi.local (Raspberry Pi OS) works in place of the IP address.

3. Connect from the Mac. Open Terminal (Applications → Utilities → Terminal) and type, using your Pi's address:

ssh pi@192.168.1.224
  • The first time, it asks "Are you sure you want to continue connecting?" Type yes and press Enter.
  • Enter the Pi's password. Nothing appears as you type; that's normal.
  • The prompt changes to pi@digipi:~ $ (or similar). You're now typing on the Pi.
  • Type exit to disconnect.

4. Copying files to the Pi. scp copies files over the same connection. Run it in a Terminal window on the Mac (not inside the SSH session), from the folder that holds the file:

cd ~/Downloads
scp battery_monitor.py pi@192.168.1.224:/home/pi/

If you see "Too many authentication failures": the Mac offered several stored SSH keys before the password, and the Pi stopped counting. Tell SSH to go straight to the password:

ssh -o PubkeyAuthentication=no pi@192.168.1.224

To make that fix permanent, see Optional — Save your connection settings below.

Optional — Connecting from Windows (PowerShell)

Windows 10 and 11 include the same SSH tools as the Mac, so the commands are identical.

1. Open PowerShell. Right-click the Start button and choose Terminal or Windows PowerShell.

2. Check SSH is installed:

ssh -V

If you get "ssh is not recognized", turn it on in Settings → System → Optional features → Add a feature → OpenSSH Client, then reopen PowerShell.

3. Connect (use your Pi's address):

ssh pi@192.168.1.224

Answer yes the first time and enter the Pi's password, just as on the Mac.

4. Copy files with scp, in a PowerShell window on the PC, from the folder that holds the file:

cd $HOME\Downloads
scp battery_monitor.py pi@192.168.1.224:/home/pi/

Notes for Windows:

  • Names ending in .local (such as digipi.local) often don't work on Windows. Use the IP address, or give the Pi a short name as described next.
  • The "Too many authentication failures" message and its fix are the same as on the Mac.

Optional — Save your connection settings

Instead of typing the IP address, user name and options every time, you can save them once in an SSH settings file. Both the Mac and Windows use a file named config in a hidden folder named .ssh in your home folder.

1. The settings. These lines give the Pi the short name digipi:

Host digipi
    HostName 192.168.1.224
    User pi
    PubkeyAuthentication no
  • Host is the short name you'll type. Pick any name.
  • HostName is the Pi's IP address (or digipi.local).
  • User is the Pi's user name.
  • PubkeyAuthentication no goes straight to the password and prevents the "Too many authentication failures" error.

Check first whether the file already exists. Other software, or an earlier setup, may have created it. If it has, add your lines at the end and leave the existing lines alone. If it already has a Host block for this Pi's IP address, edit that block instead of adding a second one.

2a. Create or edit the file on a Mac. In Terminal, look at what's there:

cat ~/.ssh/config
  • If it shows existing settings, open the file and add your lines at the end:

    nano ~/.ssh/config
  • If it says "No such file or directory", the .ssh folder may not exist yet either. Create the folder, then the file:

    mkdir ~/.ssh
    nano ~/.ssh/config

    If mkdir replies "File exists", the folder was already there. That's fine; carry on with the nano line.

Paste the lines, change the IP address to your Pi's, then save with Ctrl-O, Enter, Ctrl-X.

2b. Create or edit the file on Windows. In PowerShell, look at what's there:

type $HOME\.ssh\config
  • If it shows existing settings, open the file and add your lines at the end:

    notepad $HOME\.ssh\config
  • If it says the path doesn't exist, create the .ssh folder (if needed), then the file:

    mkdir $HOME\.ssh
    notepad $HOME\.ssh\config

    If mkdir says the item already exists, the folder was already there. Carry on with the notepad line. When Notepad asks whether to create a new file, choose Yes.

Paste the lines, change the IP address, and save. Notepad sometimes adds .txt to the name, and SSH then ignores the file. Check with:

dir $HOME\.ssh

If you see config.txt, rename it:

ren $HOME\.ssh\config.txt config

3. Use the short name. On either computer:

ssh digipi
scp battery_monitor.py digipi:/home/pi/

For several Pis, add one Host block for each, with a different name and IP address.


Rules that matter

  1. Never put 12 V on the INA226 VCC pin. VCC is the module's logic supply: 3.3 V from the Pi only.
  2. Only the battery goes on the Current + side. Every charger, solar controller and load connects on the Current − side. A charger clipped straight onto the battery terminals bypasses the shunt, so the monitor never sees the charge.
  3. The V+ and V− sense terminals must be wired. Without them the module reads about 0 V, and the software assumes a flat battery.
  4. Use ferrules or ring terminals in the screw terminals, and strain-relieve the leads. A loose battery lead can leave a charger feeding the loads alone, which browns out the Pi.
  5. Keep the I2C jumpers short (under about 20 cm) and away from antennas and coax.

Step 1 — Check the INA226 module

Shunt value. Find the large flat resistor between the screw terminals and read its marking:

Marking Value Use
R002 0.002 Ω ✔ Correct for this guide (up to ±20 A)
R010 0.010 Ω Works up to about 8 A; set R_SHUNT = 0.010
R100 0.100 Ω Only about 0.8 A; not suitable for a battery

Header pins. If the pin header came loose in the bag, it must be soldered to the board. Pins pushed through the holes don't make reliable contact.

Address pads. Leave the address solder pads untouched. The module then answers at I2C address 0x40.


Step 2 — Power wiring

ina226-power-wiring
INA226 terminal Connects to
Current + Battery +, through the fuse or breaker
Current − The +12 V bus: charger or solar controller, 12 V loads, buck converter
V+ A short jumper to Current + (measures battery voltage)
V− Battery −

All negatives (battery, charger, loads, buck converter and the Pi's ground) tie together on one negative bus.

Check with a multimeter: across V+ and V− you should read the battery voltage, about 13 V.


Step 3 — Connect the INA226 to the Pi

The INA226 module used in this guide is the INA226 Voltage Current Monitor 0–36V 20A I2C Power Monitoring Sensor Module from Amazon: https://www.amazon.com/dp/B0DRNG1VKM. Other INA226 boards work too, but their pin labels and header order may differ, so match the wiring by the printed labels, not by position.

The INA226 goes on a second, software I2C bus (bus 3) on pins 17, 16, 18 and 20. This leaves the Pi's standard I2C pins (3 and 5) and header pins 1–9 free for an optional real-time clock (RTC) module, which plugs onto those pins. Use this wiring whether or not you fit an RTC. * Optional: an RTC (real-time clock) module on header pins 1–9, so the Pi keeps the correct time if GPS is lost. The wiring in this guide leaves those pins free for it. See Adding a Real-Time Clock (RTC) to a Raspberry Pi.

ina226-pi-header
INA226 pin Pi pin Function
VCC 17 3.3 V
SDA 16 GPIO 23, I2C bus 3 data
SCL 18 GPIO 24, I2C bus 3 clock
GND 20 Ground
ALE / ALERT — Leave unconnected

Pins 16, 18 and 20 are in the outer row of the header (even numbers). Pin 17 is in the inner row, beside pin 18. Count carefully: pin 20 (ground) is right next to pin 18, and a wire one pin out stops the module from answering.


Step 4 — Enable I2C and find the module

DigiPi: run sudo remount first, before any step that installs or edits files. A reboot returns the filesystem to read-only, so run it again after each reboot.

Turn on I2C. This loads the I2C driver that the tools and the program use:

sudo raspi-config

Choose Interface Options → I2C → Yes, then Finish. (DigiPi: I2C is normally already on.)

Next, make a backup copy of config.txt. A mistake in this file can stop the Pi from booting, and the backup lets you put it back:

sudo cp /boot/firmware/config.txt /boot/firmware/config.txt.bak

Then open it for editing:

sudo nano /boot/firmware/config.txt

Add this line at the end of the file. It creates I2C bus 3 on GPIO 23 and 24 (pins 16 and 18):

dtoverlay=i2c-gpio,bus=3,i2c_gpio_sda=23,i2c_gpio_scl=24

Save with Ctrl-O, Enter, Ctrl-X, then:

sudo reboot

If the Pi doesn't boot properly afterwards, put the SD card in another computer, open the small bootfs partition, and copy config.txt.bak over config.txt.

After the reboot (DigiPi: sudo remount again), install the tools and scan the bus:

sudo apt install -y i2c-tools python3-smbus2
i2cdetect -y 3

You should see 40:

     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
40: 40 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
What you see Meaning
40 ✔ Module found
Only -- No contact. Check VCC (pin 17) and GND (pin 20) first, then SDA/SCL
Every address filled in SDA is stuck low. Usually the module has no power (VCC loose), or SDA is on a ground pin

Step 5 — Install the software

Get battery_monitor.py into the Pi's home folder, using either method.

Option 1 — download it straight onto the Pi (the Pi needs internet access):

wget -O /home/pi/battery_monitor.py https://raw.githubusercontent.com/sonoaltercocker/Scott-weewx-aprs/main/ina226/battery_monitor.py

Option 2 — copy it from the Mac or PC (see Before you start). First download it from the ina226 folder, then:

scp battery_monitor.py pi@<pi-address>:/home/pi/

On the Pi:

chmod +x /home/pi/battery_monitor.py
grep "^VERSION" /home/pi/battery_monitor.py      # VERSION = "1.6" or later

Open the file and check the settings near the top:

nano /home/pi/battery_monitor.py
Setting Default Change it when…
I2C_BUS 3 leave at 3 for the wiring in Step 3
R_SHUNT 0.002 your shunt isn't R002
CAPACITY_AH 10.0 your battery isn't 10 Ah
FULL_V 14.0 your charger holds less than 14 V when full (for example 13.55 for a 13.6 V charger)
SHUTDOWN_SOC / SHUTDOWN_V 5.0 / 12.0 you want a different safe-shutdown point
INVERT False charging shows as negative amps (set True)
CURRENT_OFFSET 0.0 the amps aren't zero with nothing connected (see Step 6)

Step 6 — Test by hand

cd /home/pi
./battery_monitor.py
Battery monitor v1.6  (INA226 0x40 on I2C bus 3)
No saved state - estimating 54% from 13.17 V (accurate only if battery has been resting)
16:02:39   13.17 V   -0.401 A    -5.28 W  SoC  54.0%  ( 5.40 Ah)  ~ 13.5 h left

Press Ctrl-C to stop. Then check:

  • Volts match your multimeter across V+ and V− (within about 0.05 V).
  • Amps are negative with only loads running, and positive while a charger runs. If they're backwards, set INVERT = True.
  • Zero offset (optional): disconnect everything from the Current − side for a moment. If the amps read, say, +0.012, set CURRENT_OFFSET = 0.012.

Starting charge. With no saved state, the program estimates the charge from the voltage, which is only a rough guess for LiFePO4. If you know the battery is full, set it before starting the service:

echo '{"ah_remaining": 10.0}' > /home/pi/battery_state.json

Note: this example assumes a 10 Ah battery. For a different battery, replace 10.0 with your battery's capacity in amp-hours, the same value you set for CAPACITY_AH in Step 5. For example, use 16.0 for a 16 Ah battery or 20.0 for a 20 Ah battery.

Otherwise it corrects itself the first time the battery reaches full charge.


Step 7 — Start it automatically at every boot

This is a one-time setup. Once it's done, the Pi starts the battery monitor by itself every time it boots, and restarts it if it ever stops. There is nothing to run after a reboot.

DigiPi: run sudo remount first. Otherwise the service file isn't saved to the SD card and is lost at the next reboot.

1. Create the service file:

sudo nano /etc/systemd/system/battery.service

Paste these lines, then save with Ctrl-O, Enter, Ctrl-X:

[Unit]
Description=Battery monitor
After=local-fs.target

[Service]
User=pi
ExecStart=/usr/bin/python3 /home/pi/battery_monitor.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

2. Turn it on. enable makes it start at every boot, and --now also starts it right away:

sudo systemctl daemon-reload
sudo systemctl enable --now battery

3. Watch the live readings (press Ctrl-C to stop watching; the monitor keeps running):

sudo journalctl -u battery -f

4. Confirm it survives a reboot:

sudo reboot

After the Pi comes back up, log in again and check:

systemctl is-active battery          # should say: active

How it works

State of charge by counting amp-hours. LiFePO4 voltage stays almost flat from about 20% to 90% charge, so voltage alone can't tell 30% from 80%. The program adds up every amp-hour in and out, and saves the total to battery_state.json once a minute so a reboot doesn't lose it.

Automatic resync to 100%. When the voltage is at or above FULL_V and the charge current has tapered below 0.5 A for 2 minutes, the battery is full, and the count is reset to 100%.

Safe shutdown. If the battery is discharging and falls to 5% or 12.0 V for a full minute, the program saves its state and shuts the Pi down cleanly, before the battery's BMS cuts the power. Short dips while a radio transmits are ignored. The shutdown uses sudo, which works without a password for the pi user on Raspberry Pi OS and DigiPi.

Wiring-fault protection. A reading below 9 V is treated as a wiring problem, not a flat battery, so a loose sense wire can't trigger a shutdown.

Sensor dropouts. If the INA226 stops answering (a loose jumper, for example), the program waits and retries instead of crashing, and fills in short gaps with the last known current.

Live reading for other programs. Every reading is also written to /dev/shm/battery_now.json, in RAM, for other tools such as the APRS telemetry sender.

Files

File Contents
/home/pi/battery_monitor.py The program (the Python script itself)
/etc/systemd/system/battery.service The service that starts the program at every boot. Its name is battery, so the commands below use systemctl ... battery
/home/pi/battery_state.json Saved charge level (amp-hours remaining)
/home/pi/battery_log.csv One reading per minute: time, volts, amps, watts, SoC, Ah
/dev/shm/battery_now.json Latest reading, updated every 2 seconds
/tmp/battery_* DigiPi: fallback copies when the home folder is read-only (cleared at reboot)

Everyday commands

Task Command
Is it running? systemctl is-active battery
Live readings sudo journalctl -u battery -f
Last 20 lines sudo journalctl -u battery -n 20 --no-pager
Latest reading cat /dev/shm/battery_now.json
Restart after editing settings sudo systemctl restart battery
Stop and disable sudo systemctl disable --now battery
Whole power system check battery-check.py (next section)

Check the whole power system

battery-check.py checks everything in one command: the battery monitor is running, the Pi's 5 V supply has had no undervoltage, and the last 24 hours of battery_log.csv (lowest voltage, amp-hours in and out, gaps). Run it on a new station after 24 hours on its own power, and after any change to the power system. The station build (station-build.sh 2.2 and later) installs it; on other systems:

sudo wget -O /usr/local/bin/battery-check.py https://raw.githubusercontent.com/sonoaltercocker/Scott-weewx-aprs/main/ina226/battery-check.py
sudo chmod 755 /usr/local/bin/battery-check.py
battery-check.py              # last 24 hours
battery-check.py --hours 6    # a shorter period

Every check should read PASS. See Power System Check for how to read the results.


Optional — Send battery status as APRS telemetry

aprs-send-telemetry.py reads /dev/shm/battery_now.json and sends a standard APRS telemetry packet every 10 minutes. It goes over RF through Direwolf, and to APRS-IS when the Pi has internet. aprs.fi graphs the values on the station's Telemetry page.

Channel Value Range
A1 Battery voltage 10.00–15.10 V
A2 Net current (+ = charging) −5.00 to +5.20 A
A3 State of charge 0–100%
A4 Pi CPU temperature 0–127.5 °C
A5 Net power −70 to +83 W
Bits Charging · Low battery · Fault · Full on/off

1. Download it onto the Pi (or copy it over with scp as in Step 5, then sudo mv it into /usr/local/bin/):

sudo wget -O /usr/local/bin/aprs-send-telemetry.py https://raw.githubusercontent.com/sonoaltercocker/Scott-weewx-aprs/main/ina226/aprs-send-telemetry.py
sudo chmod 755 /usr/local/bin/aprs-send-telemetry.py

2. Set your callsign and APRS-IS passcode. Open the script:

sudo nano /usr/local/bin/aprs-send-telemetry.py

Near the top you'll find USER = None and PASS = None. Replace None with your own values, in quotes, then save with Ctrl-O, Enter, Ctrl-X:

USER = "N0CALL-3"      # your callsign-SSID
PASS = "12345"         # your APRS-IS passcode

Then test it:

aprs-send-telemetry.py --dry-run      # shows the packets, sends nothing
aprs-send-telemetry.py --defs         # sends once, with channel names and units

3. Stop systemd from deleting the telemetry counter. By default, systemd removes a user's files in /dev/shm whenever that user logs out. That resets the packet counter after every cron run:

sudo mkdir -p /etc/systemd/logind.conf.d
printf '[Login]\nRemoveIPC=no\n' | sudo tee /etc/systemd/logind.conf.d/no-removeipc.conf
sudo systemctl restart systemd-logind

4. Schedule it with crontab -e (DigiPi: sudo remount first, or the schedule is lost at the next reboot):

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
2-59/10 * * * * /usr/local/bin/aprs-send-telemetry.py >/dev/null 2>&1

Each send adds one line to /dev/shm/aprs-send.log:

2026-10-28 17:32:08  telemetry #001        APRS-IS: no internet   RF: sent     13.16 V -0.10 A 53% CPU 40.8 C

Run it as the pi user, not with sudo. Direwolf must be running (KISS port 8001) for the RF path.


Troubleshooting

Symptom Likely cause
i2cdetect -y 3 shows no 40 Loose VCC (pin 17) or GND (pin 20) jumper; bus 3 line missing from config.txt; header not soldered
Every address shows in i2cdetect SDA stuck low: module has no power
No such device or address in the log, repeating A jumper came loose (often VCC on pin 17); reseat it
Volts read about 0 V+ / V− sense wires missing
Amps stay negative while charging Charger is on the battery side of the shunt; move it to the +12 V bus
Charging shows negative, loads positive Set INVERT = True
Never reaches 100% Charger stops below FULL_V; lower it to just under your charger's voltage
Pi shuts down soon after boot Wrong saved state (for example after a wiring fault). Stop the service, set battery_state.json by hand, start it again
Telemetry always T#000 RemoveIPC=no not set (Optional section, step 3)
Telemetry RF: failed Direwolf not running

Clone this wiki locally