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.

How to read the source tags Project notes comes from the original project's bring-up records (2-board chain, Makefile fixes, the dead-LED fault). Datasheet was checked against Analog Devices' datasheets and board guides. Engineering practice is standard BMS / embedded practice or a reconstruction. The C driver in Appendix A re-implements the original firmware's structure. It compiles and passes a PC simulation of a 2-device chain, but it has not been run on hardware.
ADBMS6830B
16-cell monitor IC, ±1.8 mV
isoSPI
isolated 2-wire daisy chain, 2 Mbps
MAX32690
Cortex-M4F @ 120 MHz, bare-metal C
40S7P
144 V nominal · 168 V max · 280 cells
Part I — Overview & structure

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:

1.2 Scope of the work

AreaWork done
MCU firmwareBare-metal C on the MAX32690 using MaximSDK and parts of ADI's no-OS framework, built in VS Code Project notes
ADBMS programmingWake-up sequence, configuration registers, ADC start commands, register-group reads, PEC generation and checking, multi-device frame parsing, balancing control
Bring-upSingle board first, then a 2-board daisy chain with 5 active cells on board 1 and 7 on board 2 Project notes
DebuggingisoSPI wiring and termination, PEC errors (−77), a NULL-pointer HardFault (dead LED), MaximSDK / no-OS build integration
Not in scopePCB design (ADI evaluation boards were used), pack-current sensing, SOC estimation, vehicle CAN integration

1.3 One-minute technical summary (for interviews)

The pack is 40S7P (144 V nominal, 168 V max), built from eight 5S7P modules. The BMS uses a modular architecture: ADBMS6830B cell monitors, each covering up to 16 series groups, daisy-chained over isoSPI to a MAX32690 controller through an ADBMS6822 transceiver. The firmware wakes the chain, writes the configuration to every device in one frame, runs the cell ADCs in continuous mode, and reads the register groups. Each device's data sits at offset 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

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

Pack hierarchy. A parallel group behaves electrically like one big cell, so it needs one BMS voltage channel. In this project, 7 cells form a group, 5 groups form a 5S7P module, and 8 modules in series form the 40S7P pack.
Figure 1. Pack hierarchy. A parallel group behaves electrically like one big cell, so it needs one BMS voltage channel. In this project, 7 cells form a group, 5 groups form a 5S7P module, and 8 modules in series form the 40S7P pack.
LevelWhat it isWhat the BMS sees
CellOne 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 barsOne 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, enclosureThe whole daisy chain + MCU + pack-level sensors

2.2 Hardware blocks and signal path

Hardware architecture. Everything in the red box sits on the battery's high-voltage side. Everything in the blue box is on the low-voltage side. The only connection between them is the isolated isoSPI link.
Figure 2. Hardware architecture. Everything in the red box sits on the battery's high-voltage side. Everything in the blue box is on the low-voltage side. The only connection between them is the isolated isoSPI link.
BlockPartRole
Cell monitor (×N)ADBMS6830B on the EVAL-ADBMS6830BMSW board DatasheetMeasures up to 16 series cells and 10 GPIO/temperature inputs. Drives 16 balancing switches. Has 2 isoSPI ports.
isoSPI masterADBMS6822 dual transceiver (EVAL-ADBMS6822, Arduino-shield format)Converts the MCU's 4-wire SPI into isolated 2-wire pulses and back
ControllerMAX32690 on the AD-APARD32690-SL boardArm Cortex-M4F at 120 MHz, ~3 MB flash, 1 MB SRAM, 2× CAN 2.0B, BLE 5, RISC-V co-processor. Runs the firmware.
DebugMAX32625PICO (CMSIS-DAP)SWD flashing and debugging, plus the UART console
HostPC with VS Code + MaximSDKBuild, flash, serial monitor

Following one cell measurement end to end

  1. The cell group's voltage reaches the monitor board through a sense wire and an RC filter on pins Cn / Cn−1.
  2. 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.
  3. The MCU sends RDCVA (with its PEC15) over SPI to the ADBMS6822. The ADBMS6822 turns it into isoSPI pulses on the twisted pair.
  4. 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.
  5. 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.
  6. 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 WRCFGB frame.

2.3 Layered view (hardware + firmware)

Seven layers from the cells up to the vehicle. Each layer talks only to its neighbours. The firmware covers layers 3–5, and layer 2 is the isolation barrier.
Figure 3. Seven layers from the cells up to the vehicle. Each layer talks only to its neighbours. The firmware covers layers 3–5, and layer 2 is the isolation barrier.

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.
Part II — Battery & pack fundamentals

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

Inside a Li-ion cell. Lithium ions shuttle through the electrolyte between a graphite anode and a metal-oxide cathode. Electrons take the external path through the load or charger.
Figure 4. Inside a Li-ion cell. Lithium ions shuttle through the electrolyte between a graphite anode and a metal-oxide cathode. Electrons take the external path through the load or charger.

A Li-ion cell has two electrodes that can each store lithium inside their crystal structure, a process called intercalation:

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.

ChemistryNominal / max / min VEnergy density (cell, typical)Cycle life (typical)Thermal stabilityBMS notes
NMC (this project)3.6–3.7 / 4.2 / 2.5–3.0High (≈150–250 Wh/kg)~1000–2000ModerateUsable OCV slope, good voltage-based SOC near the ends
NCA3.6 / 4.2 / 2.5–3.0Very high~1000LowerTight voltage and temperature control
LFP3.2 / 3.65 / 2.5Lower (≈90–160 Wh/kg)~2000–5000+HighVery flat OCV: SOC from voltage is hard, balancing needs care
LTO (anode)2.4 / 2.8 / 1.5Low10 000+Very highMany 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:

3.4 The safe operating window and why each limit exists

LimitTypical NMC / NCA value Engineering practiceWhat happens outside it
Maximum cell voltage4.20 VThe 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 voltage2.5–3.0 VThe anode's copper foil starts to dissolve. On the next charge the copper can re-deposit as dendrites and short the cell internally.
Charge temperature0 °C to ~45 °CIn 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 °CAgeing accelerates sharply with heat. Self-heating reactions begin somewhere between about 80 and 130 °C depending on the chemistry.
CurrentDatasheet C-rate (continuous and pulse)I²R heating inside the cell, a voltage sag that can drop below cut-off, faster ageing.
Thermal runaway in one paragraphOnce a cell gets hot enough, the SEI breaks down and the electrolyte reacts with the electrodes. Those reactions release more heat, which drives faster reactions. The separator melts, the electrodes short, and the stored energy is released in seconds as fire and gas. It can then spread to neighbouring cells (propagation). A BMS can't stop runaway once it starts. Its job is to keep every cell far away from the conditions that trigger it.

3.5 Voltage and state of charge: the OCV curve

Open-circuit voltage vs state of charge. NMC has a usable slope, while LFP is almost flat in the middle. Shapes are illustrative.
Figure 5. Open-circuit voltage vs state of charge. NMC has a usable slope, while LFP is almost flat in the middle. Shapes are illustrative.

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:

  1. The cell must be at rest. Under current, the terminal voltage differs from OCV (next sections).
  2. 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.
  3. 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

CC-CV charging: constant current until the cell reaches 4.20 V, then constant voltage while the current decays, stopping at about C/20.
Figure 6. CC-CV charging: constant current until the cell reaches 4.20 V, then constant voltage while the current decays, stopping at about C/20.

Li-ion cells are charged in two phases:

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

Left: first-order Thevenin model. Right: response of a cell to a 10 A pulse. An instant I·R0 drop, a slow RC sag, then slow relaxation back towards OCV.
Figure 7. Left: first-order Thevenin model. Right: response of a cell to a 10 A pulse. An instant I·R0 drop, a slow RC sag, then slow relaxation back towards OCV.

Engineers model a cell electrically with the Thevenin equivalent circuit:

V_terminal = OCV(SOC, T) − I·R0 − V_RC dV_RC/dt = I/C1 − V_RC/(R1·C1) time constant τ = R1·C1

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

