Who wins arbitration?
Simulate bitwise arbitration: dominant zeros win, and losers stop at the first difference. A medium embedded C problem (CAN), run and graded in the browser.
medium · CAN · can · arbitration · bits
When several CAN nodes start sending at once, they arbitrate on the ID, bit by bit from the most significant (bit 10). The bus is a wired-AND: a 0 is dominant and overrides a 1. Each node reads the bus back; a node that sent 1 but reads 0 has lost, and stops sending. Nobody's frame is damaged: the winner carries on.
Write can_arbitrate(ids, n, lost_at): return the index of the winning node, and set lost_at[i] to the bit number (10 down to 0) at which node i dropped out, or -1 for the winner. All IDs are different.
Starter code
int can_arbitrate(const uint16_t *ids, int n, int *lost_at) {
int best = 0;
for (int i = 1; i < n; i++) if (ids[i] > ids[best]) best = i;
for (int i = 0; i < n; i++) lost_at[i] = -1;
return best;
}Example tests
Two nodes
uint16_t ids[] = { 0x123, 0x0F0 };
show(ids, 2);Expected output:
winner 0x0F0; 0x123 lost at bit 8;Three nodes
uint16_t ids[] = { 0x7FF, 0x400, 0x401 };
show(ids, 3);Expected output:
winner 0x400; 0x7FF lost at bit 9; 0x401 lost at bit 0;Learn it first
- CAN · Arbitration, bit timing, frames, CAN FD and error handling.
More CAN problems
- Acceptance filter · Decide whether a frame passes an ID-and-mask filter.
- Pack a signal into a frame · Place a little-endian signal of any length at any bit, without disturbing the others.
- Decode a scaled signal · Turn a raw signal into a physical value with sign, factor and offset.
- Electric car: decode the battery's CAN frame · Decode voltage, current, charge and status from the battery management system's CAN frame.