Skip to main content

Logging battery SOC from an RS485 BMS with Python, then finding out what the data says

Updated 6 min readMarkdown

Most solar batteries know far more about themselves than their owners ever see. The BMS tracks state of charge, pack voltage, current, temperatures and individual cell voltages, and it will usually hand them over on an RS485 or CAN port. The inverter reads a few of those values and shows a percentage on its screen. Everything else disappears.

I wanted a simple way to log battery SOC with Python on remote sites, keep the raw data as CSV, and answer three questions later: how deep does the battery go each night, how many cycles is it really doing, and are the cells drifting apart? This post is the minimal version of that setup. It runs on a Raspberry Pi or any old laptop.

A warning before the code

There is no universal BMS register map. Some batteries speak Modbus RTU over RS485, many use a vendor protocol on the same wires, and others only expose CAN for the inverter. Register addresses, scaling and even byte order vary by manufacturer and firmware.

The register map below is an example only. It is not the map of any particular product. Get the real protocol document from your battery supplier and change the table at the top of the script. If the battery uses a non-Modbus protocol, the logging and analysis parts still apply; only the read function changes.

Also: if the inverter is already talking to the BMS on that port, don't add a second master on the same bus. Use a separate monitoring port if the battery has one, or read the values from the inverter instead.

What you need

  • A USB-to-RS485 adapter (two wires, A and B, plus ground if the port provides it)
  • Python 3.9 or newer
  • pip install minimalmodbus pandas
  • The battery's protocol document: slave address, baud rate, register addresses and scaling

Part 1: the logger

minimalmodbus is small and its API has been stable for years, which matters on a box nobody will touch for months.

# bms_logger.py  — poll a BMS over Modbus RTU and append rows to a CSV.
# REGISTER MAP IS AN EXAMPLE ONLY. Replace with your battery's protocol document.
import csv, time, datetime as dt
import minimalmodbus

PORT, SLAVE_ID, BAUD = "/dev/ttyUSB0", 1, 9600
INTERVAL_S = 60

# name: (register address, scale, signed)
REGS = {
    "pack_v":   (0x0000, 0.01, False),   # volts
    "current_a":(0x0001, 0.01, True),    # + charge / - discharge
    "soc_pct":  (0x0002, 1,    False),
    "temp_c":   (0x0003, 0.1,  True),
    "cell_max_mv": (0x0004, 1, False),
    "cell_min_mv": (0x0005, 1, False),
}

bms = minimalmodbus.Instrument(PORT, SLAVE_ID)
bms.serial.baudrate = BAUD
bms.serial.timeout = 1.0

def read_all():
    row = {"ts": dt.datetime.now().isoformat(timespec="seconds")}
    for name, (addr, scale, signed) in REGS.items():
        raw = bms.read_register(addr, 0, functioncode=3, signed=signed)
        row[name] = round(raw * scale, 3)
    return row

with open("bms_log.csv", "a", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["ts", *REGS])
    if f.tell() == 0:
        w.writeheader()
    while True:
        try:
            w.writerow(read_all()); f.flush()
        except (IOError, ValueError) as e:      # timeouts, CRC errors
            print("read failed:", e)
        time.sleep(INTERVAL_S)

A few practical notes from running this kind of script in the field:

  • One-minute polling is plenty. SOC moves slowly. Faster polling just makes larger files and more bus traffic.
  • Log raw readings, analyse later. Don't compute anything clever in the logger. If the scaling turns out to be wrong, you can fix it in the analysis and keep the data.
  • Expect gaps. Serial reads fail occasionally. The try block keeps the logger alive, and the analysis below copes with missing rows.
  • Run it as a service. A systemd unit with Restart=always brings it back after a power cut.

Part 2: what the data says

After a few weeks you have tens of thousands of rows. Here is the analysis script I use, built around pandas.

# analyse.py — daily summary from bms_log.csv
import pandas as pd

NOMINAL_AH = 100          # example only: your battery's rated capacity
IMBALANCE_MV = 50         # example alert threshold, check the BMS manual

df = pd.read_csv("bms_log.csv", parse_dates=["ts"]).set_index("ts").sort_index()

# Integrate current over time (Ah). Gaps longer than 5 min are not integrated.
dt_h = df.index.to_series().diff().dt.total_seconds().div(3600)
dt_h = dt_h.where(dt_h < 5/60, 0)
df["ah"] = df["current_a"] * dt_h
df["delta_mv"] = df["cell_max_mv"] - df["cell_min_mv"]

daily = pd.DataFrame({
    "soc_min":    df["soc_pct"].resample("D").min(),
    "soc_max":    df["soc_pct"].resample("D").max(),
    "ah_out":     -df["ah"].clip(upper=0).resample("D").sum(),
    "ah_in":      df["ah"].clip(lower=0).resample("D").sum(),
    "temp_max":   df["temp_c"].resample("D").max(),
    "delta_max":  df["delta_mv"].resample("D").max(),
})
daily["equiv_cycles"] = daily["ah_out"] / NOMINAL_AH
daily["imbalance_flag"] = daily["delta_max"] > IMBALANCE_MV

print(daily.round(2).tail(14))
print("total equivalent cycles:", round(daily["equiv_cycles"].sum(), 1))
print("days below 20% SOC:", int((daily["soc_min"] < 20).sum()))

Reading the summary

soc_min per day is the number I look at first. If the battery bottoms out near its lower limit most nights, the system is undersized for the load or the PV is not refilling it. If it never drops below 70%, the battery may be oversized for this site, which is useful to know before building the next one.

equiv_cycles converts discharged amp-hours into full-cycle equivalents. A battery that goes from 100% to 70% every night is doing about 0.3 equivalent cycles a day, roughly 110 a year. That is the figure to compare against the cycle-life claim on the datasheet, together with the depth of discharge and temperature the claim was tested at.

ah_in versus ah_out over a week gives a rough idea of round-trip losses and whether the battery is being fully recharged. If ah_in is consistently lower than ah_out and SOC drifts down day after day, the PV can't keep up.

delta_max is the largest gap between the highest and lowest cell voltage each day. A small, stable gap is normal. A gap that grows week by week, especially near full charge, is an early sign of imbalance worth raising with the supplier while the battery is still under warranty. The 50 mV threshold here is a placeholder; use the value your BMS documentation gives.

temp_max catches cabinets that cook in the afternoon, which shortens battery life quietly.

Where this fits

When you log battery SOC with Python on unattended sites like weather stations, water-level monitors and cameras, the log is often the only evidence of how the power system behaves in the worst month. It tells you whether the battery and PV were sized correctly in the first place. If you are at that sizing stage, I found these notes on choosing a power setup for monitoring sites a useful checklist of the inputs to collect. For the general sizing order — loads, daily energy, autonomy, PV, battery, then inverter — there is a reference at https://solarenergystoragesystem.com/en/knowledge.

The code above is deliberately short. Add a chart, push the CSV to a server, send yourself an alert when soc_min drops below a threshold. Start with the boring version that logs reliably, though. Data you didn't collect can't be analysed.


Disclosure: I work with TORCHN. Yangzhou Weikechuang handles export trade and projects, and Yangzhou Dongtai handles production; both share the TORCHN brand.

No comments yet. Be the first to comment.