TermMeaningExample
Nominal voltageAverage voltage over a discharge3.6–3.7 V (NMC), 3.2 V (LFP)
Capacity (Ah)Charge delivered from full to empty3.0 Ah 18650
Energy (Wh)Vnominal × Ah3.7 V × 3.0 Ah = 11.1 Wh
C-rateCurrent relative to capacity: 1C = full capacity in one hour1C of 3 Ah = 3 A; 3C = 9 A
Internal resistanceCauses voltage sag (I·R) and heat (I²R)15–30 mΩ for an 18650
Self-dischargeSlow internal charge loss at restA few % per month. Differences between cells cause drift.
SOC / SOHState 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

Pack nominal voltage V_pack = n × V_cell Pack max / min voltage V_max = n × 4.2 V V_min = n × V_cutoff Pack capacity Ah_pack = m × Ah_cell Pack energy E_pack = n × m × V_cell × Ah_cell (Wh) Max continuous current I_max = m × I_cell_max Max power P_max ≈ V_pack × I_max = n × m × V_cell × I_cell_max Pack resistance R_pack = (n / m) × R_cell (+ bus bars, welds, fuses) Heat at current I P_loss = I² × R_pack BMS voltage channels = n (not n × m!) sense wires = n + 1

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.

The same 12 cells arranged three ways. Energy and peak power are identical. Voltage, current, resistance and the number of BMS channels change.
Figure 8. The same 12 cells arranged three ways. Energy and peak power are identical. Voltage, current, resistance and the number of BMS channels change.

4.2 nS vs mP: what each number changes

PropertyIncrease n (more series groups)Increase m (more cells per group)
Pack voltage↑ proportionallyunchanged
Capacity (Ah)unchanged↑ proportionally
Energy (Wh)↑↑
Max currentunchanged↑ (current shared across m cells)
Current for the same power↓ → thinner cables, smaller contactors, less I²R lossunchanged
Pack resistance↑ (n·R)↓ (R/m)
BMS channels / monitor ICs↑ one channel per groupno change
Balancing timeunchanged 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 failureAn open cell in a 1P string stops the whole packGroup 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.

Simulation of five groups with slightly different self-discharge. The charger stops when the highest group is full, so the others start each cycle a little emptier. Without balancing the spread keeps growing.
Figure 9. Simulation of five groups with slightly different self-discharge. The charger stops when the highest group is full, so the others start each cycle a little emptier. Without balancing the spread keeps growing.

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)

Left: cells paralleled into groups, then the groups put in series. This is the standard EV approach. Right: whole series strings put in parallel. The middle nodes are not shared, so every cell in every string needs its own channel.
Figure 10. Left: cells paralleled into groups, then the groups put in series. This is the standard EV approach. Right: whole series strings put in parallel. The middle nodes are not shared, so every cell in every string needs its own channel.

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)

  1. 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 minimum and n × 4.2 V ≤ controller maximum. The nominal voltage then falls out as n × 3.7 V.
  2. 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.
  3. Check current. Peak current is highest at the lowest voltage: I_peak = P_peak / V_min. Per-cell current is I_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.
  4. Check heat and sag. I² × R_pack gives the losses and I × R_pack the voltage drop at peak load, which must not push the pack below the controller minimum.
  5. 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).
  6. 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.
  7. 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 project pack: eight 5S7P modules in series (40S7P, 280 cells). Module voltage ranges are at full charge. Dashed blocks are typical pack hardware (shunt, contactors, pre-charge, fuse) outside this project's scope.
Figure 11. The project pack: eight 5S7P modules in series (40S7P, 280 cells). Module voltage ranges are at full charge. Dashed blocks are typical pack hardware (shunt, contactors, pre-charge, fuse) outside this project's scope.

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

QuantityFormulaResult
Nominal voltage40 × 3.6 V144 V (a 144 V-class drive system)
Maximum voltage40 × 4.2 V168 V: charger CV setpoint, and the voltage that every contactor, fuse, connector and the isoSPI isolation must handle
Minimum voltage40 × 3.0 V (or 2.5 V)120 V (100 V). The controller must keep running down to this.
Capacity7 × Ahcell17.5 Ah (2.5 Ah cells) / 21 Ah (3.0 Ah cells)
Energy144 V × 7 × Ahcell2.52 kWh / 3.02 kWh
Continuous current7 × Icell105 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 channelsn40 voltage channels (41 sense points), regardless of the 7P
Monitor ICsceil(40 / 16)≥ 3 (e.g. 15S + 15S + 10S on module boundaries), or 8 with one IC per module
Read frame (8 ICs)4 + 8 × 868 bytes per register group → 544 µs at 1 MHz
Balancing5 % of 7 × 2.5 Ah ÷ 118 mA0.875 Ah → ≈ 7.4 h. Larger groups take proportionally longer.
Safety class168 V > 60 V DCHigh-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?

4.8 Failure modes to know

FailureIn seriesIn parallelBMS visibility
Cell open-circuitWhole string stops (1P)Group loses 1/m capacity and its voltage moves faster under loadSeen indirectly: that group sags more and reaches limits first
Cell internal shortCell discharges itself, then UVGroup-mates dump current into the short → heat. Needs per-cell fuse links.Group voltage drops at rest. Temperature rises.
Capacity mismatchDrift in SOC → needs balancingSelf-corrected inside the groupVisible as group-to-group voltage spread
Joining unequal cells—Large inrush current when cells at different voltages are welded togetherMatch cell voltages before assembly

Interactive pack calculator

Key takeaways — series and paralleln sets voltage and BMS channel count. m sets capacity, current capability and balancing time. Energy depends only on n × m. Build parallel groups first, then put the groups in series. Choose n from the load's voltage window, and m from energy and peak current.

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.
Why per-cell monitoring is mandatoryThe pack voltage is a sum. One group at 4.40 V and another at 4.00 V can add up to a perfectly normal-looking total while one group is dangerously overcharged. Every safety limit applies per group.

5.2 Architectures

TypeHow it worksProsCons
CentralisedOne board, long sense wires to every cellCheapest for small packsHeavy wiring harness, hard to scale, wires run across HV areas
Modular / distributed (this project)One monitor IC per module, daisy-chained to one master MCUShort sense wires, scales to any voltage, modules testable aloneNeeds isolated communication (isoSPI)
WirelessMonitor ICs talk to the master by radioNo communication harnessRF 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.
Coulomb counting alone drifts because of a 3 % gain error and a 0.15 A offset. Re-anchoring to the OCV curve during rest periods pulls the estimate back to the truth.
Figure 12. Coulomb counting alone drifts because of a 3 % gain error and a 0.15 A offset. Re-anchoring to the OCV curve during rest periods pulls the estimate back to the truth.

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:

