A CAN log shows 123 [2] 11 22. On the wire, that frame is 62 bits, two of which the controller added and the receiver removes again. This guide builds that frame bit by bit, so you can see where every bit comes from and read it on a logic analyser. The frame types guide explains the fields; this one is about the bits.

The fields in transmission order

A classical CAN data frame with an 11-bit ID, as it leaves the controller:

FieldBitsValue for 123 [2] 11 22
SOF10
Identifier1100100100011 (0x123)
RTR, IDE, r03000 (data frame, 11-bit ID)
DLC40010 (2 bytes)
Data1600010001 00100010
CRC15Calculated below
CRC delimiter11
ACK slot1Sent as 1, overwritten with 0 by any receiver
ACK delimiter11
End of frame71111111

Every field is sent most significant bit first. 0 is the dominant level and 1 the recessive level.

Step 1: the CRC-15

The CRC is calculated over the bits from SOF to the end of the data field, before any stuff bits are added. CAN uses the polynomial 0x4599 (x¹⁵ + x¹⁴ + x¹⁰ + x⁸ + x⁷ + x⁴ + x³ + 1), with a start value of 0 and no final XOR. Calculated bit by bit:

Python
def crc15(bits):
    """CAN CRC-15 (polynomial 0x4599) over a list of 0/1 bits, most significant first."""
    crc = 0
    for bit in bits:
        feedback = bit ^ (crc >> 14)
        crc = (crc << 1) & 0x7FFF
        if feedback:
            crc ^= 0x4599
    return crc


def to_bits(value, width):
    return [(value >> i) & 1 for i in range(width - 1, -1, -1)]


check = crc15([b for byte in b"123456789" for b in to_bits(byte, 8)])
print(f"check value: 0x{check:04X}")

Output:

Example
check value: 0x059E

0x059E is the published check value for CRC-15/CAN in the CRC RevEng catalogue, which confirms the polynomial and bit order before we use the function on a frame.

Step 2: stuff bits

CAN has no clock line. Receivers resynchronise on edges, so the transmitter must not send long runs of the same level. After five identical bits, it inserts one bit of the opposite level. The stuff bit counts as the first bit of the next run. Stuffing covers everything from SOF to the end of the CRC sequence; the CRC delimiter, ACK field and end of frame are fixed-form and never stuffed.

Python
def stuff(bits):
    """Insert a complementary bit after every five identical bits. Returns bits and stuff positions."""
    out, stuffed, run_bit, run = [], [], None, 0
    for bit in bits:
        out.append(bit)
        run = run + 1 if bit == run_bit else 1
        run_bit = bit
        if run == 5:
            out.append(1 - bit)
            stuffed.append(len(out) - 1)
            run_bit, run = 1 - bit, 1  # the stuff bit starts the next run
    return out, stuffed


def classical_frame(can_id, data):
    """Bits of a classical CAN data frame with an 11-bit ID, as sent on the bus."""
    head = [0] + to_bits(can_id, 11) + [0, 0, 0] + to_bits(len(data), 4)  # SOF, ID, RTR, IDE, r0, DLC
    body = head + [b for byte in data for b in to_bits(byte, 8)]
    crc = crc15(body)  # over SOF to the end of the data field, before stuffing
    stuffed, positions = stuff(body + to_bits(crc, 15))
    tail = [1, 0, 1] + [1] * 7  # CRC delimiter, ACK slot (driven dominant by receivers), ACK delimiter, EOF
    return stuffed + tail, crc, positions


bits, crc, positions = classical_frame(0x123, bytes([0x11, 0x22]))
print(f"CRC: 0x{crc:04X}")
print(f"stuff bits at positions {positions}")
print(f"{len(bits)} bits on the bus, {len(positions)} of them stuff bits")
print("".join(map(str, bits)))

Output:

Example
CRC: 0x04B7
stuff bits at positions [17, 40]
62 bits on the bus, 2 of them stuff bits
00010010001100000110000100010010001000001100101101111011111111

Count the first stuff bit yourself: RTR, IDE and r0 are 000, and the DLC starts with 00. That is five dominant bits in a row, so the transmitter inserts a 1 at position 17, between the second and third DLC bit. The receiver sees five equal bits, knows the next one is a stuff bit, and throws it away.

