Robot communication: UART, I²C, SPI, CAN and Modbus

← Robot list · The basics

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

LinkWhat travelsHow oftenUsual bus
IMU → microcontroller3 accelerations, 3 angular speeds (12 bytes)100 to 1000 times a secondI²C, SPI
Joint encoder → microcontrollerone angle (2 bytes)up to 10 000 times a secondSPI
Microcontroller ↔ motor drivesset-points, then speed, current, errors1000 times a secondCAN, EtherCAT
Computer ↔ microcontrollercommands, odometry, logs10 to 100 times a secondUSB, UART
PLC ↔ conveyor drive, gripperstart, stop, speed, status10 times a secondModbus (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 = 65 = 0x41 = 0100 0001₂   (0x4 = 0100, 0x1 = 0001)

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

WordMeaningExamples
Synchronousa clock wire tells when to read each bitI²C, SPI
Asynchronousno clock wire: both sides agree on the bit rate and resynchronise on edgesUART, CAN, RS-485
Single-endedone wire, measured against ground: simple, sensitive to noiseUART TTL, I²C, SPI
Differentialtwo wires with opposite signals; the receiver reads the difference, so noise common to both cancelsCAN, RS-485, Ethernet, USB
Point-to-point / bustwo devices only, or many devices sharing the same wires (multidrop)UART / I²C, CAN, RS-485
Master-slaveone master starts every exchange; slaves only answer (new names: controller and target, client and server)I²C, SPI, Modbus
Multi-masterany node may start talking; a rule decides who wins if two start togetherCAN

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.

  1. 1011 0110
  2. 1101 0110
  3. 1011 1100
  4. 0110 1011

Solution

Rule used each hex digit is 4 bits: B = 1011, 6 = 0110 lesson 1 — 1.2 From a number to bits

  1. B = 11 = 8 + 2 + 1 → 1011.
  2. 6 = 4 + 2 → 0110.
  3. Put them side by side: 1011 0110 (= 182).

Answer A: 1011 0110

Level 1 · Beginner2

What is the time of one bit at 19 200 baud, in µs?

Solution

Rule used Tbit = 1 / baud lesson 1 — 1.3 (formula)

  1. 1 / 19 200 = 0.0000521 s.
  2. × 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 used baud ≥ bits / time lesson 1 — 1.3 and the worked example

  1. Bits: 12 × 10 = 120 bits.
  2. 120 bits in 2 ms → 120 / 0.002 = 60 000 bit/s.
  3. The next standard rate above is 115 200 baud (57 600 is too low).

Answer 60 000 baud minimum: use 115 200

Check yourself
  1. Why do robots prefer serial links to parallel ones?

    Fewer wires through the joints and over long cables, and no skew between 8 wires.

  2. What is the time of one bit at 1 Mbit/s?

    1 µs.

  3. 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).

LevelLogic 1 (and idle)Logic 0Distance
TTL 5 V (Arduino Uno)5 V0 V≈ 1 m
TTL 3.3 V (ESP32, Raspberry Pi, STM32)3.3 V0 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 VA − B < −0.2 Vup 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

  1. Idle: the line rests HIGH.
  2. Start bit: one bit LOW. Its falling edge wakes the receiver up.
  3. Data: 5 to 9 bits (almost always 8), least significant bit first.
  4. Parity (optional): one bit that makes the number of 1s even (E) or odd (O).
  5. 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.

Byte012 … n+1n+2
Contentstart 0xAAlength ndatachecksum (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 used start + data + parity + stop lesson 2 — 2.2 The frame

  1. 1 start + 8 data + 1 parity (E = even) + 1 stop.
  2. = 11 bits for 8 useful bits.

Answer 11 bits

Level 2 · Intermediate2

The character “5” (0x35 = 0011 0101) is sent in 8E1. What is the parity bit?

  1. 0
  2. 1

Solution

Rule used even parity: the total number of 1s (data + parity) is even lesson 2 — 2.2 The frame

  1. 0011 0101 has four 1s.
  2. Four is already even, so the parity bit is 0.

Answer 0

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 used drift = 9.5 × error; it must stay below 0.5 bit lesson 2 — 2.3 How the receiver reads

  1. 9.5 × 0.04 = 0.38 bit.
  2. 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.

Answer 0.38 bit: it works, barely

Check yourself
  1. 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.

  2. 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.

  3. 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

ModeClockRise time tr maxBus capacitance max
Standard100 kHz1000 ns400 pF
Fast400 kHz300 ns400 pF
Fast-mode Plus1 MHz120 ns550 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).