snippets.c — coulomb
/* 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;
}
snippets.c — ocv
/* 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.

  1. Close the main − contactor.
  2. Close the pre-charge relay. The motor controller's DC-link capacitor charges through the resistor.
  3. When the DC-link voltage reaches about 95 % of the pack voltage, close the main + contactor.
  4. Open the pre-charge relay. The pack is now connected with only a small voltage across the closing contacts.
  5. 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:

V_link(t) = V_pack × (1 − e^(−t/τ)) τ = R_pre × C_link I(t) = (V_pack / R_pre) × e^(−t/τ) peak current = V_pack / R_pre 95 % after 3τ, 99 % after 5τ. Energy dissipated in R_pre = ½·C·V² (equal to the energy stored in C) Example: R = 100 Ω, C = 1 mF → τ = 100 ms, 95 % at 300 ms, peak 1.68 A, 14.1 J in the resistor
Pre-charging a 1 mF DC link from 168 V with three resistor values. A smaller resistor is faster but has a higher peak current. The resistor absorbs ½CV² regardless of its value.
Figure 13. Pre-charging a 1 mF DC link from 168 V with three resistor values. A smaller resistor is faster but has a higher peak current. The resistor absorbs ½CV² regardless of its value.

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:

snippets.c — precharge
/* 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

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

Q = I²·R_internal (Joule heat, always positive) + I·T·dU/dT (reversible / entropic heat: small, sign depends on direction and SOC) + side reactions (negligible normally, dominant during runaway)

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

m·c_p · dT/dt = Q − h·A·(T − T_ambient) Thermal time constant τ_th = m·c_p / (h·A) Steady-state rise ΔT = Q / (h·A) 18650-class cell: m ≈ 45 g, c_p ≈ 1 J/(g·K) → heat capacity ≈ 45 J/K At 15 A per cell and 20 mΩ: Q = 4.5 W → adiabatic rise ≈ 0.1 K/s (6 K per minute)
Left: heat per cell and for the whole 280-cell pack vs pack current. Right: lumped-model temperature rise at three pack currents without active cooling. Illustrative parameters; the shape is what matters.
Figure 14. Left: heat per cell and for the whole 280-cell pack vs pack current. Right: lumped-model temperature rise at three pack currents without active cooling. Illustrative parameters; the shape is what matters.

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

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:

snippets.c — derate
/* 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);
}
Part III — Hardware

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.

Inside the ADBMS6830B: two independent measurement paths (C-ADC and S-ADC), filtering, auxiliary measurement for the GPIOs, discharge switches, and the isoSPI ports.
Figure 15. Inside the ADBMS6830B: two independent measurement paths (C-ADC and S-ADC), filtering, auxiliary measurement for the GPIOs, discharge switches, and the isoSPI ports.

8.1 Key specifications Datasheet

FeatureValue
ChannelsUp 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-ADC16 ADCs, one per channel, continuously sampling at 4.096 MHz. A new 16-bit result every 1 ms, 150 µV/LSB.
Averaged results8-sample average every 8 ms
IIR filterProgrammable 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 ADC10 GPIOs plus VREF2, supply voltages, die temperature (ITMP)
VREF23.0 V buffered output for biasing 10 kΩ NTC thermistors
Balancing16 internal discharge switches, up to 300 mA each. Static (DCC) or 4-bit PWM per cell. Adjacent cells can balance together.
CommunicationisoSPI, 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).
OtherGPIO3–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

V = (signed 16-bit code) × 150 µV + 1.5 V Example: 0x3951 = 14673 → 14673 × 0.00015 + 1.5 = 3.7010 V Range: −32768 → −3.415 V +32767 → +6.415 V (the +1.5 V offset centres the range on cell voltages) UV / OV thresholds (12-bit, 16× coarser = 2.4 mV/LSB): V = VUV × 16 × 150 µV + 1.5 V 4.20 V → 1125 2.80 V → 542 Die temperature: T(°C) = V_ITMP / 7.5 mV − 273

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)

EVAL-ADBMS6830BMSW. Black screw terminal J1 = cell connections. Centre = ADBMS6830B. Rows of black SMD parts = balancing resistors. Top = GPIO header J5. White DuraClik connectors on the right = isoSPI J3 (port A) and J4 (port B). Photo: Analog Devices.
Figure 16. EVAL-ADBMS6830BMSW. Black screw terminal J1 = cell connections. Centre = ADBMS6830B. Rows of black SMD parts = balancing resistors. Top = GPIO header J5. White DuraClik connectors on the right = isoSPI J3 (port A) and J4 (port B). Photo: Analog Devices.
Board block diagram: cell inputs through RC filters, balancing circuitry on the S-pins, thermistor biasing on the GPIOs, termination circuitry on both isoSPI ports. Source: Analog Devices.
Figure 17. Board block diagram: cell inputs through RC filters, balancing circuitry on the S-pins, thermistor biasing on the GPIOs, termination circuitry on both isoSPI ports. Source: Analog Devices.
RefFunctionNotes Datasheet
J1Cell connectorPosition 1 = C0 (stack −), 2…15 = C1…C14, 16–17 = C15/C16 (stack +). Wire from position 1, the most negative.
J3isoSPI port AToward the master
J4isoSPI port BToward the next board up
J5GPIO headerGPIO1…10 + V− pins (thermistors, test points)
J2IREG headerAmmeter here measures regulator current
J6Supply headerPower the board separately from the stack (remove R55)
D2LEDVREG active: lit only while the chip is awake
Why the D2 LED mattersVREG is generated from the ADBMS6830B's DRIVE pin only after a wake-up (tWAKE is specified "VREG from DRIVE"). So D2 off means the board never received a wake-up pulse. That was the key clue in the dead-LED fault (Section 20.1).

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.

Resistor-ladder connection for bench testing. Source: Analog Devices.
Figure 18. Resistor-ladder connection for bench testing. Source: Analog Devices.

9.2 EVAL-ADBMS6822 (dual isoSPI adapter)

EVAL-ADBMS6822: the microcontroller's SPI enters through the shield headers. The ADBMS6822 drives two isolated ports (MAIN and AUX), which allows a redundant ring. Source: Analog Devices.
Figure 19. EVAL-ADBMS6822: the microcontroller's SPI enters through the shield headers. The ADBMS6822 drives two isolated ports (MAIN and AUX), which allows a redundant ring. Source: Analog Devices.

9.3 AD-APARD32690-SL (MAX32690 controller)

AD-APARD32690-SL board (Arduino Mega form factor). Source: Analog Devices.
Figure 20. AD-APARD32690-SL board (Arduino Mega form factor). Source: Analog Devices.
Header pin-out. The Arduino SPI pins are SPI1 on the MAX32690, which is why the firmware uses SPI1 with a GPIO chip select. Source: Analog Devices.
Figure 21. Header pin-out. The Arduino SPI pins are SPI1 on the MAX32690, which is why the firmware uses SPI1 with a GPIO chip select. Source: Analog Devices.

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

OptionProblem for a modular BMS
Plain SPINeeds a common ground. The boards sit at different high voltages.
SPI + digital isolatorsNeeds an isolator and an isolated power supply on every board, plus 4+ wires per link
CAN per moduleNeeds an MCU, a CAN transceiver and isolation on every module
isoSPIOne 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.

Top: the byte 0x04 (second byte of RDCVA) on the MCU's SPI bus in mode 3. Bottom: the same transaction on the isoSPI pair. A long pulse marks CS falling, short pulses carry the bits, and a long pulse marks CS rising.
Figure 22. Top: the byte 0x04 (second byte of RDCVA) on the MCU's SPI bus in mode 3. Bottom: the same transaction on the isoSPI pair. A long pulse marks CS falling, short pulses carry the bits, and a long pulse marks CS rising.

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.

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:

10.4 The bench chain (5 + 7 active channels) Project notes

The 2-board bench chain: MAX32690 → ADBMS6822 → board 1 port A; board 1 port B → board 2 port A; board 2 port B unused. Termination switch OFF on board 1 and ON on board 2, the end of the line.
Figure 23. The 2-board bench chain: MAX32690 → ADBMS6822 → board 1 port A; board 1 port B → board 2 port A; board 2 port B unused. Termination switch OFF on board 1 and ON on board 2, the end of the line.
ItemBoard 1 (bottom, device 0)Board 2 (top, device 1)
Active cells5 (C1–C5)7 (C1–C7)
Port A (J3)from the ADBMS6822from board 1 port B
Port B (J4)to board 2unused
Termination switchOFFON (end of line)
Unused inputsC6–C16 tied to the top of cell 5 / VBATC8–C16 tied to the top of cell 7 / VBAT
Data position in a readrx[4..11]rx[12..19]
Precise wording about terminationEach isoSPI link has to be terminated with a resistance matched to the twisted pair. Otherwise pulses reflect, bits are mis-decoded, and the data PEC fails (the −77 error). With these switch settings the chain communicated reliably, with the top board terminating the end of the line. Don't describe the signal as "passing through" board 1 electrically. Each ADBMS6830B receives on port A and re-transmits on port B.

10.5 Topologies supported by the boards Datasheet

Typical: master to the bottom board's J3, then J4 to J3 upward. This is the configuration used here. Source: ADI.
Figure 24. Typical: master to the bottom board's J3, then J4 to J3 upward. This is the configuration used here. Source: ADI.
Reverse: master to the top board's J4, then downward. Source: ADI.
Figure 25. Reverse: master to the top board's J4, then downward. Source: ADI.
Redundant ring: MAIN drives the bottom and AUX drives the top. Source: ADI.
Figure 26. Redundant ring: MAIN drives the bottom and AUX drives the top. Source: ADI.

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

Key takeaways — isoSPIIsolation is mandatory because every module floats at a different voltage. isoSPI carries SPI over one transformer-coupled twisted pair as DC-free pulse doublets. Each device receives on port A and re-transmits on port B. Writes go top-device-first, reads come back bottom-device-first. Termination and cabling problems show up as PEC errors.

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.

Fewer than 16 groups on a monitor: real groups use the bottom channels. The unused upper inputs are tied to the top of the last real group (and V+). Those channels then read 0 V.
Figure 27. Fewer than 16 groups on a monitor: real groups use the bottom channels. The unused upper inputs are tied to the top of the last real group (and V+). Those channels then read 0 V.
ADI's cell-depopulation example on the AD-BMSE2E3W-SL reference design. Source: Analog Devices.
Figure 28. ADI's cell-depopulation example on the AD-BMSE2E3W-SL reference design. Source: Analog Devices.
Part IV — Communication & measurement

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

TypeMCU sendsChain returnsExamples
ActionCMD0 CMD1 PEC0 PEC1nothingADCV, ADAX, SNAP, MUTE, CLRCELL
WriteCMD + PEC, then 6 data + 2 PEC per device, top device firstnothingWRCFGA, WRCFGB, WRPWMA
ReadCMD + PEC, then dummy bytes (0xFF) to clock the response out6 data + 2 PEC per device, bottom device firstRDCVA, RDAUXA, RDSTATA, RDCFGA

12.2 Byte map of a 2-device read Project notes

An RDCVA response from the 2-board chain. Bytes 0–3 echo the command, bytes 4–11 are board 1, bytes 12–19 are board 2. Device i always starts at 4 + 8·i.
Figure 29. An RDCVA response from the 2-board chain. Bytes 0–3 echo the command, bytes 4–11 are board 1, bytes 12–19 are board 2. Device i always starts at 4 + 8·i.
Frame length = 4 + 8 × N_devices Device i data = rx[4 + 8·i] … rx[4 + 8·i + 5] Cell k value = rx[o + 2k] | (rx[o + 2k + 1] << 8) (signed, k = 0..2) PEC byte 6 = CCNT[5:0] << 2 | PEC[9:8] PEC byte 7 = PEC[7:0]

12.3 PEC (CRC) and the command counter Datasheet

Command PECData PEC
Width15 bits (sent as 16, LSB = 0)10 bits
Polynomialx15+x14+x10+x8+x7+x4+x3+1 (0x4599)x10+x7+x3+x2+x+1 (0x08F)
Seed0x00100x010
CoversThe 2 command bytes6 data bytes, + the 6-bit command counter on reads
Known vectorsWRCFGA 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.

The −77 errorThe driver returns -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:
  1. termination or cabling on an isoSPI link;
  2. NUM_DEV larger than the real chain (the missing device's slot reads 0xFF);
  3. chain not woken (tWAKE / tREADY not respected);
  4. wrong SPI mode or clock above 2 MHz;
  5. 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:

adbms6830.c — adbms_pec15()
/* ------------------------------------------------------------------------ */
/*  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.

adbms6830.c — adbms_pec10()
/* ------------------------------------------------------------------------ */
/*  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:

snippets.c — crc_table
/* 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:

adbms6830.c — make_cmd()
/* ------------------------------------------------------------------------ */
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);
}
adbms6830.c — adbms_write()
/* 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);
}
adbms6830.c — adbms_read()
/* 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;
}
Design noteA PEC failure on one device doesn't abort the parse. Every device's data is copied and the error is reported at the end. The caller can then see that, for example, only the top board failed (pointing to the last cable) instead of losing all data.

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

CommandCodePurpose
WRCFGA / RDCFGA0x001 / 0x002Config A: REFON, CTH, GPO (GPIO pull-downs), FC (IIR corner), MUTE/SNAP status
WRCFGB / RDCFGB0x024 / 0x026Config B: VUV, VOV, DTMEN, DTRNG, DCTO, DCC[16:1]
WRPWMA / WRPWMB0x020 / 0x021PWM duty for cells 1–12 / 13–16 (4 bits each)
ADCV0x260 + bitsStart 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
ADSV0x168 + bitsS-ADC only
ADAX0x410 + bitsAUX ADC (GPIOs etc.). CH = 0 converts all inputs.
RDCVA…RDCVF0x004, 0x006, 0x008, 0x00A, 0x009, 0x00BRaw cell voltages, 3 per group (F holds only C16)
RDCVALL0x00CAll 16 cells in one frame (32 bytes + one PEC)
RDACx / RDFCx / RDSVx0x044… / 0x012… / 0x003…Averaged / IIR-filtered / S-ADC results
RDAUXA…RDAUXD0x019, 0x01A, 0x01B, 0x01FGPIO1–3, 4–6, 7–9, GPIO10 + VMV + VPV
RDSTATA…RDSTATE0x030…0x034VREF2 + ITMP; VD/VA/VRES; fault flags + conversion counter; OV/UV flags
SNAP / UNSNAP0x02D / 0x02FFreeze / release the result registers
MUTE / UNMUTE0x028 / 0x029Pause / resume all discharge switches (< 65 µs)
CLRCELL / CLOVUV / CLRFLAG0x711 / 0x715 / 0x717Clear results / OV-UV flags / fault flags
RDSID / SRST / RSTCC0x02C / 0x027 / 0x02ESerial ID / soft reset / reset command counter
PLADC / PLAUX0x718 / 0x71EPoll ADC / AUX conversion status
Porting trapOn the older LTC6811, the read codes run 0x004, 0x006, 0x008, 0x00A, 0x00C. On the ADBMS6830B, RDCVE is 0x009 and 0x00C is RDCVALL. Copying the old table silently reads the wrong registers.

Command builder (computes the 4 bytes to send)

Key takeaways — protocolEvery frame is 4 command bytes plus 8 bytes per device. Device i's data starts at index 4 + 8·i. A 15-bit PEC protects commands, and a 10-bit PEC (including the 6-bit command counter) protects each device's data. −77 means a data-PEC failure. Check the cable, the termination, NUM_DEV and the wake-up before suspecting the code.

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.

Core states and isoSPI port states. Cross the SLEEP → STANDBY step once per device with a wake-up pulse. Use the short IDLE → READY wake before each burst of commands.
Figure 30. Core states and isoSPI port states. Cross the SLEEP → STANDBY step once per device with a wake-up pulse. Use the short IDLE → READY wake before each burst of commands.
ParameterValue DatasheetWhat the firmware does
tWAKE200–500 µs (VREG from DRIVE)One CS pulse per device, 500 µs each, at start-up or after sleep
tREADY≤ 10 µsShort CS pulse per device before each burst (port was idle)
tIDLE4.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 msAvoided 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:

adbms6830.c — adbms_wakeup()
/* 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);
    }
}
adbms6830.c — adbms_wakeup_idle()
/* 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:

ConceptMeaningADBMS6830B
ResolutionThe smallest step the ADC output can show (1 LSB)150 µV per code, 16-bit signed register
RangeSpan 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 monitor is powered by and referenced to its own module. It only ever measures small differential voltages between adjacent C-pins. The isolation burden moves to the isoSPI transformers.
Figure 31. Each monitor is powered by and referenced to its own module. It only ever measures small differential voltages between adjacent C-pins. The isolation burden moves to the isoSPI transformers.

14.3 Result registers and when to use each

RegisterRead withUpdate rateUse for
Raw C-ADC (CV)RDCVx1 msFast protection, measurement right after MUTE
Averaged (AC)RDACx8 msLower noise without filter lag
IIR-filtered (FC)RDFCxcontinuous, corner set by FCSmooth values for balancing and SOC
S-ADC (SV)RDSVx8 msRedundant 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]000001010011100101110111
Corneroff110 Hz45 Hz21 Hz10 Hz5 Hz1.25 Hz0.625 Hz
a—2481632128256

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.

Left: step response for several FC settings (corner frequencies computed from a match the datasheet table). Right: raw 1 ms results with noise and 50 Hz ripple, smoothed by the 10 Hz and 1.25 Hz settings. The slower filter is cleaner but reacts more slowly to the real load step.
Figure 32. Left: step response for several FC settings (corner frequencies computed from a match the datasheet table). Right: raw 1 ms results with noise and 50 Hz ripple, smoothed by the 10 Hz and 1.25 Hz settings. The slower filter is cleaner but reacts more slowly to the real load step.
snippets.c — iir
/* 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

  1. ADCV with CONT = 1, RD = 1 once at start-up. Both ADC sets now run forever.
  2. Each loop: wake (tREADY) → MUTE → wait 2 ms (fresh conversions without balancing current) → SNAP.
  3. RDCVA, RDCVB, RDCVC. Groups A–C cover C1–C9, enough for 7 active cells. Each frame carries every device.
  4. 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:

adbms6830.c — adbms_read_cells()
/* 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:

bms_app.c — bms_app_measure()
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;
}
Why SNAP?Results refresh every 1 ms, and reading three register groups takes longer than that. Without a snapshot, group A and group C could come from different conversions. SNAP freezes everything so all cells come from the same instant.

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.

NTC divider: VREF2 (3.0 V) through a 10 kΩ bias resistor, with the NTC to V−. The midpoint feeds a GPIO through the board's RC filter.
Figure 33. NTC divider: VREF2 (3.0 V) through a 10 kΩ bias resistor, with the NTC to V−. The midpoint feeds a GPIO through the board's RC filter.
GPIO voltage and NTC resistance vs temperature for a 10 kΩ, B = 3435 NTC on a 10 kΩ pull-up.
Figure 34. GPIO voltage and NTC resistance vs temperature for a 10 kΩ, B = 3435 NTC on a 10 kΩ pull-up.
V_gpio = VREF2 × R_ntc / (R_bias + R_ntc) R_ntc = R_bias × V_gpio / (VREF2 − V_gpio) 1/T = 1/T0 + ln(R_ntc / R0) / B T in kelvin, T0 = 298.15 K, R0 = 10 kΩ Check points (B = 3435): 0 °C → 2.22 V 25 °C → 1.50 V 45 °C → 0.98 V 60 °C → 0.69 V

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:

thermistor.c — ntc_volt_to_celsius()
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;
}
snippets.c — steinhart
/* 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.

Sensitivity of the divider in mV/°C and the temperature step represented by one ADC LSB. The ADC is never the limiting factor; the NTC's own tolerance (±1 % R, ±1 % B) dominates.
Figure 35. Sensitivity of the divider in mV/°C and the temperature step represented by one ADC LSB. The ADC is never the limiting factor; the NTC's own tolerance (±1 % R, ±1 % B) dominates.

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.

Part V — Balancing & protection

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:

An unbalanced pack therefore loses usable capacity, and the high group is stressed every charge.

Left: state of charge before and after balancing. Right: cell voltages converging under bleed-to-minimum balancing. Illustrative simulation.
Figure 36. Left: state of charge before and after balancing. Right: cell voltages converging under bleed-to-minimum balancing. Illustrative simulation.

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
PrincipleBurn the excess charge of high groups in a resistorMove charge from high to low groups (switched capacitor, inductor, transformer, DC-DC)
EnergyLost as heat80–95 % transferred
Cost and complexityVery low, built into the monitor ICExtra power stage per cell or module
Typical current50–300 mA1–5 A
Best forTop-balancing while charging, small mismatchLarge packs, large mismatch, maximising range
Passive balancing vs three active topologies, at block level.
Figure 37. Passive balancing vs three active topologies, at block level.

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

One balancing channel. An external resistor sits between the cell and the S-pins. The internal FET closes when DCCn = 1 (or during the PWM on-time). Measurement uses the separate C-pins.
Figure 38. One balancing channel. An external resistor sits between the cell and the S-pins. The internal FET closes when DCCn = 1 (or during the PWM on-time). Measurement uses the separate C-pins.
FeatureDetail
Discharge currentUp 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.
PWMWRPWMA/B, 4 bits per cell: 0x0 off, 0x1 ≈ 6.6 %, 0xF = 100 %. Period ≈ 937 ms. Limits the average current and heat.
Adjacent cellsCan balance at the same time
DCTODischarge 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 / UNMUTEAll switches off within 65 µs without losing the DCC/PWM settings
PriorityThermal shutdown > MUTE > WRCFGB > DCC > ADC measurement > WRPWM > PWM
I_bleed = V_cell / R_bal P = V_cell² / R_bal Example (illustrative): 3.9 V / 33 Ω = 118 mA, 0.46 W per channel; 10 channels ≈ 4.6 W on one board Balancing time = imbalance (Ah) / I_bleed → 5 % of 3 Ah = 150 mAh / 118 mA ≈ 1.3 h 5 % of 42 Ah (14P) = 2.1 Ah / 118 mA ≈ 18 h
Left: static DCC vs PWM duty patterns over the ~937 ms period. Right: board heat grows linearly with the number of channels balancing at once, which is the reason to limit duty or channel count.
Figure 39. Left: static DCC vs PWM duty patterns over the ~937 ms period. Right: board heat grows linearly with the number of channels balancing at once, which is the reason to limit duty or channel count.

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:

adbms6830.c — adbms_set_dcc()
/* ------------------------------------------------------------------------ */
/*  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);
}
adbms6830.c — adbms_set_pwm()
/* 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 */
}
adbms6830.c — adbms_set_discharge_timeout()
/* 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 */
}
adbms6830.c — adbms_mute()
/* 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);
}
Time to remove a 5 % imbalance grows with the number of cells per parallel group. Large-capacity packs need more bleed current, or balancing that runs every charge.
Figure 40. Time to remove a 5 % imbalance grows with the number of cells per parallel group. Large-capacity packs need more bleed current, or balancing that runs every charge.

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:

With 118 mA flowing through ~0.25 Ω of filter and wiring resistance, the reading is ~30 mV low while the cell bleeds. During the MUTE window the reading returns to the true value. Path resistance is illustrative.
Figure 41. With 118 mA flowing through ~0.25 Ω of filter and wiring resistance, the reading is ~30 mV low while the cell bleeds. During the MUTE window the reading returns to the true value. Path resistance is illustrative.
  1. MUTE → wait → measure → UNMUTE (used in this firmware; costs a ~2 ms gap per loop).
  2. Balance at less than 100 % duty and measure during the off-time.
  3. Compensate per channel: ADI's own discharge demo calibrates a per-cell gain with switches on vs off.

16.5 Balancing algorithm

Per-cell balancing state machine with hysteresis: start at Vmin + 10 mV, stop at Vmin + 3 mV. Disabled on faults or a hot die. Hardware timeout as a backstop.
Figure 42. Per-cell balancing state machine with hysteresis: start at Vmin + 10 mV, stop at Vmin + 3 mV. Disabled on faults or a hot die. Hardware timeout as a backstop.
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

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.

bms_app.c — bms_balance_compute()
/* 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:

bms_app.c — bms_app_apply_balance()
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 / cellC1C2C3C4C5C6C7
Board 1 (V)3.7013.7123.6953.7303.703——
Board 2 (V)3.6983.7023.7443.7003.6993.7213.703
  1. Pack minimum Vmin = 3.695 V (board 1, C3). Start threshold = 3.705 V, stop threshold = 3.698 V.
  2. 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.
  3. Board 2: C3 (3.744) and C6 (3.721) → bits 2 and 5 → DCC mask 0x0024.
  4. One WRCFGB frame carries board 2's bytes first (…24 00), then board 1's (…0A 00), each with DCTO = 2 min.
  5. 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.
Key takeaways — balancingBalancing removes slow drift, not big differences, so tens to hundreds of mA are enough. Bleed every group that is clearly above the pack minimum, with hysteresis. Measure with the switches muted, limit heat, and always arm the hardware timeout. Large parallel groups balance slowly, so balance every charge.

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.

FaultDetectionFirmware responseProduction response Engineering practice
Over-voltageCell > 4.20 V (software) + VOV comparator (hardware)FAULT_OV, balancing disabledStop charging, open the charge contactor if it persists
Under-voltageCell < 2.80 V + VUV comparatorFAULT_UVLimit or stop discharge
Over-temperatureNTC > 60 °CFAULT_OTDerate current, then open the contactors
Under-temperatureNTC < 0 °CFAULT_UTBlock charging
Sensor faultNTC open or shortedFAULT_SENSORTreat as worst case and derate
CommunicationData PEC mismatch (−77), CCNT mismatchFAULT_COMM, error counterRetry. Repeated failures within the fault-tolerant time → safe state.
ADC driftC-ADC vs S-ADC → CSxFLT(read RDSTATC)Safe state
Open sense wireOpen-wire test (OW bits)(start-up check)Safe state
MCU hangDCTO timer, 2 s watchdogHardware turns balancing offPlus 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:

17.2 Limits, debounce, hysteresis and latching

A good protection scheme answers four questions for every monitored value:

  1. What are the limits? Usually two levels: a warning limit (reduce current, stop balancing) and a hard limit (open the contactors).
  2. 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.
  3. 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.
  4. 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.
Typical fault state machine: NORMAL → WARNING (derate) → latched FAULT → SAFE STATE (contactors open). Recovery from the safe state needs a deliberate reset.
Figure 43. Typical fault state machine: NORMAL → WARNING (derate) → latched FAULT → SAFE STATE (contactors open). Recovery from the safe state needs a deliberate reset.
snippets.c — debounce
/* 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:

bms_app.c — bms_app_protect()
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. */
}
Part VI — Firmware

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

