EV Battery Management System
ADBMS6830B daisy chain + MAX32690 firmware
Complete technical reference: pack design (series / parallel), BMS structure, isoSPI communication, cell measurement, temperature sensing, cell balancing, firmware, debugging, and interview preparation.
1. Project overview
1.1 What the system does
The project is the battery management system (BMS) for a college electric-vehicle battery pack. The pack is a 40S7P lithium-ion pack: 280 cells, 144 V nominal and 168 V at full charge (40 × 3.6 V and 40 × 4.2 V). It is built from eight 5S7P modules (5 parallel groups of 7 cells each, 18 V nominal, 21 V max per module). The cells are watched by Analog Devices ADBMS6830B cell-monitor ICs. The monitor ICs are linked in a daisy chain over isoSPI, an isolated two-wire link, back to an ADBMS6822 isoSPI transceiver and a MAX32690 microcontroller running bare-metal C firmware.
The firmware:
- wakes the chain and configures every monitor;
- runs the ADCs and reads every cell voltage and thermistor temperature;
- verifies each packet's CRC (PEC);
- detects over-voltage, under-voltage and over-temperature;
- performs passive cell balancing by switching bleed resistors across the highest cells.
1.2 Scope of the work
| Area | Work done |
|---|---|
| MCU firmware | Bare-metal C on the MAX32690 using MaximSDK and parts of ADI's no-OS framework, built in VS Code Project notes |
| ADBMS programming | Wake-up sequence, configuration registers, ADC start commands, register-group reads, PEC generation and checking, multi-device frame parsing, balancing control |
| Bring-up | Single board first, then a 2-board daisy chain with 5 active cells on board 1 and 7 on board 2 Project notes |
| Debugging | isoSPI wiring and termination, PEC errors (−77), a NULL-pointer HardFault (dead LED), MaximSDK / no-OS build integration |
| Not in scope | PCB design (ADI evaluation boards were used), pack-current sensing, SOC estimation, vehicle CAN integration |
1.3 One-minute technical summary (for interviews)
4 + 8·i in the response. Every frame is validated with a 10-bit data PEC that includes the device's command counter. Cell temperatures come from NTC thermistors on the monitor's GPIOs, biased from its 3 V reference. Balancing uses the IC's internal discharge FETs with a bleed-to-minimum algorithm, hysteresis and a hardware timeout. The bench bring-up moved from one monitor board to a 2-board chain with an uneven 5 + 7 active-channel split, which required correct port-A/port-B wiring, line termination, tie-off of unused cell inputs and per-device parsing.
1.4 Resume bullet options
- Developed bare-metal C firmware on a MAX32690 (Arm Cortex-M4F) to control a daisy chain of ADBMS6830B 16-channel battery cell monitors over isolated isoSPI for a 144 V (40S7P, 280-cell) EV battery pack.
- Implemented cell-voltage and NTC temperature acquisition with CRC (PEC15 / PEC10) validation, over/under-voltage and temperature fault detection, and passive cell balancing with hysteresis and hardware timeout.
- Scaled the driver from a single module to a multi-device chain with uneven channel counts (5 + 7 active cells): isoSPI termination, unused-channel tie-off, and multi-device frame parsing.
- Root-caused a Cortex-M HardFault (NULL device pointer from a mismatched device table) and resolved MaximSDK / ADI no-OS build integration issues (VPATH / IPATH, AUTOSEARCH conflicts).
2. System structure
The system has four levels: the physical hierarchy of the battery, the hardware blocks, the layers of software and hardware a measurement passes through, and the voltage domains it crosses. Understanding these four views makes every later section easier.
2.1 Physical hierarchy: cell → group → module → pack
| Level | What it is | What the BMS sees |
|---|---|---|
| Cell | One Li-ion can or pouch (e.g. 3.7 V, 3 Ah) | Nothing directly unless the group is 1P |
| Parallel group (mP) | m cells welded together on common bus bars | One voltage channel (the group's shared voltage) |
| Module (kS) | k groups in series, mechanically one unit (here 5S7P: 35 cells, 18 V nominal) | k channels + a few NTCs on one monitor IC |
| Pack (nS mP) | Modules in series + fuse, contactors, current sensor, enclosure | The whole daisy chain + MCU + pack-level sensors |
2.2 Hardware blocks and signal path
| Block | Part | Role |
|---|---|---|
| Cell monitor (×N) | ADBMS6830B on the EVAL-ADBMS6830BMSW board Datasheet | Measures up to 16 series cells and 10 GPIO/temperature inputs. Drives 16 balancing switches. Has 2 isoSPI ports. |
| isoSPI master | ADBMS6822 dual transceiver (EVAL-ADBMS6822, Arduino-shield format) | Converts the MCU's 4-wire SPI into isolated 2-wire pulses and back |
| Controller | MAX32690 on the AD-APARD32690-SL board | Arm Cortex-M4F at 120 MHz, ~3 MB flash, 1 MB SRAM, 2× CAN 2.0B, BLE 5, RISC-V co-processor. Runs the firmware. |
| Debug | MAX32625PICO (CMSIS-DAP) | SWD flashing and debugging, plus the UART console |
| Host | PC with VS Code + MaximSDK | Build, flash, serial monitor |
Following one cell measurement end to end
- The cell group's voltage reaches the monitor board through a sense wire and an RC filter on pins Cn / Cn−1.
- The ADBMS6830B's C-ADC for that channel converts it continuously. A new 16-bit result appears in the CVx register group every 1 ms.
- The MCU sends
RDCVA(with its PEC15) over SPI to the ADBMS6822. The ADBMS6822 turns it into isoSPI pulses on the twisted pair. - Board 1 receives the command on port A and forwards it out of port B to board 2. Each device then shifts out its 6 data bytes + 2 PEC bytes. The bottom device's data arrives first.
- The ADBMS6822 converts the returning pulses back to SPI MISO bytes. The MCU checks each device's PEC10 and converts each code:
V = code × 150 µV + 1.5 V. - The application layer compares each value with the OV/UV limits, updates the balancing decision, and writes the new discharge bits back to the whole chain in a single
WRCFGBframe.
2.3 Layered view (hardware + firmware)
Keeping the layers separate is what makes the firmware testable. The device driver (layer 4) talks to hardware only through the three HAL functions of layer 3 (spi_xfer, cs_set, delay_us). So the same driver runs on the MAX32690 or against a simulated chain on a PC (Appendix B).
2.4 Voltage domains and why isolation is needed
High-voltage side
Each monitor board's ground is the negative terminal of its own module. With one monitor per module, module 2's "0 V" is up to 21 V above module 1's, module 3's up to 42 V, and the top module (M8) sits at 147–168 V above the pack negative at full charge.Low-voltage side
The MCU, PC, VCU and charger share the vehicle's 12 V / chassis ground. Plain SPI between these domains is impossible: shared ground plus large voltage differences means destroyed parts and a shock hazard. isoSPI's transformer coupling gives galvanic isolation on every link.3. How a lithium-ion cell works
A BMS only makes sense once you know what it is protecting. A lithium-ion cell is not a tank of electricity. It is a slow, reversible chemical reaction held inside a narrow safe window, and nearly every BMS feature traces back to one property of that reaction. This chapter builds that picture: the chemistry, how voltage relates to charge, how charging works, and how a cell behaves electrically under load.
3.1 The rocking-chair chemistry
A Li-ion cell has two electrodes that can each store lithium inside their crystal structure, a process called intercalation:
- Anode (negative): graphite coated on copper foil. When charged, lithium sits between the graphite layers (LiC6).
- Cathode (positive): a lithium metal oxide on aluminium foil. NMC (nickel-manganese-cobalt) and NCA are the high-energy types; LFP (lithium iron phosphate) is the safer, flatter-voltage type.
- Electrolyte: a lithium salt (LiPF6) dissolved in organic carbonates. It lets ions through but not electrons.
- Separator: a porous polymer film that keeps the electrodes apart. If it fails, the cell is internally shorted.
When the cell charges, the charger pushes electrons into the anode through the external circuit, and lithium ions leave the cathode and travel through the electrolyte to the anode. When it discharges, the process reverses and the electrons do useful work in the load on their way back. Because the ions "rock" back and forth between the electrodes, this is called rocking-chair chemistry.
On the first charges, a thin SEI (solid electrolyte interphase) layer forms on the anode. It protects the electrolyte from further reaction, but it slowly thickens over the cell's life, consuming lithium. This is one main reason capacity fades with age. High temperature and high voltage speed it up, so the BMS's limits also protect lifetime, not just safety.
3.2 Chemistries compared
"Lithium-ion" is a family. The cathode material sets the voltage, energy density, lifetime and, above all, how violently the cell fails. The BMS limits have to match the chemistry: an LFP pack with NMC limits would never fully charge, and an NMC pack with LFP limits would be overcharged.
| Chemistry | Nominal / max / min V | Energy density (cell, typical) | Cycle life (typical) | Thermal stability | BMS notes |
|---|---|---|---|---|---|
| NMC (this project) | 3.6–3.7 / 4.2 / 2.5–3.0 | High (≈150–250 Wh/kg) | ~1000–2000 | Moderate | Usable OCV slope, good voltage-based SOC near the ends |
| NCA | 3.6 / 4.2 / 2.5–3.0 | Very high | ~1000 | Lower | Tight voltage and temperature control |
| LFP | 3.2 / 3.65 / 2.5 | Lower (≈90–160 Wh/kg) | ~2000–5000+ | High | Very flat OCV: SOC from voltage is hard, balancing needs care |
| LTO (anode) | 2.4 / 2.8 / 1.5 | Low | 10 000+ | Very high | Many series cells for a given voltage |
With NMC cells, 144 V nominal / 168 V max corresponds to exactly 40 in series (3.6 V and 4.2 V per cell). The same pack voltage with LFP would need 45 cells in series.
3.3 Cell formats and how a parallel group is built
Cylindrical
18650 (18 mm × 65 mm) or 21700. Rigid steel can, cheap, very consistent, easy to cool between cells. Small capacity per cell, so many cells and many welds. Common in student and light-EV packs.Prismatic
Large rectangular aluminium can, tens to hundreds of Ah. Few cells, simple bus bars, but swelling must be held by end plates.Pouch
Laminated foil bag. Best packing density and light, but needs mechanical support and compression, and swells as it ages.A cylindrical-cell group such as the project's 7P is built by spot-welding nickel (or nickel-plated copper) strips across the 7 positive and 7 negative terminals. Good practice:
- Match the cells first (same batch, capacity- and resistance-graded, voltages within a few millivolts). Joining cells at different voltages causes a large equalising current at the moment of welding.
- Fuse each cell (fuse wire or a narrow neck in the strip). If one cell shorts internally, the other six would otherwise dump current into it.
- Equal current paths. If one cell sits on a longer strip path, it carries less current and ages differently. Cells inside a group still drift slightly even though the group shares one voltage.
- Sense wire placement: the BMS sense point should sit on the group's bus bar, not on a single cell, so it reads the group voltage and not a strip voltage drop.
3.4 The safe operating window and why each limit exists
| Limit | Typical NMC / NCA value Engineering practice | What happens outside it |
|---|---|---|
| Maximum cell voltage | 4.20 V | The cathode becomes unstable and the electrolyte oxidises. Gas and heat are released, and metallic lithium can plate onto the anode. Overcharge is the classic trigger for thermal runaway. |
| Minimum cell voltage | 2.5–3.0 V | The anode's copper foil starts to dissolve. On the next charge the copper can re-deposit as dendrites and short the cell internally. |
| Charge temperature | 0 °C to ~45 °C | In the cold, lithium can't enter the graphite fast enough, so it plates as metal on the surface: permanent capacity loss and a short-circuit risk. |
| Discharge temperature | −20 °C to ~60 °C | Ageing accelerates sharply with heat. Self-heating reactions begin somewhere between about 80 and 130 °C depending on the chemistry. |
| Current | Datasheet C-rate (continuous and pulse) | I²R heating inside the cell, a voltage sag that can drop below cut-off, faster ageing. |
3.5 Voltage and state of charge: the OCV curve
A cell left at rest settles to its open-circuit voltage (OCV), which depends almost entirely on how much lithium sits in each electrode, i.e. on the state of charge (SOC). That is why a BMS can estimate SOC from voltage, but only under three conditions:
- The cell must be at rest. Under current, the terminal voltage differs from OCV (next sections).
- The curve must have slope. In the flat middle region a few millivolts can mean 10–20 % of SOC. NMC is usable, LFP is notoriously hard.
- The curve depends on temperature and age, so real BMSs store a table per temperature.
The same curve explains why balancing is usually done near full charge: the curve is steep there, so a voltage difference between groups maps reliably to an SOC difference.
3.6 How a Li-ion cell is charged: CC-CV
Li-ion cells are charged in two phases:
- Constant current (CC): the charger pushes a fixed current (e.g. 0.5C) and the voltage rises. About 70–80 % of the charge goes in during this phase.
- Constant voltage (CV): once the cell reaches 4.20 V, the charger holds the voltage and the current falls naturally as the cell fills. Charging ends when the current drops to a small value (typically C/20 to C/10).
For a pack, the charger's CV setpoint is n × 4.20 V, but the charger only sees the pack total. If one group is higher than the others, it reaches 4.20 V before the pack total says "full", and only the BMS can see that. This is the most important reason for per-group monitoring: the BMS must stop or reduce the charge when the highest group reaches its limit, even though the charger thinks there is room left.
3.7 The cell as a circuit: equivalent circuit model
Engineers model a cell electrically with the Thevenin equivalent circuit:
- OCV(SOC, T): the ideal voltage source from the OCV curve.
- R0: ohmic resistance (electrolyte, foils, tabs). It causes the instant voltage step when current changes.
- R1 ∥ C1: charge-transfer and diffusion effects. They cause the slow sag under load and the slow recovery (relaxation) after it.
The model explains several BMS behaviours. Voltage limits must allow for the I·R0 drop, or a hard acceleration would look like an under-voltage. SOC from voltage needs a rest period, or the RC voltage is mistaken for SOC. Measuring R0 from the step (ΔV/ΔI) is a common way to track ageing (SOH). And because balancing current also flows through resistances (the filter and wiring), the same reasoning explains the measurement error during balancing (Section 16.4).
3.8 Terms used throughout
| Term | Meaning | Example |
|---|---|---|
| Nominal voltage | Average voltage over a discharge | 3.6–3.7 V (NMC), 3.2 V (LFP) |
| Capacity (Ah) | Charge delivered from full to empty | 3.0 Ah 18650 |
| Energy (Wh) | Vnominal × Ah | 3.7 V × 3.0 Ah = 11.1 Wh |
| C-rate | Current relative to capacity: 1C = full capacity in one hour | 1C of 3 Ah = 3 A; 3C = 9 A |
| Internal resistance | Causes voltage sag (I·R) and heat (I²R) | 15–30 mΩ for an 18650 |
| Self-discharge | Slow internal charge loss at rest | A few % per month. Differences between cells cause drift. |
| SOC / SOH | State of charge (%) / state of health (capacity or resistance vs new) | SOC 80 %, SOH 92 % |
4. Series and parallel: designing an nS mP pack
A pack described as nS mP has n parallel groups connected in series, and each group contains m cells in parallel. Total cells = n × m. The two numbers do completely different jobs: n sets the voltage, m sets the capacity and current. The product n × m sets the energy.
4.1 The rules
For a fixed number of cells, energy is fixed. What the n/m split changes is the trade between voltage and current, and with it the BMS cost.
4.2 nS vs mP: what each number changes
| Property | Increase n (more series groups) | Increase m (more cells per group) |
|---|---|---|
| Pack voltage | ↑ proportionally | unchanged |
| Capacity (Ah) | unchanged | ↑ proportionally |
| Energy (Wh) | ↑ | ↑ |
| Max current | unchanged | ↑ (current shared across m cells) |
| Current for the same power | ↓ → thinner cables, smaller contactors, less I²R loss | unchanged |
| Pack resistance | ↑ (n·R) | ↓ (R/m) |
| BMS channels / monitor ICs | ↑ one channel per group | no change |
| Balancing time | unchanged per group | ↑ (bigger Ah per group, same bleed current) |
| Insulation and safety | ↑ requirements (above the commonly used 60 V DC threshold, high-voltage rules apply) | unchanged |
| Single-cell failure | An open cell in a 1P string stops the whole pack | Group keeps working with less capacity; a shorted cell is fed by its group-mates (needs cell fusing) |
4.3 Why series groups drift apart
Groups in series carry exactly the same current, so it's tempting to think they stay perfectly matched. They don't. Each group has slightly different capacity (manufacturing spread of 1–2 %), self-discharge (small leakage currents that differ cell to cell), temperature (a group in the middle of a module runs warmer and ages faster) and parasitic loads (a monitor IC powered from part of the stack drains those cells). Every one of these effects adds up cycle after cycle.
The charger can only stop when the highest group reaches 4.20 V, and the vehicle must stop when the lowest group reaches cut-off. As the spread grows, the usable window shrinks from both ends. The pack loses range even though no cell is damaged. Balancing exists to remove this drift, and it only needs to remove the rate of drift (tens of mA), not move the pack's full charge current. That's why small bleed currents are enough.
4.4 Parallel-first vs series-first (why "nS mP" means groups)
Parallel-first (nS mP)
- Cells in a group sit on common bus bars, so they self-equalise.
- The BMS needs only n channels, whatever m is.
- A weak cell is "averaged" by its group-mates.
- Standard for EV modules and battery packs.
Series-first (m strings of nS)
- Each string is independent. Mid-string nodes are not shared.
- Needs n × m channels (a BMS per string). Otherwise cells go unmonitored.
- Strings with different voltages circulate current between them.
- Used when strings must be switched separately (redundancy, very large storage systems).
4.5 How to choose n and m (step by step)
- Pick the voltage window from the load. The motor controller / inverter has an input range, for example 39–60 V for a 48 V system. Choose n so that
n × V_cutoff ≥ controller minimumandn × 4.2 V ≤ controller maximum. The nominal voltage then falls out as n × 3.7 V. - Pick m from the energy (range) requirement.
m = ceil( E_required / (n × V_cell × Ah_cell) ). Add margin for ageing (often 10–20 %) and for not using 0–100 % SOC. - Check current. Peak current is highest at the lowest voltage:
I_peak = P_peak / V_min. Per-cell current isI_peak / m, and it must stay inside the cell's continuous and pulse ratings with thermal margin. If not, increase m or choose a higher-power cell. - Check heat and sag.
I² × R_packgives the losses andI × R_packthe voltage drop at peak load, which must not push the pack below the controller minimum. - Fit the BMS. Channels = n. Monitor ICs =
ceil(n / 16)as a minimum. In practice the pack is split into modules that each fit one IC (e.g. 5S, 8S, 12S, 16S). Unused channels are tied off (Section 11). - Split into modules. Choose a module size that is easy to handle and assemble, ideally under 60 V DC per module, and divides n evenly. Modules also set the mechanical layout, cooling and service units.
- Charger and protection. Charger constant-voltage setpoint = n × 4.2 V (often slightly lower for longer life). Fuse, contactors and cables are rated for Ipeak at Vmax.
4.6 Worked example: the project pack, 40S7P
The pack is 40S7P. Running the selection steps backwards shows why each number makes sense. Cell capacity and current rating are left as variables. The table shows two common 18650 capacities (2.5 Ah and 3.0 Ah) and an illustrative 15 A continuous rating and 20 mΩ resistance, so the arithmetic can be redone with the real cell's datasheet. Engineering practice
| Quantity | Formula | Result |
|---|---|---|
| Nominal voltage | 40 × 3.6 V | 144 V (a 144 V-class drive system) |
| Maximum voltage | 40 × 4.2 V | 168 V: charger CV setpoint, and the voltage that every contactor, fuse, connector and the isoSPI isolation must handle |
| Minimum voltage | 40 × 3.0 V (or 2.5 V) | 120 V (100 V). The controller must keep running down to this. |
| Capacity | 7 × Ahcell | 17.5 Ah (2.5 Ah cells) / 21 Ah (3.0 Ah cells) |
| Energy | 144 V × 7 × Ahcell | 2.52 kWh / 3.02 kWh |
| Continuous current | 7 × Icell | 105 A with 15 A cells → ≈ 15 kW at 144 V |
| Pack resistance (cells only) | (40 / 7) × 20 mΩ | 114 mΩ → at 100 A: 1.14 kW of heat and 11.4 V of sag (plus bus bars and welds) |
| BMS channels | n | 40 voltage channels (41 sense points), regardless of the 7P |
| Monitor ICs | ceil(40 / 16) | ≥ 3 (e.g. 15S + 15S + 10S on module boundaries), or 8 with one IC per module |
| Read frame (8 ICs) | 4 + 8 × 8 | 68 bytes per register group → 544 µs at 1 MHz |
| Balancing | 5 % of 7 × 2.5 Ah ÷ 118 mA | 0.875 Ah → ≈ 7.4 h. Larger groups take proportionally longer. |
| Safety class | 168 V > 60 V DC | High-voltage system: insulation, contactors with pre-charge, insulation monitoring (Section 6) |
Why 7P? The parallel count is what sets capacity (range) and current capability. Seven cells per group gives a pack in the 17–21 Ah class and, with high-drain cells, around 100 A continuous, which is plausible for a small EV motor. More parallel cells would add range and current, but also weight, and every group would take longer to balance.
Why 40S? The series count is fixed by the drive system's voltage. 40 groups of 3.6 V give the 144 V nominal class, and the 120–168 V operating span has to fit the motor controller's input window. Doubling the voltage instead of the current halves the cable current for the same power, which cuts I²R losses by four.
A generic example for comparison (48 V, 2 kWh)
A 39–60 V controller needs 13S (39.0–54.6 V). 2 kWh ÷ (13 × 3.7 V × 3 Ah) = 13.9 → 14P (13S14P, 182 cells, 42 Ah). At 6 kW and 39 V that is 154 A → 11 A per cell. Balancing a 5 % imbalance at 118 mA takes about 18 h because each group is 42 Ah. The same method gives a very different shape for a different target.
4.7 Why 5S modules?
- Safe to handle: 5 × 4.2 V = 21 V maximum per module (18 V nominal). Well under 60 V DC, so modules can be built, tested and replaced as low-voltage parts. Only the assembled 168 V pack is high voltage.
- Scales in steps: pack series count = 5 × (number of modules). The project uses 8 modules = 40S = 144 V nominal, 168 V max.
- Fits the monitor: one 16-channel ADBMS6830B can watch one module (11 channels tied off), or three modules (15S) to save ICs at the cost of longer sense wires between modules.
- Thermal and mechanical: a small module is easier to cool, fix to the chassis, and fit NTCs into.
4.8 Failure modes to know
| Failure | In series | In parallel | BMS visibility |
|---|---|---|---|
| Cell open-circuit | Whole string stops (1P) | Group loses 1/m capacity and its voltage moves faster under load | Seen indirectly: that group sags more and reaches limits first |
| Cell internal short | Cell discharges itself, then UV | Group-mates dump current into the short → heat. Needs per-cell fuse links. | Group voltage drops at rest. Temperature rises. |
| Capacity mismatch | Drift in SOC → needs balancing | Self-corrected inside the group | Visible as group-to-group voltage spread |
| Joining unequal cells | — | Large inrush current when cells at different voltages are welded together | Match cell voltages before assembly |
Interactive pack calculator
5. What a BMS does, and BMS architectures
5.1 Five functions
1 · Measure
Every group's voltage, temperatures at several points, pack current, pack voltage, insulation resistance.2 · Protect
Keep every group inside its window. Request current limits. Open the contactors on faults.3 · Balance
Keep group SOCs matched so the full capacity stays usable.4 · Estimate
SOC (coulomb counting + OCV correction, often a Kalman filter), SOH, power limits.5 · Communicate
CAN to the VCU and charger: limits, faults, SOC, balancing status.This project
Covers functions 1–3 at the cell-monitor level, plus fault reporting on the console.5.2 Architectures
| Type | How it works | Pros | Cons |
|---|---|---|---|
| Centralised | One board, long sense wires to every cell | Cheapest for small packs | Heavy wiring harness, hard to scale, wires run across HV areas |
| Modular / distributed (this project) | One monitor IC per module, daisy-chained to one master MCU | Short sense wires, scales to any voltage, modules testable alone | Needs isolated communication (isoSPI) |
| Wireless | Monitor ICs talk to the master by radio | No communication harness | RF design, security, newer technology |
5.3 Estimating SOC and SOH
The monitor ICs deliver voltages and temperatures, but a driver wants to know "how much range is left". That is the job of SOC estimation, done by the master MCU. Two basic techniques have opposite strengths:
Coulomb counting
Integrate the pack current over time:SOC(t) = SOC₀ − ∫I dt / Capacity. Smooth and accurate in the short term, but any sensor gain or offset error accumulates without limit, and it needs a known starting SOC.OCV lookup
After the pack has rested, read the voltage and look up SOC on the OCV curve. No drift, but only valid at rest, and inaccurate in flat regions of the curve.Practical BMSs combine both: coulomb counting while driving, corrected by OCV whenever the pack has rested long enough. Better systems use a Kalman filter with the equivalent circuit model from Section 3.7, which corrects continuously even under load. A minimal version of the combined approach:
/* Coulomb counting with OCV correction at rest (simplified).
* current_a > 0 = discharge. dt_s = sample period in seconds. */
typedef struct {
float soc; /* 0.0 .. 1.0 */
float capacity_ah; /* usable capacity of the pack (or group) */
float rest_s; /* how long the current has been ~0 */
} soc_t;
float ocv_to_soc(float v_cell); /* lookup table, see below */
void soc_update(soc_t *s, float current_a, float v_cell_min, float dt_s)
{
s->soc -= current_a * dt_s / 3600.0f / s->capacity_ah; /* integrate charge */
if (fabsf(current_a) < 0.05f * s->capacity_ah / 20.0f) { /* below ~C/400 */
s->rest_s += dt_s;
if (s->rest_s > 1800.0f) /* rested 30 min */
s->soc = ocv_to_soc(v_cell_min); /* re-anchor to OCV */
} else {
s->rest_s = 0.0f;
}
if (s->soc < 0.0f) s->soc = 0.0f;
if (s->soc > 1.0f) s->soc = 1.0f;
}
/* OCV -> SOC by linear interpolation in a table measured for the cell.
* (Table values are illustrative NMC numbers.) */
float ocv_to_soc(float v)
{
static const float tv[] = { 3.00f, 3.30f, 3.45f, 3.55f, 3.62f, 3.68f, 3.75f, 3.85f, 3.95f, 4.07f, 4.20f };
static const float tsoc[] = { 0.00f, 0.05f, 0.10f, 0.20f, 0.30f, 0.40f, 0.50f, 0.60f, 0.70f, 0.85f, 1.00f };
const int n = (int)(sizeof(tv) / sizeof(tv[0]));
if (v <= tv[0]) return 0.0f;
if (v >= tv[n - 1]) return 1.0f;
for (int i = 1; i < n; i++)
if (v < tv[i])
return tsoc[i - 1] + (tsoc[i] - tsoc[i - 1]) * (v - tv[i - 1]) / (tv[i] - tv[i - 1]);
return 1.0f;
}
SOH (state of health) tracks ageing in two ways: capacity fade (how many Ah a full charge now delivers, compared with new) and resistance growth (R0 estimated from ΔV/ΔI at current steps). Both feed the power limits the BMS reports to the vehicle.
The Kalman filter idea in one paragraph. A Kalman filter runs the equivalent circuit model alongside the real pack. Every step it predicts SOC and the RC voltage from the measured current (that's coulomb counting), predicts what the terminal voltage should be, compares it with the measured voltage, and corrects the SOC in proportion to the error. How much it trusts the model vs the measurement is set by noise estimates. Because the voltage correction runs continuously and accounts for I·R0 and RC effects, it needs no rest periods. Extended (EKF) and unscented (UKF) variants handle the non-linear OCV curve.
6. High-voltage pack safety: contactors, pre-charge and insulation
At 168 V the project pack is no longer a "battery" in the hobby sense. Above 60 V DC an electrical system counts as high voltage (voltage class B in ISO 6469-3 / UN ECE R100 terms): contact can be dangerous, and arcs can be sustained. That brings a set of pack-level functions around the cell monitoring. They were outside this project's firmware, but they explain why the BMS exists in the vehicle and they come up in interviews.
6.1 Contactors and the switching sequence
The pack connects to the vehicle through two main contactors (one in HV+, one in HV−), so the pack can be fully isolated from the vehicle on a fault, during service, or when the car is off. Using two contactors means a single welded contact still doesn't leave the vehicle connected. A pre-charge relay with a resistor sits in parallel with the HV+ contactor.
- Close the main − contactor.
- Close the pre-charge relay. The motor controller's DC-link capacitor charges through the resistor.
- When the DC-link voltage reaches about 95 % of the pack voltage, close the main + contactor.
- Open the pre-charge relay. The pack is now connected with only a small voltage across the closing contacts.
- Opening: ask the controller to reduce current to near zero first. DC arcs don't self-extinguish like AC arcs, so contactors are rated for a limited breaking current at the pack voltage.
6.2 Pre-charge theory
A motor controller has a large DC-link capacitor (hundreds of µF to a few mF). Connecting it straight to a 168 V pack would draw a current limited only by milliohms of wiring and contact resistance, in the kiloamp range, and weld the contactor closed. Pre-charge turns that into a gentle RC charge:
The supervision logic also catches faults: if the link voltage doesn't reach 95 % within a few time constants, something is wrong (shorted DC link, open resistor, failed relay), and the sequence aborts instead of closing onto a short:
/* Pre-charge supervision (simplified state machine, called every 10 ms).
* Closes the main contactor only when the DC link has reached 95 % of the
* pack voltage, and aborts if that takes far longer than ~3 time constants
* (shorted DC link, open pre-charge resistor, failed relay). */
typedef enum { PC_IDLE, PC_PRECHARGING, PC_CLOSED, PC_FAULT } pc_state_t;
pc_state_t precharge_step(pc_state_t st, float v_pack, float v_link,
uint32_t *elapsed_ms, bool drive_request)
{
const uint32_t TIMEOUT_MS = 1000; /* > 5 tau for 100 ohm, 1 mF */
switch (st) {
case PC_IDLE:
if (drive_request) { *elapsed_ms = 0; return PC_PRECHARGING; } /* close neg + pre-charge relay */
return PC_IDLE;
case PC_PRECHARGING:
*elapsed_ms += 10;
if (v_link >= 0.95f * v_pack) return PC_CLOSED; /* close main +, open pre-charge relay */
if (*elapsed_ms > TIMEOUT_MS) return PC_FAULT; /* open everything, report */
return PC_PRECHARGING;
case PC_CLOSED:
return drive_request ? PC_CLOSED : PC_IDLE;
default:
return PC_FAULT; /* latched until service */
}
}
6.3 Insulation monitoring and HVIL
- Isolated (IT) system: neither HV+ nor HV− is connected to the chassis. A single insulation fault doesn't create a dangerous current path, but a second one could, so the first must be detected.
- Insulation resistance monitoring: the BMS periodically switches known resistors between each HV rail and chassis and measures the voltage shift to calculate the leakage resistance. A commonly cited minimum (UN ECE R100) is 100 Ω/V for DC circuits (500 Ω/V where AC circuits are connected). For 168 V that is at least 16.8 kΩ, and real systems warn at much higher values.
- HVIL (high-voltage interlock loop): a low-voltage signal loop through every HV connector and cover. Unplugging any HV connector breaks the loop, and the BMS opens the contactors before the HV contacts separate.
- Fusing: a DC-rated fuse sized for the pack's short-circuit current. With ~114 mΩ of cell resistance, a 168 V pack can push around 1.5 kA into a dead short, so the fuse's breaking capacity must exceed that.
- Isolation of the BMS itself: every path from the HV side to the LV side, including the isoSPI link to the ADBMS6822, must be isolated for the full 168 V plus transients, with suitable creepage and clearance on the PCBs.
7. Thermal behaviour of the pack
Temperature drives everything a BMS cares about: safety (runaway), lifetime (SEI growth roughly doubles for every ~10 °C), available power (resistance rises in the cold) and imbalance (warm cells age faster). So the BMS measures temperature at several points per module, and it derates current long before a hard limit.
7.1 Where the heat comes from
For a 7P group, each cell carries 1/7 of the pack current, so heat per cell scales with (I_pack / 7)². Doubling the pack current quadruples the heat.
7.2 A lumped thermal model
The model explains why continuous ratings depend on cooling. A cell that can supply 15 A briefly can't sustain it inside a tightly packed module without airflow or a cold plate. It also explains NTC placement: the hottest cells sit in the middle of the module, furthest from the cooling surfaces.
7.3 Cooling options and current derating
- Passive / natural air: simplest, adequate only for low C-rates.
- Forced air: fans across the cylindrical cells. Common in student and light-EV packs.
- Liquid cold plates: glycol loop under the modules. Standard in production EVs.
- Phase-change material: absorbs heat peaks by melting. Smooths short high loads.
Instead of a hard on/off limit, the BMS tells the motor controller the maximum allowed current and reduces it smoothly as the hottest (or coldest) cell approaches its limit:
/* Temperature-based current derating: full current between 10 and 45 C,
* linear reduction to zero at 60 C (hot) and at -20 C (cold, discharge).
* The BMS sends this limit to the motor controller over CAN. */
float discharge_limit_a(float t_max_c, float t_min_c, float i_rated_a)
{
float k_hot = (t_max_c <= 45.0f) ? 1.0f : (t_max_c >= 60.0f ? 0.0f : (60.0f - t_max_c) / 15.0f);
float k_cold = (t_min_c >= 10.0f) ? 1.0f : (t_min_c <= -20.0f ? 0.0f : (t_min_c + 20.0f) / 30.0f);
return i_rated_a * (k_hot < k_cold ? k_hot : k_cold);
}
8. ADBMS6830B cell monitor IC
The ADBMS6830B is the analog front end (AFE) of the system: the chip that touches the cells. It does the precision measurement, the redundancy checks and the balancing switching, and leaves only the decisions to the MCU. Knowing its internal blocks makes the firmware almost obvious: each command in Section 12 simply drives one of these blocks.
8.1 Key specifications Datasheet
| Feature | Value |
|---|---|
| Channels | Up to 16 cells in series |
| Accuracy | ±1.8 mV total measurement error (TME) at 3.3 V per cell, −40 °C to +125 °C, over lifetime |
| Input range | −2 V to +5.5 V per channel (handles bus-bar channels and negative bus-bar voltages) |
| C-ADC | 16 ADCs, one per channel, continuously sampling at 4.096 MHz. A new 16-bit result every 1 ms, 150 µV/LSB. |
| Averaged results | 8-sample average every 8 ms |
| IIR filter | Programmable corner (FC[2:0]): 110, 45, 21, 10, 5, 1.25, 0.625 Hz, or off |
| S-ADC (redundant) | Second set of 16 ADCs on the S-pins, every 8 ms. Compared with the C-ADC; mismatches set the CSxFLT flags. |
| AUX ADC | 10 GPIOs plus VREF2, supply voltages, die temperature (ITMP) |
| VREF2 | 3.0 V buffered output for biasing 10 kΩ NTC thermistors |
| Balancing | 16 internal discharge switches, up to 300 mA each. Static (DCC) or 4-bit PWM per cell. Adjacent cells can balance together. |
| Communication | isoSPI, 2 ports (A and B), 2 Mbps, twisted pair (up to 20 m per segment per ADI) |
| Low power | ~4 µA sleep. Sleeps after ~2 s without a valid command (watchdog). |
| Other | GPIO3–5 usable as I²C/SPI master. Low-power cell monitoring (LPCM) while the vehicle is off. Open-wire detection. Hardware OV/UV comparators. |
8.2 Converting raw codes
8.3 ADBMS6830 vs ADBMS6830B
The plain ADBMS6830 is the automotive part, developed under the ISO 26262 process for ASIL-D systems; its full documentation is under NDA. The ADBMS6830B is the broad-market version (e-bikes, energy storage, robots, power tools) with a public datasheet and evaluation kits. The EVAL-ADBMS6830BMSW boards carry the B part. Datasheet
9. Evaluation boards
9.1 EVAL-ADBMS6830BMSW (cell-monitor board)
| Ref | Function | Notes Datasheet |
|---|---|---|
| J1 | Cell connector | Position 1 = C0 (stack −), 2…15 = C1…C14, 16–17 = C15/C16 (stack +). Wire from position 1, the most negative. |
| J3 | isoSPI port A | Toward the master |
| J4 | isoSPI port B | Toward the next board up |
| J5 | GPIO header | GPIO1…10 + V− pins (thermistors, test points) |
| J2 | IREG header | Ammeter here measures regulator current |
| J6 | Supply header | Power the board separately from the stack (remove R55) |
| D2 | LED | VREG active: lit only while the chip is awake |
Bench testing without cells: ADI's procedure uses a ladder of 16 × 100 Ω (½ W or more) resistors on J1, fed by a lab supply (e.g. 52.8 V gives 3.3 V per channel), or the DC2472A battery emulator.
9.2 EVAL-ADBMS6822 (dual isoSPI adapter)
9.3 AD-APARD32690-SL (MAX32690 controller)
10. isoSPI and the daisy chain
The hardest problem in a modular BMS isn't measuring a cell, it's getting the measurement out. Each monitor board sits at a different voltage, tens to hundreds of volts away from the controller, yet it must exchange data at megabits per second, reliably, next to a motor inverter that radiates noise. This chapter explains how isoSPI solves that, starting from plain SPI and ending with the exact wiring of the bench chain.
10.1 Why isoSPI Datasheet
| Option | Problem for a modular BMS |
|---|---|
| Plain SPI | Needs a common ground. The boards sit at different high voltages. |
| SPI + digital isolators | Needs an isolator and an isolated power supply on every board, plus 4+ wires per link |
| CAN per module | Needs an MCU, a CAN transceiver and isolation on every module |
| isoSPI | One twisted pair per link through a small transformer (or capacitors). No MCU or isolated supply on the modules. Low EMI, RF-immune, 2 Mbps. |
10.2 How the signal is encoded Datasheet
Starting point: SPI between the MCU and the ADBMS6822. The MCU talks to the transceiver over ordinary 4-wire SPI in mode 3. The clock idles high (CPOL = 1), the MCU changes MOSI on the falling edge, and both sides sample on the rising edge (CPHA = 1). Bytes go MSB first. Chip select (CS) frames each command.
On the twisted pair: the ADBMS6822 turns every SPI event into a pulse doublet (a positive half followed by a negative half, or the reverse). A doublet has no average (DC) value, which is exactly what a transformer can pass, so the link can be isolated by tiny transformers rated for hundreds of volts. The receiving device converts the doublets back into CS, clock and data levels for its own logic.
- The transmitter drives the pair differentially at ±VA (~20 mA). The receiver threshold is ~300 mV, giving high noise immunity next to a motor inverter.
- Each symbol is a doublet: positive-then-negative (+1) or negative-then-positive (−1). A transformer passes doublets because they have no DC content.
- Long pulses (~150 ns per half) mark chip-select falling and rising edges. Short pulses (~50 ns per half) carry data bits.
- The slave side rebuilds SCK/MOSI/CS from the pulses. Read data travels back as pulses toward the master.
- The ADBMS6822 handles the master side. It supports long cables (ADI quotes up to 100 m) and two independent ports.
10.3 How the daisy chain behaves
Each ADBMS6830B has port A (toward the MCU) and port B (away from it). A command arriving on port A is executed and also re-transmitted on port B to the next device. Read data comes back down the same way. Every link is point-to-point and every device re-drives the signal. It is not a shared bus like CAN. Logically the chain behaves like a long shift register, which explains the data order:
- Writes: the top (farthest) device's data is sent first because it has the farthest to travel.
- Reads: the bottom (nearest) device's data comes back first.
10.4 The bench chain (5 + 7 active channels) Project notes
| Item | Board 1 (bottom, device 0) | Board 2 (top, device 1) |
|---|---|---|
| Active cells | 5 (C1–C5) | 7 (C1–C7) |
| Port A (J3) | from the ADBMS6822 | from board 1 port B |
| Port B (J4) | to board 2 | unused |
| Termination switch | OFF | ON (end of line) |
| Unused inputs | C6–C16 tied to the top of cell 5 / VBAT | C8–C16 tied to the top of cell 7 / VBAT |
| Data position in a read | rx[4..11] | rx[12..19] |
10.5 Topologies supported by the boards Datasheet
The redundant ring gives broken-wire protection. If a cable breaks in the middle, the MCU reads the lower boards through MAIN and the upper boards through AUX. This is the main reason the monitor has two ports and the transceiver is dual.
10.6 Scaling the chain
- Monitor ICs ≥
ceil(n / 16). For the 40S pack that is at least 3 ICs (15S + 15S + 10S when grouped by whole modules), or 8 with one IC per 5S7P module. - Every frame grows by 8 bytes per device:
length = 4 + 8 × N. Wake-up needs N pulses. - At 1 MHz SPI, a 2-device RDCVA frame (20 bytes) takes 160 µs. Even 10 devices × 6 groups is only a few milliseconds per full scan.
11. Cell connections and unused channels
A 16-channel monitor watching a 5-cell module leaves 11 inputs with nothing to measure. Inputs can't just be left floating, because the measurement chain and the chip's internal supply arrangement expect a defined voltage on every pin. The fix is simple, but it has a firmware consequence that is easy to forget.
- Active groups always start at the bottom (C0 = module negative).
- Unused upper inputs are shorted to the highest active cell terminal and V+ Project notes. Both pins of an unused channel sit at the same potential, so the channel reads 0 V. Nothing floats, and the ADC inputs stay in range.
- The firmware must ignore those channels (or mask their UV flags). Otherwise they look like dead cells and trigger undervoltage faults.
- ADI's light-EV reference design uses the same idea:
12. Communication protocol
Everything the firmware does to the chain (configure, measure, balance, diagnose) is done through a small set of fixed-format frames. Once the three frame types, the byte layout and the two CRCs are clear, the rest of the driver is bookkeeping. This chapter goes from the frame formats to the CRC mathematics to the actual C that builds and parses the frames, and includes two interactive tools that use the same algorithms as the driver.
12.1 Frame types Datasheet
| Type | MCU sends | Chain returns | Examples |
|---|---|---|---|
| Action | CMD0 CMD1 PEC0 PEC1 | nothing | ADCV, ADAX, SNAP, MUTE, CLRCELL |
| Write | CMD + PEC, then 6 data + 2 PEC per device, top device first | nothing | WRCFGA, WRCFGB, WRPWMA |
| Read | CMD + PEC, then dummy bytes (0xFF) to clock the response out | 6 data + 2 PEC per device, bottom device first | RDCVA, RDAUXA, RDSTATA, RDCFGA |
- Chip select stays low for the whole frame. The CS edges become the isoSPI long pulses that mark the start and end of a command.
- Commands are 11-bit codes sent as two bytes, MSB first. SPI mode 3 (CPOL = 1, CPHA = 1), at most 2 MHz. The firmware uses 1 MHz.
- Inside each register group, 16-bit values are little-endian (low byte first) and signed.
12.2 Byte map of a 2-device read Project notes
12.3 PEC (CRC) and the command counter Datasheet
| Command PEC | Data PEC | |
|---|---|---|
| Width | 15 bits (sent as 16, LSB = 0) | 10 bits |
| Polynomial | x15+x14+x10+x8+x7+x4+x3+1 (0x4599) | x10+x7+x3+x2+x+1 (0x08F) |
| Seed | 0x0010 | 0x010 |
| Covers | The 2 command bytes | 6 data bytes, + the 6-bit command counter on reads |
| Known vectors | WRCFGA 0x001 → 0x3D6E · RDCVA 0x004 → 0x07C2 | (see the frame decoder below) |
Command counter (CCNT): a 6-bit counter inside each device. It increments on commands that change state (writes and actions, not reads), rolls over from 63 to 1 (never to 0), and resets on power-up, sleep, RSTCC or SRST. Because CCNT is inside the read PEC, the MCU can detect a lost or duplicated command, not just corrupted bits.
-EBADMSG on a data-PEC mismatch. In the ARM newlib C library (arm-none-eabi-gcc, used by MaximSDK and no-OS), EBADMSG = 77, so −77 means "data PEC failed". Typical causes, in order of likelihood:
- termination or cabling on an isoSPI link;
NUM_DEVlarger than the real chain (the missing device's slot reads 0xFF);- chain not woken (tWAKE / tREADY not respected);
- wrong SPI mode or clock above 2 MHz;
- CS released in the middle of a frame.
12.4 How the PEC is computed (CRC theory)
A CRC treats the message bits as the coefficients of a big polynomial and divides it by a fixed generator polynomial using XOR arithmetic (addition without carries). The remainder of that division is the CRC. The sender appends it, the receiver repeats the division over the same bytes, and any mismatch means the data changed in transit. For frames as short as these, a 15-bit CRC like the command PEC detects every single-bit and double-bit error, every odd number of bit errors (the polynomial has an even number of terms, so it contains the factor x+1), and every error burst up to 15 bits long. That is why a few PEC failures always mean a real physical-layer problem, not bad luck.
In hardware this division is a shift register with XOR taps (an LFSR): shift in one message bit at a time, and whenever the bit leaving the top differs from the incoming bit, XOR the polynomial into the register. The driver does exactly that in software:
/* ------------------------------------------------------------------------ */
/* PEC15 : command PEC. x^15+x^14+x^10+x^8+x^7+x^4+x^3+1, seed 0x0010. */
/* Result is shifted left by 1 (LSB is always 0) and sent MSB first. */
/* ------------------------------------------------------------------------ */
uint16_t adbms_pec15(const uint8_t *data, uint8_t len)
{
uint16_t rem = 0x0010; /* seed 000000000010000 */
for (uint8_t i = 0; i < len; i++) {
for (int8_t b = 7; b >= 0; b--) {
uint16_t in = ((data[i] >> b) & 1u) ^ ((rem >> 14) & 1u);
rem = (uint16_t)((rem << 1) & 0x7FFF);
if (in) rem ^= 0x4599; /* polynomial taps */
}
}
return (uint16_t)(rem << 1);
}
The data PEC is the same idea with a 10-bit polynomial (0x08F). On reads, six extra bits are shifted in after the data: the device's command counter. So the PEC proves that the bytes are intact and that the device saw the expected number of commands.
/* ------------------------------------------------------------------------ */
/* PEC10 : data PEC. x^10+x^7+x^3+x^2+x+1, seed 0x010. */
/* On READ data the 6-bit command counter (CCNT) is also covered. */
/* ------------------------------------------------------------------------ */
uint16_t adbms_pec10(const uint8_t *data, uint8_t len, bool is_read, uint8_t ccnt)
{
uint16_t rem = 0x010;
for (uint8_t i = 0; i < len; i++) {
rem ^= (uint16_t)data[i] << 2;
for (uint8_t b = 0; b < 8; b++)
rem = (rem & 0x200) ? (uint16_t)((rem << 1) ^ 0x08F) : (uint16_t)(rem << 1);
}
if (is_read) { /* 6 more bits: CCNT[5:0] */
rem ^= (uint16_t)(ccnt & 0x3F) << 4;
for (uint8_t b = 0; b < 6; b++)
rem = (rem & 0x200) ? (uint16_t)((rem << 1) ^ 0x08F) : (uint16_t)(rem << 1);
}
return rem & 0x3FF;
}
For high-throughput systems, the bitwise loop can be replaced by a 256-entry lookup table that processes a whole byte per step. The test program checks that the table version matches the bitwise version for all 65,536 possible 2-byte commands:
/* Table-driven PEC15 (the speed-optimised alternative to the bitwise loop).
* The table holds the CRC of every possible 8-bit value: 256 x 2 bytes. */
static uint16_t pec15_table[256];
void pec15_table_init(void)
{
for (int i = 0; i < 256; i++) {
uint16_t rem = (uint16_t)(i << 7);
for (int bit = 8; bit > 0; bit--) {
if (rem & 0x4000) rem = (uint16_t)((rem << 1) ^ 0x4599);
else rem = (uint16_t)(rem << 1);
}
pec15_table[i] = rem & 0x7FFF;
}
}
uint16_t pec15_fast(const uint8_t *data, int len)
{
uint16_t rem = 16; /* seed */
for (int i = 0; i < len; i++) {
uint8_t addr = (uint8_t)(((rem >> 7) ^ data[i]) & 0xFF);
rem = (uint16_t)(((rem << 8) ^ pec15_table[addr]) & 0x7FFF);
}
return (uint16_t)(rem << 1); /* LSB is always 0 */
}
12.5 Building and parsing frames in C
Every command starts the same way: two command bytes followed by their PEC15. Writes then append one 8-byte slot per device, top device first. Reads clock out dummy bytes and parse one slot per device, bottom device first, at offset 4 + 8·i, checking each slot's PEC10 with its command counter:
/* ------------------------------------------------------------------------ */
static void make_cmd(uint16_t cmd, uint8_t out[ADBMS_CMD_LEN])
{
out[0] = (uint8_t)(cmd >> 8);
out[1] = (uint8_t)(cmd & 0xFF);
uint16_t pec = adbms_pec15(out, 2);
out[2] = (uint8_t)(pec >> 8);
out[3] = (uint8_t)(pec & 0xFF);
}
/* data[i] = 6 bytes destined for device i (i = 0 is the bottom device). */
int adbms_write(adbms_chain_t *ch, uint16_t cmd, const uint8_t data[][ADBMS_REG_LEN])
{
uint8_t tx[ADBMS_CMD_LEN + ADBMS_MAX_DEV * ADBMS_DEV_FRAME_LEN];
uint8_t rx[sizeof(tx)];
uint16_t len = ADBMS_CMD_LEN + ch->num_dev * ADBMS_DEV_FRAME_LEN;
make_cmd(cmd, tx);
uint8_t *p = &tx[ADBMS_CMD_LEN];
/* Top device first: its data has to travel through every device below. */
for (int8_t dev = (int8_t)ch->num_dev - 1; dev >= 0; dev--) {
memcpy(p, data[dev], ADBMS_REG_LEN);
uint16_t pec = adbms_pec10(p, ADBMS_REG_LEN, false, 0);
p[6] = (uint8_t)((pec >> 8) & 0x03); /* PEC[9:8] in low bits */
p[7] = (uint8_t)(pec & 0xFF); /* PEC[7:0] */
p += ADBMS_DEV_FRAME_LEN;
}
return frame(ch, tx, rx, len);
}
/* data[i] receives the 6 bytes from device i (i = 0 is the bottom device). */
int adbms_read(adbms_chain_t *ch, uint16_t cmd, uint8_t data[][ADBMS_REG_LEN])
{
uint8_t tx[ADBMS_CMD_LEN + ADBMS_MAX_DEV * ADBMS_DEV_FRAME_LEN];
uint8_t rx[sizeof(tx)];
uint16_t len = ADBMS_CMD_LEN + ch->num_dev * ADBMS_DEV_FRAME_LEN;
make_cmd(cmd, tx);
memset(&tx[ADBMS_CMD_LEN], 0xFF, len - ADBMS_CMD_LEN); /* dummy clocks */
int ret = frame(ch, tx, rx, len);
if (ret) return ret;
int status = ADBMS_OK;
for (uint8_t dev = 0; dev < ch->num_dev; dev++) {
const uint8_t *d = &rx[ADBMS_CMD_LEN + dev * ADBMS_DEV_FRAME_LEN]; /* 4, 12, 20 ... */
uint8_t ccnt = d[6] >> 2; /* CCNT[5:0] */
uint16_t rx_pec = (uint16_t)(((d[6] & 0x03) << 8) | d[7]);
uint16_t calc = adbms_pec10(d, ADBMS_REG_LEN, true, ccnt);
memcpy(data[dev], d, ADBMS_REG_LEN);
ch->last_ccnt[dev] = ccnt;
if (rx_pec != calc) { /* corrupted, or nobody answered */
ch->pec_errors++;
status = ADBMS_E_PEC; /* keep parsing, report at the end */
}
}
return status;
}
Interactive frame decoder (same PEC algorithm as the C driver)
Paste the RX bytes of a cell-voltage read. The default is the real 2-device RDCVA frame produced by the driver. Press "Corrupt one byte" to see a PEC failure.
12.6 Command reference Datasheet
| Command | Code | Purpose |
|---|---|---|
| WRCFGA / RDCFGA | 0x001 / 0x002 | Config A: REFON, CTH, GPO (GPIO pull-downs), FC (IIR corner), MUTE/SNAP status |
| WRCFGB / RDCFGB | 0x024 / 0x026 | Config B: VUV, VOV, DTMEN, DTRNG, DCTO, DCC[16:1] |
| WRPWMA / WRPWMB | 0x020 / 0x021 | PWM duty for cells 1–12 / 13–16 (4 bits each) |
| ADCV | 0x260 + bits | Start the cell ADCs. RD (bit 8) adds the S-ADC; CONT (7) = continuous; DCP (4) = discharge permitted; RSTF (2) = reset filter; OW (1:0) = open-wire |
| ADSV | 0x168 + bits | S-ADC only |
| ADAX | 0x410 + bits | AUX ADC (GPIOs etc.). CH = 0 converts all inputs. |
| RDCVA…RDCVF | 0x004, 0x006, 0x008, 0x00A, 0x009, 0x00B | Raw cell voltages, 3 per group (F holds only C16) |
| RDCVALL | 0x00C | All 16 cells in one frame (32 bytes + one PEC) |
| RDACx / RDFCx / RDSVx | 0x044… / 0x012… / 0x003… | Averaged / IIR-filtered / S-ADC results |
| RDAUXA…RDAUXD | 0x019, 0x01A, 0x01B, 0x01F | GPIO1–3, 4–6, 7–9, GPIO10 + VMV + VPV |
| RDSTATA…RDSTATE | 0x030…0x034 | VREF2 + ITMP; VD/VA/VRES; fault flags + conversion counter; OV/UV flags |
| SNAP / UNSNAP | 0x02D / 0x02F | Freeze / release the result registers |
| MUTE / UNMUTE | 0x028 / 0x029 | Pause / resume all discharge switches (< 65 µs) |
| CLRCELL / CLOVUV / CLRFLAG | 0x711 / 0x715 / 0x717 | Clear results / OV-UV flags / fault flags |
| RDSID / SRST / RSTCC | 0x02C / 0x027 / 0x02E | Serial ID / soft reset / reset command counter |
| PLADC / PLAUX | 0x718 / 0x71E | Poll ADC / AUX conversion status |
Command builder (computes the 4 bytes to send)
13. Power states and wake-up
The ADBMS6830B spends most of its life asleep to save the battery, and its isoSPI port drops into idle after a few milliseconds of silence. Many "the chain doesn't answer" problems are simply wake-up timing problems, so it pays to know the states and their timings exactly.
| Parameter | Value Datasheet | What the firmware does |
|---|---|---|
| tWAKE | 200–500 µs (VREG from DRIVE) | One CS pulse per device, 500 µs each, at start-up or after sleep |
| tREADY | ≤ 10 µs | Short CS pulse per device before each burst (port was idle) |
| tIDLE | 4.3–6.7 ms (5.5 typical) | After this much silence the isoSPI port goes idle |
| tSLEEP (watchdog) | ~2 s (1.8–2.2 s) | Loop period of ~1 s keeps the chain awake |
| tREFUP | ~3.5 ms | Avoided by setting REFON = 1 |
The wake-up ripples up the chain: device 1 wakes and only then passes the pulse to device 2. That is why the pulse is repeated once per device. After sleep, the command counter is reset. Treat the configuration as lost and re-write it after a wake from sleep. Engineering practice
13.1 Wake-up in code
The wake-up routines are short, but the timing is what matters. A full wake gives every device in the chain its tWAKE. A short idle wake is enough when the core is already awake and only the isoSPI port has gone idle:
/* Wake every device from SLEEP. Each CSB edge becomes an isoSPI "long pulse";
* device k wakes, then forwards the pulse to device k+1, so we repeat once
* per device and give each one tWAKE. */
void adbms_wakeup(adbms_chain_t *ch)
{
for (uint8_t i = 0; i < ch->num_dev; i++) {
ch->hal->cs_set(0);
ch->hal->delay_us(T_WAKE_US);
ch->hal->cs_set(1);
ch->hal->delay_us(T_WAKE_US);
}
}
/* Core is awake but the isoSPI port went IDLE (no traffic for tIDLE ~5.5 ms). */
void adbms_wakeup_idle(adbms_chain_t *ch)
{
for (uint8_t i = 0; i < ch->num_dev; i++) {
ch->hal->cs_set(0);
ch->hal->delay_us(T_READY_US);
ch->hal->cs_set(1);
ch->hal->delay_us(T_READY_US);
}
}
In the main loop, every burst of commands starts with adbms_wakeup_idle(), because the 1 s gap between loops is much longer than tIDLE (~5.5 ms). The full adbms_wakeup() is only needed at start-up or if the chain was allowed to sleep.
14. Cell voltage measurement
Measuring 16 cell voltages to within ±1.8 mV, on a stack that floats tens of volts above ground and carries hundreds of amps of switching current, is the core of what the ADBMS6830B does. This chapter covers the measurement theory (resolution vs accuracy, sampling, filtering), the result registers, and the exact sequence the firmware uses to read a consistent snapshot.
14.1 ADC theory: resolution, accuracy and sampling
Three different numbers describe a measurement, and interviewers like to check that you don't mix them up:
| Concept | Meaning | ADBMS6830B |
|---|---|---|
| Resolution | The smallest step the ADC output can show (1 LSB) | 150 µV per code, 16-bit signed register |
| Range | Span of input it can measure | −2 V to +5.5 V (register span −3.4 to +6.4 V) |
| Accuracy (TME) | Worst-case difference between reading and true value, including offset, gain, reference drift, temperature and lifetime | ±1.8 mV at 3.3 V over −40 to +125 °C and lifetime |
Resolution is about 12× finer than the accuracy. The extra resolution is still useful: it lets the filters average away noise, and it makes differences between cells (what balancing cares about) visible below the absolute error. Why does ±1.8 mV matter? On a flat NMC curve, 1 mV can be a few tenths of a percent of SOC, and on LFP much more. Balancing decisions in the 3–10 mV range are only meaningful with an accurate front end.
Sampling: the C-ADCs run continuously at 4.096 MHz and are decimated to one result per millisecond. Heavy oversampling plus digital filtering means the external RC filter can be simple, and short spikes (for example from motor PWM) are averaged rather than aliased into false readings. All 16 channels convert simultaneously, so the cell voltages in one snapshot belong to the same instant, which matters when the pack current is changing quickly.
14.2 Measuring a floating stack
The top cell of the 40S pack sits up to 168 V above the pack negative, but its voltage must be measured to about 1 mV. No single ADC can measure 4 V on top of 164 V with that precision, so the design breaks the stack up:
- Each ADBMS6830B's V− connects to the bottom of the cells it monitors and its V+ to the top. That module is the chip's local ground and supply (through its regulator), so the chip floats with its module.
- Each channel measures Cn − Cn−1 differentially. The input stage only needs to handle the module's own span (at most 16 cells, ≤ 67 V for NMC), not the pack voltage.
- The absolute pack voltage never appears inside any monitor. It appears across the isolation barriers: between neighbouring boards (the voltage of one module, ~21 V here, plus transients) and, in full, between the chain and the MCU.
- The pack voltage itself is measured separately and summed. The sum of all 40 cell readings should match an independent pack-voltage measurement, which is a useful plausibility check (the firmware's per-board
b1_sum/b2_sumtotals do the same at board level).
14.3 Result registers and when to use each
| Register | Read with | Update rate | Use for |
|---|---|---|---|
| Raw C-ADC (CV) | RDCVx | 1 ms | Fast protection, measurement right after MUTE |
| Averaged (AC) | RDACx | 8 ms | Lower noise without filter lag |
| IIR-filtered (FC) | RDFCx | continuous, corner set by FC | Smooth values for balancing and SOC |
| S-ADC (SV) | RDSVx | 8 ms | Redundant check (the chip compares it automatically → CSxFLT) |
14.4 IIR filter settings Datasheet
Filter: Y[n] = Y[n−1] + (X[n] − Y[n−1]) / a
| FC[2:0] | 000 | 001 | 010 | 011 | 100 | 101 | 110 | 111 |
|---|---|---|---|---|---|---|---|---|
| Corner | off | 110 Hz | 45 Hz | 21 Hz | 10 Hz | 5 Hz | 1.25 Hz | 0.625 Hz |
| a | — | 2 | 4 | 8 | 16 | 32 | 128 | 256 |
The filter is a classic first-order low-pass, updated once per 1 ms result. Its corner frequency follows directly from a: fc = −ln(1 − 1/a) × 1000 / (2π). For a = 16 that gives 10.3 Hz and for a = 2 it gives 110 Hz, matching the datasheet table exactly. That confirms the filter runs at the 1 kHz result rate.
/* The ADBMS6830B's IIR filter, written out in C.
* a = 2, 4, 8 ... 256 (set by FC[2:0]); runs once per 1 ms C-ADC result.
* Corner frequency: fc = -ln(1 - 1/a) * 1000 Hz / (2*pi) -> a = 16 gives 10.3 Hz */
typedef struct { float y; bool primed; } iir_t;
float iir_step(iir_t *f, float x, float a)
{
if (!f->primed) { f->y = x; f->primed = true; } /* start at the first sample */
f->y += (x - f->y) / a; /* Y[n] = Y[n-1] + (X[n]-Y[n-1])/a */
return f->y;
}
Choosing FC: the trade-off is noise vs reaction time. Protection logic should use raw or lightly filtered values so a real over-voltage isn't hidden behind filter lag. Balancing and SOC can use heavy filtering because they act over minutes. The firmware uses 10 Hz as a middle ground (the filtered registers are read with RDFCx).
14.5 Measurement sequence used
ADCVwith CONT = 1, RD = 1 once at start-up. Both ADC sets now run forever.- Each loop: wake (tREADY) →
MUTE→ wait 2 ms (fresh conversions without balancing current) →SNAP. RDCVA,RDCVB,RDCVC. Groups A–C cover C1–C9, enough for 7 active cells. Each frame carries every device.UNSNAP→UNMUTE. Parse 5 cells from board 1 and 7 from board 2, ignore the tied-off channels, and compute per-board totals (b1_sum,b2_sum) Project notes.
The cell-reading function implements steps 2–4 for all devices at once. It works out which register groups are needed from the number of cells, wraps the reads in SNAP/UNSNAP, and decodes the little-endian signed codes:
/* Reads only the register groups needed for n_cells (5 cells -> A,B ;
* 7 cells -> A,B,C). SNAP freezes all result registers so that every group
* comes from the same 1 ms conversion; UNSNAP lets them update again. */
int adbms_read_cells(adbms_chain_t *ch, uint8_t n_cells,
float volts[][ADBMS_CELLS_PER_DEV])
{
uint8_t buf[ADBMS_MAX_DEV][ADBMS_REG_LEN];
uint8_t groups = (uint8_t)((n_cells + 2) / 3);
int status = ADBMS_OK, ret;
if (n_cells == 0 || n_cells > ADBMS_CELLS_PER_DEV) return ADBMS_E_PARAM;
adbms_cmd(ch, CMD_SNAP);
for (uint8_t g = 0; g < groups; g++) {
ret = adbms_read(ch, cv_cmds[g], buf);
if (ret) status = ret;
for (uint8_t dev = 0; dev < ch->num_dev; dev++) {
for (uint8_t k = 0; k < 3; k++) {
uint8_t cell = (uint8_t)(g * 3 + k);
if (cell >= ADBMS_CELLS_PER_DEV) break; /* CVF holds only C16 */
uint16_t code = (uint16_t)(buf[dev][2*k] | (buf[dev][2*k + 1] << 8));
volts[dev][cell] = ADBMS_CODE_TO_V(code); /* little-endian, signed */
}
}
}
adbms_cmd(ch, CMD_UNSNAP);
return status;
}
The application wraps it with MUTE/UNMUTE, reads the temperatures, and keeps only the wired channels:
int bms_app_measure(adbms_chain_t *ch, bms_data_t *d)
{
float cells[ADBMS_MAX_DEV][ADBMS_CELLS_PER_DEV];
float gpios[ADBMS_MAX_DEV][ADBMS_GPIOS_PER_DEV];
int ret, status = ADBMS_OK;
adbms_wakeup_idle(ch);
/* Balancing current flows through the cell-input filter resistors and
* makes the reading wrong (IR drop). Mute the switches, let a fresh
* 1 ms conversion happen, read, then un-mute. */
adbms_mute(ch, true);
ch->hal->delay_us(2000);
ret = adbms_read_cells(ch, MAX_CELLS_ANY_DEV, cells);
adbms_mute(ch, false);
if (ret) status = ret;
/* Temperatures: start AUX ADC, read GPIOs + VREF2 for a ratiometric result */
adbms_start_aux_adc(ch);
if ((ret = adbms_read_gpios(ch, gpios))) status = ret;
if ((ret = adbms_read_vref2(ch, d->vref2, d->die_c))) status = ret;
for (int dev = 0; dev < NUM_DEV; dev++) {
d->stack_v[dev] = 0.0f;
for (int c = 0; c < ADBMS_CELLS_PER_DEV; c++) {
/* Only the wired cells are meaningful. Unused inputs are tied to
* the top cell, so they read ~0 V and would trip UV if used. */
d->cell_v[dev][c] = (c < cells_per_dev[dev]) ? cells[dev][c] : 0.0f;
d->stack_v[dev] += d->cell_v[dev][c];
}
for (int g = 0; g < ADBMS_GPIOS_PER_DEV; g++) {
d->gpio_v[dev][g] = gpios[dev][g];
d->temp_c[dev][g] = (g < ntc_per_dev[dev])
? ntc_volt_to_celsius(gpios[dev][g], d->vref2[dev])
: 0.0f;
}
}
if (status == ADBMS_E_PEC) d->faults |= FAULT_COMM;
return status;
}
15. Temperature sensing
Voltage tells the BMS how full a cell is. Temperature tells it how safe and how healthy it is. Cells are measured with NTC thermistors bonded to the cell cans or bus bars and read by the monitor IC's auxiliary ADC, so no extra hardware or wiring to the MCU is needed.
- Ratiometric: VREF2 is measured too (RDSTATA), and only the ratio Vgpio/VREF2 is used. Reference errors cancel.
- GPO bits = 1 (CFGA bytes 3–4) switch off each pin's pull-down so it works as an analog input. With GPO = 0 the pull-down would load the divider.
- Sensor faults: V ≈ VREF2 → NTC open. V ≈ 0 V → NTC shorted. Both are faults, never temperatures.
- Placement: on cell cans or bus bars at the hottest points (middle of the module, near the terminals), typically a few per module.
- Die temperature (ITMP) is also available:
T = V/7.5 mV − 273 °C. It is used to throttle balancing.
15.1 NTC theory: Beta vs Steinhart–Hart, self-heating, resolution
An NTC (negative temperature coefficient) thermistor is a ceramic resistor whose resistance falls roughly exponentially as it warms: a 10 kΩ part is about 33 kΩ at 0 °C and about 2.5 kΩ at 60 °C. Two models convert resistance to temperature:
- Beta equation (used in the firmware): one constant B, accurate to a fraction of a degree over a ±25 °C range around the reference point. Simple and fast.
- Steinhart–Hart: three coefficients (A, B, C), accurate to about 0.1 °C over a wide range. Better for a full −20 to +80 °C span.
float ntc_volt_to_celsius(float v_gpio, float vref2)
{
/* Open NTC -> V_gpio ~ VREF2 ; shorted NTC -> V_gpio ~ 0 V.
* Both are sensor faults, not temperatures. */
if (v_gpio <= 0.02f * vref2 || v_gpio >= 0.98f * vref2)
return -273.0f;
float r_ntc = NTC_R_BIAS_OHM * v_gpio / (vref2 - v_gpio);
float inv_t = (1.0f / NTC_T0_K) + logf(r_ntc / NTC_R0_OHM) / NTC_BETA;
return (1.0f / inv_t) - 273.15f;
}
/* Steinhart-Hart: more accurate than the Beta equation over a wide range.
* 1/T = A + B*ln(R) + C*ln(R)^3 (T in kelvin). Coefficients come from the
* NTC datasheet or from a 3-point fit. Values below suit a generic 10k NTC. */
float ntc_steinhart_c(float r_ohm)
{
const float A = 1.009249522e-3f, B = 2.378405444e-4f, C = 2.019202697e-7f;
float ln_r = logf(r_ohm);
float inv_t = A + B * ln_r + C * ln_r * ln_r * ln_r;
return 1.0f / inv_t - 273.15f;
}
Self-heating: the bias current heats the NTC itself. With 3 V across 20 kΩ at 25 °C the divider draws 150 µA, and the NTC dissipates about 0.23 mW. With a typical dissipation constant of a few mW/°C, that's well under 0.1 °C of error. Choosing Rbias equal to R0 keeps the current low and puts the most sensitive part of the curve near room temperature.
Since one LSB is 150 µV and the divider moves 10–30 mV/°C, the ADC resolves well below 0.01 °C. Real accuracy is limited by the NTC's tolerance, its thermal contact with the cell, and the fact that it measures the cell surface, while the core can be several degrees hotter under heavy load.
16. Cell balancing
16.1 Why balancing is needed
Series groups carry identical current, but they differ slightly in capacity, self-discharge, temperature and ageing. Over many cycles their states of charge drift apart, and the pack is limited by its extremes:
- Charging must stop when the highest group reaches 4.2 V.
- Discharging must stop when the lowest group reaches cut-off.
An unbalanced pack therefore loses usable capacity, and the high group is stressed every charge.
Top balancing vs bottom balancing. Most EV packs top-balance: they align the groups at full charge so that every group reaches 4.20 V together, which maximises the energy that can be charged. Bottom balancing aligns the groups at empty instead, which protects the weakest group at deep discharge. Passive balancing naturally top-balances, because bleeding during the end of charge is when the voltage differences are largest and most meaningful.
Voltage-based vs SOC-based. The simple approach (used here) compares voltages. Advanced BMSs compare SOC (or the charge each group needs to remove) using the OCV curve and capacity estimates. They can then balance at any time, even in flat regions, and know exactly how long each resistor must stay on.
16.2 Passive vs active balancing
| Passive (this project) | Active | |
|---|---|---|
| Principle | Burn the excess charge of high groups in a resistor | Move charge from high to low groups (switched capacitor, inductor, transformer, DC-DC) |
| Energy | Lost as heat | 80–95 % transferred |
| Cost and complexity | Very low, built into the monitor IC | Extra power stage per cell or module |
| Typical current | 50–300 mA | 1–5 A |
| Best for | Top-balancing while charging, small mismatch | Large packs, large mismatch, maximising range |
- Switched capacitor: a capacitor is connected alternately across two neighbouring cells and carries charge from the higher to the lower one. Simple and needs no control loop, but it only moves charge between neighbours, and it becomes slow when the voltage difference is small.
- Inductive (buck-boost between neighbours): MOSFETs store energy from one cell in an inductor and release it into the next. Efficient and controllable, but charge still moves cell by cell along the string.
- Transformer / isolated DC-DC: takes energy from the whole module (or pack) and delivers it to whichever cell is low, or the reverse. Moves charge anywhere in one step, but needs the most hardware.
For a 40S7P pack of matched cells, passive balancing at ~100 mA is a standard and sensible choice. Active balancing pays off mainly in large packs with many ageing cells, where the recovered capacity is worth the extra parts.
16.3 Balancing hardware in the ADBMS6830B Datasheet
| Feature | Detail |
|---|---|
| Discharge current | Up to 300 mA per channel, set by the external resistor |
| DCC[16:1] | CFGB bytes 4–5. 1 = switch fully on (static). DCC overrides PWM. |
| PWM | WRPWMA/B, 4 bits per cell: 0x0 off, 0x1 ≈ 6.6 %, 0xF = 100 %. Period ≈ 937 ms. Limits the average current and heat. |
| Adjacent cells | Can balance at the same time |
| DCTO | Discharge timeout (CFGB byte 3): 0–63 min (1 min/LSB) or 0–16.8 h (16 min/LSB with DTRNG = 1). Switches turn off automatically if the MCU stops refreshing. 0 = timed out / not set. |
| MUTE / UNMUTE | All switches off within 65 µs without losing the DCC/PWM settings |
| Priority | Thermal shutdown > MUTE > WRCFGB > DCC > ADC measurement > WRPWM > PWM |
All balancing hardware is controlled through four small driver functions. DCC bits live in configuration register B, PWM nibbles in the PWM registers, the timeout in CFGB byte 3, and MUTE is a single action command:
/* ------------------------------------------------------------------------ */
/* Balancing (passive) */
/* ------------------------------------------------------------------------ */
/* bit 0 = cell 1 ... bit 15 = cell 16. DCC = static 100 % discharge and it
* overrides PWM for that cell. Call adbms_write_config() to apply. */
void adbms_set_dcc(adbms_chain_t *ch, uint8_t dev, uint16_t dcc_mask)
{
if (dev >= ch->num_dev) return;
ch->regs[dev].cfgb[4] = (uint8_t)(dcc_mask & 0xFF);
ch->regs[dev].cfgb[5] = (uint8_t)(dcc_mask >> 8);
}
/* cell = 1..16, duty4 = 0..15 (0 = off, 15 = 100 %). Period ~937 ms. */
void adbms_set_pwm(adbms_chain_t *ch, uint8_t dev, uint8_t cell, uint8_t duty4)
{
if (dev >= ch->num_dev || cell < 1 || cell > 16) return;
duty4 &= 0x0F;
uint8_t idx = (uint8_t)(cell - 1);
uint8_t *reg = (idx < 12) ? ch->regs[dev].pwma : ch->regs[dev].pwmb;
uint8_t byte = (uint8_t)((idx % 12) / 2);
if (idx % 2 == 0) reg[byte] = (uint8_t)((reg[byte] & 0xF0) | duty4); /* odd cell */
else reg[byte] = (uint8_t)((reg[byte] & 0x0F) | (duty4 << 4)); /* even cell */
}
/* Discharge timeout = hardware watchdog for balancing: if the MCU stops
* refreshing the config, the chip turns its own switches off. */
void adbms_set_discharge_timeout(adbms_chain_t *ch, uint8_t minutes)
{
if (minutes > 63) minutes = 63;
for (uint8_t i = 0; i < ch->num_dev; i++)
ch->regs[i].cfgb[3] = (uint8_t)((ch->regs[i].cfgb[3] & ~(CFGB3_DTRNG | CFGB3_DCTO_MASK))
| minutes); /* DTRNG = 0 -> 1 min/LSB */
}
/* MUTE turns every discharge switch off within ~65 us without forgetting the
* DCC/PWM settings; UNMUTE restores them. Used to take clean measurements. */
int adbms_mute(adbms_chain_t *ch, bool mute)
{
return adbms_cmd(ch, mute ? CMD_MUTE : CMD_UNMUTE);
}
16.4 Measurement error during balancing
Bleed current flows through the filter and S-pin resistors, connectors and wiring. The IR drop makes the measured voltage of a bleeding group lower than its true voltage. If this is ignored, the algorithm sees the group as low, stops balancing it, sees it recover, starts again, and oscillates. Remedies:
- MUTE → wait → measure → UNMUTE (used in this firmware; costs a ~2 ms gap per loop).
- Balance at less than 100 % duty and measure during the off-time.
- Compensate per channel: ADI's own discharge demo calibrates a per-cell gain with switches on vs off.
16.5 Balancing algorithm
Vmin = lowest active group voltage in the WHOLE chain
for each active group:
if not bleeding and V > Vmin + 10 mV and V > 3.60 V -> start (DCC = 1)
if bleeding and (V < Vmin + 3 mV or V < 3.60 V) -> stop (DCC = 0)
if any fault or die temperature > 85 °C -> all DCC = 0
write DCC for every board in ONE WRCFGB frame, re-arm DCTO each write
- Global minimum: the MCU sees every group in every module, so the whole pack converges to one level. A monitor IC alone only knows its own 16 channels.
- Hysteresis (10 mV on / 3 mV off) prevents chattering on noise.
- Minimum voltage: never bleed a nearly empty group.
- When to balance: near the top of charge or at rest, where the OCV curve is steep and voltage tracks SOC well. NMC curves are flat mid-range, LFP even more so.
- Thermal limit: cap the number of simultaneous channels, or use PWM below 100 %, when the board gets hot.
16.6 Balancing in code
The decision logic is pure C with no hardware access, so it is easy to unit-test (Appendix B checks the masks and the hysteresis). Note that bal_mask is both input and output: the previous state is needed to apply the hysteresis.
/* Passive balancing with hysteresis, "bleed down to the lowest cell".
* bal_mask is in/out so that hysteresis remembers which cells were ON. */
void bms_balance_compute(const float cell_v[][ADBMS_CELLS_PER_DEV],
uint16_t bal_mask[NUM_DEV], bool allowed)
{
float vmin = 10.0f;
for (int dev = 0; dev < NUM_DEV; dev++)
for (int c = 0; c < cells_per_dev[dev]; c++)
if (cell_v[dev][c] < vmin) vmin = cell_v[dev][c];
for (int dev = 0; dev < NUM_DEV; dev++) {
uint16_t m = allowed ? bal_mask[dev] : 0;
for (int c = 0; allowed && c < cells_per_dev[dev]; c++) {
float v = cell_v[dev][c];
bool on = (m >> c) & 1u;
if (!on && v > vmin + BAL_START_DELTA_V && v > BAL_MIN_CELL_V)
m |= (uint16_t)(1u << c); /* start bleeding */
else if (on && (v < vmin + BAL_STOP_DELTA_V || v < BAL_MIN_CELL_V))
m &= (uint16_t)~(1u << c); /* close enough */
}
bal_mask[dev] = m;
}
}
Applying the decision means setting each device's DCC bits in its shadow register, re-arming the hardware timeout, and writing the whole chain in one frame:
int bms_app_apply_balance(adbms_chain_t *ch, const bms_data_t *d)
{
for (int dev = 0; dev < NUM_DEV; dev++) {
uint16_t m = d->bal_mask[dev];
if (d->die_c[dev] > BAL_MAX_DIE_TEMP_C) m = 0; /* thermal back-off */
adbms_set_dcc(ch, (uint8_t)dev, m);
}
/* Re-arm the hardware watchdog on every write: if this loop dies, the
* ADBMS6830 switches the bleed resistors off by itself. */
adbms_set_discharge_timeout(ch, BAL_TIMEOUT_MIN);
adbms_wakeup_idle(ch);
return adbms_write_config(ch);
}
16.7 A worked balancing decision
Take the bench chain with these readings (the same values the PC test uses):
| Board / cell | C1 | C2 | C3 | C4 | C5 | C6 | C7 |
|---|---|---|---|---|---|---|---|
| Board 1 (V) | 3.701 | 3.712 | 3.695 | 3.730 | 3.703 | — | — |
| Board 2 (V) | 3.698 | 3.702 | 3.744 | 3.700 | 3.699 | 3.721 | 3.703 |
- Pack minimum Vmin = 3.695 V (board 1, C3). Start threshold = 3.705 V, stop threshold = 3.698 V.
- Board 1: C2 (3.712) and C4 (3.730) exceed 3.705 V → bits 1 and 3 → DCC mask
0x000A. C5 at 3.703 V is within the window and stays off. - Board 2: C3 (3.744) and C6 (3.721) → bits 2 and 5 → DCC mask
0x0024. - One
WRCFGBframe carries board 2's bytes first (…24 00), then board 1's (…0A 00), each with DCTO = 2 min. - Next loops: when board 1 C2 falls to 3.700 V (5 mV above minimum) it keeps bleeding (hysteresis). At 3.697 V it stops.
17. Protection and fault handling
Measurement and balancing are only useful if the system reacts correctly when something goes wrong. The table below lists every fault the firmware detects, how it is detected, and how a production BMS would respond. The theory section then explains how robust fault logic is built.
| Fault | Detection | Firmware response | Production response Engineering practice |
|---|---|---|---|
| Over-voltage | Cell > 4.20 V (software) + VOV comparator (hardware) | FAULT_OV, balancing disabled | Stop charging, open the charge contactor if it persists |
| Under-voltage | Cell < 2.80 V + VUV comparator | FAULT_UV | Limit or stop discharge |
| Over-temperature | NTC > 60 °C | FAULT_OT | Derate current, then open the contactors |
| Under-temperature | NTC < 0 °C | FAULT_UT | Block charging |
| Sensor fault | NTC open or shorted | FAULT_SENSOR | Treat as worst case and derate |
| Communication | Data PEC mismatch (−77), CCNT mismatch | FAULT_COMM, error counter | Retry. Repeated failures within the fault-tolerant time → safe state. |
| ADC drift | C-ADC vs S-ADC → CSxFLT | (read RDSTATC) | Safe state |
| Open sense wire | Open-wire test (OW bits) | (start-up check) | Safe state |
| MCU hang | DCTO timer, 2 s watchdog | Hardware turns balancing off | Plus an MCU watchdog and an independent safety path |
17.1 Functional safety basics (ISO 26262)
Automotive BMSs are developed under ISO 26262. The ideas are worth knowing even for a student project, because they explain design choices in the ADBMS6830 family:
- Hazard analysis and risk assessment (HARA): each hazard (e.g. "cell overcharged → thermal event") is rated for Severity, Exposure and Controllability, giving an ASIL from A (lowest) to D (highest). Overcharge protection is typically high-ASIL.
- Safety goal and safe state: e.g. "prevent overcharge of any cell". The safe state is "contactors open, current zero".
- FTTI: the fault-tolerant time interval between a fault and the hazard. Detection plus reaction must fit inside it.
- Diagnostic coverage: how many faults the system can detect. The ADBMS6830's redundant S-ADC, open-wire checks, PEC with command counter, and reference and oscillator checks all exist to raise coverage of the measurement path.
- Independent paths: a single fault must not both cause the hazard and disable its detection. Hardware OV/UV comparators, separate from the MCU's software checks, are an example.
17.2 Limits, debounce, hysteresis and latching
A good protection scheme answers four questions for every monitored value:
- What are the limits? Usually two levels: a warning limit (reduce current, stop balancing) and a hard limit (open the contactors).
- How long must it be violated? A single bad sample (noise, a PEC-valid but transient spike) shouldn't shut the car down, so a fault needs N consecutive violations. N × sample period must still fit inside the fault-tolerant time interval (FTTI), the time between a fault occurring and the cell being damaged.
- When is it clear again? Releasing at the same threshold makes the output chatter. A hysteresis band (e.g. set at 4.20 V, clear below 4.15 V) avoids that.
- Does it latch? Serious faults (hard OV, communication loss) stay latched until a deliberate reset, so the system can't oscillate between running and tripping.
/* Fault debounce: a limit must be violated for N consecutive samples before
* the fault is declared (filters noise and single bad readings), and it must
* be clear by a hysteresis margin before it can be released. */
typedef struct {
uint8_t count; /* consecutive violations seen */
bool active; /* fault currently declared */
} debounce_t;
bool fault_ov_update(debounce_t *d, float v_cell)
{
const float OV_SET = 4.20f; /* declare above this */
const float OV_CLEAR = 4.15f; /* release below this (50 mV) */
const uint8_t N = 3; /* 3 samples x 100 ms = 300 ms */
if (v_cell > OV_SET) {
if (d->count < N) d->count++;
if (d->count >= N) d->active = true;
} else {
d->count = 0;
if (d->active && v_cell < OV_CLEAR) d->active = false;
}
return d->active;
}
The project firmware keeps protection deliberately simple: it recomputes fault bits every loop and disables balancing whenever any fault is present. The debounce and latching above are the natural next step for a vehicle:
void bms_app_protect(bms_data_t *d)
{
d->faults &= FAULT_COMM; /* recompute everything except comms */
for (int dev = 0; dev < NUM_DEV; dev++) {
for (int c = 0; c < cells_per_dev[dev]; c++) {
if (d->cell_v[dev][c] > CELL_OV_V) d->faults |= FAULT_OV;
if (d->cell_v[dev][c] < CELL_UV_V) d->faults |= FAULT_UV;
}
for (int g = 0; g < ntc_per_dev[dev]; g++) {
float t = d->temp_c[dev][g];
if (t <= -273.0f) d->faults |= FAULT_SENSOR;
else if (t > CELL_TEMP_MAX_C) d->faults |= FAULT_OT;
else if (t < CELL_TEMP_MIN_C) d->faults |= FAULT_UT;
}
}
/* In the car this is where the BMS tells the VCU / opens the contactor. */
}
18. Firmware architecture
The firmware is small (under 1000 lines), but its structure is what makes it reliable and testable: a portable device driver, a thin hardware abstraction layer, a separate application layer, and one configuration file that describes the physical chain. This chapter walks through that structure with the real code.
18.1 Modules
| File | Layer | Responsibility |
|---|---|---|
adbms6830_regs.h | Driver | Command codes, register bit positions, conversion macros |
adbms6830.c/.h | Driver | PEC15/PEC10, wake-up, action/write/read frames, configuration, cells, GPIOs, VREF2, DCC/PWM/DCTO/MUTE |
parameters.c/.h | Config | NUM_DEV, dev_list[], cells and NTCs per board, limits |
bms_app.c/.h | Application | Measure → protect → balance → print |
thermistor.c/.h | Application | NTC voltage → °C (Beta equation) |
platform_max32690.c | HAL | SPI1 (mode 3, 1 MHz), GPIO chip select, microsecond delay (MaximSDK) |
main.c | Entry | Init, safety trap, 1 s main loop |
project.mk | Build | MaximSDK build configuration |
18.2 Design decisions
HAL with function pointers
The driver core contains no MCU-specific code. Porting means rewriting about 40 lines, and the driver can be unit-tested on a PC against a simulated chain.Shadow registers
A write frame must carry data for every device, so a single device cannot be written alone. The driver keeps a RAM copy of each device's CFGA/CFGB/PWMA/PWMB, edits only the needed fields, and writes the whole chain.Read-modify-write configuration
At init the driver reads CFGA/CFGB first and changes only REFON, GPO, FC, VUV/VOV, DCTO and DCC. Unknown reset values are never overwritten blindly.Errors returned, never ignored
Every function returns a status. A PEC failure on one device doesn't stop the others from being parsed, but it's reported. Init failure triggers a safety trap instead of continuing with bad pointers.18.3 The HAL and the main loop in code
The whole hardware dependency of the driver is the adbms_hal_t structure of three function pointers. The MAX32690 platform file fills it with MaximSDK calls, and the PC test fills it with a simulated chain. Initialisation validates the HAL and the device count before anything touches the hardware, which is exactly the check that would have caught the dead-LED fault:
/* ------------------------------------------------------------------------ */
int adbms_init(adbms_chain_t *ch, const adbms_hal_t *hal, uint8_t num_dev)
{
/* This check exists because of the "dead LED" bug: NUM_DEV was changed
* to 2 but only one device was described, so init got an invalid entry
* and the chain pointer stayed NULL. Fail loudly instead of hard-faulting. */
if (!ch || !hal || !hal->spi_xfer || !hal->cs_set || !hal->delay_us)
return ADBMS_E_PARAM;
if (num_dev == 0 || num_dev > ADBMS_MAX_DEV)
return ADBMS_E_PARAM;
memset(ch, 0, sizeof(*ch));
ch->hal = hal;
ch->num_dev = num_dev;
hal->cs_set(1);
return ADBMS_OK;
}
static int plat_spi_xfer(const uint8_t *tx, uint8_t *rx, uint16_t len)
{
mxc_spi_req_t req = {0};
req.spi = BMS_SPI;
req.txData = (uint8_t *)tx;
req.rxData = rx;
req.txLen = len;
req.rxLen = len;
req.ssIdx = 0;
req.ssDeassert = 0; /* CS is ours (GPIO), keep HW SS out of it */
req.completeCB = NULL;
return (MXC_SPI_MasterTransaction(&req) == E_NO_ERROR) ? 0 : -1;
}
int main(void)
{
printf("\n=== ADBMS6830 daisy chain on MAX32690 ===\n");
if (platform_init() != 0) {
printf("SPI init failed\n");
while (1) {}
}
/* Safety trap: if init fails we stop HERE with a message and a fast
* blinking LED, instead of hard-faulting later on a bad pointer. */
int ret = bms_app_init(&chain, &max32690_hal);
if (ret != 0) {
printf("BMS init failed (%d). Check NUM_DEV / dev_list / wiring.\n", ret);
while (1) {
LED_Toggle(0);
MXC_Delay(MXC_DELAY_MSEC(100));
}
}
while (1) {
ret = bms_app_measure(&chain, &data);
if (ret == ADBMS_E_PEC)
printf("PEC error (-77): check isoSPI cable / termination / tie-offs\n");
bms_app_protect(&data);
/* Balance only when the pack is healthy (in the car: also only while
* charging or resting, never while driving at high current). */
bms_balance_compute((const float (*)[ADBMS_CELLS_PER_DEV])data.cell_v,
data.bal_mask, data.faults == 0);
bms_app_apply_balance(&chain, &data);
bms_app_print(&data);
LED_Toggle(0);
MXC_Delay(MXC_DELAY_MSEC(MEAS_PERIOD_MS)); /* < 2 s so the chain's
watchdog never sleeps it */
}
}
18.4 Program flow
18.5 Timing budget of one loop (2 devices, 1 MHz SPI)
| Step | Approximate time |
|---|---|
| Idle wake (2 × 20 µs) | 0.04 ms |
| MUTE + 2 ms settle + SNAP | ~2.1 ms |
| 3 × 20-byte reads + UNSNAP + UNMUTE | ~0.6 ms |
| ADAX + conservative wait + 4 AUX reads + STATA | ~21 ms (could use PLAUX polling instead) |
| Balancing decision + 4 config writes | < 1 ms |
| Total active time | ≈ 25 ms per 1 s loop |
19. Multi-board bring-up (1 board → 2-board 5 + 7 channel chain)
Before the full 40S7P pack is connected, the firmware is brought up on the bench: first one monitor board, then a two-board chain. Deliberately using different cell counts on each board (5 and 7 active channels) proves that the per-device parsing and channel masking are correct. The same code then scales to the pack's chain by changing the device table.
- Physical layer. Port A/B wiring, termination set for the end of the chain, unused inputs tied off. Before this, reads returned −77 (PEC failures). Project notes
- Device table.
NUM_DEV = 2anddev_list = { DEV_ADBMS6830, DEV_ADBMS6830 }. The two must always agree (see Section 20.1). - Broadcast commands. The ADC start and register reads are sent once and reach both devices. Write frames carry board 2's data first, then board 1's.
- Read groups A, B, C for every device (7 cells need C1–C7, which fall in groups A–C).
- Parse with offsets. Board 1 at
rx[4], board 2 atrx[12]. Take 5 cells from board 1 and 7 from board 2, ignore the rest. - Running totals.
b1_sumandb2_sumprint the per-board stack voltage next to each cell, a quick sanity check against a multimeter across each board's stack.
20. Debugging case studies
20.1 The "dead LED" HardFault Project notes
| STAR | Content |
|---|---|
| Situation | Adding a second monitor board to the chain. After the change the firmware appeared to run, but the board's LED never lit and nothing printed. |
| Task | Find why neither board responded after moving to NUM_DEV = 2. |
| Action | Used the LED as a clue: D2 lights only when the chip is awake, so no wake-up pulse had reached it. Stepping through init showed it returning an error and leaving the device pointer NULL. The cause: dev_list[NUM_DEV] had one initializer, so C zero-filled the second entry (0x00 = invalid device ID). The next call dereferenced NULL → HardFault. |
| Result | Listed both devices in parameters.c, added return-value checks and a while(1) safety trap that prints the error. Both boards then reported. |
| Lesson | Never ignore return codes. Derive array lengths from one source of truth. |
/* Make the mismatch impossible: the count is derived from the list */
static const dev_type_t dev_list[] = { DEV_ADBMS6830, DEV_ADBMS6830 };
#define NUM_DEV (sizeof(dev_list) / sizeof(dev_list[0]))
_Static_assert(NUM_DEV <= ADBMS_MAX_DEV, "too many devices in the chain");
20.2 The build that produced no .elf Project notes
- No .elf file.
build/heldmain.obut nomaxim_*.o, so the linker failed on undefined symbols. The no-OS platform sources live indrivers/platform/maxim/max32690/, one level deeper than the VPATH entry. Fix: point VPATH at the max32690 folder. - Missing
maxim_dma.hand deprecated-API errors inmaxim_rtc.c,maxim_pwm.c. (a) Newer no-OS moved shared headers to…/maxim/common/, so it was added to IPATH. (b) MaximSDK's AUTOSEARCH compiles every.cin every VPATH folder, which pulled in unused drivers written for an older SDK. - Final configuration. no-OS paths added after the autosearch step (or AUTOSEARCH = 0 with an explicit source list),
common/on the include path,-Wno-strict-prototypes, and onlymaxim_delay.ccompiled from no-OS.
| Make concept | Meaning |
|---|---|
VPATH | Folders where make searches for source files |
IPATH → -I | Folders where the compiler searches for headers |
SRCS | Source files to compile |
AUTOSEARCH | MaximSDK option: add every .c in the project and VPATH folders to SRCS |
| Link failure | An object file was never built → undefined reference → no .elf |
20.3 Checklist for −77 (PEC) errors
- Is
NUM_DEVequal to the real number of devices? (An extra slot always fails.) - Are the D2 LEDs lit on every board after wake-up? If not, it's a wake-up or cabling issue.
- Port A toward the MCU, port B away? Termination correct at the end of the line?
- SPI mode 3, ≤ 2 MHz, CS held low for the entire frame?
- Frame length = 4 + 8 × N? Reading the PEC at the right offset (bytes 6–7 of each slot)?
- Is the CCNT taken from the top 6 bits of byte 6 and included in the PEC calculation?
- Does only the top board fail? Then suspect the cable or termination of the last link.
20.4 Finding a HardFault on Cortex-M Engineering practice
- Read CFSR (configurable fault status), HFSR, MMFAR/BFAR (fault address). An address near 0x00000000 means a NULL dereference.
- Unwind the stacked frame: the stacked PC points at the faulting instruction, the LR at the caller.
- Usual suspects: unchecked return values, uninitialised pointers, stack overflow, unaligned access, a wrong function pointer.
21. Toolchain and build
| Tool | Role |
|---|---|
| MaximSDK (MSDK) | ADI's SDK for MAX32xxx: peripheral drivers (MXC_SPI_*, MXC_GPIO_*, MXC_Delay), start-up code, linker scripts, Makefile system, bundled arm-none-eabi-gcc and OpenOCD |
| VS Code | Editor. MSDK projects include a .vscode/ folder with build/flash tasks and a Cortex-Debug launch configuration. |
| arm-none-eabi-gcc | Cross compiler → build/max32690.elf |
| OpenOCD + MAX32625PICO | SWD flashing and debugging (breakpoints, fault registers) |
| ADI no-OS | Open-source bare-metal driver framework. The platform layer for this MCU is in drivers/platform/maxim/max32690. |
| Serial terminal | 115200 8N1 on the PICO's virtual COM port (VS Code serial monitor or PuTTY) |
Commands on Windows (MaximSDK's MSYS2 terminal, or the VS Code tasks that call the same targets):
make -r -j # build -> build/max32690.elf
make flash.openocd # flash through the MAX32625PICO
make clean # remove build/
Running the PC test harness on Windows (MSYS2 or MinGW gcc in PATH):
cd code\test
gcc -Wall -I.. -o host_test.exe host_test.c ..\adbms6830.c ..\bms_app.c ..\parameters.c ..\thermistor.c -lm
host_test.exe
22. Production BMS and improvements
22.1 Built-in diagnostics worth using Datasheet
- C-ADC vs S-ADC redundancy → CSxFLT flags (detects a drifting measurement path).
- Open-wire detection (OW bits): small pull currents on odd/even channels. A disconnected sense wire produces a large shift. Odd and even are tested separately so a fault can't hide behind a resistive divider.
- Hardware OV/UV comparators with flags in STATD.
- Supply and reference checks (VA, VD, VREF2), oscillator check, thermal shutdown.
- LPCM: the chip monitors cells and temperatures by itself while the vehicle is off and can wake the system on a threshold breach.
22.2 What a vehicle BMS adds Engineering practice
| Function | How |
|---|---|
| Pack current | Shunt or Hall sensor with a pack monitor (e.g. ADI ADBMS2950) |
| SOC / SOH | Coulomb counting + OCV correction, often a Kalman filter. Capacity and resistance tracking. |
| Contactors | Main ± contactors, pre-charge resistor and relay, welded-contact detection |
| Isolation | Insulation resistance monitoring between HV and chassis |
| Communication | CAN to the VCU and charger: current/voltage limits, SOC, faults (MAX32690 has 2 × CAN 2.0B) |
| Functional safety | ISO 26262: safety goals, fault-tolerant time intervals, safe states, ASIL-D-process parts (the non-B ADBMS6830) |
| Robustness | Redundant isoSPI ring, DMA-driven SPI on a timer schedule, non-volatile fault log, bootloader / OTA updates |
22.3 Next improvements for this firmware
- Redundant isoSPI ring using the ADBMS6822 AUX port, with automatic fall-back on a broken link.
- Timer-driven scheduler and DMA SPI instead of blocking delays. Protection runs at 10–100 ms.
- Read the S-ADC and CSxFLT, and run open-wire checks at start-up.
- Replace the fixed ADAX wait with PLAUX polling.
- Per-channel IR-drop compensation so measurement can continue during balancing.
- CAN reporting, current sensing and SOC estimation.
23. Interview question bank
93 questions with model answers, grouped by topic. Click a question to reveal its answer.
23.1 Battery and pack fundamentals
Q1. What does a BMS do?
Measures (group voltages, temperatures, current), protects (keeps every group inside its voltage and temperature window, requests current limits, opens contactors), balances, estimates SOC/SOH, and communicates with the vehicle (usually CAN).
Q2. Why monitor every group instead of just the pack voltage?
The pack voltage is a sum. One group at 4.40 V and another at 4.00 V can produce a normal-looking total while one group is overcharged. Every limit is per group.
Q3. What does 13S14P mean?
13 parallel groups in series. Each group has 14 cells in parallel. 182 cells in total. Voltage = 13 × Vcell, capacity = 14 × Ahcell.
Q4. How do n and m affect voltage, capacity, energy and current?
n multiplies voltage, m multiplies capacity and current capability. Energy = n × m × V × Ah, so for a fixed number of cells the energy is fixed, and the split only trades voltage against current.
Q5. How do you choose n?
From the load's voltage window: n × Vcutoff must stay above the controller's minimum input and n × 4.2 V below its maximum. Then check charger and component voltage ratings.
Q6. How do you choose m?
From energy (m = E / (n × V × Ah), plus margin) and from current (peak current at minimum voltage divided by m must be within the cell's rating).
Q7. Why use a higher pack voltage?
Same power at lower current: thinner cables, smaller contactors, I²R losses fall with the square of current. Costs: more BMS channels, insulation and safety requirements above ~60 V DC, more cells in series to balance.
Q8. Why does parallel need no balancing inside a group?
Cells in a group share the same bus bars, so they are forced to the same voltage and exchange charge automatically.
Q9. Why do series groups drift apart?
They carry the same current but differ in capacity, self-discharge, temperature and ageing, so their states of charge diverge over cycles.
Q10. Parallel-first vs series-first?
Parallel-first (groups then series) needs only n channels and the groups self-equalise. This is the standard EV approach. Series-first (strings then parallel) needs n × m channels or cells go unmonitored, and strings can circulate current.
Q11. What limits pack capacity?
The highest group ends charging, the lowest group ends discharging. Balancing aligns them.
Q12. How does pack resistance scale?
Rpack = (n/m) × Rcell plus interconnects. More series adds resistance, more parallel reduces it.
Q13. Why fuse individual cells in a parallel group?
If one cell shorts internally, its group-mates discharge into it with very high current. A fuse link per cell isolates it.
Q14. What is a C-rate?
Current relative to capacity: 1C discharges the full capacity in one hour. 2C of a 3 Ah cell = 6 A.
Q15. Why not charge below 0 °C?
Lithium plates on the anode instead of intercalating. Permanent capacity loss and internal-short risk.
Q16. What is thermal runaway?
A self-heating chain reaction (SEI breakdown, electrolyte reactions, separator melt, internal short). The BMS exists to keep cells far away from its trigger conditions.
Q17. Why 5S7P modules?
21 V maximum per module (safe to handle, below 60 V DC). Eight modules give the 40S, 144 V pack, and one 16-channel monitor fits one module (or three).
Q18. Describe the project pack.
40S7P: 280 Li-ion cells, 7 in parallel per group, 40 groups in series, built from eight 5S7P modules. 144 V nominal (40 × 3.6 V), 168 V at full charge (40 × 4.2 V), about 120 V at a 3.0 V/cell cut-off. 40 voltage channels.
Q19. Why is a 168 V pack treated as high voltage?
It exceeds the commonly used 60 V DC limit for touch-safe low voltage, so it needs insulation, contactors with pre-charge, insulation monitoring, fusing and safe service procedures.
Q20. SOC and SOH?
SOC: coulomb counting corrected by the OCV curve at rest, often fused with a Kalman filter. SOH: capacity or resistance compared with a new cell.
23.2 ADBMS6830B
Q21. Key specifications?
16 channels, ±1.8 mV TME, −2 V to +5.5 V input, 150 µV/LSB, results every 1 ms in continuous mode, programmable IIR filter, redundant S-ADC, 10 GPIOs with a 3 V reference, 16 × 300 mA balancing switches with PWM, 2 isoSPI ports at 2 Mbps, 4 µA sleep.
Q22. How is a raw code converted?
Signed 16-bit code × 150 µV + 1.5 V. Example: 0x3951 → 3.7010 V.
Q23. What is the S-ADC for?
A second, independent measurement path via the S-pins. The chip compares it with the C-ADC and sets CSxFLT if they disagree. This is redundancy for functional safety.
Q24. Raw vs averaged vs filtered results?
Raw (RDCV) for fast protection, averaged (RDAC, 8 samples) for lower noise, IIR-filtered (RDFC) for smooth values used in balancing and SOC.
Q25. Why SNAP / UNSNAP?
Results update every 1 ms. SNAP freezes all result registers so every group read belongs to the same conversion instant.
Q26. What does REFON do?
Keeps the reference powered between conversions, avoiding a ~3.5 ms start-up (tREFUP) each time.
Q27. What if the MCU stops communicating?
After ~2 s the watchdog puts the device into sleep (~4 µA). The firmware must wake it and re-write the configuration. The DCTO timer independently ends balancing.
Q28. How are fewer than 16 cells connected?
Real groups on the bottom channels. Unused upper inputs tied to the top cell / V+. Those channels read 0 V and are ignored in firmware.
Q29. How are temperatures measured?
10 kΩ NTC + 10 kΩ bias from VREF2 into a GPIO, AUX ADC, ratiometric against VREF2, Beta equation.
Q30. Why must GPO bits be 1 for thermistor inputs?
GPO = 0 enables the pin's pull-down, which would load the divider and give wrong readings.
Q31. How does open-wire detection work?
The OW bits apply small pull currents to odd or even channels during a conversion. A disconnected wire causes a large shift. Odd and even are tested separately so the fault can't be masked.
Q32. ADBMS6830 vs ADBMS6830B?
The automotive ISO 26262 / ASIL-D-process part vs the broad-market version with a public datasheet and evaluation kits.
Q33. What is LPCM?
Low-power cell monitoring: autonomous threshold checks of cells and temperatures while the vehicle is off, with wake-up on a breach.
Q34. Why is RDCVF special?
Group F holds only cell 16. The other bytes read as 0xFF.
23.3 isoSPI and daisy chain
Q35. Why isoSPI rather than SPI or CAN?
The monitors sit at different high voltages, so isolation is required. isoSPI provides isolated, low-EMI, 2 Mbps communication over one twisted pair through a transformer, without an MCU, isolator or isolated supply on each module.
Q36. How is data encoded?
Differential doublet pulses. Long pulses (~150 ns per half) for CS edges, short pulses (~50 ns per half) for data bits. Drive about ±20 mA, receive threshold about 300 mV.
Q37. What is the ADBMS6822?
The master-side SPI ↔ isoSPI transceiver. The dual version has two independent ports, so it can drive both ends of the chain.
Q38. Write order vs read order?
Writes carry the top device's data first. Reads return the bottom device's data first. The chain behaves like a shift register.
Q39. Where is device i's data in a read?
At offset 4 + 8·i: a 4-byte command echo, then 6 data + 2 PEC bytes per device. With two devices: 4 and 12.
Q40. How is a chain of N devices woken?
N chip-select pulses, each followed by tWAKE (up to 500 µs), because the wake-up ripples from device to device. From isoSPI idle (after ~5.5 ms of silence) only tREADY ≤ 10 µs per device is needed.
Q41. Why does termination matter?
Matched termination at the ends of each link prevents reflections. Wrong termination corrupts bits → PEC errors.
Q42. What is a redundant (ring) isoSPI connection?
The transceiver's MAIN port drives the bottom of the chain and AUX drives the top. If a cable breaks, each side of the break is still reachable.
Q43. Maximum SPI clock?
≤ 2 MHz (isoSPI is 2 Mbps). This firmware uses 1 MHz, SPI mode 3.
Q44. Why must CS stay low for the whole frame?
CS edges become the long pulses that delimit a command. Releasing CS mid-frame ends the command early.
Q45. What if NUM_DEV is wrong?
Too large: the extra slots read 0xFF with invalid PEC → −77. Too small: only the first devices are parsed, and write data is shifted onto the wrong devices.
Q46. How does the design scale?
ceil(n/16) or more monitors, frames of 4 + 8·N bytes, N wake pulses. Still a few milliseconds per full scan for tens of devices.
23.4 PEC and data integrity
Q47. What is a PEC?
Packet error code, ADI's name for a CRC: 15 bits on commands, 10 bits on data.
Q48. Which polynomials?
Command: x¹⁵+x¹⁴+x¹⁰+x⁸+x⁷+x⁴+x³+1 (0x4599), seed 16. Data: x¹⁰+x⁷+x³+x²+x+1 (0x08F), seed 16.
Q49. What is the command counter for?
A 6-bit per-device counter included in the read PEC. It reveals lost or duplicated commands, not just bit errors.
Q50. What was the −77 error?
−EBADMSG in ARM newlib, returned on a data-PEC mismatch. Causes: termination, cabling, wrong device count, chain not woken, SPI settings.
Q51. What happens after a PEC error?
Discard that frame, retry, count errors. Repeated failures within the fault-tolerant time → communication fault → safe state. Never keep acting on stale values.
Q52. How is the CRC implemented?
A bitwise shift-register loop (small flash, fast enough at these rates). A 256-entry lookup table is the speed alternative.
23.5 Cell balancing
Q53. Passive vs active balancing?
Passive burns excess charge in resistors (cheap, built in, 50–300 mA). Active moves charge between cells (efficient, 1–5 A, more hardware).
Q54. How does the ADBMS6830B balance?
An internal FET per channel with an external resistor between the S-pins. DCC bits for static on, 4-bit PWM for duty control, up to 300 mA.
Q55. Which balancing algorithm is used?
Bleed every group more than 10 mV above the pack minimum, stop at 3 mV (hysteresis), never below 3.6 V, disabled on any fault or a die above 85 °C, hardware timeout re-armed on every write.
Q56. Why hysteresis?
Without it, noise and IR drop would switch the resistors on and off every loop.
Q57. Why does balancing disturb the measurement?
The bleed current causes IR drops in the filter resistors and wiring. Remedies: MUTE before measuring, measure in the PWM off-time, or compensate per channel.
Q58. What is DCTO?
Discharge timeout. If the MCU stops refreshing the configuration, the chip turns the balancing switches off by itself.
Q59. What is MUTE?
A command that turns off all discharge switches within 65 µs while keeping the DCC/PWM settings, so UNMUTE restores them.
Q60. How long does balancing take?
Imbalance in Ah divided by the bleed current. 150 mAh / 118 mA ≈ 1.3 h. With large parallel groups (e.g. 2.1 Ah at 14P) it is about 18 h.
Q61. How much heat?
P = V²/R per channel. About 0.46 W at 3.9 V with 33 Ω. Ten channels on one board is about 4.6 W, so limit the duty or the channel count.
Q62. When should balancing run?
During charging near the top of charge or at rest, where voltage tracks SOC well. Not during heavy discharge.
Q63. DCC vs PWM?
DCC = maximum speed. PWM = a lower average current and less heat without changing resistors.
Q64. Why does the MCU decide instead of the chip?
The MCU sees every group in the pack (the global minimum), plus temperatures and charger state. One monitor only knows its own channels.
23.6 Firmware and embedded C
Q65. Walk through the main loop.
Wake (tREADY) → MUTE → wait → SNAP → read groups A–C → UNSNAP → UNMUTE → ADAX → read GPIOs and VREF2 → convert temperatures → protection checks → balancing decision → write DCC + DCTO to the whole chain → print → wait (~1 s, below the 2 s watchdog).
Q66. How is the driver structured?
A portable core with a HAL of three function pointers (SPI transfer, CS, delay). Per-device shadow registers. Whole-chain write frames.
Q67. Why shadow registers?
A write frame must contain data for every device, so the firmware keeps a RAM copy of each device's registers and edits only the required fields.
Q68. Why read-modify-write the configuration?
To avoid overwriting bits whose reset values are not being deliberately changed.
Q69. Endianness?
Commands are sent MSB first. 16-bit results inside register groups are little-endian.
Q70. Signed or unsigned codes?
Signed. Cast to int16_t before scaling, otherwise negative inputs (bus bars, faults) are misread.
Q71. Explain the dead-LED fault.
NUM_DEV was raised to 2 while dev_list kept one entry. C zero-filled the second entry, init failed and left a NULL device pointer, and the first wake-up dereferenced it → HardFault. No wake-up ever reached the chain, so the VREG LED stayed off. Fixed by completing the list and checking return values with a safety trap.
Q72. How do you debug a HardFault?
Read CFSR/HFSR and BFAR/MMFAR. An address near zero means a NULL dereference. Unwind the stacked PC/LR to the faulting line.
Q73. How do you prevent the NUM_DEV mismatch?
Derive the count from sizeof(list)/sizeof(list[0]) and add a _Static_assert.
Q74. Are blocking delays acceptable?
For a prototype, yes. A production design uses a timer or RTOS task with a fixed period, and DMA SPI.
Q75. SPI configuration?
Mode 3 (CPOL = 1, CPHA = 1), 8-bit, MSB first, 1 MHz, chip select driven manually by a GPIO.
Q76. Why a manual chip select?
CS must stay low across multi-byte frames, and wake-up needs bare CS pulses without clocks.
Q77. How was the driver tested?
On a PC against a simulated 2-device chain that checks every PEC and the frame ordering (21 checks). On hardware: a resistor ladder or battery emulator on J1, with readings compared against a multimeter.
Q78. How would CAN be added?
Use one of the MAX32690's two CAN 2.0B controllers. Periodic frames with min/max/average group voltage, temperatures, faults and balancing state for the VCU and charger.
Q79. Why a 1 s loop?
Well inside the 2 s watchdog and sufficient for monitoring. A production protection loop runs at 10–100 ms.
23.7 Build system and tools
Q80. VPATH vs IPATH?
VPATH: where make finds source files. IPATH (→ -I): where the compiler finds headers.
Q81. What did AUTOSEARCH break?
It compiled every .c file in the no-OS platform folder, including drivers that use APIs deprecated in the installed MaximSDK.
Q82. Why was no .elf produced?
The no-OS objects were never built (VPATH one level too high), so the linker hit undefined references and aborted.
Q83. How is the board flashed and debugged?
OpenOCD over SWD with the MAX32625PICO, from VS Code tasks or Cortex-Debug. printf output on the UART console.
Q84. What is ADI no-OS?
ADI's open-source bare-metal driver framework, with a platform abstraction (delay, SPI, GPIO) per MCU family.
23.8 Design judgement
Q85. What would be improved next?
Redundant isoSPI ring, DMA + timer scheduling, S-ADC and CSxFLT checks, open-wire tests at start-up, PLAUX polling, IR compensation during balancing, CAN, current sensing and SOC.
Q86. A channel reads 0 V. What could it be?
A tied-off unused channel (expected, should be masked), an open sense wire (run the open-wire check), or a dead group (UV fault → safe state).
Q87. How is a broken isoSPI cable detected?
Every device above the break returns invalid data / PEC errors. With a redundant ring, reading from the other end locates the break.
Q88. How fast must an over-voltage be handled?
Within the system's fault-tolerant time interval (the datasheet uses a 100 ms FTTI as its example). Hardware OV flags help reach that.
Q89. What happens to balancing if the MCU resets?
Rely on DCTO, not just the watchdog. The timeout guarantees the resistors switch off after a bounded time.
Q90. How would this scale to 100+ series groups?
More monitors in the chain (ceil(n/16)), longer frames (4 + 8·N bytes), N wake pulses, a redundant ring, and a faster scheduled loop. Still only milliseconds per scan.
23.9 Questions about the scope of the project
Q91. Was the PCB custom?
No. ADI evaluation boards were used (EVAL-ADBMS6830BMSW, EVAL-ADBMS6822, AD-APARD32690-SL). The work was the firmware and the chain bring-up.
Q92. Was SOC estimation implemented?
No. The scope was cell monitoring, protection and balancing. Be ready to explain how SOC would be added (coulomb counting + OCV correction).
Q93. How large was the full pack?
40S7P, 280 cells, 144 V nominal and 168 V maximum, built from eight 5S7P modules. The bench bring-up used two monitor boards with 5 and 7 active channels.
24. Multiple-choice quiz (52 questions)
52 decent-to-hard questions covering pack design, cell theory, the ADBMS6830B, the protocol, isoSPI, balancing, protection and firmware. Click an option to check it. The explanation shows the working. Your score is counted at the top.
24.1 Pack design
24.2 Cell theory
24.3 ADBMS6830B
24.4 Protocol
24.5 isoSPI
24.6 Balancing
24.7 Protection & HV
24.8 Firmware
25. Cheat sheet
| ADBMS6830B | |
|---|---|
| Channels / IC | 16 |
| LSB / offset | 150 µV / +1.5 V, signed 16-bit |
| UV/OV threshold LSB | 2.4 mV (×16), 12-bit |
| Accuracy | ±1.8 mV (3.3 V, full temperature range, lifetime) |
| C-ADC / average / S-ADC | 1 ms / 8 ms / 8 ms |
| GPIOs / VREF2 | 10 / 3.0 V |
| Balancing | ≤ 300 mA, 4-bit PWM, ~937 ms period |
| DCTO | 0–63 min or 0–16.8 h |
| MUTE | < 65 µs |
| Sleep current | ~4 µA |
| Protocol and timing | |
|---|---|
| SPI | mode 3, ≤ 2 MHz (1 MHz used) |
| tWAKE / tREADY | 200–500 µs / ≤ 10 µs |
| tIDLE / tSLEEP / tREFUP | ~5.5 ms / ~2 s / ~3.5 ms |
| Command PEC | 15-bit, 0x4599, seed 0x10 |
| Data PEC | 10-bit, 0x08F, seed 0x10, + CCNT on reads |
| Frame length | 4 + 8 × N bytes |
| Device i offset | rx[4 + 8·i] |
| ADCV / ADAX / ADSV | 0x260 / 0x410 / 0x168 (+ bits) |
| RDCVA–F | 004, 006, 008, 00A, 009, 00B |
| −77 | −EBADMSG (newlib) = data PEC failure |
| Pack design | |
|---|---|
| Voltage | n × Vcell |
| Capacity / current | m × Ahcell / m × Icell |
| Energy | n × m × V × Ah |
| Resistance | (n/m) × Rcell |
| BMS channels | n (sense wires n + 1) |
| Monitor ICs | ≥ ceil(n / 16) |
| Charger setpoint | n × 4.2 V |
| Project pack | 40S7P, 280 cells, 144 V nom / 168 V max |
| Module | 5S7P (35 cells), 18 V nom / 21 V max, × 8 |
| Hardware | |
|---|---|
| MCU | MAX32690, Cortex-M4F 120 MHz, 1 MB SRAM, ~3 MB flash, 2× CAN |
| Transceiver | ADBMS6822 dual isoSPI |
| Monitor board | EVAL-ADBMS6830BMSW (J1 cells, J3 port A, J4 port B, J5 GPIO, D2 VREG LED) |
| MCU board | AD-APARD32690-SL (Arduino SPI = SPI1) |
| Bench chain | Board 1: 5 cells, TERM off · Board 2: 7 cells, TERM on |
26. Glossary
| Term | Meaning |
|---|---|
| AFE / cell monitor | Analog front-end IC that measures cell voltages (the ADBMS6830B) |
| ASIL | Automotive Safety Integrity Level (ISO 26262), A (lowest) to D (highest) |
| CCNT | 6-bit command counter inside each monitor |
| C-rate | Current relative to capacity (1C = full capacity in one hour) |
| DCC | Discharge cell control bit (balancing switch on/off) |
| DCTO | Discharge timeout (balancing watchdog) |
| FTTI | Fault-tolerant time interval |
| HardFault | Cortex-M exception for bus, memory or usage faults |
| IIR | Infinite impulse response low-pass filter |
| isoSPI | ADI's isolated 2-wire transport for SPI |
| LPCM | Low-power cell monitoring (while the vehicle is off) |
| MSDK | MaximSDK, the SDK for MAX32xxx MCUs |
| nS mP | n parallel groups in series, m cells per group |
| NTC | Negative-temperature-coefficient thermistor |
| OCV | Open-circuit (rest) voltage |
| PEC | Packet error code (CRC) |
| SOC / SOH | State of charge / state of health |
| SWD | Serial Wire Debug (ARM programming and debug interface) |
| TME | Total measurement error |
| VCU | Vehicle control unit |
Appendix A — C driver source code
Reference implementation of the project firmware. Click a file to expand it, and use the Copy button to copy it. The portable files (adbms6830.*, bms_app.*, parameters.*, thermistor.*) compile and pass the PC tests in Appendix B. platform_max32690.c, main.c and project.mk use MaximSDK APIs and have not been compiled against a specific MSDK version. In particular, the argument list of MXC_SPI_Init differs between MSDK releases, so check spi.h in the installed SDK.
A.1 Device driver
adbms6830_regs.h
/**
* adbms6830_regs.h
* ----------------------------------------------------------------------------
* ADBMS6830B command codes, register layout and conversion constants.
*
* Every value here was cross-checked against the ADBMS6830B data sheet (Rev. 0):
* - Command codes: "Command Codes" table (11-bit CC[10:0])
* - ADCV / ADSV / ADAX: bit patterns from the ADC command tables
* - Voltage formula: code * 150 uV + 1.5 V (code is SIGNED 16-bit)
* - UV/OV threshold: VUV/VOV * 16 * 150 uV + 1.5 V
* - PEC15 / PEC10: polynomials + seeds from "Command PEC" / "Data PEC"
*
* Reference implementation of the project firmware (same structure as the
* original driver, rewritten and re-verified against the datasheet).
* ----------------------------------------------------------------------------
*/
#ifndef ADBMS6830_REGS_H
#define ADBMS6830_REGS_H
#include <stdint.h>
/* ---------------------------- Frame sizes -------------------------------- */
#define ADBMS_CMD_LEN 4 /* CMD0, CMD1, PEC0, PEC1 */
#define ADBMS_REG_LEN 6 /* every register group = 6 data bytes */
#define ADBMS_DPEC_LEN 2 /* data PEC (10 bit) + 6-bit cmd counter */
#define ADBMS_DEV_FRAME_LEN (ADBMS_REG_LEN + ADBMS_DPEC_LEN) /* = 8 */
#define ADBMS_CELLS_PER_DEV 16
#define ADBMS_GPIOS_PER_DEV 10
/* ------------------------ Configuration / control ------------------------ */
#define CMD_WRCFGA 0x001
#define CMD_RDCFGA 0x002
#define CMD_WRCFGB 0x024
#define CMD_RDCFGB 0x026
#define CMD_WRPWMA 0x020
#define CMD_WRPWMB 0x021
#define CMD_RDPWMA 0x022
#define CMD_RDPWMB 0x023
#define CMD_RDSID 0x02C /* serial ID */
#define CMD_SRST 0x027 /* soft reset */
#define CMD_RSTCC 0x02E /* reset command counter */
#define CMD_MUTE 0x028 /* pause all discharge (balancing) switches */
#define CMD_UNMUTE 0x029
#define CMD_SNAP 0x02D /* freeze result registers (coherent read) */
#define CMD_UNSNAP 0x02F
/* -------------------------- Clear commands ------------------------------- */
#define CMD_CLRCELL 0x711
#define CMD_CLOVUV 0x715
#define CMD_CLRFLAG 0x717
/* -------------------------- Poll commands -------------------------------- */
#define CMD_PLADC 0x718
#define CMD_PLAUX 0x71E
/* ------------------------ Read result registers -------------------------- */
/* C-ADC cell voltages (instantaneous, updated every 1 ms in continuous mode) */
#define CMD_RDCVA 0x004 /* C1 - C3 */
#define CMD_RDCVB 0x006 /* C4 - C6 */
#define CMD_RDCVC 0x008 /* C7 - C9 */
#define CMD_RDCVD 0x00A /* C10 - C12 */
#define CMD_RDCVE 0x009 /* C13 - C15 (note: NOT 0x00C!) */
#define CMD_RDCVF 0x00B /* C16 */
#define CMD_RDCVALL 0x00C /* all 16 cells, 32 data bytes + 1 PEC */
/* Averaged cell voltages (8-sample average) */
#define CMD_RDACA 0x044
#define CMD_RDACB 0x046
#define CMD_RDACC 0x048
#define CMD_RDACD 0x04A
#define CMD_RDACE 0x049
#define CMD_RDACF 0x04B
/* IIR-filtered cell voltages (filter corner set by FC[2:0] in CFGA) */
#define CMD_RDFCA 0x012
#define CMD_RDFCB 0x013
#define CMD_RDFCC 0x014
#define CMD_RDFCD 0x015
#define CMD_RDFCE 0x016
#define CMD_RDFCF 0x017
/* S-ADC (redundant) cell voltages */
#define CMD_RDSVA 0x003
#define CMD_RDSVB 0x005
#define CMD_RDSVC 0x007
#define CMD_RDSVD 0x00D
#define CMD_RDSVE 0x00E
#define CMD_RDSVF 0x00F
/* Auxiliary (GPIO) results */
#define CMD_RDAUXA 0x019 /* GPIO1 - GPIO3 */
#define CMD_RDAUXB 0x01A /* GPIO4 - GPIO6 */
#define CMD_RDAUXC 0x01B /* GPIO7 - GPIO9 */
#define CMD_RDAUXD 0x01F /* GPIO10, VMV, VPV */
/* Status */
#define CMD_RDSTATA 0x030 /* VREF2, ITMP (die temp) */
#define CMD_RDSTATB 0x031 /* VD, VA, VRES */
#define CMD_RDSTATC 0x032 /* fault flags, conv counter*/
#define CMD_RDSTATD 0x033 /* per-cell OV/UV flags */
#define CMD_RDSTATE 0x034
/* ---------------------- ADC start commands (with bits) ------------------- */
/* ADCV : 0 1 RD CONT 1 1 DCP 0 RSTF OW1 OW0 */
#define CMD_ADCV_BASE 0x260
#define ADCV_RD (1u << 8) /* also start the redundant S-ADC */
#define ADCV_CONT (1u << 7) /* continuous conversion */
#define ADCV_DCP (1u << 4) /* keep discharge ON during measurement */
#define ADCV_RSTF (1u << 2) /* reset the IIR filter */
#define ADCV_OW(x) ((x) & 0x3u) /* open-wire: 0 off,1 even,2 odd,3 all */
/* ADSV : 0 0 1 CONT 1 1 DCP 1 0 OW1 OW0 */
#define CMD_ADSV_BASE 0x168
#define ADSV_CONT (1u << 7)
#define ADSV_DCP (1u << 4)
/* ADAX : 1 0 OW PUP CH4 0 1 CH3 CH2 CH1 CH0 */
#define CMD_ADAX_BASE 0x410
#define ADAX_OW (1u << 8)
#define ADAX_PUP (1u << 7)
#define ADAX_CH(ch) ((((ch) & 0x10u) << 2) | ((ch) & 0x0Fu))
#define ADAX_CH_ALL 0 /* CH = 00000 -> convert all inputs */
/* ---------------------------- Conversions -------------------------------- */
#define ADBMS_LSB_V 0.000150f /* 150 uV / LSB */
#define ADBMS_OFFSET_V 1.5f /* +1.5 V offset */
#define ADBMS_CODE_TO_V(c) ((float)(int16_t)(c) * ADBMS_LSB_V + ADBMS_OFFSET_V)
#define ADBMS_V_TO_CODE(v) ((int16_t)((((v) - ADBMS_OFFSET_V) / ADBMS_LSB_V) + 0.5f))
/* UV/OV threshold registers are 12-bit and 16x coarser (2.4 mV / LSB) */
#define ADBMS_V_TO_THR(v) ((int16_t)((((v) - ADBMS_OFFSET_V) / (16.0f * ADBMS_LSB_V)) + 0.5f))
/* -------------------- CFGA bit positions (byte, mask) -------------------- */
#define CFGA0_REFON 0x80 /* keep reference on -> faster next conversion */
#define CFGA0_CTH_MASK 0x07 /* C-ADC vs S-ADC comparison threshold */
#define CFGA5_FC_MASK 0x07 /* IIR filter corner */
#define CFGA5_COMM_BK 0x08
#define CFGA5_MUTE_ST 0x10 /* read-only: discharge muted */
#define CFGA5_SNAP_ST 0x20 /* read-only: snapshot active */
/* GPO[8:1] in CFGA byte 3, GPO[10:9] in CFGA byte 4 bits 1:0.
* Write 1 = pull-down OFF -> pin usable as analog input (thermistors!) */
/* IIR filter settings for FC[2:0] (-3 dB corner) */
enum adbms_fc {
ADBMS_FC_OFF = 0, ADBMS_FC_110HZ, ADBMS_FC_45HZ, ADBMS_FC_21HZ,
ADBMS_FC_10HZ, ADBMS_FC_5HZ, ADBMS_FC_1HZ25, ADBMS_FC_0HZ625
};
/* -------------------- CFGB bit positions --------------------------------- */
/* B0 = VUV[7:0] | B1 = VOV[3:0]<<4 | VUV[11:8] | B2 = VOV[11:4]
* B3 = DTMEN(7) DTRNG(6) DCTO[5:0]
* B4 = DCC[8:1] B5 = DCC[16:9] */
#define CFGB3_DTMEN 0x80 /* discharge timer monitor enable */
#define CFGB3_DTRNG 0x40 /* 0: 1 min/LSB (0-63 min), 1: 16 min/LSB */
#define CFGB3_DCTO_MASK 0x3F /* discharge timeout. 0 = timed out / not set */
/* -------------------- PWM registers --------------------------------------
* 4 bits per cell. 0x0 = off, 0x1 = 6.6 %, ... 0xF = 100 % duty.
* PWMA bytes 0..5 hold PWM1..PWM12 (low nibble = odd cell, high = even cell)
* PWMB bytes 0..1 hold PWM13..PWM16 */
#endif /* ADBMS6830_REGS_H */adbms6830.h
/**
* adbms6830.h - Bare-metal ADBMS6830B daisy-chain driver (portable core)
* ----------------------------------------------------------------------------
* The driver knows nothing about the MCU. All hardware access goes through
* the three HAL callbacks in adbms_hal_t, so the same file runs on the
* MAX32690 (see platform_max32690.c) and on a PC test harness (test/).
*
* Chain ordering convention used everywhere in this driver:
* dev index 0 = bottom board, closest to the MCU (isoSPI port A
* connected to the ADBMS6822 master)
* dev index num_dev-1 = top board, farthest from the MCU
* ----------------------------------------------------------------------------
*/
#ifndef ADBMS6830_H
#define ADBMS6830_H
#include <stdint.h>
#include <stdbool.h>
#include "adbms6830_regs.h"
#define ADBMS_MAX_DEV 8
/* Error codes. ADBMS_E_PEC is -EBADMSG. With the ARM newlib C library
* (arm-none-eabi-gcc, MaximSDK, no-OS) EBADMSG == 77, i.e. the "-77" error
* reported whenever a data PEC check fails. */
#define ADBMS_OK 0
#define ADBMS_E_PEC (-77)
#define ADBMS_E_PARAM (-22) /* -EINVAL */
#define ADBMS_E_IO (-5) /* -EIO */
/* --------------------------------------------------------------------------
* HAL: implemented per platform
* ------------------------------------------------------------------------ */
typedef struct {
/* Full-duplex SPI transfer of len bytes. CS is NOT touched here. */
int (*spi_xfer)(const uint8_t *tx, uint8_t *rx, uint16_t len);
/* Drive chip select: 0 = low (active), 1 = high (idle). */
void (*cs_set)(int level);
/* Busy-wait delay in microseconds. */
void (*delay_us)(uint32_t us);
} adbms_hal_t;
/* Shadow copy of the writable registers of one device. The driver always
* writes the WHOLE chain from these shadows (that is how a daisy-chain
* write works: one frame carries data for every device). */
typedef struct {
uint8_t cfga[ADBMS_REG_LEN];
uint8_t cfgb[ADBMS_REG_LEN];
uint8_t pwma[ADBMS_REG_LEN];
uint8_t pwmb[ADBMS_REG_LEN];
} adbms_regs_t;
typedef struct {
const adbms_hal_t *hal;
uint8_t num_dev; /* devices in the chain */
adbms_regs_t regs[ADBMS_MAX_DEV]; /* shadow registers */
uint8_t last_ccnt[ADBMS_MAX_DEV]; /* command counter seen */
uint32_t pec_errors; /* running error count */
} adbms_chain_t;
/* ---- PEC (CRC) helpers -------------------------------------------------- */
uint16_t adbms_pec15(const uint8_t *data, uint8_t len);
uint16_t adbms_pec10(const uint8_t *data, uint8_t len, bool is_read, uint8_t ccnt);
/* ---- link layer --------------------------------------------------------- */
int adbms_init(adbms_chain_t *ch, const adbms_hal_t *hal, uint8_t num_dev);
void adbms_wakeup(adbms_chain_t *ch); /* full wake from SLEEP */
void adbms_wakeup_idle(adbms_chain_t *ch); /* isoSPI IDLE -> READY */
int adbms_cmd(adbms_chain_t *ch, uint16_t cmd);
int adbms_write(adbms_chain_t *ch, uint16_t cmd,
const uint8_t data[][ADBMS_REG_LEN]);
int adbms_read(adbms_chain_t *ch, uint16_t cmd,
uint8_t data[][ADBMS_REG_LEN]);
/* ---- configuration ------------------------------------------------------ */
int adbms_config_defaults(adbms_chain_t *ch, enum adbms_fc fc,
float uv_volt, float ov_volt);
int adbms_write_config(adbms_chain_t *ch);
/* ---- measurements ------------------------------------------------------- */
int adbms_start_cell_adc(adbms_chain_t *ch, bool continuous, bool redundant);
int adbms_read_cells(adbms_chain_t *ch, uint8_t n_cells,
float volts[][ADBMS_CELLS_PER_DEV]);
int adbms_start_aux_adc(adbms_chain_t *ch);
int adbms_read_gpios(adbms_chain_t *ch, float volts[][ADBMS_GPIOS_PER_DEV]);
int adbms_read_vref2(adbms_chain_t *ch, float vref2[], float die_temp_c[]);
/* ---- balancing ---------------------------------------------------------- */
void adbms_set_dcc(adbms_chain_t *ch, uint8_t dev, uint16_t dcc_mask);
void adbms_set_pwm(adbms_chain_t *ch, uint8_t dev, uint8_t cell, uint8_t duty4);
void adbms_set_discharge_timeout(adbms_chain_t *ch, uint8_t minutes);
int adbms_mute(adbms_chain_t *ch, bool mute);
#endif /* ADBMS6830_H */adbms6830.c
/**
* adbms6830.c - Bare-metal ADBMS6830B daisy-chain driver (portable core)
* ----------------------------------------------------------------------------
* See adbms6830.h for the API and chain-ordering convention.
*
* Frame formats (ADBMS6830B data sheet, "Bus Protocols"):
*
* Action command (ADCV, SNAP, MUTE ...):
* CSB low | CMD0 CMD1 PEC0 PEC1 | CSB high
*
* Write command, N devices:
* CSB low | CMD0 CMD1 PEC0 PEC1 |
* D(N-1)[0..5] DPEC(N-1)[0..1] <- top device's data FIRST
* ...
* D(0)[0..5] DPEC(0)[0..1] <- bottom device's data LAST
* CSB high
*
* Read command, N devices:
* MCU sends CMD0 CMD1 PEC0 PEC1 then clocks N*8 dummy bytes (0xFF).
* RX buffer: [0..3] = echo of the command (ignored)
* [4 .. 11] = bottom device (dev 0): 6 data + 2 PEC
* [12 .. 19] = dev 1
* ... (bottom device shifts out FIRST)
*
* This is why, with 2 boards, board 1's data starts at index 4 and
* board 2's at index 12.
* ----------------------------------------------------------------------------
*/
#include <string.h>
#include "adbms6830.h"
/* Timing (data sheet electrical characteristics) */
#define T_WAKE_US 500u /* tWAKE : 200-500 us, SLEEP -> STANDBY */
#define T_READY_US 10u /* tREADY : 10 us max, isoSPI IDLE -> READY */
#define T_CADC_US 1100u /* C-ADC result every 1 ms (+ margin) */
#define T_SADC_US 8500u /* S-ADC result every 8 ms (+ margin) */
#define T_AUX_ALL_US 20000u /* conservative wait for ADAX on all channels.
Production code should poll with PLAUX. */
/* ------------------------------------------------------------------------ */
/* PEC15 : command PEC. x^15+x^14+x^10+x^8+x^7+x^4+x^3+1, seed 0x0010. */
/* Result is shifted left by 1 (LSB is always 0) and sent MSB first. */
/* ------------------------------------------------------------------------ */
uint16_t adbms_pec15(const uint8_t *data, uint8_t len)
{
uint16_t rem = 0x0010; /* seed 000000000010000 */
for (uint8_t i = 0; i < len; i++) {
for (int8_t b = 7; b >= 0; b--) {
uint16_t in = ((data[i] >> b) & 1u) ^ ((rem >> 14) & 1u);
rem = (uint16_t)((rem << 1) & 0x7FFF);
if (in) rem ^= 0x4599; /* polynomial taps */
}
}
return (uint16_t)(rem << 1);
}
/* ------------------------------------------------------------------------ */
/* PEC10 : data PEC. x^10+x^7+x^3+x^2+x+1, seed 0x010. */
/* On READ data the 6-bit command counter (CCNT) is also covered. */
/* ------------------------------------------------------------------------ */
uint16_t adbms_pec10(const uint8_t *data, uint8_t len, bool is_read, uint8_t ccnt)
{
uint16_t rem = 0x010;
for (uint8_t i = 0; i < len; i++) {
rem ^= (uint16_t)data[i] << 2;
for (uint8_t b = 0; b < 8; b++)
rem = (rem & 0x200) ? (uint16_t)((rem << 1) ^ 0x08F) : (uint16_t)(rem << 1);
}
if (is_read) { /* 6 more bits: CCNT[5:0] */
rem ^= (uint16_t)(ccnt & 0x3F) << 4;
for (uint8_t b = 0; b < 6; b++)
rem = (rem & 0x200) ? (uint16_t)((rem << 1) ^ 0x08F) : (uint16_t)(rem << 1);
}
return rem & 0x3FF;
}
/* ------------------------------------------------------------------------ */
static void make_cmd(uint16_t cmd, uint8_t out[ADBMS_CMD_LEN])
{
out[0] = (uint8_t)(cmd >> 8);
out[1] = (uint8_t)(cmd & 0xFF);
uint16_t pec = adbms_pec15(out, 2);
out[2] = (uint8_t)(pec >> 8);
out[3] = (uint8_t)(pec & 0xFF);
}
static int frame(adbms_chain_t *ch, const uint8_t *tx, uint8_t *rx, uint16_t len)
{
ch->hal->cs_set(0);
int ret = ch->hal->spi_xfer(tx, rx, len); /* one unbroken CSB-low window */
ch->hal->cs_set(1);
return ret ? ADBMS_E_IO : ADBMS_OK;
}
/* ------------------------------------------------------------------------ */
int adbms_init(adbms_chain_t *ch, const adbms_hal_t *hal, uint8_t num_dev)
{
/* This check exists because of the "dead LED" bug: NUM_DEV was changed
* to 2 but only one device was described, so init got an invalid entry
* and the chain pointer stayed NULL. Fail loudly instead of hard-faulting. */
if (!ch || !hal || !hal->spi_xfer || !hal->cs_set || !hal->delay_us)
return ADBMS_E_PARAM;
if (num_dev == 0 || num_dev > ADBMS_MAX_DEV)
return ADBMS_E_PARAM;
memset(ch, 0, sizeof(*ch));
ch->hal = hal;
ch->num_dev = num_dev;
hal->cs_set(1);
return ADBMS_OK;
}
/* Wake every device from SLEEP. Each CSB edge becomes an isoSPI "long pulse";
* device k wakes, then forwards the pulse to device k+1, so we repeat once
* per device and give each one tWAKE. */
void adbms_wakeup(adbms_chain_t *ch)
{
for (uint8_t i = 0; i < ch->num_dev; i++) {
ch->hal->cs_set(0);
ch->hal->delay_us(T_WAKE_US);
ch->hal->cs_set(1);
ch->hal->delay_us(T_WAKE_US);
}
}
/* Core is awake but the isoSPI port went IDLE (no traffic for tIDLE ~5.5 ms). */
void adbms_wakeup_idle(adbms_chain_t *ch)
{
for (uint8_t i = 0; i < ch->num_dev; i++) {
ch->hal->cs_set(0);
ch->hal->delay_us(T_READY_US);
ch->hal->cs_set(1);
ch->hal->delay_us(T_READY_US);
}
}
int adbms_cmd(adbms_chain_t *ch, uint16_t cmd)
{
uint8_t tx[ADBMS_CMD_LEN], rx[ADBMS_CMD_LEN];
make_cmd(cmd, tx);
return frame(ch, tx, rx, ADBMS_CMD_LEN);
}
/* data[i] = 6 bytes destined for device i (i = 0 is the bottom device). */
int adbms_write(adbms_chain_t *ch, uint16_t cmd, const uint8_t data[][ADBMS_REG_LEN])
{
uint8_t tx[ADBMS_CMD_LEN + ADBMS_MAX_DEV * ADBMS_DEV_FRAME_LEN];
uint8_t rx[sizeof(tx)];
uint16_t len = ADBMS_CMD_LEN + ch->num_dev * ADBMS_DEV_FRAME_LEN;
make_cmd(cmd, tx);
uint8_t *p = &tx[ADBMS_CMD_LEN];
/* Top device first: its data has to travel through every device below. */
for (int8_t dev = (int8_t)ch->num_dev - 1; dev >= 0; dev--) {
memcpy(p, data[dev], ADBMS_REG_LEN);
uint16_t pec = adbms_pec10(p, ADBMS_REG_LEN, false, 0);
p[6] = (uint8_t)((pec >> 8) & 0x03); /* PEC[9:8] in low bits */
p[7] = (uint8_t)(pec & 0xFF); /* PEC[7:0] */
p += ADBMS_DEV_FRAME_LEN;
}
return frame(ch, tx, rx, len);
}
/* data[i] receives the 6 bytes from device i (i = 0 is the bottom device). */
int adbms_read(adbms_chain_t *ch, uint16_t cmd, uint8_t data[][ADBMS_REG_LEN])
{
uint8_t tx[ADBMS_CMD_LEN + ADBMS_MAX_DEV * ADBMS_DEV_FRAME_LEN];
uint8_t rx[sizeof(tx)];
uint16_t len = ADBMS_CMD_LEN + ch->num_dev * ADBMS_DEV_FRAME_LEN;
make_cmd(cmd, tx);
memset(&tx[ADBMS_CMD_LEN], 0xFF, len - ADBMS_CMD_LEN); /* dummy clocks */
int ret = frame(ch, tx, rx, len);
if (ret) return ret;
int status = ADBMS_OK;
for (uint8_t dev = 0; dev < ch->num_dev; dev++) {
const uint8_t *d = &rx[ADBMS_CMD_LEN + dev * ADBMS_DEV_FRAME_LEN]; /* 4, 12, 20 ... */
uint8_t ccnt = d[6] >> 2; /* CCNT[5:0] */
uint16_t rx_pec = (uint16_t)(((d[6] & 0x03) << 8) | d[7]);
uint16_t calc = adbms_pec10(d, ADBMS_REG_LEN, true, ccnt);
memcpy(data[dev], d, ADBMS_REG_LEN);
ch->last_ccnt[dev] = ccnt;
if (rx_pec != calc) { /* corrupted, or nobody answered */
ch->pec_errors++;
status = ADBMS_E_PEC; /* keep parsing, report at the end */
}
}
return status;
}
/* ------------------------------------------------------------------------ */
/* Configuration */
/* ------------------------------------------------------------------------ */
int adbms_write_config(adbms_chain_t *ch)
{
uint8_t buf[ADBMS_MAX_DEV][ADBMS_REG_LEN];
int ret;
for (uint8_t i = 0; i < ch->num_dev; i++) memcpy(buf[i], ch->regs[i].cfga, 6);
if ((ret = adbms_write(ch, CMD_WRCFGA, (const uint8_t (*)[6])buf))) return ret;
for (uint8_t i = 0; i < ch->num_dev; i++) memcpy(buf[i], ch->regs[i].cfgb, 6);
if ((ret = adbms_write(ch, CMD_WRCFGB, (const uint8_t (*)[6])buf))) return ret;
for (uint8_t i = 0; i < ch->num_dev; i++) memcpy(buf[i], ch->regs[i].pwma, 6);
if ((ret = adbms_write(ch, CMD_WRPWMA, (const uint8_t (*)[6])buf))) return ret;
for (uint8_t i = 0; i < ch->num_dev; i++) memcpy(buf[i], ch->regs[i].pwmb, 6);
return adbms_write(ch, CMD_WRPWMB, (const uint8_t (*)[6])buf);
}
/* Read-modify-write: start from what the chip reports after reset, then set
* only the fields we care about. Avoids guessing reset values. */
int adbms_config_defaults(adbms_chain_t *ch, enum adbms_fc fc,
float uv_volt, float ov_volt)
{
uint8_t a[ADBMS_MAX_DEV][ADBMS_REG_LEN], b[ADBMS_MAX_DEV][ADBMS_REG_LEN];
int ret;
if ((ret = adbms_read(ch, CMD_RDCFGA, a))) return ret;
if ((ret = adbms_read(ch, CMD_RDCFGB, b))) return ret;
uint16_t vuv = (uint16_t)ADBMS_V_TO_THR(uv_volt) & 0x0FFF;
uint16_t vov = (uint16_t)ADBMS_V_TO_THR(ov_volt) & 0x0FFF;
for (uint8_t i = 0; i < ch->num_dev; i++) {
adbms_regs_t *r = &ch->regs[i];
memcpy(r->cfga, a[i], 6);
memcpy(r->cfgb, b[i], 6);
r->cfga[0] |= CFGA0_REFON; /* keep VREF up */
r->cfga[3] = 0xFF; /* GPO8..1 = 1 */
r->cfga[4] = (uint8_t)((r->cfga[4] & ~0x03) | 0x03); /* GPO10..9 = 1 */
r->cfga[5] = (uint8_t)((r->cfga[5] & ~CFGA5_FC_MASK) | (fc & 0x07));
r->cfgb[0] = (uint8_t)(vuv & 0xFF);
r->cfgb[1] = (uint8_t)(((vov & 0x0F) << 4) | ((vuv >> 8) & 0x0F));
r->cfgb[2] = (uint8_t)(vov >> 4);
r->cfgb[3] = 0; /* no discharge timer */
r->cfgb[4] = 0; /* DCC[8:1] off */
r->cfgb[5] = 0; /* DCC[16:9] off */
memset(r->pwma, 0, 6);
memset(r->pwmb, 0, 6);
}
return adbms_write_config(ch);
}
/* ------------------------------------------------------------------------ */
/* Measurements */
/* ------------------------------------------------------------------------ */
int adbms_start_cell_adc(adbms_chain_t *ch, bool continuous, bool redundant)
{
uint16_t cmd = CMD_ADCV_BASE;
if (continuous) cmd |= ADCV_CONT;
if (redundant) cmd |= ADCV_RD;
int ret = adbms_cmd(ch, cmd);
/* In continuous mode results refresh every 1 ms forever; we still wait
* for the first result. In single-shot mode this is the conversion time. */
ch->hal->delay_us(redundant ? T_SADC_US : T_CADC_US);
return ret;
}
static const uint16_t cv_cmds[6] = {
CMD_RDCVA, CMD_RDCVB, CMD_RDCVC, CMD_RDCVD, CMD_RDCVE, CMD_RDCVF
};
/* Reads only the register groups needed for n_cells (5 cells -> A,B ;
* 7 cells -> A,B,C). SNAP freezes all result registers so that every group
* comes from the same 1 ms conversion; UNSNAP lets them update again. */
int adbms_read_cells(adbms_chain_t *ch, uint8_t n_cells,
float volts[][ADBMS_CELLS_PER_DEV])
{
uint8_t buf[ADBMS_MAX_DEV][ADBMS_REG_LEN];
uint8_t groups = (uint8_t)((n_cells + 2) / 3);
int status = ADBMS_OK, ret;
if (n_cells == 0 || n_cells > ADBMS_CELLS_PER_DEV) return ADBMS_E_PARAM;
adbms_cmd(ch, CMD_SNAP);
for (uint8_t g = 0; g < groups; g++) {
ret = adbms_read(ch, cv_cmds[g], buf);
if (ret) status = ret;
for (uint8_t dev = 0; dev < ch->num_dev; dev++) {
for (uint8_t k = 0; k < 3; k++) {
uint8_t cell = (uint8_t)(g * 3 + k);
if (cell >= ADBMS_CELLS_PER_DEV) break; /* CVF holds only C16 */
uint16_t code = (uint16_t)(buf[dev][2*k] | (buf[dev][2*k + 1] << 8));
volts[dev][cell] = ADBMS_CODE_TO_V(code); /* little-endian, signed */
}
}
}
adbms_cmd(ch, CMD_UNSNAP);
return status;
}
int adbms_start_aux_adc(adbms_chain_t *ch)
{
int ret = adbms_cmd(ch, CMD_ADAX_BASE | ADAX_CH(ADAX_CH_ALL));
ch->hal->delay_us(T_AUX_ALL_US);
return ret;
}
int adbms_read_gpios(adbms_chain_t *ch, float volts[][ADBMS_GPIOS_PER_DEV])
{
static const uint16_t aux_cmds[4] = { CMD_RDAUXA, CMD_RDAUXB, CMD_RDAUXC, CMD_RDAUXD };
uint8_t buf[ADBMS_MAX_DEV][ADBMS_REG_LEN];
int status = ADBMS_OK, ret;
adbms_cmd(ch, CMD_SNAP);
for (uint8_t g = 0; g < 4; g++) {
ret = adbms_read(ch, aux_cmds[g], buf);
if (ret) status = ret;
for (uint8_t dev = 0; dev < ch->num_dev; dev++) {
for (uint8_t k = 0; k < 3; k++) {
uint8_t gpio = (uint8_t)(g * 3 + k); /* AUXD = G10, VMV, VPV */
if (gpio >= ADBMS_GPIOS_PER_DEV) break;
uint16_t code = (uint16_t)(buf[dev][2*k] | (buf[dev][2*k + 1] << 8));
volts[dev][gpio] = ADBMS_CODE_TO_V(code);
}
}
}
adbms_cmd(ch, CMD_UNSNAP);
return status;
}
/* Status A: VREF2 (thermistor bias, ~3 V) and ITMP (die temperature). */
int adbms_read_vref2(adbms_chain_t *ch, float vref2[], float die_temp_c[])
{
uint8_t buf[ADBMS_MAX_DEV][ADBMS_REG_LEN];
int ret = adbms_read(ch, CMD_RDSTATA, buf);
for (uint8_t dev = 0; dev < ch->num_dev; dev++) {
uint16_t vr = (uint16_t)(buf[dev][0] | (buf[dev][1] << 8));
uint16_t it = (uint16_t)(buf[dev][2] | (buf[dev][3] << 8));
if (vref2) vref2[dev] = ADBMS_CODE_TO_V(vr);
if (die_temp_c) die_temp_c[dev] = ADBMS_CODE_TO_V(it) / 0.0075f - 273.0f;
}
return ret;
}
/* ------------------------------------------------------------------------ */
/* Balancing (passive) */
/* ------------------------------------------------------------------------ */
/* bit 0 = cell 1 ... bit 15 = cell 16. DCC = static 100 % discharge and it
* overrides PWM for that cell. Call adbms_write_config() to apply. */
void adbms_set_dcc(adbms_chain_t *ch, uint8_t dev, uint16_t dcc_mask)
{
if (dev >= ch->num_dev) return;
ch->regs[dev].cfgb[4] = (uint8_t)(dcc_mask & 0xFF);
ch->regs[dev].cfgb[5] = (uint8_t)(dcc_mask >> 8);
}
/* cell = 1..16, duty4 = 0..15 (0 = off, 15 = 100 %). Period ~937 ms. */
void adbms_set_pwm(adbms_chain_t *ch, uint8_t dev, uint8_t cell, uint8_t duty4)
{
if (dev >= ch->num_dev || cell < 1 || cell > 16) return;
duty4 &= 0x0F;
uint8_t idx = (uint8_t)(cell - 1);
uint8_t *reg = (idx < 12) ? ch->regs[dev].pwma : ch->regs[dev].pwmb;
uint8_t byte = (uint8_t)((idx % 12) / 2);
if (idx % 2 == 0) reg[byte] = (uint8_t)((reg[byte] & 0xF0) | duty4); /* odd cell */
else reg[byte] = (uint8_t)((reg[byte] & 0x0F) | (duty4 << 4)); /* even cell */
}
/* Discharge timeout = hardware watchdog for balancing: if the MCU stops
* refreshing the config, the chip turns its own switches off. */
void adbms_set_discharge_timeout(adbms_chain_t *ch, uint8_t minutes)
{
if (minutes > 63) minutes = 63;
for (uint8_t i = 0; i < ch->num_dev; i++)
ch->regs[i].cfgb[3] = (uint8_t)((ch->regs[i].cfgb[3] & ~(CFGB3_DTRNG | CFGB3_DCTO_MASK))
| minutes); /* DTRNG = 0 -> 1 min/LSB */
}
/* MUTE turns every discharge switch off within ~65 us without forgetting the
* DCC/PWM settings; UNMUTE restores them. Used to take clean measurements. */
int adbms_mute(adbms_chain_t *ch, bool mute)
{
return adbms_cmd(ch, mute ? CMD_MUTE : CMD_UNMUTE);
}A.2 Configuration and application
parameters.h
/**
* parameters.h - what the physical chain looks like
*
* Bench setup from the project notes:
* MAX32690 --SPI--> ADBMS6822 --isoSPI--> Board 1 (5 cells) --> Board 2 (7 cells)
*
* NUM_DEV and the dev_list / cells_per_dev arrays MUST agree. Changing
* NUM_DEV to 2 while the list still had one entry is exactly what caused
* the "dead LED" hard fault (the second entry was zero-filled = invalid
* device ID -> init aborted -> NULL device pointer -> crash on first use).
*/
#ifndef PARAMETERS_H
#define PARAMETERS_H
#include <stdint.h>
#define NUM_DEV 2
typedef enum { DEV_NONE = 0, DEV_ADBMS6830 = 1 } dev_type_t;
extern const dev_type_t dev_list[NUM_DEV]; /* { DEV_ADBMS6830, DEV_ADBMS6830 } */
extern const uint8_t cells_per_dev[NUM_DEV]; /* { 5, 7 } */
extern const uint8_t ntc_per_dev[NUM_DEV]; /* thermistors on GPIO1..n */
/* Compile-time guard: catches "changed NUM_DEV but not the arrays" early. */
#define MAX_CELLS_ANY_DEV 7
/* Li-ion (NMC) limits used by this example - adjust to the cell datasheet */
#define CELL_UV_V 2.80f
#define CELL_OV_V 4.20f
#define CELL_TEMP_MAX_C 60.0f
#define CELL_TEMP_MIN_C 0.0f /* no charging below 0 C */
/* Balancing policy */
#define BAL_START_DELTA_V 0.010f /* start if cell > min + 10 mV */
#define BAL_STOP_DELTA_V 0.003f /* stop if cell < min + 3 mV */
#define BAL_MIN_CELL_V 3.60f /* never bleed a cell below this */
#define BAL_MAX_DIE_TEMP_C 85.0f /* back off if the IC gets hot */
#define BAL_TIMEOUT_MIN 2 /* hardware DCTO watchdog */
#define MEAS_PERIOD_MS 1000
#endifparameters.c
#include "parameters.h"
/* Bottom board first (closest to the MCU), then upwards. */
const dev_type_t dev_list[NUM_DEV] = { DEV_ADBMS6830, DEV_ADBMS6830 };
const uint8_t cells_per_dev[NUM_DEV] = { 5, 7 };
const uint8_t ntc_per_dev[NUM_DEV] = { 2, 2 };
/* If NUM_DEV grows and someone forgets to extend the lists, the missing
* entries become 0 (DEV_NONE / 0 cells). bms_app_init() checks for that and
* stops with an error message instead of hard-faulting. */thermistor.h
/**
* thermistor.h - NTC thermistor on an ADBMS6830 GPIO, biased from VREF2
*
* VREF2 (~3.0 V)
* |
* [R_BIAS] 10k
* |------------> GPIOx (measured by the AUX ADC)
* [NTC] 10k @ 25 C
* |
* V-
*
* V_gpio = VREF2 * R_ntc / (R_bias + R_ntc)
* => R_ntc = R_bias * V_gpio / (VREF2 - V_gpio)
* => T = 1 / ( 1/T0 + ln(R_ntc/R0)/B ) (Beta equation, Kelvin)
*
* Measuring VREF2 itself (Status A) and using the RATIO makes the result
* independent of the exact reference value (ratiometric measurement).
*/
#ifndef THERMISTOR_H
#define THERMISTOR_H
#define NTC_R_BIAS_OHM 10000.0f
#define NTC_R0_OHM 10000.0f /* resistance at 25 C */
#define NTC_T0_K 298.15f /* 25 C in Kelvin */
#define NTC_BETA 3435.0f /* B25/85 - take from YOUR NTC's datasheet */
/* Returns temperature in deg C, or -273 for open/short sensor. */
float ntc_volt_to_celsius(float v_gpio, float vref2);
#endifthermistor.c
#include <math.h>
#include "thermistor.h"
float ntc_volt_to_celsius(float v_gpio, float vref2)
{
/* Open NTC -> V_gpio ~ VREF2 ; shorted NTC -> V_gpio ~ 0 V.
* Both are sensor faults, not temperatures. */
if (v_gpio <= 0.02f * vref2 || v_gpio >= 0.98f * vref2)
return -273.0f;
float r_ntc = NTC_R_BIAS_OHM * v_gpio / (vref2 - v_gpio);
float inv_t = (1.0f / NTC_T0_K) + logf(r_ntc / NTC_R0_OHM) / NTC_BETA;
return (1.0f / inv_t) - 273.15f;
}bms_app.h
#ifndef BMS_APP_H
#define BMS_APP_H
#include <stdint.h>
#include <stdbool.h>
#include "adbms6830.h"
#include "parameters.h"
typedef struct {
float cell_v[NUM_DEV][ADBMS_CELLS_PER_DEV];
float gpio_v[NUM_DEV][ADBMS_GPIOS_PER_DEV];
float temp_c[NUM_DEV][ADBMS_GPIOS_PER_DEV];
float vref2[NUM_DEV];
float die_c[NUM_DEV];
float stack_v[NUM_DEV]; /* b1_sum, b2_sum */
uint16_t bal_mask[NUM_DEV]; /* which cells are bleeding */
uint32_t faults; /* FAULT_* bits */
} bms_data_t;
#define FAULT_OV (1u << 0)
#define FAULT_UV (1u << 1)
#define FAULT_OT (1u << 2)
#define FAULT_UT (1u << 3)
#define FAULT_COMM (1u << 4)
#define FAULT_SENSOR (1u << 5)
int bms_app_init(adbms_chain_t *ch, const adbms_hal_t *hal);
int bms_app_measure(adbms_chain_t *ch, bms_data_t *d);
void bms_app_protect(bms_data_t *d);
void bms_balance_compute(const float cell_v[][ADBMS_CELLS_PER_DEV],
uint16_t bal_mask[NUM_DEV], bool allowed);
int bms_app_apply_balance(adbms_chain_t *ch, const bms_data_t *d);
void bms_app_print(const bms_data_t *d);
#endifbms_app.c
/**
* bms_app.c - application layer on top of the ADBMS6830 driver
*
* init -> [ measure -> protect -> balance -> print ] every MEAS_PERIOD_MS
*/
#include <stdio.h>
#include <string.h>
#include "bms_app.h"
#include "thermistor.h"
int bms_app_init(adbms_chain_t *ch, const adbms_hal_t *hal)
{
/* 1. Sanity-check the board description (the "dead LED" lesson). */
for (int i = 0; i < NUM_DEV; i++) {
if (dev_list[i] != DEV_ADBMS6830 || cells_per_dev[i] == 0 ||
cells_per_dev[i] > ADBMS_CELLS_PER_DEV) {
printf("ERR: dev_list[%d] invalid - does NUM_DEV match the lists?\n", i);
return ADBMS_E_PARAM;
}
}
/* 2. Driver + wake the whole chain from SLEEP. */
int ret = adbms_init(ch, hal, NUM_DEV);
if (ret) return ret;
adbms_wakeup(ch);
/* 3. Config: reference on, IIR 10 Hz, GPIOs as analog inputs, UV/OV. */
ret = adbms_config_defaults(ch, ADBMS_FC_10HZ, CELL_UV_V, CELL_OV_V);
if (ret) { printf("ERR: config failed (%d)\n", ret); return ret; }
/* 4. Start the C-ADCs in continuous mode with the redundant S-ADCs. */
adbms_wakeup_idle(ch);
return adbms_start_cell_adc(ch, true, true);
}
int bms_app_measure(adbms_chain_t *ch, bms_data_t *d)
{
float cells[ADBMS_MAX_DEV][ADBMS_CELLS_PER_DEV];
float gpios[ADBMS_MAX_DEV][ADBMS_GPIOS_PER_DEV];
int ret, status = ADBMS_OK;
adbms_wakeup_idle(ch);
/* Balancing current flows through the cell-input filter resistors and
* makes the reading wrong (IR drop). Mute the switches, let a fresh
* 1 ms conversion happen, read, then un-mute. */
adbms_mute(ch, true);
ch->hal->delay_us(2000);
ret = adbms_read_cells(ch, MAX_CELLS_ANY_DEV, cells);
adbms_mute(ch, false);
if (ret) status = ret;
/* Temperatures: start AUX ADC, read GPIOs + VREF2 for a ratiometric result */
adbms_start_aux_adc(ch);
if ((ret = adbms_read_gpios(ch, gpios))) status = ret;
if ((ret = adbms_read_vref2(ch, d->vref2, d->die_c))) status = ret;
for (int dev = 0; dev < NUM_DEV; dev++) {
d->stack_v[dev] = 0.0f;
for (int c = 0; c < ADBMS_CELLS_PER_DEV; c++) {
/* Only the wired cells are meaningful. Unused inputs are tied to
* the top cell, so they read ~0 V and would trip UV if used. */
d->cell_v[dev][c] = (c < cells_per_dev[dev]) ? cells[dev][c] : 0.0f;
d->stack_v[dev] += d->cell_v[dev][c];
}
for (int g = 0; g < ADBMS_GPIOS_PER_DEV; g++) {
d->gpio_v[dev][g] = gpios[dev][g];
d->temp_c[dev][g] = (g < ntc_per_dev[dev])
? ntc_volt_to_celsius(gpios[dev][g], d->vref2[dev])
: 0.0f;
}
}
if (status == ADBMS_E_PEC) d->faults |= FAULT_COMM;
return status;
}
void bms_app_protect(bms_data_t *d)
{
d->faults &= FAULT_COMM; /* recompute everything except comms */
for (int dev = 0; dev < NUM_DEV; dev++) {
for (int c = 0; c < cells_per_dev[dev]; c++) {
if (d->cell_v[dev][c] > CELL_OV_V) d->faults |= FAULT_OV;
if (d->cell_v[dev][c] < CELL_UV_V) d->faults |= FAULT_UV;
}
for (int g = 0; g < ntc_per_dev[dev]; g++) {
float t = d->temp_c[dev][g];
if (t <= -273.0f) d->faults |= FAULT_SENSOR;
else if (t > CELL_TEMP_MAX_C) d->faults |= FAULT_OT;
else if (t < CELL_TEMP_MIN_C) d->faults |= FAULT_UT;
}
}
/* In the car this is where the BMS tells the VCU / opens the contactor. */
}
/* Passive balancing with hysteresis, "bleed down to the lowest cell".
* bal_mask is in/out so that hysteresis remembers which cells were ON. */
void bms_balance_compute(const float cell_v[][ADBMS_CELLS_PER_DEV],
uint16_t bal_mask[NUM_DEV], bool allowed)
{
float vmin = 10.0f;
for (int dev = 0; dev < NUM_DEV; dev++)
for (int c = 0; c < cells_per_dev[dev]; c++)
if (cell_v[dev][c] < vmin) vmin = cell_v[dev][c];
for (int dev = 0; dev < NUM_DEV; dev++) {
uint16_t m = allowed ? bal_mask[dev] : 0;
for (int c = 0; allowed && c < cells_per_dev[dev]; c++) {
float v = cell_v[dev][c];
bool on = (m >> c) & 1u;
if (!on && v > vmin + BAL_START_DELTA_V && v > BAL_MIN_CELL_V)
m |= (uint16_t)(1u << c); /* start bleeding */
else if (on && (v < vmin + BAL_STOP_DELTA_V || v < BAL_MIN_CELL_V))
m &= (uint16_t)~(1u << c); /* close enough */
}
bal_mask[dev] = m;
}
}
int bms_app_apply_balance(adbms_chain_t *ch, const bms_data_t *d)
{
for (int dev = 0; dev < NUM_DEV; dev++) {
uint16_t m = d->bal_mask[dev];
if (d->die_c[dev] > BAL_MAX_DIE_TEMP_C) m = 0; /* thermal back-off */
adbms_set_dcc(ch, (uint8_t)dev, m);
}
/* Re-arm the hardware watchdog on every write: if this loop dies, the
* ADBMS6830 switches the bleed resistors off by itself. */
adbms_set_discharge_timeout(ch, BAL_TIMEOUT_MIN);
adbms_wakeup_idle(ch);
return adbms_write_config(ch);
}
void bms_app_print(const bms_data_t *d)
{
for (int dev = 0; dev < NUM_DEV; dev++) {
printf("Board %d (%d cells)\n", dev + 1, cells_per_dev[dev]);
for (int c = 0; c < cells_per_dev[dev]; c++)
printf(" C%-2d %6.4f V %s\n", c + 1, (double)d->cell_v[dev][c],
((d->bal_mask[dev] >> c) & 1u) ? "[BAL]" : "");
for (int g = 0; g < ntc_per_dev[dev]; g++)
printf(" T%-2d %6.1f C\n", g + 1, (double)d->temp_c[dev][g]);
printf(" Stack = %.3f V | VREF2 = %.4f V | die = %.1f C\n",
(double)d->stack_v[dev], (double)d->vref2[dev], (double)d->die_c[dev]);
}
printf("Faults: 0x%02lX\n\n", (unsigned long)d->faults);
}A.3 Platform, entry point, build
platform_max32690.c
/**
* platform_max32690.c - HAL for the AD-APARD32690-SL (MAX32690) using MaximSDK
* ----------------------------------------------------------------------------
* Wiring: the EVAL-ADBMS6822 sits on the Arduino header. Arduino D13/D12/D11
* (SCK/MISO/MOSI) are SPI1 on the APARD32690, and D10 is used as a
* software-driven chip select (P1.23 here - confirm against the APARD32690
* schematic for your board revision).
*
* SPI settings for ADBMS68xx: mode 3 (CPOL = 1, CPHA = 1), MSB first,
* 8-bit words, <= 2 MHz because isoSPI tops out at 2 Mbps. 1 MHz is safe.
*
* NOTE: the MXC_SPI_Init() argument list changed between MSDK releases.
* This matches the MAX32690 "SPI v1" API that takes an mxc_spi_pins_t.
* If your MSDK complains, check spi.h in MaximSDK/Libraries/PeriphDrivers.
* ----------------------------------------------------------------------------
*/
#include "mxc_device.h"
#include "mxc_delay.h"
#include "mxc_errors.h"
#include "spi.h"
#include "gpio.h"
#include "adbms6830.h"
#define BMS_SPI MXC_SPI1
#define BMS_SPI_HZ 1000000
#define BMS_CS_PORT MXC_GPIO1
#define BMS_CS_PIN MXC_GPIO_PIN_23
static int plat_spi_xfer(const uint8_t *tx, uint8_t *rx, uint16_t len)
{
mxc_spi_req_t req = {0};
req.spi = BMS_SPI;
req.txData = (uint8_t *)tx;
req.rxData = rx;
req.txLen = len;
req.rxLen = len;
req.ssIdx = 0;
req.ssDeassert = 0; /* CS is ours (GPIO), keep HW SS out of it */
req.completeCB = NULL;
return (MXC_SPI_MasterTransaction(&req) == E_NO_ERROR) ? 0 : -1;
}
static void plat_cs_set(int level)
{
if (level) MXC_GPIO_OutSet(BMS_CS_PORT, BMS_CS_PIN);
else MXC_GPIO_OutClr(BMS_CS_PORT, BMS_CS_PIN);
}
static void plat_delay_us(uint32_t us)
{
MXC_Delay(us);
}
const adbms_hal_t max32690_hal = {
.spi_xfer = plat_spi_xfer,
.cs_set = plat_cs_set,
.delay_us = plat_delay_us,
};
int platform_init(void)
{
/* Chip select: plain push-pull output, idle HIGH */
mxc_gpio_cfg_t cs = {
.port = BMS_CS_PORT,
.mask = BMS_CS_PIN,
.func = MXC_GPIO_FUNC_OUT,
.pad = MXC_GPIO_PAD_NONE,
.vssel = MXC_GPIO_VSSEL_VDDIOH, /* 3.3 V I/O */
};
MXC_GPIO_Config(&cs);
MXC_GPIO_OutSet(BMS_CS_PORT, BMS_CS_PIN);
/* SPI1 master, no hardware SS (numSlaves = 0 -> we toggle CS ourselves) */
mxc_spi_pins_t pins = {
.clock = true, .miso = true, .mosi = true,
.ss0 = false, .ss1 = false, .ss2 = false,
.sdio2 = false, .sdio3 = false, .vddioh = true,
};
if (MXC_SPI_Init(BMS_SPI, 1, 0, 0, 0, BMS_SPI_HZ, pins) != E_NO_ERROR)
return -1;
MXC_SPI_SetDataSize(BMS_SPI, 8);
MXC_SPI_SetWidth(BMS_SPI, SPI_WIDTH_STANDARD);
MXC_SPI_SetMode(BMS_SPI, SPI_MODE_3);
return 0;
}main.c
/**
* main.c - MAX32690 BMS master: 2 daisy-chained ADBMS6830B boards (5 + 7 cells)
*
* Console output goes to the MAX32690 UART0 (through the MAX32625PICO /
* USB) - open it at 115200 8N1 in the VS Code serial monitor or PuTTY.
*/
#include <stdio.h>
#include "mxc_device.h"
#include "mxc_delay.h"
#include "led.h"
#include "board.h"
#include "bms_app.h"
extern const adbms_hal_t max32690_hal;
extern int platform_init(void);
static adbms_chain_t chain; /* static: never a NULL/dangling pointer */
static bms_data_t data;
int main(void)
{
printf("\n=== ADBMS6830 daisy chain on MAX32690 ===\n");
if (platform_init() != 0) {
printf("SPI init failed\n");
while (1) {}
}
/* Safety trap: if init fails we stop HERE with a message and a fast
* blinking LED, instead of hard-faulting later on a bad pointer. */
int ret = bms_app_init(&chain, &max32690_hal);
if (ret != 0) {
printf("BMS init failed (%d). Check NUM_DEV / dev_list / wiring.\n", ret);
while (1) {
LED_Toggle(0);
MXC_Delay(MXC_DELAY_MSEC(100));
}
}
while (1) {
ret = bms_app_measure(&chain, &data);
if (ret == ADBMS_E_PEC)
printf("PEC error (-77): check isoSPI cable / termination / tie-offs\n");
bms_app_protect(&data);
/* Balance only when the pack is healthy (in the car: also only while
* charging or resting, never while driving at high current). */
bms_balance_compute((const float (*)[ADBMS_CELLS_PER_DEV])data.cell_v,
data.bal_mask, data.faults == 0);
bms_app_apply_balance(&chain, &data);
bms_app_print(&data);
LED_Toggle(0);
MXC_Delay(MXC_DELAY_MSEC(MEAS_PERIOD_MS)); /* < 2 s so the chain's
watchdog never sleeps it */
}
}project.mk
# project.mk - MaximSDK project settings (MAX32690, AD-APARD32690-SL)
# -----------------------------------------------------------------------------
# MaximSDK projects come with a generic "Makefile" that includes this file.
# Build from the VS Code task "build" or from the MSYS/MinGW shell:
# make -r -j (build/ -> build/max32690.elf)
# make flash.openocd (flash through the MAX32625PICO / CMSIS-DAP)
# -----------------------------------------------------------------------------
TARGET = MAX32690
BOARD = APARD
# --- Project sources ---------------------------------------------------------
# AUTOSEARCH = 1 means "compile every .c file found in the project folder AND
# in every folder listed in VPATH". That is convenient for project code, but
# it was the cause of the no-OS build break: pointing VPATH at the whole
# no-OS max32690 platform folder made make compile EVERY driver in it
# (maxim_rtc.c, maxim_pwm.c ...), and several of those use APIs that were
# deprecated in newer MSDK releases.
AUTOSEARCH = 0
SRCS += main.c
SRCS += platform_max32690.c
SRCS += adbms6830.c
SRCS += bms_app.c
SRCS += parameters.c
SRCS += thermistor.c
# --- ADI no-OS (only what the project actually uses) -------------------------
# NO_OS_DIR is wherever no-OS was cloned. The platform .c files live one level
# deeper, in drivers/platform/maxim/max32690 - the first missing-.elf issue
# was VPATH pointing one folder too high, so the linker never got those objects.
NO_OS_DIR ?= ../no-OS
IPATH += $(NO_OS_DIR)/include
IPATH += $(NO_OS_DIR)/drivers/platform/maxim/max32690
IPATH += $(NO_OS_DIR)/drivers/platform/maxim/common # maxim_dma.h moved here
VPATH += $(NO_OS_DIR)/drivers/platform/maxim/max32690
SRCS += maxim_delay.c # only no-OS driver the project needed (no_os_udelay/mdelay
# used by the no-OS BMS code). This reference driver uses
# MXC_Delay() directly, so it builds without it too.
# --- Compiler flags ------------------------------------------------------------
PROJ_CFLAGS += -Wno-strict-prototypes # no-OS headers trip this warning
PROJ_LDFLAGS += -lm # logf() in thermistor.c
# Debug build (for the Cortex-Debug launch config in VS Code)
MXC_OPTIMIZE_CFLAGS = -OgAppendix B — PC test harness
test/host_test.c simulates two ADBMS6830B devices as described in the datasheet. It checks every command PEC, accepts writes top-device-first, answers reads bottom-device-first with CCNT + PEC10, and can corrupt a byte on demand. The PEC10 implementation is cross-checked against a bit-serial reference on 2000 random frames.
1) PEC15 known vectors (same CRC as LTC681x family)
PASS WRCFGA 0x0001 -> PEC 0x3D6E (expect 0x3D6E)
PASS RDCVA 0x0004 -> PEC 0x07C2 (expect 0x07C2)
2) PEC10 vs bit-serial reference, 2000 random frames
PASS fast PEC10 == reference PEC10 on all frames
3) Bring up 2-board chain (5 + 7 cells)
PASS init ok
PASS chain accepted every command/data PEC
PASS REFON set on both devices
PASS IIR FC written
PASS VUV code 542 -> 2.8008 V
PASS VOV code 1125 -> 4.2000 V
4) Measure: offsets 4 and 12, parsing, sums
PASS measure ok
PASS every cell matches within 1 LSB
PASS b1_sum = 18.541 V, b2_sum = 25.967 V
PASS NTC at mid-scale -> 25.00 C
PASS die temp -> 35.00 C
5) Balancing decision + it lands on the RIGHT board
PASS board1 mask 0x000A (expect 0x000A)
PASS board2 mask 0x0024 (expect 0x0024)
PASS DCC bytes in the simulated chips: 0A / 24
PASS DCTO watchdog armed (2 min)
6) Hysteresis: cell drops to min+5 mV -> still ON; to min+2 mV -> OFF
PASS C2 at +5 mV keeps bleeding
PASS C2 at +2 mV stops
7) Corrupted byte on board 2 -> -77 (EBADMSG)
PASS adbms_read_cells returned -77
8) PWM nibble packing
PASS PWMA0=0xA3 PWMB0=0x0F
ALL TESTS PASSED (0 failures)
test/host_test.c
/**
* host_test.c - runs the portable driver on a PC against a simulated chain.
*
* gcc -I.. -o host_test host_test.c ../adbms6830.c ../bms_app.c \
* ../parameters.c ../thermistor.c -lm && ./host_test
*
* The simulated chain behaves like the data sheet says:
* - checks the command PEC15 of every frame
* - write frames: top device's data first, checks each data PEC10
* - read frames: bottom device answers first, data + CCNT + PEC10
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include "adbms6830.h"
#include "bms_app.h"
#include "thermistor.h"
/* ------------------------------------------------------------------ */
/* Reference bit-serial PEC10 (same style as ADI's sample code) used */
/* only to cross-check our faster implementation. */
/* ------------------------------------------------------------------ */
static uint16_t ref_pec10_read(const uint8_t *seven) /* 6 data + PEC0 byte */
{
int pec[10] = {0,0,0,0,1,0,0,0,0,0}, poly[5];
long long d = 0;
for (int i = 0; i < 7; i++) { d |= seven[i]; d <<= 8; }
d >>= 8; d >>= 2; /* drop PEC[9:8], keep CCNT bits */
for (int i = 53; i >= 0; i--) {
poly[0] = ((d >> i) & 1) ^ pec[9];
poly[1] = poly[0] ^ pec[0]; poly[2] = poly[0] ^ pec[1];
poly[3] = poly[0] ^ pec[2]; poly[4] = poly[0] ^ pec[6];
pec[9]=pec[8]; pec[8]=pec[7]; pec[7]=poly[4]; pec[6]=pec[5];
pec[5]=pec[4]; pec[4]=pec[3]; pec[3]=poly[3]; pec[2]=poly[2];
pec[1]=poly[1]; pec[0]=poly[0];
}
uint16_t t = 0;
for (int i = 9; i >= 0; i--) t |= (uint16_t)(pec[i] << i);
return t;
}
/* ------------------------------------------------------------------ */
/* Simulated devices */
/* ------------------------------------------------------------------ */
typedef struct {
int16_t cell_code[16];
int16_t gpio_code[10];
int16_t vref2_code, itmp_code;
uint8_t cfga[6], cfgb[6], pwma[6], pwmb[6];
uint8_t ccnt;
} sim_dev_t;
static sim_dev_t sim[NUM_DEV];
static int sim_corrupt_next_read = 0;
static int sim_cmd_pec_errors = 0, sim_data_pec_errors = 0;
static void sim_reg(sim_dev_t *s, uint16_t cmd, uint8_t out[6])
{
memset(out, 0xFF, 6);
const int16_t *src = NULL; int base = 0, n = 3;
switch (cmd) {
case CMD_RDCVA: src = s->cell_code; base = 0; break;
case CMD_RDCVB: src = s->cell_code; base = 3; break;
case CMD_RDCVC: src = s->cell_code; base = 6; break;
case CMD_RDCVD: src = s->cell_code; base = 9; break;
case CMD_RDCVE: src = s->cell_code; base = 12; break;
case CMD_RDCVF: src = s->cell_code; base = 15; n = 1; break;
case CMD_RDAUXA: src = s->gpio_code; base = 0; break;
case CMD_RDAUXB: src = s->gpio_code; base = 3; break;
case CMD_RDAUXC: src = s->gpio_code; base = 6; break;
case CMD_RDAUXD: src = s->gpio_code; base = 9; n = 1; break;
case CMD_RDCFGA: memcpy(out, s->cfga, 6); return;
case CMD_RDCFGB: memcpy(out, s->cfgb, 6); return;
case CMD_RDSTATA:
out[0] = (uint8_t)s->vref2_code; out[1] = (uint8_t)(s->vref2_code >> 8);
out[2] = (uint8_t)s->itmp_code; out[3] = (uint8_t)(s->itmp_code >> 8);
return;
default: return;
}
for (int k = 0; k < n; k++) {
out[2*k] = (uint8_t)(src[base + k] & 0xFF);
out[2*k+1] = (uint8_t)((uint16_t)src[base + k] >> 8);
}
}
static int is_read_cmd(uint16_t c)
{
return (c <= 0x00F) || (c >= 0x012 && c <= 0x01F) || c == 0x002 || c == 0x026 ||
(c >= 0x030 && c <= 0x034) || (c >= 0x044 && c <= 0x04B) ||
c == 0x022 || c == 0x023;
}
static int is_write_cmd(uint16_t c)
{
return c == CMD_WRCFGA || c == CMD_WRCFGB || c == CMD_WRPWMA || c == CMD_WRPWMB;
}
static int sim_spi_xfer(const uint8_t *tx, uint8_t *rx, uint16_t len)
{
uint16_t cmd = (uint16_t)((tx[0] << 8) | tx[1]);
uint16_t pec = adbms_pec15(tx, 2);
memcpy(rx, tx, 4); /* echo region */
if (((pec >> 8) & 0xFF) != tx[2] || (pec & 0xFF) != tx[3]) {
sim_cmd_pec_errors++; /* chip ignores it */
memset(rx, 0xFF, len);
return 0;
}
if (is_write_cmd(cmd)) {
if (len != 4 + 8 * NUM_DEV) { printf("bad write len\n"); exit(1); }
for (int slot = 0; slot < NUM_DEV; slot++) {
const uint8_t *d = &tx[4 + 8 * slot];
int dev = NUM_DEV - 1 - slot; /* top device first */
uint16_t p = adbms_pec10(d, 6, false, 0);
if ((((p >> 8) & 3) != d[6]) || ((p & 0xFF) != d[7])) { sim_data_pec_errors++; continue; }
uint8_t *dst = cmd == CMD_WRCFGA ? sim[dev].cfga : cmd == CMD_WRCFGB ? sim[dev].cfgb :
cmd == CMD_WRPWMA ? sim[dev].pwma : sim[dev].pwmb;
memcpy(dst, d, 6);
sim[dev].ccnt = (uint8_t)(sim[dev].ccnt == 63 ? 1 : sim[dev].ccnt + 1);
}
return 0;
}
if (is_read_cmd(cmd)) {
for (int dev = 0; dev < NUM_DEV; dev++) { /* bottom device first */
uint8_t *o = &rx[4 + 8 * dev];
sim_reg(&sim[dev], cmd, o);
uint16_t p = adbms_pec10(o, 6, true, sim[dev].ccnt);
o[6] = (uint8_t)((sim[dev].ccnt << 2) | ((p >> 8) & 3));
o[7] = (uint8_t)(p & 0xFF);
}
if (sim_corrupt_next_read) { rx[4 + 8 + 1] ^= 0x10; sim_corrupt_next_read = 0; }
return 0;
}
for (int dev = 0; dev < NUM_DEV; dev++) /* action command */
sim[dev].ccnt = (uint8_t)(sim[dev].ccnt == 63 ? 1 : sim[dev].ccnt + 1);
return 0;
}
static uint8_t cs_level = 1;
static void sim_cs(int l) { cs_level = (uint8_t)l; }
static void sim_delay(uint32_t us) { (void)us; }
static const adbms_hal_t sim_hal = { sim_spi_xfer, sim_cs, sim_delay };
/* ------------------------------------------------------------------ */
static int fails = 0;
#define CHECK(cond, ...) do { if (cond) printf(" PASS "); else { printf(" FAIL "); fails++; } \
printf(__VA_ARGS__); printf("\n"); } while (0)
static int16_t v2c(float v) { return (int16_t)lroundf((v - 1.5f) / 0.00015f); }
int main(void)
{
printf("1) PEC15 known vectors (same CRC as LTC681x family)\n");
uint8_t wr[2] = {0x00, 0x01}, rd[2] = {0x00, 0x04};
CHECK(adbms_pec15(wr, 2) == 0x3D6E, "WRCFGA 0x0001 -> PEC 0x%04X (expect 0x3D6E)", adbms_pec15(wr, 2));
CHECK(adbms_pec15(rd, 2) == 0x07C2, "RDCVA 0x0004 -> PEC 0x%04X (expect 0x07C2)", adbms_pec15(rd, 2));
printf("2) PEC10 vs bit-serial reference, 2000 random frames\n");
srand(1234); int ok = 1;
for (int i = 0; i < 2000 && ok; i++) {
uint8_t f[7]; for (int k = 0; k < 6; k++) f[k] = (uint8_t)rand();
uint8_t cc = (uint8_t)(rand() & 0x3F);
uint16_t p = adbms_pec10(f, 6, true, cc);
f[6] = (uint8_t)((cc << 2) | ((p >> 8) & 3));
if (ref_pec10_read(f) != p) ok = 0;
}
CHECK(ok, "fast PEC10 == reference PEC10 on all frames");
printf("3) Bring up 2-board chain (5 + 7 cells)\n");
float b1[5] = {3.701f, 3.712f, 3.695f, 3.730f, 3.703f};
float b2[7] = {3.698f, 3.702f, 3.744f, 3.700f, 3.699f, 3.721f, 3.703f};
for (int c = 0; c < 16; c++) { /* unused inputs tied to top -> ~0 V */
sim[0].cell_code[c] = v2c(c < 5 ? b1[c] : 0.0f);
sim[1].cell_code[c] = v2c(c < 7 ? b2[c] : 0.0f);
}
for (int d = 0; d < 2; d++) {
sim[d].vref2_code = v2c(3.000f);
sim[d].itmp_code = v2c((35.0f + 273.0f) * 0.0075f);
for (int g = 0; g < 10; g++) sim[d].gpio_code[g] = v2c(1.5f); /* 25 C on 10k/10k */
}
adbms_chain_t ch; bms_data_t data; memset(&data, 0, sizeof data);
CHECK(bms_app_init(&ch, &sim_hal) == 0, "init ok");
CHECK(sim_cmd_pec_errors == 0 && sim_data_pec_errors == 0, "chain accepted every command/data PEC");
CHECK(sim[0].cfga[0] & 0x80 && sim[1].cfga[0] & 0x80, "REFON set on both devices");
CHECK((sim[0].cfga[5] & 7) == ADBMS_FC_10HZ, "IIR FC written");
uint16_t vuv = (uint16_t)(sim[0].cfgb[0] | ((sim[0].cfgb[1] & 0x0F) << 8));
uint16_t vov = (uint16_t)(((sim[0].cfgb[1] >> 4) & 0x0F) | (sim[0].cfgb[2] << 4));
CHECK(fabsf(vuv * 0.0024f + 1.5f - 2.80f) < 0.003f, "VUV code %u -> %.4f V", vuv, vuv * 0.0024f + 1.5f);
CHECK(fabsf(vov * 0.0024f + 1.5f - 4.20f) < 0.003f, "VOV code %u -> %.4f V", vov, vov * 0.0024f + 1.5f);
printf("4) Measure: offsets 4 and 12, parsing, sums\n");
CHECK(bms_app_measure(&ch, &data) == 0, "measure ok");
int match = 1; float s1 = 0, s2 = 0;
for (int c = 0; c < 5; c++) { match &= fabsf(data.cell_v[0][c] - b1[c]) < 0.0002f; s1 += b1[c]; }
for (int c = 0; c < 7; c++) { match &= fabsf(data.cell_v[1][c] - b2[c]) < 0.0002f; s2 += b2[c]; }
CHECK(match, "every cell matches within 1 LSB");
CHECK(fabsf(data.stack_v[0] - s1) < 0.001f && fabsf(data.stack_v[1] - s2) < 0.001f,
"b1_sum = %.3f V, b2_sum = %.3f V", data.stack_v[0], data.stack_v[1]);
CHECK(fabsf(data.temp_c[0][0] - 25.0f) < 0.1f, "NTC at mid-scale -> %.2f C", data.temp_c[0][0]);
CHECK(fabsf(data.die_c[0] - 35.0f) < 0.2f, "die temp -> %.2f C", data.die_c[0]);
printf("5) Balancing decision + it lands on the RIGHT board\n");
bms_app_protect(&data);
bms_balance_compute((const float (*)[16])data.cell_v, data.bal_mask, data.faults == 0);
/* min = 3.695 ; start threshold = min + 10 mV = 3.705
board1: C2 3.712, C4 3.730 -> bits 1,3 = 0x000A
board2: C3 3.744, C6 3.721 -> bits 2,5 = 0x0024 */
CHECK(data.bal_mask[0] == 0x000A, "board1 mask 0x%04X (expect 0x000A)", data.bal_mask[0]);
CHECK(data.bal_mask[1] == 0x0024, "board2 mask 0x%04X (expect 0x0024)", data.bal_mask[1]);
bms_app_apply_balance(&ch, &data);
CHECK(sim[0].cfgb[4] == 0x0A && sim[1].cfgb[4] == 0x24, "DCC bytes in the simulated chips: %02X / %02X",
sim[0].cfgb[4], sim[1].cfgb[4]);
CHECK((sim[0].cfgb[3] & 0x3F) == BAL_TIMEOUT_MIN, "DCTO watchdog armed (%d min)", sim[0].cfgb[3] & 0x3F);
printf("6) Hysteresis: cell drops to min+5 mV -> still ON; to min+2 mV -> OFF\n");
data.cell_v[0][1] = 3.700f; bms_balance_compute((const float (*)[16])data.cell_v, data.bal_mask, true);
CHECK(data.bal_mask[0] & 0x2, "C2 at +5 mV keeps bleeding");
data.cell_v[0][1] = 3.697f; bms_balance_compute((const float (*)[16])data.cell_v, data.bal_mask, true);
CHECK(!(data.bal_mask[0] & 0x2), "C2 at +2 mV stops");
printf("7) Corrupted byte on board 2 -> -77 (EBADMSG)\n");
sim_corrupt_next_read = 1;
float cells[ADBMS_MAX_DEV][16];
int r = adbms_read_cells(&ch, 7, cells);
CHECK(r == -77, "adbms_read_cells returned %d", r);
printf("8) PWM nibble packing\n");
adbms_set_pwm(&ch, 0, 1, 0x3); adbms_set_pwm(&ch, 0, 2, 0xA); adbms_set_pwm(&ch, 0, 13, 0xF);
CHECK(ch.regs[0].pwma[0] == 0xA3 && ch.regs[0].pwmb[0] == 0x0F, "PWMA0=0x%02X PWMB0=0x%02X",
ch.regs[0].pwma[0], ch.regs[0].pwmb[0]);
printf("\n%s (%d failure%s)\n", fails ? "SOME TESTS FAILED" : "ALL TESTS PASSED", fails, fails == 1 ? "" : "s");
return fails != 0;
}Appendix C — Real frames produced by the driver
Useful for recognising traffic on a logic analyser. All PECs are computed by the driver's own functions.
TX: 00 04 07 C2 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
RX: 00 04 07 C2 51 39 9B 39 29 39 17 A9 3D 39 58 39 70 3A 14 F3
dev1 C1 code=0x3951 (14673) -> 3.7009 V
dev1 C2 code=0x399B (14747) -> 3.7120 V
dev1 C3 code=0x3929 (14633) -> 3.6949 V
dev2 C1 code=0x393D (14653) -> 3.6979 V
dev2 C2 code=0x3958 (14680) -> 3.7020 V
dev2 C3 code=0x3A70 (14960) -> 3.7440 V
WRCFGB TX: 00 24 B1 9E 1E 52 46 02 24 00 02 43 1E 52 46 02 0A 00 02 5D
ADCV(CONT,RD)=0x3E0 PEC=0xB04A
RDCVB 0x006 -> frame 00 06 9A 94
RDCVC 0x008 -> frame 00 08 5E 52
SNAP 0x02D -> frame 00 2D D2 A2
UNSNAP 0x02F -> frame 00 2F 4F F4
MUTE 0x028 -> frame 00 28 E8 0E
UNMUTE 0x029 -> frame 00 29 63 3C
WRCFGA 0x001 -> frame 00 01 3D 6E
RDCFGA 0x002 -> frame 00 02 2B 0A
RDAUXA 0x019 -> frame 00 19 8E 4E
RDSTATA 0x030 -> frame 00 30 5B 2E
ADAX(all) 0x410 -> frame 04 10 51 14
VUV(2.8)=542 VOV(4.2)=1125
Sources
- ADBMS6830B datasheet (Rev. 0), Analog Devices — analog.com/…/adbms6830b.pdf
- ADBMS6830B product page — analog.com/en/products/adbms6830b.html
- ADBMS6830 product page — analog.com/en/products/adbms6830.html
- EVAL-ADBMS6830BMSW user guide (board photo, block diagram, connection figures) — analogdevicesinc.github.io/system-level/…/eval-adbms6830bmsw
- EVAL-ADBMS6830BMSW product page — analog.com/…/eval-adbms6830bmsw.html
- ADBMS6821/ADBMS6822 isoSPI transceiver — analog.com/en/products/adbms6822.html
- EVAL-ADBMS6822 — analog.com/…/EVAL-ADBMS6822.html
- MAX32690 — analog.com/en/products/MAX32690.html
- AD-APARD32690-SL user guide (board photo, pin-out) — analogdevicesinc.github.io/…/ad-apard32690-sl
- AD-BMSE2E3W-SL light-EV BMS reference design (cell depopulation figure) — analogdevicesinc.github.io/…/ad-bmse2e3w-sl
- AD-CELLPACKBM-SL BMS kit hardware guide — analogdevicesinc.github.io/…/ad-cellpackbm-sl
- ADI discharge-algorithm demo for ADBMS6830 (pyBMS), in kamilkopyra/pyBMS-RPi-Pico-bridge — github.com/kamilkopyra/pyBMS-RPi-Pico-bridge
- APARD32690 + ADBMS6830 community example (MSDK driver structure, no-OS-BMS-Examples configuration) — github.com/hari4579/BMS2027
Images marked "Source: Analog Devices" are from ADI's public documentation and are reproduced for personal study. All other figures were drawn for this guide. Pack-design examples use illustrative cell parameters.