StepWrite a registerRead a register
1STARTSTART
2address + W (0), ACK from the chipaddress + W (0), ACK
3register number, ACKregister number, ACK
4data byte, ACK (more bytes go to the next registers)repeated START, address + R (1), ACK
5STOPthe 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?

  1. 0x76
  2. 0xEC
  3. 0xED
  4. 0x77

Solution

Rule used address byte = address × 2 + R/W (read = 1) lesson 3 — 3.2 A transaction

  1. 0x76 × 2 = 0xEC (shift left by one bit).
  2. + 1 for read → 0xED.

Answer C: 0xED

Level 2 · Intermediate2

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 used tr ≈ 0.85 R C ≤ 300 ns lesson 3 — 3.1 Open drain and pull-up resistors

  1. R ≤ 300 ns / (0.85 × 150 pF).
  2. = 300 × 10⁻⁹ / 127.5 × 10⁻¹² = 2353 Ω.
  3. 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?

  1. The IMU acknowledged and waits for the register number
  2. No chip has the address 0x68 on this bus (NACK)
  3. The master wants to read
  4. The bus is stuck LOW

Solution

Rule used ACK = the receiver pulls SDA LOW on the 9th clock; HIGH = NACK lesson 3 — 3.2 and 3.4

  1. 0xD0 = 0x68 × 2 + 0: write to address 0x68.
  2. SDA stayed HIGH: nobody pulled it, so nobody has that address (or it is unpowered, or the wires are wrong).

Answer B: NACK, no chip at 0x68

Check yourself
  1. What is the write address byte of a chip at 7-bit address 0x3C?

    0x3C × 2 + 0 = 0x78 (and 0x79 to read).

  2. 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.

  3. 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

WireOther namesDriven byRole
SCLKSCK, CLKmasterthe clock: one pulse per bit
MOSICOPI, SDO (master side), DINmasterdata from the master to the device
MISOCIPO, SDI (master side), DOUTselected devicedata from the device to the master
CSSS, NSS, CEmaster (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

ModeCPOL (clock idle)CPHAData read onData change on
00 (LOW)0rising edgefalling edge
10 (LOW)1falling edgerising edge
21 (HIGH)0falling edgerising edge
31 (HIGH)1rising edgefalling 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.

#include <SPI.h>
const int CS = 10;
SPISettings enc(1000000, MSBFIRST, SPI_MODE1);   // 1 MHz, MSB first, mode 1
uint16_t xfer(uint16_t out) {
  SPI.beginTransaction(enc); digitalWrite(CS, LOW);
  uint16_t in = SPI.transfer16(out);
  digitalWrite(CS, HIGH); SPI.endTransaction();
  return in;
}
void setup() { Serial.begin(115200); pinMode(CS, OUTPUT); digitalWrite(CS, HIGH); SPI.begin(); }
void loop() {
  xfer(0xFFFF);                                  // ask for the angle
  uint16_t raw = xfer(0xFFFF) & 0x3FFF;          // the answer comes now: 14 bits
  Serial.println(raw * 360.0 / 16384.0);         // degrees
  delay(10);
}
Worked example

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²CSPI
Wires2 for all the devices3 + one CS per device
Speed0.1 to 1 Mbit/s1 to 50 Mbit/s
Addressing7-bit address in the framea wire (CS)
Knows if the device is thereyes (ACK)no (a missing device reads as 0x00 or 0xFF)
Duplexhalffull
Typical useslow sensors, configuration, small screensencoders, 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?

  1. Mode 0
  2. Mode 1
  3. Mode 2
  4. Mode 3

Solution

Rule used CPOL = idle level; with CPOL = 1 the first edge is falling, so reading on the rising (second) edge means CPHA = 1 lesson 4 — 4.3 The four modes (table)

  1. Idle HIGH → CPOL = 1.
  2. Each pulse goes HIGH → LOW (leading) → HIGH (trailing, rising). Read on the trailing edge → CPHA = 1.
  3. CPOL 1, CPHA 1 = mode 3.

Answer D: mode 3

Level 2 · Intermediate2

An AS5047P encoder (14 bits) returns 0x2AAA after masking. What is the angle, in degrees?

Solution

Rule used angle = value × 360 / 2¹⁴ lesson 4 — 4.4 Reading a magnetic encoder

  1. 0x2AAA = 2 × 4096 + 10 × 256 + 10 × 16 + 10 = 10 922.
  2. 10 922 × 360 / 16 384 = 239.99 ≈ 240°.

Answer ≈ 240°

Level 2 · Intermediate3

SPI at 8 MHz. How long does it take to read 6 bytes from an IMU (plus 1 command byte), in µs?

Solution

Rule used 1 bit per clock pulse; time = bits / frequency lesson 4 — 4.2 A ring of shift registers

  1. 7 bytes × 8 = 56 clock pulses.
  2. 56 / 8 MHz = 7 µs (plus a little time for CS).
  3. The same 6 bytes over I²C at 400 kHz take about 250 µs.

Answer 7 µs

Check yourself
  1. 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).

  2. An SPI bus has 4 devices. How many wires leave the master (without ground)?

    3 shared + 4 CS = 7.

  3. 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:

