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).
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.
| Layer | Runs on | Typical job | Typical rate |
|---|---|---|---|
| Locomotion policy | Robot computer (CPU/GPU) | Observations → joint targets | 10s of Hz |
| Joint control | Motor-driver firmware | Target → torque command (e.g. PD) | 100s of Hz – kHz |
| Current control | Motor-driver firmware | Torque command → phase voltages | 10s of kHz |
| PWM / power stage | Hardware peripherals | Switching transistors | 10s 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.
- Robot Computerpolicy, state estimation, SocketCAN
- CAN Bustwisted pair, shared by all nodes
- Motor Controllersfirmware: control loops, protection
- Encoders and Actuatorsmeasure angle, produce torque
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:
- 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.
- 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 state | Logical bit | CAN_H (typical) | CAN_L (typical) | Difference |
|---|---|---|---|---|
| Recessive | 1 | ≈ 2.5 V | ≈ 2.5 V | ≈ 0 V |
| Dominant | 0 | ≈ 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:
| Field | Bits | Purpose |
|---|---|---|
| Start of frame (SOF) | 1 | A dominant bit that synchronises all nodes |
| Identifier | 11 (or 29) | What the message is, and its priority |
| RTR, IDE, r0 (control bits) | 3 | Remote request, identifier format, reserved |
| Data length code (DLC) | 4 | Number of data bytes, 0–8 |
| Data | 0–64 | The payload, 0–8 bytes |
| CRC | 15 + 1 delimiter | Error detection |
| ACK | 1 + 1 delimiter | Any receiver that got the frame correctly drives this bit dominant |
| End of frame (EOF) | 7 | Seven recessive bits |
| Intermission (IFS) | 3 | Minimum 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.
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."
A made-up feedback frame for joint 1, ID 0x181, 8 bytes:
| Bytes | Field | Type | Scale |
|---|---|---|---|
| 0–1 | position | int16, little-endian | 0.001 rad per count |
| 2–3 | velocity | int16, little-endian | 0.01 rad/s per count |
| 4–5 | current | int16, little-endian | 0.001 A per count |
| 6 | temperature | uint8 | 1 °C per count |
| 7 | status flags | uint8 | bit 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 CAN | CAN FD | |
|---|---|---|
| Maximum payload | 8 bytes | 64 bytes (lengths 0–8, 12, 16, 20, 24, 32, 48, 64) |
| Bit rate | One rate, up to 1 Mbit/s | Nominal rate for arbitration; optional faster rate for the data phase (bit-rate switch, BRS) |
| Typical data-phase rate | n/a | 2–5 Mbit/s, sometimes higher |
| CRC | 15-bit | 17-bit (≤ 16 bytes) or 21-bit (> 16 bytes), plus a stuff-bit counter |
| Arbitration | Bitwise, lowest ID wins | Same |
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 data bytes, the fields before the CRC delimiter (SOF through CRC) total bits. After them come 10 fixed bits (CRC delimiter, ACK slot, ACK delimiter, 7 EOF) and a 3-bit intermission:
For , that is 111 bits (108 without the intermission). With a 29-bit identifier the stuffable part grows to , 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:
For : stuff bits, so a worst-case frame is 135 bits.
Frame time
At bit rate , the frame occupies the bus for :
| Bit rate | Bit time | 8-byte frame, no stuffing | 8-byte frame, worst case |
|---|---|---|---|
| 125 kbit/s | 8 µs | 888 µs | 1080 µs |
| 500 kbit/s | 2 µs | 222 µs | 270 µs |
| 1 Mbit/s | 1 µs | 111 µs | 135 µ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
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:
- Worst-case bus time per second: , so 64.8 % bus load
- Without stuffing: , so 53.3 %
- Time to send all 24 frames of one tick: , 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.
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:
| Stage | What adds delay |
|---|---|
| Sensing | Encoder sampling, filtering in firmware |
| Waiting for the bus | The frame waits for the bus to be idle and for higher-priority frames to finish |
| Transmission | The frame time itself (≈ 111–135 µs for 8 bytes at 1 Mbit/s) |
| Receiving | CAN controller, kernel driver, socket buffer, user-space wake-up |
| Waiting for the controller | The measurement sits until the next policy step reads it |
| Computing | Observation construction and neural-network inference |
| Back to the actuator | Command 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.
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.
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 existsInstall the user-space tools (can-utils on Debian/Ubuntu: sudo apt install can-utils) and open two terminals:
candump vcan0cansend 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 msTerminal 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:
sudo ip link set vcan0 mtu 72 # enable CAN FD frames on vcan0
cansend vcan0 123##1DEADBEEFCAFEF00D0102030405060708On real hardware the interface also needs a bit rate, which vcan ignores:
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 can0Sending 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.
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())The python-can library wraps this and adds filters, CAN FD, logging and many hardware back-ends:
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()}")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.
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:
| Prefix | Byte order | Padding |
|---|---|---|
< | little-endian | none ("standard" sizes) |
> or ! | big-endian | none |
= | native | none |
@ (default) | native | native 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:
With rad and a signed 16-bit integer, the range is 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.
Worked example: IMU readings over UDP
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.
| Offset | Size | Field | Type |
|---|---|---|---|
| 0 | 4 | seq | uint32 |
| 4 | 8 | t_us | uint64 |
| 12 | 12 | gyro x, y, z | 3 × float32 |
| 24 | 12 | accel x, y, z | 3 × float32 |
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()))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}")Three details are worth copying into real code:
- Check the length before unpacking.
struct.unpackraises an error on a wrong-sized buffer, and any process can send to an open port. - 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.
- 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
- Menlo, Understanding Your Simulation Environment, the Asimov processor-in-the-loop description.
- Linux kernel documentation, SocketCAN — Controller Area Network.
- linux-can/can-utils on GitHub:
candump,cansend,cangen,canbusload. - python-can documentation, including the SocketCAN interface.
- Python documentation:
struct— interpret bytes as packed binary data andsocket— low-level networking interface (includes a SocketCAN example). - Robert Bosch GmbH, CAN Specification Version 2.0 (1991), and ISO 11898-1 (data link layer, including CAN FD since 2015) and ISO 11898-2 (high-speed physical layer).
- Robert Bosch GmbH, CAN with Flexible Data-Rate Specification, version 1.0 (2012).
- R. I. Davis, A. Burns, R. J. Bril and J. J. Lukkien, "Controller Area Network (CAN) schedulability analysis: Refuted, revisited and revised," Real-Time Systems 35, 2007. Source of the worst-case stuffing formula used here.
- J. Postel, RFC 768: User Datagram Protocol (1980).