Skip to content
Physical AI
Chapter 05 26 min read

Robot Communication and Firmware

CAN bus, SocketCAN, virtual CAN, UDP and binary serialization — how bytes move between a robot computer and its motors.

A walking policy can decide what every joint should do. Its decisions are useless until they reach the motors, and it is blind until the motors' measurements come back. Everything between the robot computer and the actuators is communication: bytes on wires, packed in fixed formats, delivered after a delay that is never exactly the same twice. This chapter explains how that works, from firmware and the CAN bus to Linux sockets and binary packets, and why a learned controller has to be trained with the same timing it will experience on hardware.

What firmware is

Firmware is software that runs on a small embedded processor inside a device, usually a microcontroller, rather than on a general-purpose computer. It is called firm because it sits between hardware and ordinary software. It is stored in the device's flash memory, starts the moment power is applied, and is updated rarely.

On a robot, every motor driver (also called a motor controller or actuator driver) has firmware. A typical motor-driver firmware does a handful of jobs, in hard real time:

  • Reads sensors attached to the motor: the encoder that measures rotor angle, phase currents, supply voltage and temperature.
  • Runs control loops. The innermost loop regulates motor current, and therefore torque, often tens of thousands of times per second using field-oriented control. Outer loops can regulate velocity or position.
  • Communicates with the robot computer: receives commands and sends back measurements over a bus such as CAN.
  • Protects the hardware: limits current and temperature, and stops the motor if commands stop arriving (a communication timeout or watchdog).
General principle

The robot computer and the motor firmware run at very different rates. A locomotion policy might run at tens of hertz, a joint position loop at around a kilohertz, and a current loop at tens of kilohertz. Each layer hands the next a target and leaves the fast details to it. Exact rates vary by product.

LayerRuns onTypical jobTypical rate
Locomotion policyRobot computer (CPU/GPU)Observations → joint targets10s of Hz
Joint controlMotor-driver firmwareTarget → torque command (e.g. PD)100s of Hz – kHz
Current controlMotor-driver firmwareTorque command → phase voltages10s of kHz
PWM / power stageHardware peripheralsSwitching transistors10s of kHz

The rates in the table are general orders of magnitude, not Asimov's values. For Asimov, Menlo documents a 50 Hz policy and a 200 Hz IO path in simulation; Chapter 6 covers that in detail.

Why firmware matters for learned control

A policy trained in simulation never talks to motors directly. It talks to whatever interface the firmware exposes: a command format, a feedback format, update rates and delays. If the simulator models a different interface (say, perfect torque control with no delay) the policy learns for a robot that does not exist. That is why Menlo's processor-in-the-loop setup runs the real software interface against the simulator, as described at the end of this chapter.

How a robot computer communicates with motor controllers

A humanoid's legs might have a dozen motors spread over a metre of body. The robot computer sits in the torso. The simplest way to connect them would be a separate cable from the computer to each motor, but that scales badly: twelve motors would need twelve connectors on the computer, twelve cable runs through moving joints, and twelve sets of drivers.

Instead, robots use a shared communication bus: one pair of wires that runs past every motor controller, with each device tapping into it.

  1. Robot Computerpolicy, state estimation, SocketCAN
  2. CAN Bustwisted pair, shared by all nodes
  3. Motor Controllersfirmware: control loops, protection
  4. Encoders and Actuatorsmeasure angle, produce torque
Commands flow right (targets, modes); measurements flow left (position, velocity, current, temperature, faults).

Each arrow carries traffic in both directions:

  • Downstream (computer → motors): commanded joint targets, gains or modes, enable/disable.
  • Upstream (motors → computer): measured joint position and velocity, motor current or torque estimate, temperature, error flags.
  • Inside each motor controller: the firmware reads the encoder and drives the motor phases. Those signals never leave the actuator; only summaries go onto the bus.

What a communication bus is

A bus is a shared communication medium. All devices (called nodes) are connected to the same wires, and any node's transmission is seen by every other node. Two consequences follow:

  1. Only one node can transmit at a time. If two transmit at once, the bus needs a rule to decide who continues. This is called arbitration or medium access control.
  2. Messages must say what they are. Because everyone hears everything, each message carries an identifier so that receivers can pick out the ones they care about.

Different buses make different choices. Ethernet uses switches so that each cable is point-to-point. EtherCAT passes one frame through every device in a ring. RS-485 usually relies on a single master polling each device in turn. CAN (Controller Area Network) lets every node transmit whenever the bus is idle and resolves collisions without losing any bus time. That is a large part of why it is used so widely in cars, industrial machines and robot actuators.

CAN bus fundamentals

CAN was developed by Bosch in the 1980s for vehicles and standardised as ISO 11898. It is designed for short messages, harsh electrical environments and predictable priority.

CAN_H and CAN_L: differential signalling

A high-speed CAN bus is a twisted pair of wires called CAN_H (CAN high) and CAN_L (CAN low), terminated at each end with a 120 Ω resistor.

Information is carried by the difference between the two wires, not by either wire's voltage relative to ground:

Bus stateLogical bitCAN_H (typical)CAN_L (typical)Difference
Recessive1≈ 2.5 V≈ 2.5 V≈ 0 V
Dominant0≈ 3.5 V≈ 1.5 V≈ 2 V

This is differential signalling. Electrical noise from motors, switching power stages and cables usually couples onto both wires almost equally because they are twisted together. A receiver that subtracts CAN_L from CAN_H cancels that common-mode noise. You can switch on noise in the arbitration experiment below: both wires wobble, and the difference stays clean.

The 120 Ω terminations at the two physical ends of the bus match the cable's characteristic impedance, so that signal edges are absorbed instead of reflecting back and corrupting later bits. A bus with missing or extra terminations may work on the bench and fail intermittently on a robot.

Dominant and recessive bits

The names describe what happens when two nodes disagree. A transmitter sending a 0 actively drives the wires apart (dominant). A transmitter sending a 1 lets go and the terminations pull the wires together (recessive). If one node sends 0 and another sends 1 at the same moment, the bus shows 0: the dominant bit wins. Logically, the bus behaves like a wired-AND of every transmitter's bit.

This one electrical property makes CAN's arbitration possible.

CAN frames and identifiers

A CAN message is called a frame. A classical CAN data frame has these fields:

FieldBitsPurpose
Start of frame (SOF)1A dominant bit that synchronises all nodes
Identifier11 (or 29)What the message is, and its priority
RTR, IDE, r0 (control bits)3Remote request, identifier format, reserved
Data length code (DLC)4Number of data bytes, 0–8
Data0–64The payload, 0–8 bytes
CRC15 + 1 delimiterError detection
ACK1 + 1 delimiterAny receiver that got the frame correctly drives this bit dominant
End of frame (EOF)7Seven recessive bits
Intermission (IFS)3Minimum gap before the next frame

Standard 11-bit and extended 29-bit identifiers

CAN 2.0A uses an 11-bit identifier, so there are 2048 possible IDs (0x000–0x7FF). CAN 2.0B adds an extended 29-bit identifier (about 537 million IDs) at the cost of 20 extra bits per frame. Both formats can share a bus.

The identifier does not name a sender or a receiver. It names the content: "joint 3 feedback" rather than "from motor 3". Each receiver filters the IDs it cares about, often in hardware.

Arbitration: lower ID means higher priority

When the bus goes idle, any node with something to send starts its frame. If several start together, they all transmit their identifiers bit by bit, most significant bit first, and listen to the bus while they do:

  • A node that sends 1 (recessive) but reads 0 (dominant) knows another node is sending a lower ID. It stops immediately and becomes a receiver.
  • A node whose bits always match what it reads continues. At the end of the identifier exactly one node remains.

Because 0 is dominant, the numerically lowest identifier always wins. The winner's frame is never damaged, and no bus time is lost to the collision. This is called non-destructive bitwise arbitration. Losers simply retry when the bus is next idle.

Worked example with 11-bit IDs 0x120, 0x123 and 0x1F0:

  • 0x120 = 001 0010 0000
  • 0x123 = 001 0010 0011
  • 0x1F0 = 001 1111 0000

All three agree for the first three bits. On bit 7 (the fourth bit sent), 0x1F0 sends 1 while the others send 0, so 0x1F0 drops out. 0x120 and 0x123 agree until bit 1, where 0x123 sends 1 and 0x120 sends 0. 0x120 wins.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

Bitwise, non-destructive arbitration: why the lowest identifier always wins; and what a real classical CAN frame looks like bit by bit, with CRC, stuff bits and the CAN_H/CAN_L differential voltages.

How it works

Three nodes start transmitting at the same instant. On each identifier bit, the bus level is the wired-AND of everything being sent: a dominant 0 overrides a recessive 1. A node that sends 1 but reads 0 stops transmitting and becomes a receiver.

The winning frame is built exactly as a classical CAN 2.0A data frame: SOF, 11-bit identifier, RTR, IDE, r0, DLC, data, a CRC-15 computed over those bits, then bit stuffing (a complementary bit after five equal bits), and the fixed delimiter, ACK, end-of-frame and intermission bits. The waveform maps each bit to typical high-speed CAN voltages. Optional common-mode noise is added equally to both wires, so the differential signal is unchanged.

Adjustable parameters

  • Three 11-bit identifiers (hex)
  • Payload per node (0–8 bytes hex)
  • Common-mode noise on/off
  • Bit rate (125k, 500k, 1M)

Known limitations

  • Only identical-start arbitration on standard 11-bit data frames is shown; remote frames and extended-ID arbitration (SRR/IDE) are not animated.
  • Voltages are idealised square levels: no rise time, ringing or propagation delay.
  • The ACK slot is drawn as dominant, as it appears once at least one receiver has acknowledged.

Equations