FileLayerResponsibility
adbms6830_regs.hDriverCommand codes, register bit positions, conversion macros
adbms6830.c/.hDriverPEC15/PEC10, wake-up, action/write/read frames, configuration, cells, GPIOs, VREF2, DCC/PWM/DCTO/MUTE
parameters.c/.hConfigNUM_DEV, dev_list[], cells and NTCs per board, limits
bms_app.c/.hApplicationMeasure → protect → balance → print
thermistor.c/.hApplicationNTC voltage → °C (Beta equation)
platform_max32690.cHALSPI1 (mode 3, 1 MHz), GPIO chip select, microsecond delay (MaximSDK)
main.cEntryInit, safety trap, 1 s main loop
project.mkBuildMaximSDK 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:

adbms6830.c — adbms_init()
/* ------------------------------------------------------------------------ */
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;
}
platform_max32690.c — plat_spi_xfer()
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;
}
main.c — main()
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

Start-up and main loop. The loop period (~1 s) stays below the 2 s watchdog so the chain never sleeps while the system is running.
Figure 44. Start-up and main loop. The loop period (~1 s) stays below the 2 s watchdog so the chain never sleeps while the system is running.

18.5 Timing budget of one loop (2 devices, 1 MHz SPI)

StepApproximate 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.

  1. 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
  2. Device table. NUM_DEV = 2 and dev_list = { DEV_ADBMS6830, DEV_ADBMS6830 }. The two must always agree (see Section 20.1).
  3. 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.
  4. Read groups A, B, C for every device (7 cells need C1–C7, which fall in groups A–C).
  5. Parse with offsets. Board 1 at rx[4], board 2 at rx[12]. Take 5 cells from board 1 and 7 from board 2, ignore the rest.
  6. Running totals. b1_sum and b2_sum print 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