Two consequences:

  • Frame length depends on the data. The same ID and DLC can give frames of different lengths, which is why bus load calculations use a worst case.
  • Six equal bits are an error. Inside the stuffed part, six identical bits can only mean something went wrong. A receiver that sees them signals a stuff error. Error frames use exactly this: six dominant bits that break the rule on purpose, so every node notices.

Step 3: arbitration

Every node can start sending when the bus is idle. When several start at once, they all send their IDs bit by bit and listen at the same time. A dominant 0 from any node overwrites a recessive 1, so the bus behaves like a wired AND. A node that sends 1 but reads 0 has lost: it stops and becomes a receiver.

Python
def arbitrate(*ids):
    """Bit-by-bit arbitration of 11-bit IDs: a dominant 0 overwrites a recessive 1."""
    contenders = set(ids)
    for position, shift in enumerate(range(10, -1, -1), start=1):
        bus = min((i >> shift) & 1 for i in contenders)  # wired AND
        losers = {i for i in contenders if (i >> shift) & 1 != bus}
        for i in sorted(losers):
            print(f"ID bit {position}: 0x{i:03X} sends 1, reads 0, stops")
        contenders -= losers
    return contenders.pop()


winner = arbitrate(0x65A, 0x652, 0x6F0)
print(f"winner: 0x{winner:03X}")

Output:

Example
ID bit 4: 0x6F0 sends 1, reads 0, stops
ID bit 8: 0x65A sends 1, reads 0, stops
winner: 0x652

The lowest ID wins, and the winning frame is not delayed at all: from its point of view, nobody else was sending. That is why CAN IDs work as priorities: a message that must not wait gets a low ID.

Two details follow from this:

  • A data frame beats a remote frame with the same ID, because the RTR bit is dominant in a data frame.
  • An 11-bit ID beats a 29-bit ID with the same first 11 bits, because the IDE bit is dominant for 11-bit IDs.

What changes in CAN FD

CAN FD keeps arbitration exactly as above, then changes the rest of the frame:

Classical CANCAN FD
CRCCRC-15, polynomial 0x4599CRC-17 (0x1685B) for up to 16 data bytes, CRC-21 (0x102899) for more
Stuffing in the CRC fieldDynamic, after five equal bitsFixed stuff bits at set positions
Stuff countNoneA field that carries the number of dynamic stuff bits, so a receiver can detect a lost or extra stuff bit
Payload0 to 8 bytes0 to 64 bytes

The polynomials are from the CRC RevEng catalogue entries for CRC-17/CAN-FD and CRC-21/CAN-FD. The CAN FD guide covers the frame format and bit rate switch.

Reading it on a scope or logic analyser

  • Find SOF: the first falling edge after the bus has been idle (recessive).
  • Mark the stuff bits: after five equal bits, the next bit is always the opposite and is not data. Most protocol decoders mark them; if yours does not, remove them yourself before reading fields.
  • Check the ACK slot: if it stays recessive, no other node received the frame correctly. The transmitter reports an ACK error and repeats the frame. A single node on a bench always does this.
  • Measure one bit: at 500 kbit/s it is 2 µs. The bit timing guide explains what a wrong value means.

Frequently asked questions

What is bit stuffing in CAN?

After five consecutive bits of the same level, the transmitter inserts one bit of the opposite level, and the receiver removes it. It guarantees edges for resynchronisation. It applies from the start of frame to the end of the CRC sequence.

Is the CAN CRC calculated before or after bit stuffing?

Before. The CRC-15 covers the destuffed bits from the start of frame to the end of the data field. The stuff bits are added afterwards, over the CRC as well.

Why does the lowest CAN ID win arbitration?

Dominant bits (0) overwrite recessive bits (1) on the bus. All nodes send their ID bit by bit and stop when they send a 1 but read a 0. The ID with the first 0 where others have a 1, which is the numerically lowest ID, keeps sending.

How many stuff bits can a CAN frame have?

It depends on the data. Each stuff bit needs at least four further equal bits before the next one, so long runs of equal bits in the ID, DLC, data or CRC add more. Calculate it for your frames, as above, or use the worst case when planning bus load.

References