busk=⋀i ∈ activebi,k(0=dominant)\text{bus}_k = \bigwedge_{i\,\in\,\text{active}} b_{i,k} \quad (0 = \text{dominant})
Vdiff=VCAN_H−VCAN_L≈{2 Vdominant0 VrecessiveV_{diff} = V_{CAN\_H} - V_{CAN\_L} \approx \begin{cases} 2\,\text{V} & \text{dominant} \\ 0\,\text{V} & \text{recessive} \end{cases}
CRC-15: x15+x14+x10+x8+x7+x4+x3+1\text{CRC-15: } x^{15}+x^{14}+x^{10}+x^{8}+x^{7}+x^{4}+x^{3}+1

Core update rule

for (let b = 0; b < 11; b++) {
  const levels = ids.map((id, i) => (active[i] ? (id >> (10 - b)) & 1 : null));
  const bus = levels.some((l) => l === 0) ? 0 : 1;   // wired-AND
  active = active.map((a, i) => a && levels[i] === bus); // sent 1, saw 0 → back off
}
// stuffing: after five equal bits insert the complement
if (run === 5) { out.push(1 - b); run = 1; }

Explained in Chapter 5: Communication & Firmware

Designing an identifier plan

Because ID is priority, choose IDs deliberately. Safety messages such as an emergency stop get the lowest IDs, then time-critical commands, then feedback, and diagnostics last. A design where feedback IDs are all higher than command IDs means feedback always waits until every command has gone out. You can see this in the bus experiment below.

Binary payloads

The data field is just 0–8 raw bytes in classical CAN. CAN itself attaches no meaning to them; the meaning is a convention shared by the firmware and the robot software. A motor driver's manual (or an internal specification) says, for example, "bytes 0–1: position target, signed 16-bit little-endian, 0.001 rad per count."

Illustrative example

A made-up feedback frame for joint 1, ID 0x181, 8 bytes:

BytesFieldTypeScale
0–1positionint16, little-endian0.001 rad per count
2–3velocityint16, little-endian0.01 rad/s per count
4–5currentint16, little-endian0.001 A per count
6temperatureuint81 °C per count
7status flagsuint8bit field

This layout and its identifiers are examples for teaching. They are not Asimov's protocol, which Menlo has not published.

Eight bytes is not much. Engineers fit the data by choosing compact integer types and scale factors instead of 4-byte floats. The section on serialization below explains the trade-off.

Classical CAN versus CAN FD

CAN FD (Flexible Data-rate), standardised in ISO 11898-1:2015, keeps CAN's arbitration and adds two things: bigger payloads and a faster data phase.

Classical CANCAN FD
Maximum payload8 bytes64 bytes (lengths 0–8, 12, 16, 20, 24, 32, 48, 64)
Bit rateOne rate, up to 1 Mbit/sNominal rate for arbitration; optional faster rate for the data phase (bit-rate switch, BRS)
Typical data-phase raten/a2–5 Mbit/s, sometimes higher
CRC15-bit17-bit (≤ 16 bytes) or 21-bit (> 16 bytes), plus a stuff-bit counter
ArbitrationBitwise, lowest ID winsSame

The arbitration phase must stay slow because every node on the bus has to see each bit at the same time during arbitration, and signals take time to travel along the cable. Once one node has won, only that node is transmitting, so the data can be sent faster.

Concrete comparison at a 1 Mbit/s nominal rate, using the worst-case bit counts computed in the next section: eight classical frames carrying 64 bytes take about 8 × 135 µs ≈ 1.08 ms. One CAN FD frame carrying the same 64 bytes with a 5 Mbit/s data phase takes roughly 140–170 µs. That is why newer actuators and robots often use CAN FD: one frame can carry several joints' worth of data.

Message timing

To reason about latency you need to know how long a frame occupies the bus.

Counting bits

For a classical frame with an 11-bit identifier and nn data bytes, the fields before the CRC delimiter (SOF through CRC) total 34+8n34 + 8n bits. After them come 10 fixed bits (CRC delimiter, ACK slot, ACK delimiter, 7 EOF) and a 3-bit intermission:

Nno stuffing=34+8n+13=47+8nN_{\text{no stuffing}} = 34 + 8n + 13 = 47 + 8n

For n=8n = 8, that is 111 bits (108 without the intermission). With a 29-bit identifier the stuffable part grows to 54+8n54 + 8n, giving 131 bits for 8 bytes.

Bit stuffing

CAN receivers recover timing from edges in the signal. A long run of identical bits has no edges, so the transmitter inserts a stuff bit of opposite value after every five identical bits, from SOF through the CRC. Receivers remove it automatically. Stuffing also doubles as an error check: six identical bits in that region can only mean an error.

The number of stuff bits depends on the data. In the worst case, each stuff bit starts a new run that is followed by four more identical bits, giving one stuff bit for every four bits after the first:

Nstuff, max=⌊34+8n−14⌋N_{\text{stuff, max}} = \left\lfloor \frac{34 + 8n - 1}{4} \right\rfloor

For n=8n = 8: ⌊97/4⌋=24\lfloor 97/4 \rfloor = 24 stuff bits, so a worst-case frame is 135 bits.

Frame time

At bit rate RR, the frame occupies the bus for T=N/RT = N/R:

Bit rateBit time8-byte frame, no stuffing8-byte frame, worst case
125 kbit/s8 µs888 µs1080 µs
500 kbit/s2 µs222 µs270 µs
1 Mbit/s1 µs111 µs135 µs

These numbers include the 3-bit intermission. Frame times are the same on every bus of that bit rate. They are a property of the protocol, not of any particular robot.

Worked example: bus load for 12 motors at 200 Hz

Illustrative example

Suppose a robot has 12 joint motors on one bus at 1 Mbit/s with 11-bit IDs. At every 200 Hz control tick, the computer sends each motor an 8-byte command and each motor replies with an 8-byte feedback frame. This traffic pattern is an assumption for the example, not Asimov's documented design.

  • Frames per second: 12×2×200=480012 \times 2 \times 200 = 4800
  • Worst-case bus time per second: 4800×135 μs=0.648 s4800 \times 135\,\mu s = 0.648\,s, so 64.8 % bus load
  • Without stuffing: 4800×111 μs=0.533 s4800 \times 111\,\mu s = 0.533\,s, so 53.3 %
  • Time to send all 24 frames of one tick: 24×135 μs=3.24 ms24 \times 135\,\mu s = 3.24\,ms, out of a 5 ms period

At 500 kbit/s the same traffic would need 130 % of the bus, which is impossible. Common fixes are to split the motors over two or more buses (for example one per leg), use CAN FD, or pack several joints into one frame.

Notice the last bullet. Even when the average load is fine, the frames of one tick are sent one after another. With the ID plan in the experiment below (commands 0x101–0x10C, feedback 0x181–0x18C), all 12 commands win arbitration before any feedback. The first motor's feedback arrives about 1.8 ms after the tick and the twelfth motor's about 3.2 ms after. Different joints' measurements describe different moments in time. That is the origin of the timing skew that Chapter 6 shows Asimov's simulator modelling.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

How a single shared CAN bus carries commands to, and feedback from, several motor controllers, how bus load grows with motor count and control rate, and why motors with higher identifiers get their feedback later.

How it works

A discrete-event scheduler models the bus. At every control tick the robot computer queues one command frame per motor (illustrative IDs 0x101, 0x102, …). Whenever the bus is idle, the pending frame with the lowest identifier wins arbitration and occupies the bus for its full frame time, computed from the frame format with worst-case bit stuffing.

When a motor controller receives its command it queues a feedback frame (IDs 0x181, …) after a short processing delay. The round trip is measured from the control tick to the moment the feedback frame finishes. If the offered load exceeds the bus capacity, the queue grows until frames are dropped.

The animation runs in slow motion: by default 2 ms of bus time per real second.

Adjustable parameters

  • Motor controllers (1–12)
  • Control rate (50–1000 Hz)
  • Nominal bit rate (125 kbit/s – 1 Mbit/s)
  • Classical CAN or CAN FD (2 or 5 Mbit/s data phase, 8–64 byte payload)
  • 11-bit or 29-bit identifiers
  • Slow-motion factor

Known limitations

  • Identifiers, payloads and the request–response pattern are illustrative, not Asimov's protocol.
  • Frame times use worst-case bit stuffing; real frames are usually a little shorter.
  • No error frames, retransmissions, bus-off handling or controller transmit-buffer effects.
  • The CAN FD bit count treats the bit-rate switch as whole bits, a small approximation.

Equations

Nbitsclassical=g+8n+13+⌊g+8n−14⌋,g=34 (11-bit), 54 (29-bit)N_{bits}^{classical} = g + 8n + 13 + \left\lfloor \tfrac{g + 8n - 1}{4} \right\rfloor,\quad g = 34\ (\text{11-bit}),\ 54\ (\text{29-bit})
Tframe=Nbits/RbitT_{frame} = N_{bits} / R_{bit}
U=∑ifi Tframe,i=2 Nmotors fctrl TframeU = \sum_i f_i\,T_{frame,i} = 2\,N_{motors}\,f_{ctrl}\,T_{frame}

Core update rule

// When the bus goes idle, the lowest pending ID wins (lib/sim/ch05-can.ts)
const ready = pending.filter((f) => f.tQueued <= now);
const win = ready.reduce((a, b) => (b.id < a.id ? b : a));
win.tStart = now;
win.tEnd = now + frameTime(spec, bitrate, dataBitrate);
// on completion: a delivered command makes that motor queue its feedback
if (win.kind === "cmd") pending.push(feedbackFrame(win.motor, win.tEnd + replyDelay));

Explained in Chapter 5: Communication & Firmware

Things to try:

  • Set 12 motors at 200 Hz, 1 Mbit/s and compare the calculated load with the worst round trip.
  • Drop the bit rate to 500k. The bus saturates, queues grow, and frames are eventually dropped.
  • Switch to CAN FD with a 5 Mbit/s data phase. The load falls even though the arbitration phase is unchanged.

Latency, jitter and stale observations

Latency is the time between something happening and the system acting on it. For a robot joint measurement, it accumulates along the whole path:

StageWhat adds delay
SensingEncoder sampling, filtering in firmware
Waiting for the busThe frame waits for the bus to be idle and for higher-priority frames to finish
TransmissionThe frame time itself (≈ 111–135 µs for 8 bytes at 1 Mbit/s)
ReceivingCAN controller, kernel driver, socket buffer, user-space wake-up
Waiting for the controllerThe measurement sits until the next policy step reads it
ComputingObservation construction and neural-network inference
Back to the actuatorCommand frame transmission, firmware handling, current loop response

Jitter is variation in latency from one message to the next. On CAN, a frame that becomes ready just after another frame starts must wait for that frame to finish, because transmission cannot be pre-empted. Operating-system scheduling, interrupt load and USB-to-CAN adapters add more. Jitter matters because a controller tuned for a constant delay can be surprised by a variable one, and because large jitter can make messages overtake each other.

A stale observation is a measurement that is older than the controller assumes. Every observation is somewhat stale. The question is by how much, and whether training saw the same thing. For a controller running at 50 Hz that reads the newest 200 Hz sensor packet, the observation age ranges from the transport latency up to roughly latency plus one sensor period, and more with jitter.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

Why the observation a controller uses is always older than the moment it is used, how fixed latency, jitter and the ratio between sensor and controller rates set that age, and how jitter can reorder packets.

How it works

A sensor samples a 3 Hz gyro signal and sends a timestamped packet at a fixed rate. Each packet's delay is the fixed latency plus a uniform random jitter. An event-driven model processes sends, arrivals and controller reads in time order.

At every controller tick, the controller uses the packet its receiver currently holds and records its age: read time minus send time. With the 'newest sequence' policy, a packet that arrives after a newer one is discarded; with 'last arrival', it replaces the newer value and the controller briefly goes backwards in time.

Adjustable parameters

  • Sensor rate (50–1000 Hz)
  • Fixed latency (0–30 ms)
  • Jitter (0–20 ms)
  • Controller rate (50/100/200 Hz)
  • Receiver policy
  • Playback speed

Known limitations

  • Jitter is uniform and independent per packet; real networks and buses have bursty, correlated delays.
  • Sensor and controller clocks are perfectly synchronised; real systems also drift.
  • All numbers are illustrative.

Equations

dk=L+J uk,uk∼U(0,1)d_k = L + J\,u_k,\quad u_k \sim \mathcal{U}(0,1)
age(t)=t−tj∗(t)send,j∗=arg⁡max⁡j{ seqj:tjsend+dj≤t }\text{age}(t) = t - t^{send}_{j^*(t)},\quad j^* = \arg\max_j \{\,\text{seq}_j : t^{send}_j + d_j \le t\,\}
L  ≤  age  ≲  L+J+1/fsendL \;\le\; \text{age} \;\lesssim\; L + J + 1/f_{send}

Core update rule

// next event in time order: arrival, send or read (lib/sim/ch05-link.ts)
if (arrival) {
  if (pk.seq > current.seq || receiver === "arrival") current = pk;
} else if (send) {
  inFlight.push({ seq: seq++, tSend: now, tArrive: now + latency + jitter * rng() });
} else {
  reads.push({ t: now, age: now - current.tSend, value: current.value });
}

Explained in Chapter 5: Communication & Firmware

Things to try:

  • Set jitter to 0 and watch the age readout. It cycles through a small set of values determined by the two rates.
  • Increase jitter beyond the 5 ms sensor period. Packets start arriving out of order (orange lines).
  • Switch the receiver to Last arrival. A late, older packet overwrites a newer one, so the controller's view briefly moves backwards in time.

“Latency only matters if it is large.”

A few milliseconds is small compared with human reaction time but not compared with a balance controller's time constants. A delay is a phase lag. It eats into the stability margin of every feedback loop it sits in, as the Chapter 1 experiment showed. Just as important, a policy trained without any delay has never learned to compensate for one.

SocketCAN on Linux

SocketCAN is the CAN subsystem of the Linux kernel. It presents every CAN interface (a PCIe card, a USB adapter, an on-chip controller, or a virtual bus) as a network interface like eth0, and lets programs send and receive frames through the ordinary BSD socket API. The same program works unchanged on real or virtual hardware.

Virtual CAN with vcan

The vcan kernel module creates a virtual CAN interface: a software bus inside the kernel with no hardware attached. Every frame sent on it is delivered to every socket bound to it. It is the standard way to develop and test CAN software, and it is the mechanism behind processor-in-the-loop testing, where a simulator plays the role of the motors.

Create a virtual CAN bus
sudo modprobe vcan                       # load the virtual CAN driver
sudo ip link add dev vcan0 type vcan     # create interface vcan0
sudo ip link set up vcan0                # bring it up
ip -details link show vcan0              # confirm it exists
bash

Install the user-space tools (can-utils on Debian/Ubuntu: sudo apt install can-utils) and open two terminals:

Terminal 1: watch all traffic
candump vcan0
bash
Terminal 2: send frames
cansend vcan0 123#DEADBEEF        # 11-bit ID 0x123, 4 data bytes
cansend vcan0 1F334455#1122       # 8 hex digits = 29-bit extended ID
cangen vcan0 -g 5                 # random frames every 5 ms
bash

Terminal 1 prints lines such as vcan0 123 [4] DE AD BE EF. Add -ta (candump -ta vcan0) to prefix each frame with an absolute timestamp.

CAN FD uses ## followed by a one-digit flags nibble (1 = bit-rate switch) and up to 64 data bytes. A virtual interface must first be switched to the CAN FD frame size:

CAN FD on vcan
sudo ip link set vcan0 mtu 72                 # enable CAN FD frames on vcan0
cansend vcan0 123##1DEADBEEFCAFEF00D0102030405060708
bash

On real hardware the interface also needs a bit rate, which vcan ignores:

A physical interface (example values)
sudo ip link set can0 type can bitrate 1000000
sudo ip link set can0 type can bitrate 1000000 dbitrate 5000000 fd on   # CAN FD
sudo ip link set up can0
bash

Sending and receiving from Python

Python's standard library supports SocketCAN directly. A classical frame in the kernel is a 16-byte struct can_frame: a 32-bit ID, a length byte, three padding bytes and 8 data bytes. The struct format "=IB3x8s" matches it.

raw_can.py — standard library only
import socket
import struct
 
CAN_FRAME = "=IB3x8s"           # can_id (u32), len (u8), 3 pad bytes, data[8]
 
sock = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
sock.bind(("vcan0",))
 
def send(can_id: int, data: bytes, extended: bool = False) -> None:
    if extended:
        can_id |= socket.CAN_EFF_FLAG   # mark a 29-bit identifier
    sock.send(struct.pack(CAN_FRAME, can_id, len(data), data.ljust(8, b"\x00")))
 
send(0x123, bytes([0xDE, 0xAD, 0xBE, 0xEF]))
 
frame = sock.recv(16)           # blocks until any frame arrives on vcan0
can_id, length, data = struct.unpack(CAN_FRAME, frame)
print(hex(can_id & socket.CAN_EFF_MASK), data[:length].hex())
python

The python-can library wraps this and adds filters, CAN FD, logging and many hardware back-ends:

python_can_example.py — pip install python-can
import struct
import can
 
with can.Bus(interface="socketcan", channel="vcan0") as bus:
    # Illustrative command: joint position target 0.25 rad, int16 at 0.001 rad/count
    payload = struct.pack("<h", round(0.25 / 0.001))
    bus.send(can.Message(arbitration_id=0x101, data=payload, is_extended_id=False))
 
    msg = bus.recv(timeout=1.0)          # None if nothing arrives within 1 s
    if msg is not None:
        print(f"{msg.timestamp:.6f} {msg.arbitration_id:03X} {msg.data.hex()}")
python

For CAN FD, open the bus with can.Bus(interface="socketcan", channel="vcan0", fd=True) and send can.Message(..., is_fd=True, bitrate_switch=True).

A frame you send is not echoed to your own socket

By default a raw CAN socket does not receive the frames it sent itself. In the examples above, recv returns frames from other programs on vcan0, so run cansend in another terminal to see something.

UDP communication

Not everything travels over CAN. Cameras, IMUs, network links between computers and simulator bridges commonly use Ethernet and IP. For streaming sensor data, the usual transport is UDP (User Datagram Protocol).

UDP sends independent messages called datagrams. It provides exactly two things on top of IP: port numbers, so that several programs can share one machine, and a checksum. It does not provide:

  • Delivery guarantees. A datagram can be dropped by a full buffer, a busy switch or a radio link, and nobody is told.
  • Ordering. Two datagrams can arrive in the opposite order to how they were sent.
  • Flow control or retransmission. The sender sends at whatever rate it chooses.

TCP provides all of these, by waiting for acknowledgements and retransmitting lost data. For control data, that is usually the wrong trade. A lost IMU sample from 5 ms ago is worthless once a newer one exists, and TCP would hold back every newer sample until the old one was re-sent (head-of-line blocking). With UDP the receiver simply uses the newest sample it has.

The price is that the application must handle loss and reordering itself, by putting a sequence number and a timestamp in every packet.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

What UDP does and does not guarantee: datagrams travel independently, can be lost or arrive out of order, and the receiver must use sequence numbers to detect and handle both.

How it works

The same link model as the latency experiment, slowed to a few packets per second. Each packet is drawn travelling from sender to receiver. Lost packets fall out of the network; packets that will overtake an older one are highlighted. The receive log lists packets in arrival order and marks those that arrived after a newer packet.

Adjustable parameters

  • Send rate (2–60 Hz)
  • Base latency (20–600 ms)
  • Jitter (0–400 ms)
  • Packet loss (0–50%)
  • Receiver policy

Known limitations

  • Timing is exaggerated (hundreds of milliseconds) so individual packets are visible; on a local machine or a robot's internal network, UDP latency is usually well under a millisecond.
  • Duplication, fragmentation and checksum failures are not modelled.

Equations

P(reorder)>0  ⟺  J>1/fsendP(\text{reorder}) > 0 \iff J > 1/f_{send}
expected loss=ploss Nsent\text{expected loss} = p_{loss}\,N_{sent}

Core update rule

data, addr = sock.recvfrom(64)
seq, t_us, *imu = struct.unpack("<IQ6f", data)
if seq <= last_seq:      # older than what we already have
    continue             # drop stale / duplicate datagram
lost += seq - last_seq - 1
last_seq = seq

Explained in Chapter 5: Communication & Firmware

Binary serialization and deserialization

Serialization turns values in memory into a sequence of bytes for transmission. Deserialization turns the bytes back into values. Text formats such as JSON are easy to read but slow to parse, large, and variable in size. Robot control links almost always use fixed binary layouts, where both sides agree in advance on the exact position, type and meaning of every byte.

Endianness

A multi-byte number has to be split into bytes in some order:

  • Little-endian: least significant byte first. The 16-bit value 0x1234 is sent as 34 12. x86 and most ARM processors store numbers this way in memory.
  • Big-endian (network byte order): most significant byte first, so 12 34. Many internet protocol headers use it.

Neither is better, but both ends must agree. If a little-endian int16 of 1000 (E8 03) is read as big-endian, the receiver gets 0xE803 = −6141. Floats fail even more spectacularly, as you can see in the inspector below.

Struct packing and alignment

Python's struct module and C structs describe layouts with a format. In Python, the first character sets byte order and alignment:

PrefixByte orderPadding
<little-endiannone ("standard" sizes)
> or !big-endiannone
=nativenone
@ (default)nativenative alignment, may insert padding

Always use an explicit < or > for data that crosses a wire. With @, the format "If" might be 8 bytes on one machine and different on another, and a C compiler may insert padding between struct fields for alignment. struct.calcsize(fmt) tells you the exact size.

Fixed-point scaling

A 32-bit float has about 7 significant decimal digits and costs 4 bytes. A joint angle rarely needs that. Fixed-point encoding transmits an integer that represents the value divided by a chosen scale:

q=round⁡(x/s),x^=q⋅s,∣x^−x∣≤s/2q = \operatorname{round}(x / s), \qquad \hat x = q \cdot s, \qquad |\hat x - x| \le s/2

With s=0.001s = 0.001 rad and a signed 16-bit integer, the range is ±32.767\pm 32.767 rad (far more than one turn) and the resolution 1 mrad, in 2 bytes instead of 4. The design questions are always the same: what range is needed, what resolution, and what should happen outside the range. Saturating (clipping) is safer than letting the integer wrap around from +32767 to −32768, which would turn a large positive angle into a large negative one.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

How numbers become bytes: integer and IEEE 754 float layouts, little- versus big-endian byte order, fixed-point scaling with its resolution, range and saturation, and a complete binary IMU packet.

How it works

Values are written with a JavaScript DataView, which uses exactly the same byte layouts as Python's struct module and C. In fixed-point mode the transmitted integer is round(value / scale), clipped to the type's range; the receiver multiplies by the scale again. The difference is the quantisation error, at most half a scale step unless the value saturates.

The IMU mode packs a sequence number, a microsecond timestamp and six float32 values in the illustrative layout "<IQ6f" (36 bytes) and decodes it twice: once with the correct byte order and once with the wrong one.

Adjustable parameters

  • Wire type (float32, float64, int8/16/32, uint8/16)
  • Value
  • Fixed-point scale (0.0001–0.1 per LSB)
  • Byte order
  • IMU gyro, accelerometer and sequence values

Known limitations

  • The IMU packet layout is an example, not Asimov's UDP format.
  • uint64 timestamps are shown only up to JavaScript's safe-integer range (2^53 µs, about 285 years).

Equations

q=clip⁡ ⁣(round⁡(x/s), qmin, qmax),x^=q sq = \operatorname{clip}\!\big(\operatorname{round}(x / s),\ q_{min},\ q_{max}\big), \qquad \hat x = q\,s
∣x^−x∣≤s/2(no saturation)|\hat x - x| \le s/2 \quad \text{(no saturation)}

Core update rule

import struct
raw = round(angle_rad / 0.001)            # fixed point, 1 mrad per LSB
payload = struct.pack("<h", raw)          # int16, little-endian
angle = struct.unpack("<h", payload)[0] * 0.001

packet = struct.pack("<IQ6f", seq, t_us, gx, gy, gz, ax, ay, az)  # 36 bytes

Explained in Chapter 5: Communication & Firmware

Worked example: IMU readings over UDP

Illustrative example

The following packet layout and port number are examples, not Menlo's protocol. Menlo documents that a MuJoCo bridge sends IMU readings to firmware over UDP, but not the packet format.

The packet holds a sequence number, a timestamp in microseconds, three gyroscope values (rad/s) and three accelerometer values (m/s²). The struct format "<IQ6f" is little-endian, I = uint32, Q = uint64, 6f = six float32: 4 + 8 + 24 = 36 bytes, with no padding.

OffsetSizeFieldType
04sequint32
48t_usuint64
1212gyro x, y, z3 × float32
2412accel x, y, z3 × float32
imu_sender.py
import math
import socket
import struct
import time
 
FMT = "<IQ6f"                    # seq, t_us, gx, gy, gz, ax, ay, az
DEST = ("127.0.0.1", 9870)       # illustrative address and port
RATE_HZ = 200
 
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
seq = 0
t0 = time.monotonic()
next_send = t0
 
while True:
    t = time.monotonic() - t0
    gyro = (0.0, 0.02 * math.sin(4 * t), 0.5 * math.sin(2 * math.pi * t))   # rad/s
    accel = (0.0, 0.0, 9.81)                                               # m/s^2
    t_us = time.monotonic_ns() // 1000    # shared monotonic clock on one machine
    packet = struct.pack(FMT, seq, t_us, *gyro, *accel)
    sock.sendto(packet, DEST)            # fire and forget: no connection, no ack
    seq = (seq + 1) & 0xFFFFFFFF
    next_send += 1.0 / RATE_HZ
    time.sleep(max(0.0, next_send - time.monotonic()))
python
imu_receiver.py
import socket
import struct
import time
 
FMT = "<IQ6f"
SIZE = struct.calcsize(FMT)      # 36
 
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("127.0.0.1", 9870))
 