Fault chain. Changing NUM_DEV without extending dev_list produced a zero-filled device entry, a failed init, a NULL device pointer, a HardFault on the first wake-up, and no wake pulses — so the VREG LED stayed off.
Figure 45. Fault chain. Changing NUM_DEV without extending dev_list produced a zero-filled device entry, a failed init, a NULL device pointer, a HardFault on the first wake-up, and no wake pulses — so the VREG LED stayed off.
STARContent
SituationAdding 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.
TaskFind why neither board responded after moving to NUM_DEV = 2.
ActionUsed 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.
ResultListed both devices in parameters.c, added return-value checks and a while(1) safety trap that prints the error. Both boards then reported.
LessonNever 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

Two build problems and their fixes when combining the MaximSDK Makefile with ADI no-OS sources.
Figure 46. Two build problems and their fixes when combining the MaximSDK Makefile with ADI no-OS sources.
  1. No .elf file. build/ held main.o but no maxim_*.o, so the linker failed on undefined symbols. The no-OS platform sources live in drivers/platform/maxim/max32690/, one level deeper than the VPATH entry. Fix: point VPATH at the max32690 folder.
  2. Missing maxim_dma.h and deprecated-API errors in maxim_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 .c in every VPATH folder, which pulled in unused drivers written for an older SDK.
  3. 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 only maxim_delay.c compiled from no-OS.