BitCAN_HCAN_LDifferenceWho wins
0 = dominant≈ 3.5 V≈ 1.5 V≈ 2 Valways: one node sending 0 is enough
1 = recessive≈ 2.5 V≈ 2.5 V0 Vonly 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 rate1 Mbit/s500 kbit/s250 kbit/s125 kbit/s50 kbit/s
Max length (approx.)40 m100 m250 m500 m1 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

FieldBitsRole
Start of frame1dominant: everyone synchronises
Identifier11 (29 in extended)what the message is, and its priority
RTR, IDE, r03data or request, standard or extended
DLC4number of data bytes (0–8)
Data0–64the payload: 0 to 8 bytes
CRC15 + 1 delimitererror check
ACK1 + 1 delimiterany correct receiver writes a dominant bit here
End of frame7recessive

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?

  1. 0x210
  2. 0x20F
  3. 0x300
  4. none: the frames collide

Solution

Rule used the lowest identifier wins the arbitration (dominant 0 beats recessive 1) lesson 5 — 5.3 Arbitration

  1. In binary (11 bits): 0x210 = 010 0001 0000, 0x20F = 010 0000 1111, 0x300 = 011 0000 0000.
  2. Bit 9: 0x300 sends 1, the others 0 → 0x300 drops out.
  3. Bit 4: 0x210 sends 1, 0x20F sends 0 → 0x20F wins.

Answer B: 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 used after 5 identical bits, insert one opposite bit lesson 5 — 5.2 The frame

  1. 1 1 1 1 1 → stuff 0 → the 6th 1 starts a new run: (0) 1.
  2. Then 0 0 0 0 0 → stuff 1 → the 6th 0 follows.
  3. On the wire: 1111101 0000010: 2 stuff bits.

Answer 2 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 used load = frames/s × bits/frame ÷ bit rate lesson 8 — 8.2 The bus load

  1. Frames per second: 8 × 1000 = 8000.
  2. Bits per second: 8000 × 130 = 1 040 000.
  3. 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.

Answer 208 %: too much

Check yourself
  1. 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.

  2. 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).

  3. 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

TableSizeAccessOld numberingExample in a drive
Coils1 bitread / write00001…run / stop
Discrete inputs1 bitread only10001…fault present
Input registers16 bitsread only30001…measured current
Holding registers16 bitsread / write40001…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

CodeFunction
01 / 02read coils / discrete inputs
03 / 04read holding / input registers
05 / 06write 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.

Bytes (hex)Meaning
Request03 03 00 01 00 02 94 29slave 3, read holding registers, from address 1, 2 registers, CRC
Answer03 03 04 05 D9 00 EB 48 8Bslave 3, function 3, 4 bytes: 0x05D9 = 1497 rpm, 0x00EB = 235 → 2.35 A, CRC
Exception03 83 02 61 31slave 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.
  • 03 read, 06 write one, 16 write several; exception = function + 0x80.
  • “40002” in a datasheet = address 1 in the frame.

Key terms

  • RS-485, A/B
  • half duplex, DE/RE
  • termination, bias resistors
  • Modbus master, slave
  • coil, holding register, input register
  • function code
  • exception code
  • Modbus RTU, CRC-16
  • Modbus TCP, port 502
  • timeout

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 datasheet lists the speed set-point as holding register 40011. What address goes in the Modbus frame?

Solution

Rule used 4xxxx numbering starts at 40001 = address 0 lesson 6 — 6.2 The off-by-one trap

  1. 40011 − 40001 = 10.
  2. In the frame: 00 0A.