last_seq = None
lost = 0
while True:
    data, addr = sock.recvfrom(1024)
    if len(data) != SIZE:
        continue                         # not our packet type
    seq, t_us, gx, gy, gz, ax, ay, az = struct.unpack(FMT, data)
    if last_seq is not None:
        if seq <= last_seq:              # older or duplicate: ignore (32-bit wrap ignored for brevity)
            continue
        lost += seq - last_seq - 1       # gaps in seq = lost datagrams
    last_seq = seq
    age_ms = (time.monotonic_ns() // 1000 - t_us) / 1000.0
    print(f"seq={seq} gz={gz:+.3f} rad/s age={age_ms:.2f} ms lost={lost}")
python

Three details are worth copying into real code:

  1. Check the length before unpacking. struct.unpack raises an error on a wrong-sized buffer, and any process can send to an open port.
  2. Use the sequence number to drop stale packets and count losses. Handle the wrap from 2³²−1 to 0 if the stream runs long enough.
  3. Timestamp at the source. The age printed above is only meaningful because both programs read the same monotonic clock on one machine. Across machines you need clock synchronisation (for example PTP) or a round-trip measurement.

How this connects to Asimov

Menlo describes how Asimov's simulator reuses exactly these mechanisms to test the real software stack against simulated physics.

  • In processor-in-the-loop testing, joint communication runs over virtual CAN via SocketCAN, the same software interface used by the real actuator stack.
  • A MuJoCo bridge reads the simulated IMU's angular velocity and linear acceleration (imu_ang_vel, imu_lin_acc) and sends them to the firmware over UDP. The FusionX sensor-processing path then computes the projected gravity that the policy observes.
  • Joint position and velocity observations are grouped by CAN timing groups (groups 1–3). Delay and timing skew are modelled, and CAN delay and jitter injection is used to test timing robustness.
  • Bus jitter and stale observations are called out as major sources of sim-to-real failure.

The pages do not publish CAN identifiers, bit rates, packet formats or UDP ports.

Chapter 6 builds on this chapter to explain Asimov's timing architecture and the processor-in-the-loop pipelines.

Limitations and common misconceptions

“CAN is slow, so it adds a lot of latency.”

One 8-byte frame at 1 Mbit/s takes about 0.1 ms. The latency that hurts usually comes from queuing behind other frames, from the software stack, and from waiting for the next control step, not from the wire. Measure before blaming the bus.

“The bus is either fast enough or it isn't.”

Average bus load can be comfortable while individual messages still arrive late. Frames within one control tick are serialised, so the last joint's data is always older than the first's. Worst-case response time, not average load, is what matters for control.

“UDP is unreliable, so it is bad for robots.”

For periodic sensor and command streams, "unreliable" is often exactly right: a late retransmission of old data is worse than nothing. Reliability is added where it is needed, for example acknowledged configuration messages.

What the simulations here do not show

The experiments model timing at the protocol level. They omit error frames, error counters and bus-off, electrical effects (ringing, propagation delay, ground offsets), operating-system scheduling, and adapter buffering. All identifiers, payloads, rates and delays used here are illustrative.

Key takeaways

Key takeaways

  • Firmware on each motor controller runs the fast loops and protection. The robot computer sends targets and receives measurements over a bus.
  • CAN carries bits as the voltage difference between CAN_H and CAN_L. Dominant 0 overrides recessive 1, which gives non-destructive arbitration: the lowest identifier wins.
  • An 8-byte classical CAN frame is 111–135 bits including stuffing and intermission, about 111–135 µs at 1 Mbit/s. CAN FD adds payloads up to 64 bytes and a faster data phase.
  • Bus load = frames per second × frame time. Twelve motors with command and feedback at 200 Hz use about 53–65 % of a 1 Mbit/s bus.
  • Latency, jitter and serialised transmission mean every observation is stale by some amount, and different joints are stale by different amounts.
  • SocketCAN makes CAN interfaces look like network interfaces; vcan provides a virtual bus for testing; can-utils and python-can are the everyday tools.
  • UDP gives low-latency datagrams without ordering or delivery guarantees. Put sequence numbers and timestamps in every packet.
  • Binary formats must fix byte order, sizes and scaling explicitly. Use < or > in struct formats, never native alignment.

References and further reading