Make conceptMeaning
VPATHFolders where make searches for source files
IPATH → -IFolders where the compiler searches for headers
SRCSSource files to compile
AUTOSEARCHMaximSDK option: add every .c in the project and VPATH folders to SRCS
Link failureAn object file was never built → undefined reference → no .elf

20.3 Checklist for −77 (PEC) errors

  1. Is NUM_DEV equal to the real number of devices? (An extra slot always fails.)
  2. Are the D2 LEDs lit on every board after wake-up? If not, it's a wake-up or cabling issue.
  3. Port A toward the MCU, port B away? Termination correct at the end of the line?
  4. SPI mode 3, ≤ 2 MHz, CS held low for the entire frame?
  5. Frame length = 4 + 8 × N? Reading the PEC at the right offset (bytes 6–7 of each slot)?
  6. Is the CCNT taken from the top 6 bits of byte 6 and included in the PEC calculation?
  7. 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

21. Toolchain and build

ToolRole
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 CodeEditor. MSDK projects include a .vscode/ folder with build/flash tasks and a Cortex-Debug launch configuration.
arm-none-eabi-gccCross compiler → build/max32690.elf
OpenOCD + MAX32625PICOSWD flashing and debugging (breakpoints, fault registers)
ADI no-OSOpen-source bare-metal driver framework. The platform layer for this MCU is in drivers/platform/maxim/max32690.
Serial terminal115200 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
Part VII — Beyond the prototype

22. Production BMS and improvements

22.1 Built-in diagnostics worth using Datasheet

22.2 What a vehicle BMS adds Engineering practice

FunctionHow
Pack currentShunt or Hall sensor with a pack monitor (e.g. ADI ADBMS2950)
SOC / SOHCoulomb counting + OCV correction, often a Kalman filter. Capacity and resistance tracking.
ContactorsMain ± contactors, pre-charge resistor and relay, welded-contact detection
IsolationInsulation resistance monitoring between HV and chassis
CommunicationCAN to the VCU and charger: current/voltage limits, SOC, faults (MAX32690 has 2 × CAN 2.0B)
Functional safetyISO 26262: safety goals, fault-tolerant time intervals, safe states, ASIL-D-process parts (the non-B ADBMS6830)
RobustnessRedundant isoSPI ring, DMA-driven SPI on a timer schedule, non-volatile fault log, bootloader / OTA updates

