How the sensors, boards and motor drives of a robot talk to each other: bits and frames, the serial port, I²C and SPI on the board, the CAN bus between motors, RS-485 and Modbus in industry, errors and CRCs, and how to choose and debug the network of a real robot. Every bus is drawn on a logic analyser, bit by bit, and you can step through each frame.
How to use this course
Each lesson gives the idea in one sentence, then the wiring, the frame and a worked example with real numbers, then a lab: press ▶ to send a frame one bit at a time and read what each bit means, change the settings to break the link on purpose, and meet the challenge. Only prerequisite: the electronics course (voltage, a microcontroller pin, an Arduino sketch).
1
Bits, wires and buses: how the parts of a robot talk
20 min
You will learn
why a robot is a network, how a number becomes bits, serial against parallel, the baud rate and the time of one bit, and the words used for every bus: synchronous, differential, half and full duplex, master and slave, protocol layers.
In one sentence
Inside a robot, sensors, boards and motor drives exchange numbers all the time; each number travels as bits, one after another on a few wires, following an agreement on speed, format and turn-taking: a protocol.
1.1 Who talks to whom
Link
What travels
How often
Usual bus
IMU → microcontroller
3 accelerations, 3 angular speeds (12 bytes)
100 to 1000 times a second
I²C, SPI
Joint encoder → microcontroller
one angle (2 bytes)
up to 10 000 times a second
SPI
Microcontroller ↔ motor drives
set-points, then speed, current, errors
1000 times a second
CAN, EtherCAT
Computer ↔ microcontroller
commands, odometry, logs
10 to 100 times a second
USB, UART
PLC ↔ conveyor drive, gripper
start, stop, speed, status
10 times a second
Modbus (RS-485 or TCP)
1.2 From a number to bits
A bit is 0 or 1: on a wire, a LOW or a HIGH voltage. A byte is 8 bits, a number from 0 to 255. We often write bytes in hexadecimal (base 16, digits 0–9 then A–F): two hex digits = one byte, each digit = 4 bits. Text uses the ASCII code: the letter A is 65.
A bigger number takes several bytes: a 16-bit encoder angle of 1500 is 0x05DC, sent as the two bytes 0x05 and 0xDC. Which one goes first (the byte order, or endianness) is part of the protocol: big-endian sends 0x05 first, little-endian 0xDC first.
1.3 Serial or parallel, one way or two
Robots use serial links almost everywhere: few wires, light cables through the joints, and long distances. The speed of a serial link is its bit rate, often called the baud rate (bits per second for the simple buses of this course). The time of one bit is its inverse.
Tbit = 1 / baud Tmessage = number of bits × Tbit
1.4 The words of every bus
Word
Meaning
Examples
Synchronous
a clock wire tells when to read each bit
I²C, SPI
Asynchronous
no clock wire: both sides agree on the bit rate and resynchronise on edges
UART, CAN, RS-485
Single-ended
one wire, measured against ground: simple, sensitive to noise
UART TTL, I²C, SPI
Differential
two wires with opposite signals; the receiver reads the difference, so noise common to both cancels
CAN, RS-485, Ethernet, USB
Point-to-point / bus
two devices only, or many devices sharing the same wires (multidrop)
UART / I²C, CAN, RS-485
Master-slave
one master starts every exchange; slaves only answer (new names: controller and target, client and server)
I²C, SPI, Modbus
Multi-master
any node may start talking; a rule decides who wins if two start together
CAN
Every protocol has layers. The physical layer says which voltages and wires (TTL, RS-485, CAN transceiver). The data link layer says how bits make a frame: start, address, data, error check. The application layer says what the numbers mean: “register 1 is the motor speed in rpm” (Modbus, CANopen). Many bugs are a mismatch in one layer only: right wires, wrong meaning.
Worked example
A robot sends 20 bytes of state at 115 200 baud, with 10 bits per byte on the wire (lesson 2). One bit: 1 / 115 200 = 8.68 µs. One byte: 86.8 µs. The 20 bytes: 1.74 ms. A 1 kHz control loop has 1 ms per cycle: this link is too slow for it. Options: send fewer bytes, raise the baud rate (1 Mbaud → 0.2 ms), or use a faster bus.
The essentials
A robot is a network: sensors, boards and drives exchange numbers as bits.
1 byte = 8 bits = 2 hex digits; A = 65 = 0x41.
Tbit = 1 / baud; the time of a message = its number of bits × Tbit.
Synchronous = a clock wire; differential = two opposite wires, robust to noise.
Physical, data link and application layers: check each one when a link fails.
Key terms
bit, byte, hexadecimal
serial, parallel
baud rate, bit time
synchronous, asynchronous
single-ended, differential
simplex, half duplex, full duplex
master, slave
protocol, frame, layer
byte order (endianness)
Exercises
Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.
Level 1 · Beginner1
Write the byte 0xB6 in binary.
1011 0110
1101 0110
1011 1100
0110 1011
Solution
Rule usedeach hex digit is 4 bits: B = 1011, 6 = 0110lesson 1 — 1.2 From a number to bits
B = 11 = 8 + 2 + 1 → 1011.
6 = 4 + 2 → 0110.
Put them side by side: 1011 0110 (= 182).
AnswerA: 1011 0110
Level 1 · Beginner2
What is the time of one bit at 19 200 baud, in µs?
Solution
Rule usedTbit = 1 / baudlesson 1 — 1.3 (formula)
1 / 19 200 = 0.0000521 s.
× 10⁶ → 52.1 µs.
Answer≈ 52.1 µs
Level 2 · Intermediate3
A robot must send 12 bytes every 2 ms over a UART in 8N1 (10 bits per byte on the wire). What is the smallest baud rate that fits, in baud?
Hint
Count the bits to send, then divide by the time you have.
Solution
Rule usedbaud ≥ bits / timelesson 1 — 1.3 and the worked example
Bits: 12 × 10 = 120 bits.
120 bits in 2 ms → 120 / 0.002 = 60 000 bit/s.
The next standard rate above is 115 200 baud (57 600 is too low).
Answer60 000 baud minimum: use 115 200
Check yourself
Why do robots prefer serial links to parallel ones?
Fewer wires through the joints and over long cables, and no skew between 8 wires.
What is the time of one bit at 1 Mbit/s?
1 µs.
Why is a differential pair robust to noise?
Noise hits both wires almost equally; the receiver reads the difference, in which the noise cancels.
2
UART: the serial port, bit by bit
25 min
You will learn
how to wire two UARTs, the frame (start bit, data least significant bit first, parity, stop bit), why both sides need the same baud rate and how much error is allowed, TTL and RS-232 levels, and how to send whole messages over a stream of bytes.
In one sentence
A UART sends bytes on one wire (TX) and receives on another (RX), with no clock: each byte is wrapped in a start bit 0 and a stop bit 1, and both sides must use the same baud rate and format.
2.1 Wiring
UART means Universal Asynchronous Receiver-Transmitter: the block inside the microcontroller that turns bytes into a serial signal and back. It is full duplex and point-to-point: one TX talks to one RX. A USB-serial adapter (FTDI, CH340, CP2102) shows the UART of a board to a computer as a COM port (Windows) or /dev/ttyUSB0 (Linux).
Level
Logic 1 (and idle)
Logic 0
Distance
TTL 5 V (Arduino Uno)
5 V
0 V
≈ 1 m
TTL 3.3 V (ESP32, Raspberry Pi, STM32)
3.3 V
0 V
≈ 1 m
RS-232 (old PC port, DB9)
−3 to −15 V (inverted!)
+3 to +15 V
≈ 15 m
RS-485 (lesson 6)
A − B > +0.2 V
A − B < −0.2 V
up to 1200 m
Never connect directly
A 5 V TX into a 3.3 V RX can damage it (use a level shifter or a divider), and an RS-232 port (±12 V) into a TTL pin destroys it (use a MAX232-type chip).
2.2 The frame
Idle: the line rests HIGH.
Start bit: one bit LOW. Its falling edge wakes the receiver up.
Data: 5 to 9 bits (almost always 8), least significant bit first.
Parity (optional): one bit that makes the number of 1s even (E) or odd (O).
Stop bit(s): 1 or 2 bits HIGH, so that the next start makes a new falling edge.
The format is written like 8N1: 8 data bits, No parity, 1 stop bit. That is 10 bits on the wire for 8 useful bits, so a UART carries at most baud / 10 bytes per second: 11 520 bytes/s at 115 200 baud. Modbus RTU uses 8E1 (11 bits).
2.3 How the receiver reads without a clock
The receiver watches the line about 16 times per bit. On the falling edge of the start bit it starts a timer, then reads each bit in its middle: at 1.5, 2.5, 3.5 … bit times. If its clock runs a little fast or slow, the reading points drift; at the stop bit (9.5 bits after the edge in 8N1) the drift must stay below half a bit:
9.5 × error < 0.5 ⇒ error < 5.3 % (both ends together; in practice keep each below 2 %)
Worked example
An Arduino Uno (16 MHz) cannot make exactly 115 200 baud: it divides its clock by a whole number and gets 117 647 baud, an error of +2.1 %. A board with an exact rate talks to it fine (2.1 % < 5 %), but two boards each off by 3 % in opposite directions (6 %) would not. Common rates: 9600, 19 200, 38 400, 57 600, 115 200, 1 000 000.
2.4 In code
// Arduino: echo every byte received, and print a line every second
void setup() { Serial.begin(115200); } // 8N1 by default; Serial.begin(19200, SERIAL_8E1) for 8E1
void loop() {
while (Serial.available()) Serial.write(Serial.read());
static unsigned long t = 0;
if (millis() - t > 1000) { t = millis(); Serial.println("alive"); }
}
# Python on the computer (pip install pyserial)
import serial
port = serial.Serial('/dev/ttyUSB0', 115200, timeout=1) # 'COM3' on Windows
port.write(b'V 120\n') # a text command, one line
print(port.readline().decode().strip())
2.5 From bytes to messages
A UART only carries a stream of bytes: it does not say where a message begins or ends. Two common solutions: text lines ending with a newline (easy to read, used by GPS modules: $GPGGA,…*47), or binary packets with a start byte, a length, the data and a checksum, so that the receiver can find the start again after a lost byte.
Byte
0
1
2 … n+1
n+2
Content
start 0xAA
length n
data
checksum (sum of the data, modulo 256)
The essentials
TX → RX crossed, common ground, same voltage level (or a level shifter).
Frame: idle 1, start 0, data LSB first, optional parity, stop 1. 8N1 = 10 bits per byte.
Bytes per second ≈ baud / 10 (8N1).
Read in the middle of each bit: total baud error < ≈ 5 %.
A UART carries bytes, not messages: add lines or packets with a checksum.
Key terms
UART, TX, RX
start bit, stop bit
parity (even, odd)
8N1, 8E1
LSB first
TTL level, RS-232
USB-serial adapter
framing error
packet, checksum
Exercises
Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.
Level 1 · Beginner1
In 8E1, how many bits are on the wire for one byte?
Solution
Rule usedstart + data + parity + stoplesson 2 — 2.2 The frame
1 start + 8 data + 1 parity (E = even) + 1 stop.
= 11 bits for 8 useful bits.
Answer11 bits
Level 2 · Intermediate2
The character “5” (0x35 = 0011 0101) is sent in 8E1. What is the parity bit?
0
1
Solution
Rule usedeven parity: the total number of 1s (data + parity) is evenlesson 2 — 2.2 The frame
0011 0101 has four 1s.
Four is already even, so the parity bit is 0.
Answer0
Level 3 · Professional3
A receiver is 4 % slow compared with the sender, in 8N1. How far from the middle (in bit times) does it read the stop bit?
Hint
The stop bit is read 9.5 bit times after the falling edge.
Solution
Rule useddrift = 9.5 × error; it must stay below 0.5 bitlesson 2 — 2.3 How the receiver reads
9.5 × 0.04 = 0.38 bit.
0.38 < 0.5: the reading point is still inside the stop bit, so the byte is decoded correctly — but with little margin left for noise.
Answer0.38 bit: it works, barely
Check yourself
The letter “A” (0x41) is sent in 8N1. Write the 10 bits in the order they appear on the wire.
0 1000 0010 1: start, then 0x41 = 0100 0001 read from b0 to b7, then stop.
Why does a UART need a stop bit?
To bring the line back HIGH, so that the next start bit makes a new falling edge to resynchronise on.
You see garbage characters on the serial monitor. What do you check first?
The baud rate (and format) on both sides, then TX/RX crossing, common ground and voltage levels.
3
I²C: two wires, many chips
30 min
You will learn
how I²C connects many chips with only SDA and SCL, why it needs pull-up resistors and how to size them, the START, address, ACK and STOP of a transaction, how to read a register of an IMU, and how to fix the usual problems.
In one sentence
I²C shares two wires between a master and many chips: the master makes the clock on SCL, data go both ways on SDA, every chip has a 7-bit address, and the lines are only ever pulled LOW, never driven HIGH.
3.1 Open drain and pull-up resistors
Every chip on the bus has a transistor that can connect the line to ground (LOW) or let it go. When nobody pulls, a pull-up resistor brings the line back HIGH. So two chips can never fight (one HIGH, one LOW = a short circuit): LOW always wins. The price: the rise to HIGH is slow, because the resistor must charge the capacitance of the wires and pins.
tr ≈ 0.85 R C (30 % → 70 %) Rmin = (VDD − 0.4 V) / 3 mA
Mode
Clock
Rise time tr max
Bus capacitance max
Standard
100 kHz
1000 ns
400 pF
Fast
400 kHz
300 ns
400 pF
Fast-mode Plus
1 MHz
120 ns
550 pF
Worked example
3.3 V bus at 400 kHz, C = 200 pF. Largest R: 300 ns / (0.85 × 200 pF) = 1.77 kΩ. Smallest R: (3.3 − 0.4) / 3 mA = 0.97 kΩ. A 1.5 kΩ pull-up fits. The usual 4.7 kΩ would give tr = 0.8 µs: fine at 100 kHz, too slow at 400 kHz. Beware: many breakout boards already have pull-ups, and several in parallel make R too small.
3.2 A transaction
Rule: SDA changes only while SCL is LOW, and is read while SCL is HIGH. Two exceptions mark the edges of a transaction: SDA falling while SCL is HIGH is a START, SDA rising while SCL is HIGH is a STOP. Bytes go most significant bit first, and each byte is followed by a 9th bit, the acknowledge: the receiver pulls SDA LOW (ACK) to say “got it”, or leaves it HIGH (NACK).
Step
Write a register
Read a register
1
START
START
2
address + W (0), ACK from the chip
address + W (0), ACK
3
register number, ACK
register number, ACK
4
data byte, ACK (more bytes go to the next registers)
repeated START, address + R (1), ACK
5
STOP
the chip sends the data; the master ACKs each byte, NACKs the last, then STOP
The address byte is the 7-bit address shifted left, plus the R/W bit: an MPU-6050 IMU at 0x68 gives 0xD0 to write and 0xD1 to read. Its pin AD0 changes the address to 0x69, so two IMUs can share a bus; for more identical chips, use an I²C multiplexer (TCA9548A).
3.3 In code
#include <Wire.h>
const uint8_t IMU = 0x68;
void setup() {
Serial.begin(115200);
Wire.begin(); Wire.setClock(400000); // fast mode
Wire.beginTransmission(IMU); Wire.write(0x6B); Wire.write(0x00); // PWR_MGMT_1 = 0: wake up
if (Wire.endTransmission() != 0) Serial.println("no ACK: check wiring and address");
}
void loop() {
Wire.beginTransmission(IMU); Wire.write(0x75); // register WHO_AM_I
Wire.endTransmission(false); // false = repeated START, keep the bus
Wire.requestFrom(IMU, (uint8_t)1);
if (Wire.available()) Serial.println(Wire.read(), HEX); // prints 68
delay(500);
}
3.4 When it does not work
Nothing answers: run an I²C scanner (it tries every address and lists the ACKs). No pull-ups, swapped SDA/SCL, or a wrong address (7-bit 0x68 is often written 0xD0 in 8-bit form in datasheets).
The bus is stuck LOW: a chip was reset in the middle of a byte and still holds SDA. Send 9 clock pulses on SCL by hand, then a STOP.
Errors with long wires or motors nearby: I²C is made for a board, not a 2 m cable along a motor. Shorten, slow the clock, lower the pull-up, or use a differential bus.
A slow chip may hold SCL LOW to make the master wait (clock stretching); some masters (the Raspberry Pi) handle it badly.
The essentials
SDA (data) + SCL (clock from the master) + ground; up to ≈ 100 chips with 7-bit addresses.
Open drain + pull-ups: tr ≈ 0.85 R C must stay below 1000 ns (100 kHz) or 300 ns (400 kHz).
START, address + R/W, ACK, bytes MSB first with ACK, STOP. Read = write the register, repeated START, read.
NACK after the address = nobody at that address.
Short distances only (a board, < 1 m).
Key terms
SDA, SCL
open drain, pull-up resistor
7-bit address, R/W bit
START, repeated START, STOP
ACK, NACK
register
rise time, bus capacitance
clock stretching
I²C scanner, multiplexer
Exercises
Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.
Level 1 · Beginner1
A barometer has the 7-bit address 0x76. What byte does the master send to READ from it?
An I²C bus has C = 150 pF and must run at 400 kHz (tr ≤ 300 ns). What is the largest pull-up resistor, in kΩ?
Solution
Rule usedtr ≈ 0.85 R C ≤ 300 nslesson 3 — 3.1 Open drain and pull-up resistors
R ≤ 300 ns / (0.85 × 150 pF).
= 300 × 10⁻⁹ / 127.5 × 10⁻¹² = 2353 Ω.
Check the current with 2.2 kΩ at 3.3 V: 2.9 / 2.2 = 1.3 mA < 3 mA ✓.
Answer≈ 2.35 kΩ: a standard 2.2 kΩ fits
Level 2 · Intermediate3
The master sends START, 0xD0, and the 9th bit stays HIGH. What does it mean?
The IMU acknowledged and waits for the register number
No chip has the address 0x68 on this bus (NACK)
The master wants to read
The bus is stuck LOW
Solution
Rule usedACK = the receiver pulls SDA LOW on the 9th clock; HIGH = NACKlesson 3 — 3.2 and 3.4
0xD0 = 0x68 × 2 + 0: write to address 0x68.
SDA stayed HIGH: nobody pulled it, so nobody has that address (or it is unpowered, or the wires are wrong).
AnswerB: NACK, no chip at 0x68
Check yourself
What is the write address byte of a chip at 7-bit address 0x3C?
0x3C × 2 + 0 = 0x78 (and 0x79 to read).
Why can two I²C chips never create a short circuit on SDA?
They can only pull the line LOW or release it; only the resistor pulls HIGH.
Your 4.7 kΩ pull-ups work at 100 kHz but not at 400 kHz. Why?
The rise time 0.85 R C is too long for the 300 ns limit of fast mode: lower R (respecting 3 mA) or the capacitance.
4
SPI: four wires and a fast clock
25 min
You will learn
the four SPI wires and the chip select, why SPI is a ring of shift registers (to read you must send), the four modes set by CPOL and CPHA, how to read a magnetic encoder, and when to choose SPI rather than I²C.
In one sentence
SPI uses a clock from the master, one data wire each way and one chip-select wire per device: no addresses, no acknowledge, push-pull outputs, so it runs at tens of MHz over short distances.
4.1 The wires
Wire
Other names
Driven by
Role
SCLK
SCK, CLK
master
the clock: one pulse per bit
MOSI
COPI, SDO (master side), DIN
master
data from the master to the device
MISO
CIPO, SDI (master side), DOUT
selected device
data from the device to the master
CS
SS, NSS, CE
master (one per device)
LOW = this device listens and talks
Because the outputs are push-pull (they drive HIGH and LOW actively), the edges are sharp and SPI runs fast: 1 to 50 MHz. The cost: one more pin on the master for each device, and only a few tens of centimetres of wire.
4.2 A ring of shift registers
Master and device each have an 8-bit shift register, joined in a ring by MOSI and MISO. At each clock pulse, both shift by one bit: one bit leaves the master while one bit arrives. After 8 pulses the two bytes have swapped. So SPI is always full duplex: to read a byte you must send one (often a dummy 0x00 or 0xFF), and every byte you send brings one back (often meaningless).
4.3 The four modes
Mode
CPOL (clock idle)
CPHA
Data read on
Data change on
0
0 (LOW)
0
rising edge
falling edge
1
0 (LOW)
1
falling edge
rising edge
2
1 (HIGH)
0
falling edge
rising edge
3
1 (HIGH)
1
rising edge
falling edge
CPOL is the level of the clock at rest. CPHA = 0: data are read on the first (leading) edge of each pulse, so the first bit must be on the wire as soon as CS falls; CPHA = 1: data are read on the second (trailing) edge. The datasheet of each device gives its mode; the master must use the same one, or the bytes arrive shifted by one bit.
4.4 Reading a magnetic encoder
Robot joints often use a magnetic absolute encoder such as the AS5047P: a magnet on the shaft, a chip in front of it giving a 14-bit angle (16 384 steps per turn) over SPI, mode 1, up to 10 MHz. One 16-bit exchange sends the read command 0xFFFF (read the angle register 0x3FFF); the angle comes back in the next exchange.
The encoder returns 0x1555 after masking. 0x1555 = 5461. Angle = 5461 × 360 / 16 384 = 120.0°. Resolution: 360 / 16 384 = 0.022° per step. At 10 MHz the 16 bits take 1.6 µs: the joint can be read at 100 kHz if needed.
4.5 SPI or I²C?
I²C
SPI
Wires
2 for all the devices
3 + one CS per device
Speed
0.1 to 1 Mbit/s
1 to 50 Mbit/s
Addressing
7-bit address in the frame
a wire (CS)
Knows if the device is there
yes (ACK)
no (a missing device reads as 0x00 or 0xFF)
Duplex
half
full
Typical use
slow sensors, configuration, small screens
encoders, fast ADCs, IMUs at high rate, displays, SD cards
The essentials
SCLK, MOSI, MISO shared; one CS (active LOW) per device.
A ring of shift registers: each bit sent brings one bit back; to read, send a dummy byte.
Modes 0–3 = CPOL (idle level) + CPHA (read on the first or second edge); same mode on both sides.
Fast (MHz), push-pull, but short distances and no acknowledge.
Key terms
SCLK, MOSI, MISO, CS
chip select (active LOW)
shift register
CPOL, CPHA, SPI mode
leading edge, trailing edge
push-pull output
dummy byte
absolute magnetic encoder
Exercises
Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.
Level 1 · Beginner1
A device datasheet says: “clock idle HIGH, data sampled on the rising edge”. Which SPI mode?
Mode 0
Mode 1
Mode 2
Mode 3
Solution
Rule usedCPOL = idle level; with CPOL = 1 the first edge is falling, so reading on the rising (second) edge means CPHA = 1lesson 4 — 4.3 The four modes (table)
Idle HIGH → CPOL = 1.
Each pulse goes HIGH → LOW (leading) → HIGH (trailing, rising). Read on the trailing edge → CPHA = 1.
CPOL 1, CPHA 1 = mode 3.
AnswerD: mode 3
Level 2 · Intermediate2
An AS5047P encoder (14 bits) returns 0x2AAA after masking. What is the angle, in degrees?
Solution
Rule usedangle = value × 360 / 2¹⁴lesson 4 — 4.4 Reading a magnetic encoder
SPI at 8 MHz. How long does it take to read 6 bytes from an IMU (plus 1 command byte), in µs?
Solution
Rule used1 bit per clock pulse; time = bits / frequencylesson 4 — 4.2 A ring of shift registers
7 bytes × 8 = 56 clock pulses.
56 / 8 MHz = 7 µs (plus a little time for CS).
The same 6 bytes over I²C at 400 kHz take about 250 µs.
Answer7 µs
Check yourself
How many clock pulses does it take to read one byte from an SPI device?
8, during which the master also sends 8 bits (a dummy byte if it has nothing to say).
An SPI bus has 4 devices. How many wires leave the master (without ground)?
3 shared + 4 CS = 7.
You read 0x00 from a device whatever happens. Name two causes.
CS never goes LOW (wrong pin), MISO not connected, the device not powered, or a wrong mode.
5
CAN bus: the nervous system of motors
35 min
You will learn
why CAN uses a differential pair with dominant and recessive bits, how to wire and terminate it, the fields of a frame, bit stuffing, how the arbitration lets the most urgent message pass without any loss, how CAN handles errors, and how robots use it (CANopen, CAN FD).
In one sentence
CAN is a two-wire differential bus with no master: every node can send, each message carries an identifier that says what it is and how urgent it is, and when two nodes talk at once the lower identifier wins bit by bit without destroying anything.
5.1 Dominant and recessive
CAN was made by Bosch in the 1980s for cars, where motors, sparks and long cables make a lot of noise. Each node has a CAN controller (often inside the microcontroller: STM32, ESP32 “TWAI”, or an MCP2515 chip on SPI) and a transceiver (TJA1050 at 5 V, SN65HVD230 at 3.3 V) that drives the two wires:
Bit
CAN_H
CAN_L
Difference
Who wins
0 = dominant
≈ 3.5 V
≈ 1.5 V
≈ 2 V
always: one node sending 0 is enough
1 = recessive
≈ 2.5 V
≈ 2.5 V
0 V
only if every node sends 1
So the bus behaves like an AND of all the bits sent (“wired-AND”). The line is a twisted pair with a 120 Ω resistor at each end (60 Ω measured between CAN_H and CAN_L with the power off): without them the edges reflect at the ends and the bits are corrupted. Keep the branches to each node short (stubs < 0.3 m at 1 Mbit/s).
Bit rate
1 Mbit/s
500 kbit/s
250 kbit/s
125 kbit/s
50 kbit/s
Max length (approx.)
40 m
100 m
250 m
500 m
1 km
Why does length limit the rate? During arbitration and the acknowledge, a bit must travel to the far end and back within one bit time: the signal goes at about 0.2 m/ns, plus the delays of the transceivers.
5.2 The frame
Field
Bits
Role
Start of frame
1
dominant: everyone synchronises
Identifier
11 (29 in extended)
what the message is, and its priority
RTR, IDE, r0
3
data or request, standard or extended
DLC
4
number of data bytes (0–8)
Data
0–64
the payload: 0 to 8 bytes
CRC
15 + 1 delimiter
error check
ACK
1 + 1 delimiter
any correct receiver writes a dominant bit here
End of frame
7
recessive
There are no addresses: a frame is broadcast to all the nodes, and each one keeps the identifiers it cares about (hardware filters). A frame with 8 bytes is 111 bits, plus the stuff bits: after 5 identical bits, the sender adds one opposite bit (removed by the receivers), so that an edge comes at least every 6 bits and every clock stays in step. With them, count about 130 bits for 8 bytes.
5.3 Arbitration: the most urgent passes first
When the bus is free, several nodes may start together. Each one reads the bus while it sends. A node that sends a recessive 1 but reads a dominant 0 knows that someone with a lower identifier is talking: it stops at once and becomes a receiver. The winner never notices: its frame is intact and no time is lost (non-destructive bitwise arbitration). So: give the lowest identifiers to the most urgent messages (emergency stop, current set-points), and never give the same identifier to two nodes.
5.4 Errors: a broken node silences itself
Every node checks every frame: CRC, stuff rule, fixed-form bits, and reads back its own bits. Any node that sees a problem destroys the frame at once with an error frame (6 dominant bits, which break the stuff rule on purpose), and the sender sends it again automatically. Each node counts its errors: above 127 it becomes error passive (it may no longer destroy frames), above 255 it goes bus-off and stops sending. A faulty node cannot jam the bus forever.
5.5 CAN in robots
Joint actuators: many motor controllers (ODrive, the actuators of MIT Mini Cheetah-style legged robots, servo drives) take position, speed or torque set-points over CAN at 1 Mbit/s.
CANopen (CiA 301) adds the application layer: an object dictionary per node, fast cyclic PDOs for set-points and feedback, SDOs for configuration, a heartbeat; the profile CiA 402 standardises motor drives (control word, status word, modes of operation).
CAN FD (flexible data rate): up to 64 bytes per frame and a faster data phase (2 to 8 Mbit/s), arbitration still at the normal rate.
Batteries, chargers and mobile bases report state of charge and faults on CAN, as in cars.
# Linux (Raspberry Pi with a CAN hat, or a USB-CAN adapter): SocketCAN
sudo ip link set can0 up type can bitrate 1000000
candump can0 # print every frame: can0 123 [2] 05 DC
cansend can0 123#05DC # send ID 0x123 with the bytes 05 DC
# Python (pip install python-can)
import can
bus = can.Bus(interface='socketcan', channel='can0')
bus.send(can.Message(arbitration_id=0x123, data=[0x05, 0xDC], is_extended_id=False))
msg = bus.recv(timeout=1.0) # None if nothing arrived
Worked example
A drive sends its speed 1500 rpm as a 16-bit big-endian value: data bytes 0x05 0xDC (0x05DC = 1500). At 1 Mbit/s a frame with 2 data bytes is about 65 bits with its stuff bits, so 65 µs; with 8 bytes about 130 µs. A 1 Mbit/s bus can carry at most about 7 700 eight-byte frames per second — keep the bus load under ≈ 50–70 % to leave room for retries and urgent messages.
The essentials
Differential pair, twisted, 120 Ω at both ends (60 Ω between H and L).
Dominant 0 beats recessive 1: the bus is a wired-AND.
No addresses: identifiers name the message and set its priority (lower = more urgent).
Arbitration is bitwise and non-destructive; stuff bit after 5 equal bits.
Errors are detected by every node; a faulty node goes bus-off. 1 Mbit/s up to ≈ 40 m.
Key terms
CAN_H, CAN_L
dominant, recessive
transceiver, controller
termination 120 Ω
identifier, DLC
bit stuffing
arbitration
error frame, bus-off
CANopen, PDO, SDO, CiA 402
CAN FD
Exercises
Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.
Level 1 · Beginner1
Three nodes start a frame at the same time with IDs 0x210, 0x20F and 0x300. Which one wins?
Bit 9: 0x300 sends 1, the others 0 → 0x300 drops out.
Bit 4: 0x210 sends 1, 0x20F sends 0 → 0x20F wins.
AnswerB: 0x20F, the lowest
Level 2 · Intermediate2
The bits 1 1 1 1 1 1 0 0 0 0 0 0 are to be sent (inside a CAN frame, after a 0). How many stuff bits are added?
Hint
After 5 equal bits, add one opposite bit; it counts in the next run.
Solution
Rule usedafter 5 identical bits, insert one opposite bitlesson 5 — 5.2 The frame
1 1 1 1 1 → stuff 0 → the 6th 1 starts a new run: (0) 1.
Then 0 0 0 0 0 → stuff 1 → the 6th 0 follows.
On the wire: 1111101 0000010: 2 stuff bits.
Answer2 stuff bits
Level 3 · Professional3
A CAN bus at 500 kbit/s carries 4 drives, each sending one 8-byte frame (≈ 130 bits) every 1 ms, plus the master sending 4 frames of the same size every 1 ms. What is the bus load, in %?
Solution
Rule usedload = frames/s × bits/frame ÷ bit ratelesson 8 — 8.2 The bus load
Frames per second: 8 × 1000 = 8000.
Bits per second: 8000 × 130 = 1 040 000.
Load: 1 040 000 / 500 000 = 2.08 → 208 %: the bus cannot carry it. Use 1 Mbit/s and pack the data, or lower the rate.
Answer208 %: too much
Check yourself
Two nodes send IDs 0x120 and 0x101 at the same time. Who wins?
0x101: it is lower, so it has a dominant 0 where 0x120 has a 1.
You measure 120 Ω between CAN_H and CAN_L, power off. What is wrong?
Only one terminating resistor is there: you should read 60 Ω (two 120 Ω in parallel).
Why does CAN add stuff bits?
To guarantee an edge at least every 6 bits, so that the receivers (with no clock wire) stay synchronised.
6
RS-485 and Modbus: the language of industry
35 min
You will learn
how RS-485 carries UART frames over a long differential pair to many devices, the Modbus data model (coils and registers), the main function codes, the RTU frame with its CRC-16, the answers and the exceptions, Modbus TCP, and how to read a motor drive from Python.
In one sentence
RS-485 is the wire (a differential pair, up to 1200 m and 32 devices), Modbus is the language spoken on it: a master asks one slave at a time to read or write numbered 16-bit registers, and the slave answers.
6.1 RS-485: a UART that goes far
An RS-485 transceiver (MAX485, SN75176) turns the TX of a UART into a differential pair A/B: the receiver reads 1 if A − B > +200 mV and 0 if A − B < −200 mV. The bits are the same UART frames as in lesson 2. With two wires the bus is half duplex: each transceiver has a direction pin (DE/RE) that the software switches to send, then back to receive. Like CAN: twisted pair, 120 Ω at both ends, and bias resistors that keep the idle line at a clean 1. Up to 32 standard devices (more with ⅛-load transceivers), 10 Mbit/s over a few metres or 100 kbit/s over 1200 m.
6.2 The Modbus data model
Table
Size
Access
Old numbering
Example in a drive
Coils
1 bit
read / write
00001…
run / stop
Discrete inputs
1 bit
read only
10001…
fault present
Input registers
16 bits
read only
30001…
measured current
Holding registers
16 bits
read / write
40001…
speed set-point
The off-by-one trap
Datasheets often say “register 40002”: in the frame that is holding register address 1 (40001 = address 0). Values are integers: a current of 2.35 A may be sent as 235 (unit 0.01 A); a 32-bit value takes two registers, and the order of the two words varies between makers.
6.3 Functions and answers
Code
Function
01 / 02
read coils / discrete inputs
03 / 04
read holding / input registers
05 / 06
write one coil / one register
15 / 16 (0x0F / 0x10)
write several coils / registers
A normal answer repeats the slave address and the function code, then the data. If the request is wrong, the slave answers an exception: the function code + 0x80 and an exception code: 01 illegal function, 02 illegal data address, 03 illegal data value, 04 device failure. A slave that does not exist does not answer at all: the master waits a timeout.
6.4 The RTU frame
In Modbus RTU each frame is: slave address (1 byte, 1–247; 0 = broadcast), function (1 byte), data, and a CRC-16 (2 bytes, low byte first). The 16-bit numbers inside are big-endian (high byte first). A frame ends with a silence of at least 3.5 characters. Default serial format: 8E1 (8 data bits, even parity, 1 stop) — many devices also accept 8N2 or 8N1.
slave 3, function 3, 4 bytes: 0x05D9 = 1497 rpm, 0x00EB = 235 → 2.35 A, CRC
Exception
03 83 02 61 31
slave 3, function 3 + 0x80, code 02: that address does not exist
6.5 Modbus TCP
The same requests also travel over Ethernet: Modbus TCP, port 502. The address and the CRC are replaced by a 7-byte header (transaction number, protocol 0, length, unit number); TCP checks the errors. PLCs, robot controllers and many drives speak it. Function, register and value stay the same: what you learnt on RS-485 still holds.
# Python (pip install minimalmodbus): read a drive on a USB-RS485 adapter
import minimalmodbus, serial
drive = minimalmodbus.Instrument('/dev/ttyUSB0', 3) # port, slave address
drive.serial.baudrate = 19200
drive.serial.parity = serial.PARITY_EVEN # 8E1
drive.serial.timeout = 0.2
speed, current = drive.read_registers(1, 2) # function 03, address 1, 2 registers
print(speed, 'rpm', current / 100, 'A')
drive.write_register(0, 1200) # function 06: new speed set-point
The essentials
RS-485 = differential A/B, half duplex, 120 Ω at both ends, up to 1200 m and 32 devices.
Modbus: one master asks, one slave answers; coils (bits) and 16-bit registers.
RTU frame: address, function, data, CRC-16 (low byte first), then ≥ 3.5 characters of silence.
Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.
Level 1 · Beginner1
A datasheet lists the speed set-point as holding register 40011. What address goes in the Modbus frame?
Solution
Rule used4xxxx numbering starts at 40001 = address 0lesson 6 — 6.2 The off-by-one trap
40011 − 40001 = 10.
In the frame: 00 0A.
Answer10 (0x000A)
Level 2 · Intermediate2
Answer received: 03 03 04 05 D9 00 EB 48 8B. The second register is a current in units of 0.01 A. What is the current, in A?
Solution
Rule usedafter address, function and byte count come the registers, high byte firstlesson 6 — 6.4 The RTU frame (table)
03 = slave, 03 = function, 04 = 4 data bytes.
First register 05 D9 = 1497; second 00 EB = 235.
235 × 0.01 = 2.35 A. The last two bytes 48 8B are the CRC.
Answer2.35 A
Level 2 · Intermediate3
Which request writes the value 1500 into holding register address 0 of slave 3?
03 06 00 00 05 DC 8A E1
03 03 00 00 05 DC 8A E1
06 03 00 00 05 DC 8A E1
03 06 00 00 DC 05 8A E1
Solution
Rule usedaddress, function 06, register (2 bytes), value (2 bytes, high first), CRC (low first)lesson 6 — 6.3 and 6.4
Slave first: 03; then the function: 06 (write one register).
Register 0: 00 00. Value 1500 = 0x05DC: 05 DC (big-endian).
B reads (function 03), C swaps address and function, D swaps the value bytes.
AnswerA
Check yourself
A slave answers 05 86 02 … to a function 06 request. What happened?
Exception (0x86 = 0x06 + 0x80), code 02: the register address does not exist in slave 5.
Why does an RS-485 transceiver need a direction pin?
Two-wire RS-485 is half duplex: the same pair is used to send and to receive, so only one device may drive it at a time.
How does a Modbus RTU receiver know that a frame is finished?
A silence of at least 3.5 character times on the line.
7
Noise, errors and a reliable link
25 min
You will learn
where communication errors come from in a robot, how parity, checksums and CRCs detect them (and what each one misses), how to compute a small CRC by hand, the wiring rules against noise, and what the software must do when a link fails: timeouts, retries, heartbeats and a safe stop.
In one sentence
Bits will be flipped sometimes; a good link detects it with a check code computed from the data (best: a CRC), and a good robot survives it with timeouts, retries and a safe state when messages stop coming.
7.1 Where errors come from
Cause
What you see
Cure
Motors switching (PWM), relays, welding
random bad frames when motors run
twisted pairs, differential bus, keep signal cables away from power cables, shielding, ferrites
No termination, long stubs
rings on the edges, errors at high rate only
120 Ω at both ends, short stubs
Ground difference between boards
errors that change with the load current
common ground wire, or isolated transceivers
Too much capacitance, weak pull-ups (I²C)
rounded edges, NACKs
shorter wires, smaller R, slower clock
Clock mismatch (UART)
wrong characters, framing errors
exact baud rate, crystal instead of RC oscillator
7.2 Detecting errors
The sender computes a short code from the data and sends it too; the receiver computes it again and compares. If they differ, the frame is thrown away. Three codes, from the weakest to the strongest:
Code
How
Detects
Misses
Parity bit
1 bit: makes the number of 1s even (or odd)
any odd number of flipped bits
2 flipped bits in the same byte
Checksum
sum of the bytes, modulo 256
most single errors
two bytes swapped; +1 on one byte and −1 on another
CRC
remainder of a polynomial division (XOR)
every burst shorter than the CRC, all 1- and 2-bit errors in short frames, swaps
very rare patterns (≈ 1 in 2n for an n-bit CRC)
A CRC (cyclic redundancy check) treats the message as a long binary number and divides it by a fixed generator, using XOR instead of subtraction (no carries). The remainder is the CRC. Same idea everywhere, different generators: CRC-8 in many sensors, CRC-15 in CAN, CRC-16 in Modbus, CRC-32 in Ethernet and ZIP files.
Worked example
Message 1101, generator 1011 (x³ + x + 1), a 3-bit CRC. Append 3 zeros: 1101000. Divide with XOR, each time under the leftmost 1: 1101 ⊕ 1011 = 0110 → bring down: 1100 ⊕ 1011 = 0111 → 1110 ⊕ 1011 = 0101 → 1010 ⊕ 1011 = 0001. Remainder 001: the sender sends 1101 001. The receiver divides 1101001 by 1011 and finds 000: no error seen.
7.3 When the link fails: the software side
Timeout: never wait for an answer forever; after a set time, give up on this exchange.
Retry, a limited number of times, then report the fault.
Sequence counter: a number that increases in each message shows lost or repeated messages.
Heartbeat and watchdog: each node sends “I am alive” regularly (CANopen heartbeat); a drive that stops receiving set-points for, say, 50 ms must stop the motor by itself.
Safe state: decide in advance what each part does when communication is lost — usually stop, brakes on — and test it by pulling the cable.
Safety is not a bus
An emergency stop must not depend on a message arriving: it cuts the power through a safety relay or a safe torque off (STO) input. Safety buses exist (CANopen Safety, FSoE on EtherCAT, PROFIsafe), with extra checks and certified hardware.
The essentials
Noise, missing termination, ground differences and clock mismatch cause most errors.
Parity misses even numbers of flips; a checksum misses swaps; a CRC catches nearly everything.
CRC = remainder of a division with XOR by a fixed generator.
Timeouts, retries, counters, heartbeats; a safe state when the link is lost.
Key terms
electromagnetic noise (EMI)
reflection, termination
ground loop, isolation
parity, checksum
CRC, generator polynomial
burst error
timeout, retry
heartbeat, watchdog
safe state, safe torque off (STO)
Exercises
Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.
Level 1 · Beginner1
Message 1001, generator 1011 (CRC of 3 bits). Compute the CRC.
110
011
001
000
Hint
Append 3 zeros, then XOR 1011 under each leading 1.
Solution
Rule usedCRC = remainder of (message followed by n zeros) divided by the generator, with XORlesson 7 — 7.2, worked example
1001 000.
1001 ⊕ 1011 = 0010 → 0010 000 → next leading 1: 1000 ⊕ 1011 = 0011 → 0000 110.
Remainder 110: the sender sends 1001 110.
AnswerA: 110
Level 2 · Intermediate2
Bytes 0x12 and 0x34 are swapped by an error. Which check sees it?
Parity per byte
Sum of the bytes
CRC
None of them
Solution
Rule usedparity and sum do not depend on the order of the bytes; the CRC doeslesson 7 — 7.2 Detecting errors (table)
Each byte keeps its own bits: each parity stays the same.
0x12 + 0x34 = 0x34 + 0x12: the sum is the same.
In a CRC each bit is weighted by its position: the remainder changes.
AnswerC: only the CRC
Level 2 · Intermediate3
A drive receives a set-point every 2 ms. Its watchdog must stop the motor after 5 messages in a row are missing. What timeout do you set, in ms?
Solution
Rule usedtimeout = number of missed periods × periodlesson 7 — 7.3 When the link fails
5 × 2 ms = 10 ms.
Too short and noise stops the robot for nothing; too long and the robot keeps moving blind.
Answer10 ms
Check yourself
Two bits are flipped in the same byte. Does the parity bit see it?
No: the number of 1s changes by 0 or 2, so the parity is the same.
Why is a CRC better than a sum of the bytes?
The position of each bit matters in the division, so swaps and compensating errors change the CRC; a sum ignores the order.
The CAN cable of a drive is cut. What should the drive do?
Detect the missing set-points with a timeout (watchdog) and go to its safe state: stop the motor.
8
The network of a real robot: choose, budget, debug
30 min
You will learn
how to choose a bus for each link of a robot, how to check that the bus is fast enough (bus load), what industrial Ethernet (EtherCAT) adds, and a method with the right tools to bring up and debug a link.
In one sentence
Short and fast inside a board (I²C, SPI), long and robust between boards (CAN, RS-485, Ethernet), a simple serial link to the computer — then check the timing budget and debug layer by layer with a logic analyser.
8.1 The buses side by side
UART
I²C
SPI
CAN
RS-485 / Modbus
EtherCAT
Wires (+ ground)
2
2
3 + 1 per device
2 (twisted)
2 (twisted)
Ethernet cable
Distance
≈ 1 m (TTL)
< 1 m
< 0.3 m
40 m at 1 Mbit/s
1200 m
100 m per link
Speed
up to ≈ 1 Mbit/s
0.1–1 Mbit/s
1–50 Mbit/s
1 Mbit/s (FD: 5)
≤ 10 Mbit/s
100 Mbit/s
Devices
2
≈ 100
a few
≈ 100
32 (247 addresses)
65 535
Who talks
both, any time
master
master
anyone (arbitration)
master
master (frame passes through every slave)
Error check
parity (optional)
ACK only
none
CRC-15 + ACK + retries
CRC-16
CRC-32 + counters
8.2 Is the bus fast enough? The bus load
bus load = (frames per second × bits per frame) / bit rate — keep it below ≈ 50–70 %
Worked example
A 6-axis arm with one CAN drive per joint, loop at 1 kHz. Each cycle: 6 set-point frames and 6 feedback frames, 8 bytes each, ≈ 130 bits with stuffing. Load = 12 × 1000 × 130 / 1 000 000 = 156 %: impossible. At 500 Hz: 78 %, still too high. Solutions: pack the values (16 bits per axis: 4 axes per 8-byte frame, so 2 set-point + 2 feedback frames → 4 × 1000 × 130 / 10⁶ = 52 %, at the limit), use CAN FD (64 bytes, faster data phase), split into two CAN buses, or move to EtherCAT.
8.3 Industrial Ethernet: EtherCAT
Most industrial robot arms link their joints with EtherCAT: one Ethernet frame leaves the master and passes through every drive in a line; each drive reads its set-point and writes its feedback into the frame on the fly, without stopping it, and the last one sends it back. A 1 ms cycle (often 125 µs) for dozens of axes, with distributed clocks synchronised to better than 1 µs. Other industrial Ethernets: PROFINET, EtherNet/IP, Modbus TCP (simpler, not deterministic). Wireless links (Wi-Fi, Bluetooth, radio) are for supervision and teleoperation, never for a fast control loop or a safety function.
8.4 Bring up a link: a method
Power off, multimeter: continuity of each wire, 60 Ω between CAN_H and CAN_L (or between A and B on RS-485), no short to ground.
Power on, idle levels: UART TX HIGH, I²C SDA and SCL HIGH, CAN_H = CAN_L ≈ 2.5 V.
One device at a time, at a low rate: I²C scanner, a loopback test (TX wired to RX), candump, a single Modbus read.
Look at the signals: a logic analyser (8 channels, a few euros, with the free sigrok / PulseView software) decodes UART, I²C, SPI, CAN and Modbus bytes from the wires — exactly the pictures of this course. An oscilloscope shows the analog side: slow edges, rings, noise.
Then the meaning: right register, right unit, right byte order? Compare one value with the datasheet example.
Finally under load: motors running, full rate, long cables; count the errors for an hour; pull a cable and check the safe state.
The essentials
Choose per link: distance, speed, number of devices, noise, who must talk.
Bus load = frames/s × bits/frame ÷ bit rate, below ≈ 50–70 %.
EtherCAT: one frame through all the drives, cycles of 1 ms or less, synchronised clocks.
Debug bottom-up: wires and resistances, idle levels, one device, signals (logic analyser), meaning, load.
Key terms
bus load
timing budget
EtherCAT, distributed clocks
PROFINET, EtherNet/IP
logic analyser, protocol decoder
oscilloscope
loopback test
determinism
Exercises
Try each exercise yourself first. Type your answer in the box (the checker accepts a small tolerance) or pick an option; use the hint only if you are stuck, and read the solution to compare your method.
Level 1 · Beginner1
A conveyor drive is 300 m from the PLC, in a factory, and is read 10 times a second. Which bus?
I²C
SPI
RS-485 with Modbus RTU
UART TTL
Solution
Rule usedlong distance + noise → differential bus; slow rate → RS-485 is enoughlesson 8 — 8.1 The buses side by side
I²C, SPI and TTL UART stop at about 1 m.
RS-485 goes to 1200 m at 100 kbit/s, and Modbus is the usual language of drives and PLCs.
AnswerC: RS-485 / Modbus RTU (CAN at 125 kbit/s would also work)
Level 2 · Intermediate2
A 1 Mbit/s CAN bus carries 3000 frames per second of 120 bits. What is the bus load, in %?
Solution
Rule usedload = frames/s × bits/frame ÷ bit ratelesson 8 — 8.2 The bus load
3000 × 120 = 360 000 bit/s.
360 000 / 1 000 000 = 0.36 → 36 %: comfortable.
Answer36 %
Level 3 · Professional3
A new CAN link does not work. Put the checks in a good order: (a) logic analyser on the wires, (b) 60 Ω between H and L power off, (c) compare a decoded value with the datasheet, (d) CAN_H = CAN_L ≈ 2.5 V at idle.
b, d, a, c
c, a, d, b
a, b, c, d
d, c, b, a
Solution
Rule useddebug bottom-up: wires, levels, signals, meaninglesson 8 — 8.4 Bring up a link: a method
(b) power off: resistances and continuity.
(d) power on: idle levels.
(a) the frames on the wires, decoded.
(c) only then the meaning of the values.
AnswerA: b, d, a, c
Check yourself
An IMU on the robot's board, read at 1 kHz: which bus?
SPI (or I²C at 400 kHz if the data are small): short distance, on the board.
A CAN bus at 500 kbit/s carries 2000 frames per second of 125 bits. What is the bus load?
2000 × 125 / 500 000 = 50 %.
Why debug from the wires up rather than from the code down?
If the physical layer is wrong, nothing above can work; checking resistances and idle levels takes a minute and removes half of the causes.
Glossary
All the words of the course in one place.
Term
Meaning
Baud rate
Number of bits per second on a serial line; one bit lasts 1 / baud.
Frame
A complete unit sent on a bus: start, address or identifier, data, error check, end.
UART
Asynchronous serial port: TX and RX, start bit 0, data LSB first, optional parity, stop bit 1.
8N1
UART format: 8 data bits, no parity, 1 stop bit (10 bits per byte on the wire).
I²C
Two-wire bus (SDA, SCL) with pull-up resistors, 7-bit addresses and an ACK after every byte.
Pull-up resistor
A resistor that brings an open-drain line back HIGH when nobody pulls it LOW.
ACK, NACK
Acknowledge: the receiver pulls SDA LOW on the 9th clock; NACK: it leaves it HIGH.
SPI
Four-wire synchronous bus (SCLK, MOSI, MISO, CS), full duplex, MHz speeds, short distances.
CPOL, CPHA
The SPI mode: idle level of the clock, and the edge where data are read.
CAN bus
Differential multi-master bus with identifiers, bitwise arbitration, CRC and automatic retries.
Dominant, recessive
On CAN, 0 (dominant) overrides 1 (recessive) when nodes send together.
Bit stuffing
After 5 equal bits, CAN inserts one opposite bit to keep an edge for synchronisation.
Termination
120 Ω resistors at both ends of a CAN or RS-485 line, against reflections.
RS-485
Differential physical layer for UART frames: up to 1200 m and 32 devices, half duplex on two wires.
Modbus
Master-slave protocol to read and write coils and 16-bit registers (RTU on serial lines, TCP on Ethernet).
Holding register
A 16-bit Modbus value that can be read and written (4xxxx).
CRC
Cyclic redundancy check: remainder of a division with XOR, used to detect errors.
Bus load
Share of the time a bus is busy: frames/s × bits/frame ÷ bit rate.
EtherCAT
Industrial Ethernet where one frame passes through every drive, read and written on the fly.
Logic analyser
A tool that records digital signals and decodes the bytes of UART, I²C, SPI or CAN.
Sources and references
This course was written from these books, papers, standards and documentation. They are also the best way to go further.
NXP Semiconductors, UM10204: I²C-bus specification and user manual, rev. 7.0, 2021.used for:I²C: open drain, pull-ups, rise time, START, ACK, STOP, speed modes
Robert Bosch GmbH, CAN Specification, version 2.0, 1991; ISO 11898-1 and 11898-2 (data link and high-speed physical layer).used for:CAN: dominant and recessive bits, frame, bit stuffing, arbitration, error handling
CAN in Automation (CiA), CiA 301 (CANopen application layer) and CiA 402 (drives and motion control device profile), can-cia.org.used for:CANopen, PDO, SDO, heartbeat, drive profile
Modbus Organization, Modbus Application Protocol Specification V1.1b3 and Modbus over Serial Line V1.02, modbus.org.used for:Modbus data model, function codes, exceptions, RTU frame and CRC-16, Modbus TCP
TIA/EIA-485-A standard; Texas Instruments, The RS-485 Design Guide, application report SLLA272.used for:RS-485 levels, termination, biasing, distance and rate
P. Koopman, T. Chakravarty, “Cyclic redundancy code (CRC) polynomial selection for embedded networks”, Proc. DSN, 2004.used for:what CRCs detect
P. Horowitz, W. Hill, The Art of Electronics, 3rd ed., Cambridge University Press, 2015.used for:serial links, differential signalling, noise and grounding
Arduino documentation and language reference, docs.arduino.cc; ATmega328P datasheet, Microchip.used for:Serial, Wire and SPI libraries, UART of the ATmega328P
InvenSense (TDK), MPU-6000 and MPU-6050 Register Map and Descriptions, rev. 4.2.used for:the IMU registers of the I²C example
ams OSRAM, AS5047P: 14-bit on-axis magnetic rotary position sensor, datasheet (SPI interface).used for:the magnetic encoder of the SPI example
EtherCAT Technology Group, EtherCAT: the Ethernet fieldbus, technical introduction, ethercat.org.used for:EtherCAT principle and cycle times
The sigrok project: PulseView and its protocol decoders (UART, I²C, SPI, CAN, Modbus), sigrok.org.used for:logic analyser and protocol decoders
You can now read every bit that travels in a robot!
Next: the dynamics and control course uses these links to close the loops of the motors, and the ROS 2 course carries the messages up to the computer.