Answer 10 (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 used after address, function and byte count come the registers, high byte first lesson 6 — 6.4 The RTU frame (table)

  1. 03 = slave, 03 = function, 04 = 4 data bytes.
  2. First register 05 D9 = 1497; second 00 EB = 235.
  3. 235 × 0.01 = 2.35 A. The last two bytes 48 8B are the CRC.

Answer 2.35 A

Level 2 · Intermediate3

Which request writes the value 1500 into holding register address 0 of slave 3?

  1. 03 06 00 00 05 DC 8A E1
  2. 03 03 00 00 05 DC 8A E1
  3. 06 03 00 00 05 DC 8A E1
  4. 03 06 00 00 DC 05 8A E1

Solution

Rule used address, function 06, register (2 bytes), value (2 bytes, high first), CRC (low first) lesson 6 — 6.3 and 6.4

  1. Slave first: 03; then the function: 06 (write one register).
  2. Register 0: 00 00. Value 1500 = 0x05DC: 05 DC (big-endian).
  3. B reads (function 03), C swaps address and function, D swaps the value bytes.

Answer A

Check yourself
  1. 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.

  2. 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.

  3. 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

CauseWhat you seeCure
Motors switching (PWM), relays, weldingrandom bad frames when motors runtwisted pairs, differential bus, keep signal cables away from power cables, shielding, ferrites
No termination, long stubsrings on the edges, errors at high rate only120 Ω at both ends, short stubs
Ground difference between boardserrors that change with the load currentcommon ground wire, or isolated transceivers
Too much capacitance, weak pull-ups (I²C)rounded edges, NACKsshorter wires, smaller R, slower clock
Clock mismatch (UART)wrong characters, framing errorsexact 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:

CodeHowDetectsMisses
Parity bit1 bit: makes the number of 1s even (or odd)any odd number of flipped bits2 flipped bits in the same byte
Checksumsum of the bytes, modulo 256most single errorstwo bytes swapped; +1 on one byte and −1 on another
CRCremainder of a polynomial division (XOR)every burst shorter than the CRC, all 1- and 2-bit errors in short frames, swapsvery 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

  1. Timeout: never wait for an answer forever; after a set time, give up on this exchange.
  2. Retry, a limited number of times, then report the fault.
  3. Sequence counter: a number that increases in each message shows lost or repeated messages.
  4. 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.
  5. 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.

  1. 110
  2. 011
  3. 001
  4. 000

Hint

Append 3 zeros, then XOR 1011 under each leading 1.

Solution

Rule used CRC = remainder of (message followed by n zeros) divided by the generator, with XOR lesson 7 — 7.2, worked example

  1. 1001 000.
  2. 1001 ⊕ 1011 = 0010 → 0010 000 → next leading 1: 1000 ⊕ 1011 = 0011 → 0000 110.
  3. Remainder 110: the sender sends 1001 110.

Answer A: 110

Level 2 · Intermediate2

Bytes 0x12 and 0x34 are swapped by an error. Which check sees it?

  1. Parity per byte
  2. Sum of the bytes
  3. CRC
  4. None of them

Solution

Rule used parity and sum do not depend on the order of the bytes; the CRC does lesson 7 — 7.2 Detecting errors (table)

  1. Each byte keeps its own bits: each parity stays the same.
  2. 0x12 + 0x34 = 0x34 + 0x12: the sum is the same.
  3. In a CRC each bit is weighted by its position: the remainder changes.

Answer C: 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 used timeout = number of missed periods × period lesson 7 — 7.3 When the link fails

  1. 5 × 2 ms = 10 ms.
  2. Too short and noise stops the robot for nothing; too long and the robot keeps moving blind.

Answer 10 ms

Check yourself
  1. 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.

  2. 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.

  3. 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

UARTI²CSPICANRS-485 / ModbusEtherCAT
Wires (+ ground)223 + 1 per device2 (twisted)2 (twisted)Ethernet cable
Distance≈ 1 m (TTL)< 1 m< 0.3 m40 m at 1 Mbit/s1200 m100 m per link
Speedup to ≈ 1 Mbit/s0.1–1 Mbit/s1–50 Mbit/s1 Mbit/s (FD: 5)≤ 10 Mbit/s100 Mbit/s
Devices2≈ 100a few≈ 10032 (247 addresses)65 535
Who talksboth, any timemastermasteranyone (arbitration)mastermaster (frame passes through every slave)
Error checkparity (optional)ACK onlynoneCRC-15 + ACK + retriesCRC-16CRC-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

  1. 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.
  2. Power on, idle levels: UART TX HIGH, I²C SDA and SCL HIGH, CAN_H = CAN_L ≈ 2.5 V.
  3. One device at a time, at a low rate: I²C scanner, a loopback test (TX wired to RX), candump, a single Modbus read.
  4. 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.
  5. Then the meaning: right register, right unit, right byte order? Compare one value with the datasheet example.
  6. 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?

  1. I²C
  2. SPI
  3. RS-485 with Modbus RTU
  4. UART TTL

Solution

Rule used long distance + noise → differential bus; slow rate → RS-485 is enough lesson 8 — 8.1 The buses side by side

  1. I²C, SPI and TTL UART stop at about 1 m.
  2. RS-485 goes to 1200 m at 100 kbit/s, and Modbus is the usual language of drives and PLCs.

Answer C: 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 used load = frames/s × bits/frame ÷ bit rate lesson 8 — 8.2 The bus load

  1. 3000 × 120 = 360 000 bit/s.
  2. 360 000 / 1 000 000 = 0.36 → 36 %: comfortable.

Answer 36 %

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.

  1. b, d, a, c
  2. c, a, d, b
  3. a, b, c, d
  4. d, c, b, a

Solution

Rule used debug bottom-up: wires, levels, signals, meaning lesson 8 — 8.4 Bring up a link: a method

  1. (b) power off: resistances and continuity.
  2. (d) power on: idle levels.
  3. (a) the frames on the wires, decoded.
  4. (c) only then the meaning of the values.

Answer A: b, d, a, c

Check yourself
  1. 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.

  2. 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 %.

  3. 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.

TermMeaning
Baud rateNumber of bits per second on a serial line; one bit lasts 1 / baud.
FrameA complete unit sent on a bus: start, address or identifier, data, error check, end.
UARTAsynchronous serial port: TX and RX, start bit 0, data LSB first, optional parity, stop bit 1.
8N1UART format: 8 data bits, no parity, 1 stop bit (10 bits per byte on the wire).
I²CTwo-wire bus (SDA, SCL) with pull-up resistors, 7-bit addresses and an ACK after every byte.
Pull-up resistorA resistor that brings an open-drain line back HIGH when nobody pulls it LOW.
ACK, NACKAcknowledge: the receiver pulls SDA LOW on the 9th clock; NACK: it leaves it HIGH.
SPIFour-wire synchronous bus (SCLK, MOSI, MISO, CS), full duplex, MHz speeds, short distances.
CPOL, CPHAThe SPI mode: idle level of the clock, and the edge where data are read.
CAN busDifferential multi-master bus with identifiers, bitwise arbitration, CRC and automatic retries.
Dominant, recessiveOn CAN, 0 (dominant) overrides 1 (recessive) when nodes send together.
Bit stuffingAfter 5 equal bits, CAN inserts one opposite bit to keep an edge for synchronisation.
Termination120 Ω resistors at both ends of a CAN or RS-485 line, against reflections.
RS-485Differential physical layer for UART frames: up to 1200 m and 32 devices, half duplex on two wires.
ModbusMaster-slave protocol to read and write coils and 16-bit registers (RTU on serial lines, TCP on Ethernet).
Holding registerA 16-bit Modbus value that can be read and written (4xxxx).
CRCCyclic redundancy check: remainder of a division with XOR, used to detect errors.
Bus loadShare of the time a bus is busy: frames/s × bits/frame ÷ bit rate.
EtherCATIndustrial Ethernet where one frame passes through every drive, read and written on the fly.
Logic analyserA 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.

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. P. Koopman, T. Chakravarty, “Cyclic redundancy code (CRC) polynomial selection for embedded networks”, Proc. DSN, 2004. used for: what CRCs detect
  7. P. Horowitz, W. Hill, The Art of Electronics, 3rd ed., Cambridge University Press, 2015. used for: serial links, differential signalling, noise and grounding
  8. Arduino documentation and language reference, docs.arduino.cc; ATmega328P datasheet, Microchip. used for: Serial, Wire and SPI libraries, UART of the ATmega328P
  9. InvenSense (TDK), MPU-6000 and MPU-6050 Register Map and Descriptions, rev. 4.2. used for: the IMU registers of the I²C example
  10. ams OSRAM, AS5047P: 14-bit on-axis magnetic rotary position sensor, datasheet (SPI interface). used for: the magnetic encoder of the SPI example
  11. EtherCAT Technology Group, EtherCAT: the Ethernet fieldbus, technical introduction, ethercat.org. used for: EtherCAT principle and cycle times
  12. 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.

Go to the control course → Home page