22.3 Next improvements for this firmware

  1. Redundant isoSPI ring using the ADBMS6822 AUX port, with automatic fall-back on a broken link.
  2. Timer-driven scheduler and DMA SPI instead of blocking delays. Protection runs at 10–100 ms.
  3. Read the S-ADC and CSxFLT, and run open-wire checks at start-up.
  4. Replace the fixed ADAX wait with PLAUX polling.
  5. Per-channel IR-drop compensation so measurement can continue during balancing.
  6. CAN reporting, current sensing and SOC estimation.
Part VIII — Interview preparation

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.

Score: 0 / 0 answered

24.1 Pack design

Q1 The project pack is 40S7P with NMC cells (3.6 V nominal). If the cells are 2.5 Ah, what are the pack's nominal voltage and capacity?
Answer: D. Series sets voltage: 40 × 3.6 V = 144 V. Parallel sets capacity: 7 × 2.5 Ah = 17.5 Ah. 168 V is the full-charge voltage, not nominal.
Q2 How many independent cell-voltage measurement channels does a 40S7P pack (parallel-first construction) need?
Answer: A. Each parallel group is one electrical node pair, so one channel per series group: 40. The 7 cells in a group share one voltage.
Q3 What is the minimum number of 16-channel ADBMS6830B devices needed to monitor 40 series groups?
Answer: A. ceil(40/16) = 3. Grouped on module boundaries that is 15S + 15S + 10S. Using one IC per 5S7P module would need 8.
Q4 The same 280 cells are rebuilt as 7 parallel strings of 40S each (series-first). How many voltage channels are now needed to see every cell?
Answer: C. In series-first strings the mid-string nodes aren't shared, so every cell in every string needs its own channel: 40 × 7 = 280. That's why EV packs are built parallel-first.
Q5 Cells have 21 mΩ internal resistance. What is the cell-only resistance of a 40S7P pack?
Answer: D. R_pack = (n/m) × R_cell = (40/7) × 21 mΩ = 120 mΩ.
Q6 Using the 120 mΩ pack resistance, how much heat is generated in the cells at a 70 A pack current?
Answer: C. P = I² × R = 70² × 0.12 Ω = 588 W. Heat scales with the square of current.
Q7 Changing the pack from 40S7P to 40S14P (same cells) would...
Answer: C. Parallel count multiplies Ah and current. Channels depend only on n. Resistance halves, and balancing time doubles because each group holds twice the charge.
Q8 What constant-voltage setpoint should the charger use for the 40S NMC pack?
Answer: A. 40 × 4.20 V = 168 V. Some designs charge slightly lower (e.g. 4.1 V/cell) for longer life, but never above.
Q9 Why does the same pack energy at higher voltage reduce cable losses?
Answer: B. For a fixed power P = V·I, doubling V halves I, and I²R loss drops to a quarter.
Q10 With one ADBMS6830B per 5S7P module, at what potential (relative to pack negative) does the top monitor's V− pin sit at full charge?
Answer: C. The top module (M8) starts after 35 groups: 35 × 4.2 V = 147 V. It spans 147–168 V.
Q11 One cell in a 7P group develops an internal short. What is the main danger, and the usual mitigation?
Answer: B. Parallel cells share one node, so healthy cells feed the shorted one with high current. A fuse link per cell isolates the faulty cell.

24.2 Cell theory

Q12 During CHARGING of a Li-ion cell, lithium ions move...
Answer: C. On charge, Li⁺ de-intercalates from the cathode and intercalates into the graphite anode through the electrolyte. Electrons take the external path.
Q13 Why must charging be blocked below about 0 °C?
Answer: A. At low temperature lithium can't intercalate fast enough and plates on the anode surface. This causes permanent capacity loss and a short-circuit risk.
Q14 In the Thevenin cell model, the instantaneous voltage step when the load current changes is caused by...
Answer: D. The ohmic R0 responds instantly (ΔV = ΔI × R0). The RC branch produces the slower sag and relaxation.
Q15 Why does SOC estimation from voltage need a rest period?
Answer: D. Under or just after load, V_term = OCV − I·R0 − V_RC. Only after the RC term has decayed does the terminal voltage equal OCV.
Q16 A CC-CV charge normally terminates when...
Answer: A. Reaching 4.20 V only ends the CC phase. Charging continues at constant voltage until the current has decayed to a small termination value.
Q17 For the same pack voltage (144 V), how many LFP cells (3.2 V nominal) would be needed in series?
Answer: A. 144 V / 3.2 V = 45 in series.
Q18 Why is voltage-based balancing usually done near the top of charge for NMC?
Answer: D. In the flat middle region a few mV can mean a large SOC difference. Near full charge the slope is larger, so voltage is a better proxy for SOC.

24.3 ADBMS6830B

Q19 A cell-voltage register reads 0x2EE0. What is the cell voltage?
Answer: C. 0x2EE0 = 12000. 12000 × 150 µV + 1.5 V = 1.8 V + 1.5 V = 3.300 V.
Q20 A channel reads 0xF000. What voltage does it represent?
Answer: B. The code is signed: 0xF000 = −4096. −4096 × 150 µV + 1.5 V = 0.886 V. Treating it as unsigned (61440) gives the wrong 10.716 V.
Q21 Which VOV register value sets the over-voltage threshold to 4.20 V?
Answer: C. Threshold LSB = 16 × 150 µV = 2.4 mV with a 1.5 V offset: (4.20 − 1.5) / 0.0024 = 1125.
Q22 The IIR filter setting FC = 100 uses a = 16 and updates every 1 ms. Its corner frequency is about...
Answer: A. f_c = −ln(1 − 1/16) × 1000 / 2π ≈ 10.3 Hz, matching the datasheet's 10 Hz entry.
Q23 Which result is the best choice for fast over-voltage protection?
Answer: A. Protection needs low latency. Heavy filtering adds seconds of lag that could hide a real over-voltage.
Q24 What is the main purpose of the S-ADC?
Answer: A. The S-ADCs measure through the S-pins independently. A disagreement with the C-ADC raises CSxFLT, which supports functional safety.
Q25 Why send SNAP before reading register groups A, B and C?
Answer: B. In continuous mode results update every 1 ms. SNAP freezes them so a multi-group read is coherent. UNSNAP releases them.
Q26 What does setting REFON = 1 avoid?
Answer: B. With the reference kept on, conversions can start immediately instead of waiting for the reference to power up.
Q27 A monitor board has its unused upper inputs tied to the top active cell. What do those channels read?
Answer: D. Both pins of an unused channel are at the same potential, so it reads 0 V. Without masking it would trigger an under-voltage fault.
Q28 To read NTC thermistors on GPIOs, the GPO bits for those pins must be...
Answer: B. GPO = 0 enables the pin's pull-down, which would load the NTC divider. GPO = 1 leaves the pin high-impedance for the AUX ADC.

24.4 Protocol

Q29 How long (in bytes) is a register-group read frame for a chain of 8 ADBMS6830B devices?
Answer: A. 4 command bytes + 8 bytes (6 data + 2 PEC) per device: 4 + 8 × 8 = 68.
Q30 In that 8-device read, at which RX byte index does the 6th device from the bottom (index 5) start?
Answer: A. Device i starts at 4 + 8·i = 4 + 40 = 44.
Q31 Why is the TOP device's data sent first in a daisy-chain write?
Answer: B. Data shifts up through every device. The first 8-byte slot to enter ends up at the far end, so it must belong to the top device.
Q32 What does the 10-bit data PEC cover on a READ?
Answer: A. Read PEC10 = CRC over 6 data bytes plus the 6 CCNT bits, so a lost command is detected as well as corrupted data.
Q33 After reaching 63, the command counter (CCNT) rolls over to...
Answer: D. It rolls over from 63 to 1, never to 0. 0 only appears after reset, sleep, RSTCC or SRST.
Q34 The command PEC polynomial has an even number of terms. What guarantee does that give?
Answer: C. A polynomial with an even number of terms is divisible by (x+1). Any CRC with that factor detects all errors with an odd number of flipped bits.
Q35 Firmware sets NUM_DEV = 3, but only 2 boards are connected. What is the most likely symptom?
Answer: C. Nobody drives the third slot, so it reads idle (0xFF), whose PEC can't match. The real two devices still parse.
Q36 The −77 error code returned by the driver corresponds to...
Answer: B. In the newlib C library used by arm-none-eabi-gcc, EBADMSG = 77. The driver returns it when a received data PEC doesn't match.
Q37 Which SPI mode does the ADBMS68xx family use?
Answer: A. CPOL = 1 (idle high) and CPHA = 1 (sample on the trailing, rising edge) = mode 3.
Q38 Why must chip select stay low for an entire command frame?
Answer: B. A CS rise mid-frame is transmitted as an end-of-command pulse, so the rest of the frame is lost.

