Simvik

Electric car: decode the battery's CAN frame

Decode voltage, current, charge and status from the battery management system's CAN frame. A medium embedded C problem (CAN), run and graded in the browser.

medium · CAN · can · signals · signed · product

Product: Electric vehicle battery pack (Automotive)

Requirement. The dashboard and the motor controller read the battery's status frame, ID 0x3F2 with 8 data bytes, ten times a second. A frame with another ID or length is not this message.

BytesSignal
0–1pack voltage, 0.1 V per bit, unsigned, high byte first
2–3pack current, 0.1 A per bit, signed (negative while charging), high byte first
4state of charge, 0.5 % per bit (report whole percent, rounded down)
5bit 0: main contactor closed; bit 1: fault

Decode into *out and return true, or return false for any other frame.

Starter code

bool bms_decode(uint32_t id, uint8_t dlc, const uint8_t d[8], bms_t *out) {
  out->volts_x10 = (uint16_t)(d[1] << 8 | d[0]);
  out->amps_x10 = (int16_t)(d[3] << 8 | d[2]);
  out->soc_pct = d[4];
  out->contactor = d[5] & 1;
  out->fault = d[5] & 2;
  return true;
}

Example tests

Driving

uint8_t d[8] = { 0x0E, 0x74, 0x00, 0xFA, 0xA0, 0x01, 0, 0 };
bms_t b = { 0 };
bool ok = bms_decode(0x3F2, 8, d, &b);
printf("%d %u %d %u %d %d\n", ok, b.volts_x10, b.amps_x10, b.soc_pct, b.contactor, b.fault);

Expected output:

1 3700 250 80 1 0

Charging

uint8_t d[8] = { 0x0F, 0x3C, 0xFF, 0x06, 0x51, 0x01, 0, 0 };
bms_t b = { 0 };
bms_decode(0x3F2, 8, d, &b);
printf("%u %d %u\n", b.volts_x10, b.amps_x10, b.soc_pct);

Expected output:

3900 -250 40

Learn it first

  • CAN · Arbitration, bit timing, frames, CAN FD and error handling.

More CAN problems