CAN
Arbitration, bit timing, frames, CAN FD and error handling.
A bus built for cars
CAN (Controller Area Network) connects dozens of controllers over one twisted pair in a noisy environment: cars, trucks, industrial machines, medical devices, robots. It was designed for reliability under interference and predictable timing, which shows up in every part of the protocol.
Physical layer
- Two wires, CAN_H and CAN_L, twisted together, driven differentially by a transceiver chip (the MCU's CAN controller does not connect to the bus directly).
- Dominant (logic 0): CAN_H about 3.5 V, CAN_L about 1.5 V. Recessive (logic 1): both about 2.5 V, not driven.
- A 120 Ω terminating resistor at each end of the bus (measure about 60 Ω between CAN_H and CAN_L with power off).
- Speed is limited by bus length: 1 Mbit/s up to about 40 m, 125 kbit/s up to about 500 m.
Because a dominant bit overrides a recessive one, the bus behaves like a wired-AND, and this is what makes arbitration work.
Frames
A classic CAN data frame carries up to 8 bytes:
| Field | Bits | Notes |
|---|---|---|
| Start of frame | 1 | Dominant |
| Identifier | 11 (standard) or 29 (extended) | Names the message and sets its priority |
| RTR | 1 | Remote request (rarely used) |
| Control | 6 | Includes DLC: data length 0 to 8 |
| Data | 0 to 64 | |
| CRC | 15 + delimiter | |
| ACK | 2 | Any receiver drives dominant to acknowledge |
| End of frame | 7 | Recessive |
The identifier says what the data is ("engine speed"), not who sent it or who should receive it. Every node sees every frame and uses acceptance filters in hardware to keep only the IDs it cares about.
Arbitration: lowest ID wins, nobody loses data
When two nodes start transmitting at the same time, each sends its identifier bit by bit while reading the bus. A node that sends recessive (1) but reads dominant (0) knows a higher-priority message is on the bus, stops, and becomes a receiver. The winner never notices: its frame continues undamaged. This is non-destructive bitwise arbitration, and it makes the lowest numeric ID the highest priority.
#include <stdio.h>
#include <stdint.h>
/* Simulate three nodes starting an 11-bit identifier at the same moment. */
int main(void) {
uint16_t ids[3] = { 0x1A4, 0x0F3, 0x0F7 };
int active[3] = { 1, 1, 1 };
for (int bit = 10; bit >= 0; bit--) {
int bus = 1; /* recessive unless someone drives 0 */
for (int n = 0; n < 3; n++)
if (active[n] && !((ids[n] >> bit) & 1)) bus = 0;
for (int n = 0; n < 3; n++)
if (active[n] && ((ids[n] >> bit) & 1) && bus == 0) {
active[n] = 0;
printf("bit %2d: node 0x%03X sent 1, saw 0 -> backs off\n", bit, ids[n]);
}
}
for (int n = 0; n < 3; n++) if (active[n]) printf("winner: 0x%03X\n", ids[n]);
return 0;
}
Consequences for system design: assign IDs by urgency, and remember that a low-priority message can be delayed indefinitely by a busy bus. Worst-case response time analysis for CAN is a well-studied field.
Bit timing
Each bit is divided into time quanta (tq) derived from the CAN peripheral clock:
| SYNC (1 tq) | PROP + PHASE1 (tseg1) | PHASE2 (tseg2) |
^ sample point
- Bit rate =
f_can / (prescaler * (1 + tseg1 + tseg2)). - The sample point is typically placed at 75% to 87.5% of the bit (CANopen and automotive recommend about 87.5%). All nodes on a bus should use similar sample points.
- Nodes resynchronise on recessive-to-dominant edges, adjusting by up to SJW (synchronisation jump width) quanta.
- Bit stuffing: after five identical bits the transmitter inserts an opposite bit, guaranteeing edges for resynchronisation. Receivers remove them.
Because every node samples the same bit at nearly the same time, oscillator accuracy matters: use a crystal, not an internal RC oscillator.
Error handling
CAN detects errors with five mechanisms: bit monitoring, stuff-rule check, CRC, form check and missing acknowledgement. A node that detects one sends an error frame, which destroys the current frame on every node; the transmitter then retries automatically.
To stop a faulty node from jamming the bus, each node keeps a transmit (TEC) and receive (REC) error counter:
| State | Condition | Behaviour |
|---|---|---|
| Error active | TEC and REC < 128 | Normal; signals errors with dominant error flags |
| Error passive | TEC or REC ≥ 128 | Signals errors with recessive flags (cannot disturb others); waits longer between transmissions |
| Bus off | TEC ≥ 256 | Disconnects from the bus; recovery after 128 × 11 recessive bits, and usually software decides |
Successful frames decrement the counters, so occasional errors heal themselves.
Pitfall: A node alone on the bus (or with no other node powered) never gets an ACK, so it retransmits forever and climbs to error passive. "CAN works on the bench with two boards but not with one" is this, not a bug.
CAN FD
CAN FD (flexible data rate) keeps arbitration at the classic rate but can switch to a faster bit rate (2 to 8 Mbit/s) for the data phase, and carries up to 64 bytes per frame with a stronger CRC. It is backwards-compatible on the wire only if every node is FD-capable; a classic controller sees FD frames as errors.
Higher-layer protocols
Raw CAN only defines frames. Real systems add a protocol on top: CANopen (industrial), J1939 (trucks, agriculture; 29-bit IDs), ISO-TP (ISO 15765-2, segments messages longer than 8 bytes, used by UDS diagnostics), and car makers' own DBC-described signal databases.
Interview question: Explain CAN arbitration and why it is called non-destructive.
Answer: All nodes wait for an idle bus and may start together. Each transmits its identifier bit by bit while monitoring the bus. Dominant (0) overrides recessive (1), so a node that transmits recessive but reads dominant knows another node has a lower, higher-priority identifier; it stops and becomes a receiver. The winning node's frame is never corrupted, so no bandwidth is lost to collisions, unlike Ethernet's collision-and-retry. The result is that the lowest identifier always wins.
Interview question: What are the CAN error states and why do they exist?
Answer: Each node has transmit and receive error counters that rise on errors and fall on successful frames. Below 128 it is error active and reports errors with active (dominant) error flags. At 128 or more it becomes error passive and can only signal errors passively, so it cannot disrupt other nodes. If the transmit counter reaches 256 it goes bus off and stops participating until a recovery sequence. The purpose is fault confinement: a node with a broken transceiver or wrong bit rate isolates itself instead of jamming the whole bus.
Build it: read the battery from the scooter's CAN bus
This is step 5, the last of the module project. The scooter's battery management system (BMS) broadcasts the pack's state on the scooter's CAN bus. The tracker listens, so the fleet server knows each scooter's charge and spots a dangerous battery before it fails.
Lab: Decode the battery frame and raise alarms
The BMS sends a frame with standard identifier 0x355 ten times a second. Its data sheet gives the layout, with every multi-byte value big-endian (most significant byte first), the usual order on CAN:
| Bytes | Signal | Scaling |
|---|---|---|
| 0-1 | pack voltage | unsigned, 0.01 V per bit |
| 2-3 | pack current | signed, 0.1 A per bit, negative while charging |
| 4 | state of charge | 0 to 100 % |
| 5 | hottest cell temperature | °C + 40 (so 0 means -40 °C) |
Other identifiers share the bus and must be ignored.
bms_decode(f, out)returns false for any frame that is not0x355, or that has fewer than 6 data bytes (dlc). Otherwise it fills inoutand returns true. Keep voltage in centivolts and current in deci-amps, as whole numbers.bms_alarms(b)returns a bit mask:ALARM_LOW_BATTERYwhen the charge is below 10 %,ALARM_HOTwhen the hottest cell is above 60 °C, andALARM_OVERCURRENTwhen the current is more than 30.0 A in either direction.
Going deeper
Interview question: How would you design the CAN messages for an electric vehicle's battery pack?
Answer: List each signal the other ECUs need, its range, resolution and update rate, then group signals by sender and rate into frames with priorities (IDs) that match urgency. Define everything in a DBC file and generate code from it, add a rolling counter and CRC to safety-relevant frames, and specify what receivers do on timeout. Check the bus load stays well under 50 %.
Interview question: How do CAN acceptance filters reduce CPU load?
Answer: Every node receives every frame on the bus. Hardware acceptance filters, configured with identifier lists or ID-and-mask pairs, let the CAN controller store only the frames whose identifiers the node cares about and silently drop the rest, so the CPU is not interrupted for hundreds of irrelevant frames per second. Filters are usually assigned to receive FIFOs, giving some prioritisation too.
Interview question: Why can't a single CAN node test transmission alone on the bench?
Answer: A transmitter expects at least one other node to drive a dominant bit in the ACK slot. Alone on the bus, nobody acknowledges, so it flags an ACK error and retransmits forever, its transmit error counter climbing to error passive. Use a second node, a CAN analyser, or the controller's loopback or silent loopback test mode.
Explain it: In your own words, explain why the lowest CAN identifier wins arbitration without any frame being destroyed.
Answer: All nodes start transmitting together and send their identifier bit by bit while listening. A 0 bit is dominant and overrides a 1, so the bus carries a 0 whenever anyone sends one. A node that sends a 1 but hears a 0 knows another node has a lower identifier, so it stops and becomes a receiver. The node still sending never sees a conflict, so its frame continues undamaged, and the lowest identifier, the one with 0 at the first differing bit, always wins.