24.5 isoSPI

Q39 Why are isoSPI symbols sent as doublets (positive then negative, or the reverse)?
Answer: D. A transformer can't pass DC. A balanced doublet has zero average, so it couples cleanly across the isolation barrier.
Q40 The isoSPI port has been silent for 10 ms but the core is awake. What is needed before the next command?
Answer: D. After tIDLE (~5.5 ms) the port goes idle. Getting back to READY only takes tREADY. tWAKE is for waking the core from sleep.
Q41 What happens if an ADBMS6830B receives no valid command for about 2 seconds?
Answer: C. The watchdog (tSLEEP ~2 s) sends the device to sleep. The firmware's ~1 s loop keeps the chain awake.
Q42 Why does a full wake-up of an N-device chain repeat the CS pulse N times?
Answer: A. Device 1 wakes on the first pulse and only then relays activity to device 2, and so on, each needing up to tWAKE.

24.6 Balancing

Q43 A 3.6 V cell bleeds through a 30 Ω balancing resistor. What are the current and the power?
Answer: C. I = 3.6 / 30 = 0.12 A. P = V² / R = 12.96 / 30 = 0.432 W.
Q44 A 7P group of 2.5 Ah cells is 3 % above the others. How long does a 100 mA bleed take to remove it?
Answer: B. Excess charge = 0.03 × 7 × 2.5 Ah = 0.525 Ah. 0.525 Ah / 0.1 A = 5.25 h.
Q45 Cell 4 has DCC4 = 1 and PWM4 = 0x8 at the same time. What is its effective duty?
Answer: B. Static DCC bits take priority over PWM, so the switch is fully on.
Q46 Why does the firmware MUTE balancing before taking the cell readings it uses for balancing decisions?
Answer: C. The bleed current flows through filter resistors and wiring. The resulting drop makes a bleeding cell look lower than it is, causing oscillation.
Q47 What is the role of DCTO?
Answer: C. DCTO (0–63 min or 0–16.8 h) is a fail-safe: a crashed MCU can't leave the bleed resistors on indefinitely.
Q48 With 10 mV start and 3 mV stop thresholds, a bleeding cell drops from 12 mV to 5 mV above the pack minimum. What happens?
Answer: B. Hysteresis: once on, a cell only stops below the stop threshold (3 mV). That prevents chattering.

24.7 Protection & HV

Q49 A pre-charge circuit uses R = 100 Ω and a 1 mF DC link at 168 V. About when can the main contactor be closed (95 %)?
Answer: B. τ = RC = 100 × 0.001 = 0.1 s. 95 % is reached after about 3τ = 300 ms.
Q50 During pre-charge, how much energy is dissipated in the resistor?
Answer: D. Charging a capacitor from a voltage source through any resistor dissipates exactly ½CV² in the resistor: 14.1 J for 1 mF at 168 V.
Q51 An OV fault needs 3 consecutive violations at a 100 ms sample period. What constraint must this satisfy?
Answer: D. Debouncing delays detection. Detection plus the safe-state reaction must still complete within the fault-tolerant time interval.

24.8 Firmware

Q52 A Cortex-M4 HardFault shows BFAR = 0x00000004. What is the most likely cause?
Answer: D. A fault address near zero is the signature of dereferencing a NULL pointer, exactly the dead-LED failure mode.

25. Cheat sheet

ADBMS6830B
Channels / IC16
LSB / offset150 µV / +1.5 V, signed 16-bit
UV/OV threshold LSB2.4 mV (×16), 12-bit
Accuracy±1.8 mV (3.3 V, full temperature range, lifetime)
C-ADC / average / S-ADC1 ms / 8 ms / 8 ms
GPIOs / VREF210 / 3.0 V
Balancing≤ 300 mA, 4-bit PWM, ~937 ms period
DCTO0–63 min or 0–16.8 h
MUTE< 65 µs
Sleep current~4 µA
Protocol and timing
SPImode 3, ≤ 2 MHz (1 MHz used)
tWAKE / tREADY200–500 µs / ≤ 10 µs
tIDLE / tSLEEP / tREFUP~5.5 ms / ~2 s / ~3.5 ms
Command PEC15-bit, 0x4599, seed 0x10
Data PEC10-bit, 0x08F, seed 0x10, + CCNT on reads
Frame length4 + 8 × N bytes
Device i offsetrx[4 + 8·i]
ADCV / ADAX / ADSV0x260 / 0x410 / 0x168 (+ bits)
RDCVA–F004, 006, 008, 00A, 009, 00B
−77−EBADMSG (newlib) = data PEC failure
Pack design
Voltagen × Vcell
Capacity / currentm × Ahcell / m × Icell
Energyn × m × V × Ah
Resistance(n/m) × Rcell
BMS channelsn (sense wires n + 1)
Monitor ICs≥ ceil(n / 16)
Charger setpointn × 4.2 V
Project pack40S7P, 280 cells, 144 V nom / 168 V max
Module5S7P (35 cells), 18 V nom / 21 V max, × 8
Hardware
MCUMAX32690, Cortex-M4F 120 MHz, 1 MB SRAM, ~3 MB flash, 2× CAN
TransceiverADBMS6822 dual isoSPI
Monitor boardEVAL-ADBMS6830BMSW (J1 cells, J3 port A, J4 port B, J5 GPIO, D2 VREG LED)
MCU boardAD-APARD32690-SL (Arduino SPI = SPI1)
Bench chainBoard 1: 5 cells, TERM off · Board 2: 7 cells, TERM on

26. Glossary

TermMeaning
AFE / cell monitorAnalog front-end IC that measures cell voltages (the ADBMS6830B)
ASILAutomotive Safety Integrity Level (ISO 26262), A (lowest) to D (highest)
CCNT6-bit command counter inside each monitor
C-rateCurrent relative to capacity (1C = full capacity in one hour)
DCCDischarge cell control bit (balancing switch on/off)
DCTODischarge timeout (balancing watchdog)
FTTIFault-tolerant time interval
HardFaultCortex-M exception for bus, memory or usage faults
IIRInfinite impulse response low-pass filter
isoSPIADI's isolated 2-wire transport for SPI
LPCMLow-power cell monitoring (while the vehicle is off)
MSDKMaximSDK, the SDK for MAX32xxx MCUs
nS mPn parallel groups in series, m cells per group
NTCNegative-temperature-coefficient thermistor
OCVOpen-circuit (rest) voltage
PECPacket error code (CRC)
SOC / SOHState of charge / state of health
SWDSerial Wire Debug (ARM programming and debug interface)
TMETotal measurement error
VCUVehicle control unit
Appendices

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.h157 lines
/**
 * 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.h94 lines
/**
 * 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.c382 lines
/**
 * 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.h43 lines
/**
 * 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

#endif
parameters.c10 lines
#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.h30 lines
/**
 * 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);

#endif
thermistor.c14 lines
#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.h35 lines
#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);

#endif
bms_app.c146 lines
/**
 * 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.c85 lines
/**
 * 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.c58 lines
/**
 * 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.mk45 lines
# 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 = -Og

Appendix 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.c232 lines
/**
 * 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

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.