Chapter 15: Communication Protocol
In the early 1980s, car makers had a problem made of copper. Every new feature — an electric window, an anti-lock brake, an engine sensor, a dashboard warning lamp — needed its own pair of wires running from one end of the car to the other. Each device was joined directly to every other device it had to talk to. Add ten devices and you do not add ten wires; you add the wiring needed for every pair that must speak. The bundle behind the dashboard grew until it was one of the heaviest and most failure-prone parts of the vehicle, and every extra joint was one more place for a bad connection to hide.
The engineering firm Bosch was asked to find a better way. Their answer, presented in Detroit in 1986, was a network they called the Controller Area Network, or CAN. Instead of a private wire between every pair of devices, every device would hang off one shared twisted pair, listen to everything sent along it, and keep only the messages meant for it. A production car carried it for the first time in 1991.
That idea — many devices, one shared conversation — is now how a robot’s parts talk to each other.
Photograph
Fig. 15.0-1 – a modern automotive or industrial wiring harness laid out flat before installation, showing the sheer bulk of the bundle and the many branch connectors; the frame must make the density of individual wires clearly visible. Sourcing note: a stock or manufacturer image of an unfitted harness is ideal; images showing only a fitted engine bay, or in which the wires are obscured by trim, are unusable
This chapter will answer all five of these questions.
15.1 Why a Robot Needs a Communication Protocol
A robot looks like one machine, but electrically it is a small crowd. The controller is one device. The distance sensor is another. So are the motor driver, the display, the wireless module and the board that measures tilt. None of them can do anything useful alone, and almost none of them can do anything useful without telling some other part what it has found or being told what to do.
The question this chapter answers is a plain one: how do two pieces of electronics, made by different manufacturers and knowing nothing about each other, exchange a number over a wire and both agree on what that number was?
15.1.1 Many Devices Inside One Machine
Consider a line following robot built in a school workshop. It carries an Arduino UNO as its controller, two infrared sensors under the chassis, an L298N motor driver feeding two motors, a small display, a Bluetooth module for a remote stop command, and an accelerometer and gyro module to detect if the robot has been lifted off the floor.
Look closely at what each of those parts actually has to say, because they are not all saying the same kind of thing.
The infrared sensor under the chassis reports one fact: dark surface or light surface. That is a single yes-or-no answer, and a single wire carries it perfectly well. The wire sits at a high voltage or a low voltage, the controller reads the pin, and the job is done. No agreement about speed, order or format is needed, because there is nothing to get out of order.
The accelerometer is a different matter. It has to report three acceleration values, each of which needs more than one bit to express, and it may need to be told first which measuring range to use. Now the two devices are exchanging information, not a state, and information sent along a wire arrives as a stream of voltage changes in time. Unless both ends agree in advance on how to read that stream, the receiver has no way to tell where one value ends and the next begins.
Signal lines and data links
This is the distinction that runs through the whole chapter, and it is worth fixing in Fig. 15.1-1 before anything else. A wire that carries one condition is a signal line. A connection that carries structured information is a data link, and a data link only works because both ends follow the same set of rules.
Diagram
Fig. 15.1-1 – block diagram of a line following robot: central block labelled Arduino UNO; on the left, two blocks labelled IR sensor 1 and IR sensor 2 joined to the controller by single plain arrows labelled “one signal line each, HIGH or LOW”; on the right, blocks labelled accelerometer and gyro module, display and Bluetooth module joined to the controller by double arrows labelled “data link”; below, a block labelled L298N motor driver joined by plain arrows labelled “control signals”; a note under the motor driver block reading “motor supply not shown”
That set of rules is what engineers call a protocol.
The word is borrowed from diplomacy, where protocol means the agreed order of proceedings at a formal occasion. The sense is the same. Nothing about a protocol is discovered by the devices at run time; all of it is settled beforehand, by the standard that both manufacturers followed.
15.1.2 Serial and Parallel Transmission
Before the rules can be discussed, one physical choice has to be made: how many bits travel at once?
A single letter stored in a controller is eight bits wide, and inside the chip those eight bits genuinely do move together, along eight parallel conductors. Sending them out of the chip the same way — eight wires, one bit on each, all eight arriving in the same instant — is called parallel communication. Sending them out along one wire, one bit after another, oldest first, is called serial communication.
Parallel transmission looks faster, and over a short distance at a low clock rate it is. Eight wires carry eight times as much per clock tick as one wire does. Printers and hard disks used wide parallel connections for years for exactly that reason.
Three problems ended that arrangement, and all three matter on a robot.
The first is pin count, and it is the one a student meets first. Eight data wires plus control wires consume most of a small controller’s input-output pins for one device.
The second is bulk. Eight or sixteen conductors bundled together make a stiff, heavy, expensive cable. On a robot arm that must flex through thousands of cycles, a thick cable is a mechanical part that will eventually fail.
The third is timing, and it is the one that ends the argument. The eight bits are only a valid byte if they arrive together. Real wires differ slightly in length, capacitance and routing, so the bits drift apart in time as they travel — an effect called skew. The faster the clock, the smaller the window in which all eight must land. Beyond a certain speed, a parallel link cannot be made wide and fast at once, while a serial link has no bits to keep aligned with each other and can simply be clocked harder.
Diagram
Fig. 15.1-3 – two panels; upper panel labelled “Parallel” showing a transmitter block and a receiver block joined by eight horizontal lines labelled D0 to D7, with the bit values 1 0 1 1 0 0 1 0 shown one on each line at the same instant; lower panel labelled “Serial” showing the same two blocks joined by one line, with the same eight bit values drawn along the line in sequence and a left-to-right time arrow underneath labelled “time”
UART, I2C, SPI and CAN are all serial. That is not a coincidence; it is the reason all four survived.
15.1.3 What a Protocol Must Fix Before Data Can Move
Imagine two people who must exchange a telephone number through a closed door, using only knocks. Knocking is easy. Agreeing what a knock means is the hard part, and until that is settled no number gets through.
They must agree on which side knocks and when, on how fast the knocks come so that a pause is not mistaken for a gap between digits, on some signal that marks the start of a number and another that marks its end, on what to do if both start knocking at once, and on how the listener says “I did not follow that, send it again”.
A communication protocol settles the same short list of questions for electronics, and every protocol in this chapter can be described completely by its answers:
- How many wires are used, and what does each one carry? Data in one direction, data in the other, a clock, a select line, a ground reference.
- How are the devices arranged? Two devices facing each other, or many devices sharing one bus.
- How is bit timing agreed? Either a shared wire carries a clock that marks each bit, or both ends are set to the same rate in advance and count their own time.
- How is the data packaged? How the receiver recognises where a byte starts, where it ends, and what any extra bits mean.
- How is one device told apart from another? By an address it answers to, by a dedicated wire that selects it, or not at all when only two devices exist.
- Who may transmit, and what happens if two try at once?
- How is an error caught? By an extra check bit, by a required reply from the receiver, by a calculated checksum, or not at all.
Question 7 deserves a warning that will be repeated through the chapter. A protocol that detects an error is not the same as a protocol that corrects one. Most of these four only detect, and one of them barely does even that. On a robot, the consequence of an undetected wrong byte is not a strange character on a screen; it is a motor that receives a speed it was never sent.
15.1.4 The Vocabulary Used to Describe a Protocol
The four protocols are compared, in this chapter and in industry, using the same handful of terms. They are set out here once so that later sections can use them without pausing.
Topology
The topology of a link is the shape of the connection: how many devices it joins and how they are arranged. A point-to-point topology joins exactly two devices. A bus topology runs one shared set of lines past many devices. A multi-node bus is a bus designed from the start for a large number of nodes rather than a handful.
Synchronisation
The two ends of a link must divide the passing time into bits the same way, and there are exactly two ways to arrange this.
In a synchronous link, one extra wire carries a clock line: a signal that ticks once per bit, generated by one device and followed by all the others. The receiver does not need to know the speed in advance, because the clock tells it when to look at the data line. Change the clock rate mid-transfer and the link still works.
In an asynchronous link, there is no clock wire. Both ends are configured beforehand to run at the same rate, and each keeps its own time from its own oscillator. This saves a wire and costs an agreement: if the two rates differ by more than a small percentage, the receiver drifts off the bit boundaries and reads rubbish.
Master and slave
On most buses, one device is in charge. The master generates the clock where there is one, decides when a transfer happens and chooses which other device it is addressing. The devices that answer are the slaves; a slave never begins a transfer on its own. Some buses allow more than one master, in which case the protocol must also decide what happens when two masters want the bus at the same moment.
Addressing and arbitration
Addressing is how a master picks out one device among many on a shared bus. It may be done with a number that each slave answers to, or with a separate wire per slave.
Arbitration is the rule that decides who wins when two devices begin transmitting at the same instant. A bus with only one master needs no arbitration, because no contest can arise.
Duplex
Simplex means data flows one way only. Half-duplex means it can flow either way, but only one way at a time, because the two directions share a line. Full-duplex means both directions can carry data simultaneously, which requires a separate line for each direction. Fig. 15.1-4 makes the distinction visible.
Diagram
Fig. 15.1-4 – three horizontal panels, each with two device blocks labelled A and B; top panel labelled “Simplex” with one arrow from A to B; middle panel labelled “Half-duplex” with a single line between A and B carrying a double-headed arrow and a note reading “one direction at a time”; bottom panel labelled “Full-duplex” with two separate lines between A and B, one arrow on each, pointing in opposite directions
Speed, throughput and latency
The raw speed of a link is its bit rate, the number of bits pushed onto the line each second, measured in bits per second (bps) and its multiples kbps and Mbps.
Bit rate is not the same as useful data delivered. Every protocol adds extra bits that carry no user data — start and stop markers, addresses, acknowledgements, check bits. These extra bits are the overhead, and what is left is the throughput: the amount of actual data transferred per second. A link running at 100 kbps with 20% overhead delivers 80 kbps of data.
Latency is a different quantity again: the delay between a device deciding to send something and the receiver having it. A link can have high throughput and poor latency, and for a robot latency is often what matters. A bus that streams camera frames beautifully is still the wrong choice for an emergency stop command that must arrive within a millisecond.
Range
Range is the greatest wiring length over which the link stays reliable. It is not a property of the data alone; it depends on the voltages used, on whether the signal is carried as a single voltage or as a difference between two wires, and on how the electrical noise of a robot’s own motors couples into the cable.
These ten terms are the frame on which the rest of the chapter is built. Each of the next four sections describes one protocol by filling them in, and section 15.6 sets the four completed answers side by side.
15.2 UART
The first of the four is also the oldest and the simplest. UART stands for Universal Asynchronous Receiver/Transmitter, and the name describes a piece of hardware rather than a wire. It is the module that turns bytes into a stream of voltage changes and back again, and almost every microcontroller has at least one built in.
If you have ever opened the Serial Monitor in the Arduino IDE and watched sensor readings scroll past, you have already used it.
15.2.1 Working Principle
Inside the controller, a byte exists as eight bits held side by side in a register. On the wire, it must exist as eight voltage levels held one after another in time. Something has to perform that conversion, and that something is the UART.
The conversion is done with a shift register. To transmit, the byte is loaded into the register and then shifted out one bit at a time onto the transmit line, at a rate the module counts out for itself. To receive, the incoming bits are shifted into a register until a full byte has arrived, at which point the processor is told that a byte is waiting. Fig. 15.2-1 shows the arrangement.
Diagram
Fig. 15.2-1 – block diagram of a UART inside a microcontroller: a block labelled CPU joined by a wide arrow labelled “8 bits in parallel” to a block labelled Transmit shift register, which drives a single line labelled TX leaving the chip boundary; alongside it a single line labelled RX entering the chip and feeding a block labelled Receive shift register, joined by a wide arrow labelled “8 bits in parallel” back to the CPU; a small block labelled Baud rate generator with arrows to both shift registers; the chip boundary drawn as a dashed rectangle
Notice what is not in that diagram: there is no clock wire leaving the chip. This is the meaning of the A in the name. UART is asynchronous, so the two ends never share a timing signal. Each counts its own bit periods from its own oscillator, and the whole scheme rests on their having been set to the same rate beforehand.
That leaves one problem. If the line simply sits at some voltage between bytes, how does the receiver know when a new byte has begun? The answer is a convention about the idle state. An idle UART line is held high. A transmission always opens by pulling the line low for exactly one bit period, and the receiver watches for that falling edge. Once it sees it, it knows where the byte begins and can count off the bits that follow.
15.2.2 The Data Frame and the Baud Rate
The bits sent for one character are called a frame, and its layout is fixed before communication begins. Fig. 15.2-2 shows the most common arrangement.
Diagram
Fig. 15.2-2 – timing waveform of one UART frame, drawn as a two-level line against a left-to-right time axis; the line begins high, labelled “idle (high)”; it drops for one bit period labelled “start bit (low)”; eight equal bit periods follow, labelled D0 to D7 with a note reading “least significant bit first” and the values 1 0 0 0 0 0 1 0 marked; one further bit period labelled “parity bit (optional)”; then the line returns high for one bit period labelled “stop bit (high)”; a bracket under the whole waveform labelled “one frame, 10 bit periods in 8N1”; a second bracket under one bit period labelled “bit period = 1 / baud rate”
A frame consists of:
- A start bit. One bit period at the low level, marking the beginning of the frame.
- The data bits. Usually eight, sent least significant bit first. Five to nine bits are permitted by the standard, but eight is used almost everywhere.
- A parity bit, optionally. One extra bit used for error checking, described in section 15.2.7.
- A stop bit. One bit period at the high level, or two if configured that way, which returns the line to idle and guarantees a falling edge at the start of the next frame.
This configuration is written compactly. The very common setting of eight data bits, no parity and one stop bit is written 8N1, and it puts ten bit periods on the wire for every eight bits of user data.
Baud rate
The rate at which those bit periods pass is the baud rate.
That last sentence matters. Baud and bits per second are not the same quantity in general — a modem that encodes four bits in every symbol has a bit rate four times its baud rate — but for the UART links in this chapter the two numbers are identical, and engineers use the words interchangeably when talking about UART.
Common settings are 9600, 19200, 38400, 57600 and 115200 baud. Many microcontrollers can be pushed to around 1 Mbps over a short, clean connection.
At 9600 baud one bit period lasts
\[t_{bit} = \frac{1}{9600} \text{ s} = 104\ \mu\text{s}\]
so a complete 8N1 frame occupies about 1.04 ms. Of the ten bit periods, only eight carry data, so 20% of the line’s capacity is overhead. The useful throughput at 9600 baud is \(9600 \times 8/10 = 7680\) bps, or 960 bytes each second.
On an Arduino board the rate is fixed in one instruction, which must be given before any data is sent.
What happens when the rates differ
Because neither end can check the other’s timing, a mismatch is not detected — it is simply misread.
The receiver finds the falling edge of the start bit, then samples the line near the middle of each bit period that it counts out for itself. If its bit period is slightly wrong, the sampling point drifts a little further from the middle with each bit, and by the eighth bit the accumulated drift can push the sampling point into the neighbouring bit. In practice a combined mismatch of more than roughly 2% is enough to corrupt an 8N1 frame, which is why microcontrollers intended for serial work use a crystal oscillator rather than an internal resistor-capacitor timing circuit.
15.2.3 Wiring and Topology
A UART link needs three conductors, and the third one is the one students forget.
The transmit line of one device, marked TX, connects to the receive line of the other, marked RX. The RX of the first connects to the TX of the second. The lines cross, as in Fig. 15.2-3, because each device’s output must meet the other’s input.
Diagram
Fig. 15.2-3 – two blocks labelled Device 1 and Device 2, each showing three terminals stacked as TX, RX and GND; a line from Device 1 TX crossing to Device 2 RX with an arrow showing the direction of flow; a second line from Device 2 TX crossing to Device 1 RX with its own direction arrow; a third straight line joining the two GND terminals, drawn thicker and labelled “common ground — required”; a note beside the crossed pair reading “TX always meets RX”
The third conductor joins the two grounds. A logic level is only a voltage measured with respect to something, and if the two boards have no shared reference there is nothing for the receiver to measure against. Section 15.7.1 returns to this, because it is the single most common cause of a serial link that refuses to work.
Serial modules often carry more pins than these three. Beside TX, RX and ground there is usually a supply pin, marked VCC, and larger modules may provide hardware flow control lines such as DTR (Data Terminal Ready) and CTS (Clear To Send), which let a slow receiver tell the sender to pause. Flow control is rarely wired on a small robot.
The topology is point-to-point and cannot be anything else. Two devices, two crossed signal wires. A third device cannot simply be tapped onto the same pair, because two transmitters driving one receive line will fight each other and neither message will survive.
15.2.4 Key Characteristics
Filling in the vocabulary of section 15.1.4 gives the profile in Table 15.3, which is the form used for all four protocols in this chapter.
15.2.5 Uses in Robotics
UART earns its place on a robot through minimal wiring and almost no setup. Its uses fall into four groups.
Bluetooth communication. A Bluetooth module such as an HC-05 presents itself to the controller as an ordinary serial device. Whatever the controller writes to the module is transmitted wirelessly, and whatever arrives wirelessly appears as bytes to be read. This is how a robot is driven from a phone or a laptop without any change to the controller’s own program.
GPS module interface. A satellite navigation receiver, such as a NEO-6M module, continuously sends position sentences over a UART link, typically at 9600 baud. The controller simply reads them as text. The same pattern appears with many scanning LIDAR units, which stream their distance readings out over a serial line.
Serial monitoring and debugging. The link between the board and the computer through the USB cable is a UART link. Printing the value of a variable so it can be watched while the robot runs is the most heavily used debugging tool a student has, and it costs nothing but a Serial.begin() and a Serial.print().
Microcontroller-to-microcontroller link. In a robot split across two boards — one handling motion, one handling navigation — a UART link is the easiest way for them to pass short commands and status messages to each other.
15.2.6 Speed and Performance
UART offers moderate speed. The usual working range of 9600 to 115200 bps is comfortable for short commands, text messages and periodic sensor readings, and some devices support a few Mbps, but the protocol is not built for bulk. Compared with SPI it offers far lower throughput and is a poor choice for large or fast transfers such as image data.
Three effects shape its performance in a robot.
The first is the fixed 20% framing overhead. Every eight bits of data drag two extra bit periods behind them, and no configuration removes them.
The second is the dependence on matched oscillators. Being asynchronous, the link relies on both ends holding closely matched rates, and drift shows up as corrupted frames rather than as a warning. Over short distances with crystal oscillators this is rarely a problem in practice.
The third is latency. For a short message the delay between sending and receiving is small, but it grows in proportion to message length and inversely with baud rate, so a long message at a low rate can arrive noticeably late. This is worth checking rather than assuming.
\[N = 8 \text{ characters} \times 10 \text{ bit periods per character} = 80 \text{ bit periods}\]
\[t = \frac{80}{9600 \text{ bit periods per second}} = 8.33 \times 10^{-3} \text{ s} = 8.33 \text{ ms}\]
Answer: one reading takes 8.33 ms to transmit, which fits inside the 20 ms interval with room to spare, so 9600 baud is adequate. Check: the answer is a little under half the available interval, which is sensible for 80 bits at roughly a hundred microseconds each. Had the same message been sent at 2400 baud it would need 33.3 ms — longer than the interval between readings — and the transmit buffer would fill until readings were lost. The margin, not the raw speed, is what makes a rate adequate.
Distance and line drivers
The signals a microcontroller’s UART produces are single-ended logic levels referred to ground, and they degrade quickly along a cable. A few metres at 9600 baud is realistic; at 115200 baud the usable length is shorter still.
Where the same data must travel further, the UART frames are handed to a line driver that puts them on the cable in a more robust electrical form. Standards such as RS-485 do exactly this, carrying the identical frame structure as a difference between two wires, which resists noise far better and reaches hundreds of metres. The framing is unchanged; only the electrical layer beneath it is replaced.
15.2.7 Error Detection and Reliability
UART’s error handling is deliberately thin, and knowing precisely what it does and does not catch is the point of this subsection.
The parity bit
Parity is the one optional check the protocol provides. One extra bit is appended to the data bits, and its value is chosen so that the total number of 1 bits in the frame satisfies an agreed rule. Under even parity, the parity bit is set so that the number of 1s is even; under odd parity, so that it is odd. Both ends must be configured for the same choice.
The receiver counts the 1s in the frame it received and checks the rule. If the count is wrong, the hardware flags a parity error.
The protection this gives is real but narrow. A single flipped bit always changes the count from even to odd or the reverse, so it is always caught. Two flipped bits in the same frame restore the original parity and pass unnoticed. Parity detects an odd number of bit errors, nothing more, and it can never say which bit was wrong, so it cannot correct anything.
Framing errors
The second check needs no extra bit. The receiver knows a stop bit must be present, at the high level, at a particular instant. If it finds the line low there instead, it raises a framing error. This usually means the two ends are running at mismatched rates, or that noise has disturbed the line badly enough to shift the bit boundaries.
What UART does not do
UART has no built-in error correction, no acknowledgement and no automatic retransmission. Nothing in the protocol tells the sender whether its byte arrived. If parity is not enabled — and in the default 8N1 setting it is not — corrupted data can pass into the program entirely unnoticed.
That is acceptable for a debug message on a screen, where a wrong character is obvious and harmless. It is not acceptable for a speed command sent to a motor board, and this is where a designer must add protection above the protocol rather than expect it from below: send a fixed message terminator so a truncated message can be recognised, add a checksum byte calculated from the message contents, and have the receiver reply with a short acknowledgement so the sender knows to repeat anything unanswered.
Within a well-made short link — clean wiring, a common ground, matched rates, sensible baud — UART is reliable in ordinary use. Its limitation is not that it fails often; it is that when it does fail, it fails quietly.
15.3 I2C
UART solved the problem of two devices talking. It did nothing for the problem that started this chapter: a robot has more than two devices, and a point-to-point link for each of them consumes pins the controller does not have.
I2C, short for Inter-Integrated Circuit, was designed for exactly that situation. Its name says where it was meant to work — between integrated circuits sitting on the same board — and its achievement is that it connects a whole crowd of them using two wires in total, however many devices there are.
15.3.1 Working Principle
I2C is a two-wire synchronous serial bus. Every device on it connects to the same two signals and to a common ground:
SCL, the serial clock line, which marks off the bits.SDA, the serial data line, which carries them.
Because the clock travels on its own wire, the receiver is never guessing at timing. It simply reads the data line each time the clock says a bit is valid. Nothing has to be agreed about speed in advance, which is the first practical advantage over UART: change the master’s clock rate and the slaves follow without being reconfigured.
Fig. 15.3-1 shows the arrangement that gives the bus its shape.
Diagram
Fig. 15.3-1 – I2C bus topology: a block labelled Master (microcontroller) on the left with two terminals labelled SDA and SCL; two long horizontal lines running to the right labelled SDA and SCL; six blocks labelled Slave 1 to Slave 6 arranged above and below the lines, each joined to both lines by short stubs; at the right-hand end, two resistors labelled “pull-up resistors” joining each line to a rail labelled VDD; a third horizontal line at the bottom joining every block, labelled “common ground”; a note reading “every device connects to the same two signals”
The master controls everything that happens. It starts each transfer, supplies every clock pulse, names the device it wants and decides whether that device is to be written to or read from. A slave has no way to start a conversation; it can only answer.
Because there is only one data line, the two directions cannot be used at once. I2C is half-duplex: the master and the addressed slave take turns on SDA.
15.3.3 Addressing and the Master–Slave Exchange
With everyone on the same two wires, the master needs a way to name the device it wants. I2C does this with an address built into each slave.
Each slave answers to a 7-bit address, which allows 128 combinations. Sixteen of those are reserved by the standard for special purposes, leaving about 112 usable addresses on one bus. A 10-bit addressing mode also exists but is rarely met in robotics.
The address is not chosen by the designer of the robot; it is fixed by the manufacturer of the chip, and it appears in the device’s datasheet. Many devices allow one or two bits of the address to be changed by tying an address-select pin high or low, so that two identical sensors can live on one bus.
A complete transfer runs like this, and Fig. 15.3-3 shows it as a waveform:
- The master issues a START condition, which claims the bus.
- The master sends the 7-bit address of the slave it wants, followed by one bit stating whether it intends to write or to read.
- Every slave on the bus compares that address with its own. The one that matches pulls
SDAlow during the ninth clock pulse to acknowledge. Every other slave stays silent for the rest of the transfer. - Data bytes pass in the chosen direction, each one followed by a ninth clock pulse in which the receiver acknowledges it.
- The master issues a STOP condition, releasing the bus.
Diagram
Fig. 15.3-3 – I2C transaction waveform: two stacked lines labelled SDA and SCL against a left-to-right time axis; at the left, SDA falling while SCL is high, marked START; then seven bit periods on SDA labelled A6 to A0 marked “slave address”, followed by one bit labelled “R/W”; the ninth clock period marked ACK with a note reading “pulled low by the addressed slave”; then eight bit periods labelled D7 to D0 marked “data byte” followed by a second ACK; at the right, SDA rising while SCL is high, marked STOP; a bracket beneath each group of nine periods labelled “8 bits + 1 acknowledgement”
That ninth bit is the acknowledgement, usually written ACK. It is not decoration. It is the only means either device has of learning whether the byte it just sent was received by anything at all, and section 15.3.7 returns to what it can and cannot prove.
15.3.4 Key Characteristics
Table 15.5 fills in the same profile used for UART in Table 15.3.
15.3.5 Uses in Robotics
I2C is the bus a small robot uses for its instruments. Its value is not speed; it is that a controller with two pins committed can serve a dozen devices.
Sensor modules. Gyroscopes, accelerometers, magnetometers, barometric pressure sensors and temperature sensors are supplied almost universally with an I2C interface. The combined accelerometer and gyro module used in the school laboratory is read this way: two wires carry all six measurements plus the configuration settings that select their ranges.
Displays and small peripherals. Character and OLED displays, real-time clocks and input-output expanders commonly offer I2C for the same reason. A liquid crystal display driven directly needs six or more controller pins; the same display behind an I2C adapter needs two, and shares them with everything else.
Compact, sensor-rich robots. Because devices are distinguished by address rather than by wire, adding a sensor late in a project costs no pins at all. On a robot where the controller is already crowded, that is often the deciding argument.
On an Arduino board the bus is driven by the Wire library, which handles the START and STOP conditions, the addressing and the acknowledgement bits, so that a program deals only with the device address and the bytes exchanged.
15.3.6 Speed and Performance
The bus runs in defined modes, listed in Table 15.6. The mode is set by the master’s clock rate, and the slowest device on the bus limits the whole bus.
For robotic sensing, 100 kbps or 400 kbps is almost always sufficient. Reading a compass heading or refreshing a small display places a trivial load on the bus.
Three effects limit what I2C can do.
The first is per-byte overhead. Every byte occupies nine clock periods rather than eight, because of the acknowledgement, so at best eight-ninths of the clock carries data. Address bytes, START and STOP conditions add more.
The second is that the master controls everything. A master reading six sensors in turn must complete one transaction before beginning the next, and the delays add up. Nothing on the bus can report an event by itself.
The third is the wiring. Every centimetre of track and every extra device adds bus capacitance, which slows the rise of the line when the pull-up releases it. Beyond about a metre, or with many devices, edges become sluggish and the bus grows unreliable. I2C was designed to travel across a circuit board, not across a robot.
\[N = 9 \text{ bytes} \times 9 \text{ clock periods per byte} = 81 \text{ clock periods}\]
\[t_{clock} = \frac{1}{400 \times 10^{3}} \text{ s} = 2.5\ \mu\text{s}\]
\[t = 81 \times 2.5\ \mu\text{s} = 202.5\ \mu\text{s} \approx 0.20 \text{ ms}\]
\[\text{fraction of the interval} = \frac{0.20 \text{ ms}}{5 \text{ ms}} = 0.04 = 4\%\]
Answer: the transaction occupies the bus for about 0.20 ms, which is 4% of the 5 ms interval. Check: the magnitude is sensible — 81 bits at 2.5 µs each must be a fraction of a millisecond. The margin also shows why I2C suits a sensor-rich robot: at 4% per sensor, a dozen devices can be read at this rate and the bus is still idle most of the time. Repeat the calculation at 100 kbps and the same transaction takes 0.81 ms, or 16% of the interval — still workable, but four devices would now consume two-thirds of it.
Set against the other three protocols, I2C sits in the middle. It is far slower than SPI and is unsuitable for streaming video or audio. It is not, however, slower than an ordinary UART link: a fast-mode bus at 400 kbps moves data several times faster than a serial connection running at 115200 bps, and comparisons that place UART above it are comparing UART’s rare upper limit with I2C’s ordinary setting.
15.3.7 Error Detection and Reliability
I2C detects more than UART does, and for a specific reason: it insists on a reply.
The acknowledgement
After every byte, the receiver must pull SDA low during the ninth clock pulse. If it does, the byte was received and the transfer continues. If the line stays high, that is a NACK, and the master learns immediately that something is wrong.
This is genuinely useful diagnostic information. A sensor that has come loose, lost power or been wired to the wrong address produces a NACK on the very first byte, so the master can report a missing device rather than silently using stale readings. Many programs use exactly this to scan a bus and list which addresses respond.
The limit of the acknowledgement is worth stating plainly: it confirms that a device was present and clocked in the byte. It says nothing whatever about whether the eight bits were the eight bits that were sent.
What I2C does not check
There is no checksum, no cyclic redundancy check and no error correction. A bit corrupted by noise on the data line is acknowledged as cheerfully as a correct one. I2C detects the absence of a device far better than it detects the corruption of a message.
Arbitration between masters
Where a bus carries more than one master, the two could begin transmitting at the same instant. I2C resolves this without losing data. Every transmitting master reads the line back as it drives it; a master that releases the line for a 1 but finds it held low by someone else knows it has lost and withdraws immediately. The message that continues is unaffected, and the loser retries when the bus is free.
Clock stretching
A slave that needs more time — a sensor that has not finished a conversion, for instance — may hold SCL low after the master releases it. The master waits until the line rises again. This is called clock stretching, and it lets a slow device stay on a fast bus without corrupting the exchange.
Practical reliability
Two features make the bus electrically forgiving. Devices can only pull lines low, so contention causes no damage; and every byte is confirmed, so a broken connection is noticed rather than assumed away.
Against that, reliability depends heavily on the wiring, and the failure modes are specific to this bus. Missing pull-ups leave floating lines. Too many pull-ups in parallel prevent devices pulling low. Long runs add capacitance and blur the edges. A slave that resets part-way through a transfer can hold SDA low and lock the bus until it is clocked free or the power is cycled.
Kept short, kept on one board or one small chassis, and given one correct pair of pull-ups, I2C is dependable. Stretched across a robot with motors running beside it, it is the first thing to fail.
15.4 SPI
I2C bought its two-wire economy with time. Every byte carries an acknowledgement, every transfer opens with an address, and the single data line forces the two directions to take turns.
SPI, the Serial Peripheral Interface, makes the opposite bargain. It spends wires freely and wastes almost no time at all. Where a robot must move a great deal of data quickly over a very short distance — a display buffer, a memory card, a sensor sampled hundreds of times a second — SPI is the interface it uses.
15.4.1 Working Principle
SPI is a high-speed synchronous serial interface with a master–slave architecture. The master supplies the clock and begins every transfer, exactly as in I2C. What happens during that transfer, however, is quite different.
Picture two shift registers, one in the master and one in the slave, joined end to end so that they form a single closed ring, as in Fig. 15.4-1. Each clock pulse shifts every bit in the ring one place along. A bit leaves the master and enters the slave; at the same instant, a bit leaves the slave and enters the master.
Diagram
Fig. 15.4-1 – two blocks side by side labelled Master and Slave, each containing an eight-cell shift register drawn as a row of boxes; an arrow from the master’s last cell to the slave’s first cell labelled MOSI; an arrow from the slave’s last cell to the master’s first cell labelled MISO; a clock line labelled SCLK drawn from the master to the slave with an arrow into both registers; a curved arrow around the whole arrangement labelled “one closed ring: eight clock pulses exchange the two bytes”
After eight clock pulses, the byte that was in the master is in the slave, and the byte that was in the slave is in the master. They have not been sent one after the other; they have been swapped.
This single fact explains most of SPI’s behaviour. It is inherently full-duplex, because the two directions never share a line. It has no concept of a message being “sent” — only of bytes being exchanged. And when the master wants to read from a slave and has nothing to give it, it must still clock something out, so it sends a meaningless value, usually all ones, purely to drive the exchange. Such a value is called a dummy byte.
There is also a great deal that SPI does not do. There is no start condition, no stop condition, no address in the data stream, no acknowledgement bit and no error check. The protocol is little more than a clock and two data lines, and that austerity is where its speed comes from.
15.4.2 The Four Lines and the Slave Select
A minimum SPI connection uses four signal lines plus a ground reference:
SCLK, the serial clock, generated by the master.MOSI, Master Out Slave In — the line carrying data from master to slave.MISO, Master In Slave Out — the line carrying data from slave to master.SS, Slave Select, sometimes markedCSfor chip select.
The first three are shared by every slave on the bus. The fourth is not, and this is the crucial point of Fig. 15.4-2: each slave gets its own SS line, running back to a separate pin on the master.
Diagram
Fig. 15.4-2 – a block labelled Master (microcontroller) on the left with terminals SCLK, MOSI, MISO, SS1 and SS2; two blocks on the right labelled Slave 1 and Slave 2, each with terminals SCLK, MOSI, MISO and SS; three lines running from the master to both slaves, labelled SCLK, MOSI and MISO, each shown branching to reach both; two separate lines labelled SS1 and SS2, each running to only one slave; a common ground line joining all three blocks; a note reading “shared clock and data, one select line per slave”
The select line replaces addressing. To talk to a device, the master pulls that device’s SS line low — these lines are normally active-low — and holds it low for the whole transfer. The selected slave listens to the clock, drives MISO and responds. Every unselected slave must ignore the clock entirely and release MISO into a high-impedance state, so that it neither drives the shared line nor loads it.
The consequence is a trade. Addressing costs no wires in I2C and one pin per device in SPI. Two slaves need five lines; six slaves need nine. On a controller with limited pins, this is what eventually stops a designer adding another SPI device.
Push-pull outputs
Unlike I2C, SPI lines are push-pull: a driver actively pulls its line high as well as low. No pull-up resistors are needed, and the edges are far sharper, which is a large part of why SPI clocks so much faster than I2C. The price is that two devices driving one line would genuinely oppose each other, which is why correct handling of the select lines matters so much.
Clock polarity and phase
Both ends must also agree on which clock edge carries the data. A slave may expect the master to place a bit on the rising edge and sample on the falling edge, or the reverse, and it may expect the clock to idle high or low. The four combinations are known as SPI modes 0 to 3, and they are stated in every device’s datasheet.
A mismatch here does not stop the transfer. The clock still runs, bytes still arrive, and they are simply wrong — usually shifted by one bit position. It is a fault that looks like a broken sensor and is in fact a configuration line.
15.4.3 Key Characteristics
15.4.4 Uses in Robotics
SPI appears wherever the quantity of data, or the rate at which it must be sampled, defeats the other options.
Displays and memory cards. A graphic display has to be given every pixel it shows, and a memory card stores logged data in blocks of hundreds of bytes. Both are impractical on a slower bus. The four-in-one LED matrix display used in the school laboratory is driven this way: the controller shifts the pattern for every column of every panel out along MOSI.
Fast sensors. Where a gyroscope or an analogue-to-digital converter must be sampled hundreds or thousands of times a second, SPI is preferred over I2C. Many inertial measurement units offer both interfaces on the same chip precisely so that the designer can choose.
Shift registers and driver chips. LED drivers and shift registers exist to turn a few controller pins into many outputs, and they are clocked in over SPI. This is a common way to drive more indicators than a controller has pins for.
Add-on boards. Both Arduino boards and the Raspberry Pi expose an SPI interface on their headers for connecting shields and modules. On an Arduino UNO the pins are fixed: 13 for SCLK, 12 for MISO, 11 for MOSI and 10 for the default SS, with the SPI library handling the transfers.
The limitation on all of this is the select line. Each device needs its own, so a robot with many SPI peripherals runs out of pins long before it runs out of bandwidth.
15.4.5 Speed and Performance
Two things make SPI fast, and only one of them is the clock rate.
The first is that the clock can genuinely run at megahertz rates, because push-pull drivers produce sharp edges and the wiring is short. SPI fixes no standard rate; the master chooses it, and the ceiling belongs to the board rather than to the protocol. An Arduino UNO divides its 16 MHz system clock by a minimum of two, so 8 MHz is its limit; more capable controllers and single-board computers run at tens of megahertz. Quoted ranges such as 1 Mbps to 20 Mbps describe microcontrollers as a family, and a speed is only meaningful when the board it belongs to is named.
The second matters just as much: SPI has almost no overhead. There is no address to send, no acknowledgement to wait for, no start or stop condition. Eight clock pulses transfer eight bits of data and nothing else, so nearly the whole clock rate turns into throughput. Add full-duplex operation, and a byte can travel each way in the time another protocol would take to send one.
\[\text{buffer} = 128 \times 64 = 8192 \text{ bits} = 1024 \text{ bytes}\]
For SPI:
\[t_{SPI} = \frac{8192 \text{ bits}}{8 \times 10^{6} \text{ bits per second}} = 1.024 \times 10^{-3} \text{ s} = 1.02 \text{ ms}\]
For I2C:
\[N = 1024 \times 9 = 9216 \text{ clock periods}\]
\[t_{I2C} = \frac{9216}{400 \times 10^{3}} \text{ s} = 23.0 \times 10^{-3} \text{ s} = 23.0 \text{ ms}\]
Answer: about 1.02 ms over SPI and about 23.0 ms over I2C — SPI is roughly 22 times faster for this transfer. Check: the two results should differ by the clock ratio multiplied by the overhead ratio: \(20 \times 9/8 = 22.5\), which matches. The practical meaning is a design decision rather than a number. At 23 ms a full refresh, the I2C display cannot be redrawn more than about forty times a second even if the controller does nothing else; over SPI the same redraw costs one millisecond, leaving the controller free to run the robot.
Why the range is so short
Everything that makes SPI fast also makes it fragile over distance. The signals are single-ended logic levels referred to ground, switching at megahertz rates. Long unshielded wires add capacitance that rounds the edges, allow the clock to couple into the data lines, and pick up interference from the robot’s own motors. There is no error check to catch the result.
SPI was designed to travel across a printed circuit board, and it should be treated as a board-level or module-level interface.
A useful practical point follows from the clock being under the master’s control: devices with different speed limits can share one bus, because the master can lower the clock rate before selecting a slow device and raise it again for a fast one.
15.4.6 Error Detection and Reliability
This is the shortest of the four discussions, because there is almost nothing to describe.
SPI includes no error detection whatsoever. There is no parity bit as in UART, no acknowledgement as in I2C, and no checksum. A bit corrupted anywhere between the two shift registers arrives as data and is used as data.
Nor can the master tell whether a slave is even present. Address a missing device on an I2C bus and the absent acknowledgement announces the fault at once. Select a missing device on an SPI bus and the master clocks eight pulses into empty air, reads whatever level the floating MISO line happens to sit at, and hands the program a byte of all ones or all zeros as though it were a measurement. A student debugging a sensor that reads a constant value should suspect the wiring before the sensor.
Reliability therefore rests entirely on the physical connection. Within a well-designed board with short tracks, clean grounding and correctly handled select lines, errors are genuinely rare — rare enough that the absence of checking is a reasonable engineering choice rather than an oversight. Stretch the same link across a chassis beside a motor driver and the assumption stops holding.
Where the data matters, protection is added above the protocol. Two common measures are a checksum byte appended to each block, recalculated by the receiver, and an echo response in which the slave returns the previous command so the master can confirm what was understood.
One further failure mode belongs to this interface alone. Because the outputs are push-pull, two slaves left selected at the same time will both drive MISO, opposing each other directly. The data is lost, and unlike the open-drain lines of I2C, the contention is electrically real. Mishandled chip-select lines are the characteristic SPI fault, and they are worth checking first when a bus that worked with one device stops working with two.
15.5 CAN
The three protocols so far share an assumption: that the wire is a quiet place. UART tolerates a few metres, I2C rather less, SPI less again. All three are single-ended, all three carry logic levels measured against ground, and none of them survives long in the company of a motor drawing several amperes a few centimetres away.
CAN, the Controller Area Network, was built for the opposite conditions. It is the network described at the start of this chapter, designed for the electrical mess inside a vehicle, and it is the protocol a robot reaches for when the parts that must talk are far apart, when the environment is noisy, and when a message going astray is not an inconvenience but a hazard.
15.5.1 Working Principle
CAN is a serial communication network in which every node connects to the same two-wire bus and hears everything that passes along it. Three design choices distinguish it from everything so far.
It is multi-master. There is no central controller. Any node may begin transmitting whenever it finds the bus free, without asking permission from anyone. Where I2C and SPI have a master that decides who speaks, CAN has a rule that settles the matter when two nodes speak at once.
It is broadcast-based. A message is not addressed to a recipient. When a node transmits, every other node on the bus receives the message, and each one decides for itself whether to keep it or discard it.
Messages are identified, not addressed. Every CAN message carries a message identifier that describes what the message is — a wheel speed, a battery voltage, a stop command — rather than who it is from or where it is going. A node is configured to accept the identifiers it cares about and ignore the rest.
This last idea takes some getting used to, because it inverts the usual arrangement. Fig. 15.5-1 shows what it looks like physically.
Diagram
Fig. 15.5-1 – CAN bus topology: a horizontal twisted pair drawn as two intertwined lines labelled CAN_H and CAN_L running the width of the figure; four blocks below labelled Node 1 to Node 4, each containing two sub-blocks labelled “CAN controller” and “CAN transceiver” with a short stub joining the transceiver to the twisted pair; a resistor labelled 120 Ω across the pair at each end of the bus; a common ground line joining all four nodes; a note reading “every node hears every message”
Adding a node changes nothing about the existing nodes. A new device that needs the wheel speed is simply told to accept that identifier, and nothing anywhere else is rewired or reprogrammed. On a robot whose subsystems are built by different people at different times, this is a substantial practical advantage.
Each node needs two pieces of hardware: a CAN controller, which builds and checks the frames, and a transceiver, which converts the controller’s logic levels into the differential signals the bus actually carries.
Because there is one pair of wires and everyone shares it, communication is half-duplex.
15.5.2 Differential Signalling and Bus Termination
The bus is a twisted pair, labelled CAN_H and CAN_L. What matters is not the voltage on either wire but the difference between them.
The reason this resists noise is worth following carefully, because it is the whole argument for CAN. Interference from a motor, a relay or a switching supply couples into a nearby cable as an induced voltage. Because the two wires of a twisted pair run alongside each other and are twisted together, the interference couples into both almost equally, raising or lowering both by the same amount. The receiver looks only at the difference between them, and equal disturbance on both wires cancels out of that difference entirely. Fig. 15.5-2 shows the effect.
Diagram
Fig. 15.5-2 – three stacked waveform panels sharing one time axis; top panel showing two clean traces labelled CAN_H and CAN_L, one rising as the other falls; middle panel showing the same two traces with an identical noise disturbance added to both, so both are distorted in the same way, labelled “noise couples equally into both wires”; bottom panel showing the difference CAN_H minus CAN_L as a clean two-level trace with the noise absent, labelled “the receiver reads the difference”
The two states of the bus are named rather than numbered, and the names matter:
- Recessive, logical 1. Neither wire is driven; both sit at about 2.5 V, so the difference is close to 0 V.
- Dominant, logical 0. The transceiver drives
CAN_Hup to about 3.5 V andCAN_Ldown to about 1.5 V, giving a difference of about 2 V.
The crucial property is in the names. If one node transmits recessive and another transmits dominant at the same instant, the bus goes dominant. Dominant always overwrites recessive, and no damage occurs, because the recessive state involves no driving at all. This is the same wired logic that made I2C safe to share, and here it does something more: it provides the mechanism for arbitration.
Termination
At each end of the bus sits a 120 Ω terminating resistor across the pair. These are not optional.
A signal travelling along a cable that ends abruptly reflects from the open end and travels back, interfering with the signals that follow. The faster the bus, the more damage this does. A twisted pair of the type used for CAN has a characteristic impedance of about 120 Ω, and terminating each end with a matching resistance absorbs the signal instead of reflecting it.
Termination goes at the two physical ends of the bus, not at every node. A bus with resistors at every node loads the drivers far too heavily; a bus with none reflects and fails at speed.
15.5.3 Message Identifiers and Priority Arbitration
With no master, two nodes can begin transmitting in the same instant. On any of the earlier buses this would destroy both messages. On CAN it destroys neither, and this is the protocol’s cleverest feature.
Every message begins with its identifier, sent most significant bit first. The standard format uses an 11-bit identifier; an extended format uses 29 bits.
While transmitting, every node also listens to the bus. As long as what it hears matches what it sent, it keeps going. The moment a node transmits a recessive bit but reads back a dominant one, it knows another node is transmitting a lower identifier, and it withdraws immediately and quietly.
Table 15.8 follows the contest between two nodes bit by bit.
Node A wins because its identifier is the smaller number. The rule is simply that the lower binary identifier has the higher priority, and it follows directly from dominant bits overwriting recessive ones.
Three consequences matter for a robot.
The loser loses nothing. Its message was never corrupted, only postponed; it retransmits as soon as the bus is free.
The winner is delayed by nothing at all. Its frame passes without interruption, exactly as if no contest had occurred. This is what engineers mean when they call CAN’s arbitration non-destructive.
And the designer, by choosing identifiers, chooses which messages get through first when the bus is busy. An emergency stop command given a very low identifier will always beat a routine temperature report. That is a design decision made once, in a table of identifiers, and enforced thereafter by the electrical behaviour of the bus itself.
15.5.4 Key Characteristics
15.5.5 Uses in Robotics
CAN appears in robots for reasons that follow directly from those characteristics.
Distributed control. Where a robot is built as several intelligent subsystems rather than one central controller — a board per joint, a board per wheel, a board for the sensor head — CAN joins all of them over one pair of wires. Motor controllers, sensors and actuators in such modular systems are its most common application.
Large or moving structures. A robot arm or a large mobile platform needs communication that survives several metres of cable running past power conductors and through flexing joints. This is where the two-wire twisted pair earns its place, and where I2C and SPI cannot be used at all.
Industrial and competition robots. Machines working near welders, drives and contactors depend on the noise immunity of differential signalling and on error handling that does not need a program to notice a fault.
Safety-related messages. Priority arbitration gives a critical message a bounded, predictable delay even on a busy bus. Where an emergency stop must be believed to arrive within a stated time, that guarantee is what is being bought.
CAN is rarely met in a first robotics project. An Arduino UNO has no CAN controller, and boards that do — the Arduino Due among them — still need an external transceiver before they can touch the bus. It is an interface a student meets when a robot outgrows one controller.
15.5.6 Speed and Performance
Standard CAN reaches 1 Mbps. CAN FD, a later extension, keeps the same arbitration but switches to a faster rate for the data portion of the frame and allows larger payloads, reaching several Mbps on hardware that supports it.
Two features of CAN’s performance are unusual enough to be worth understanding properly.
Speed and distance are traded against each other
Arbitration requires that every node be able to see the bus state produced by every other node within the same bit period. A signal takes time to travel the length of the cable, so the bit period must be long enough for a signal to reach the far end and for the response to be observed. Halve the bit period and the maximum length roughly halves too.
This is why the published figures always pair a speed with a distance: about 40 m at 1 Mbps, and several hundred metres once the rate drops to 125 kbps. A designer chooses a point on that curve, not a speed alone.
The frame is mostly not data
A standard CAN frame carrying the maximum of 8 data bytes occupies about 111 bit periods once the identifier, control bits, checksum, acknowledgement, end-of-frame and inter-frame space are counted. Sixty-four of those bits are data. CAN is therefore inefficient per byte, and deliberately so: it is optimised for short, critical control messages, not for bulk transfer. Sending a camera image over CAN would be a mistake of category, not of tuning.
A further small variation comes from bit stuffing. Because there is no clock line, the receiver recovers timing from the signal edges, so a long run of identical bits would leave it with nothing to resynchronise on. After five identical bits the transmitter inserts one of the opposite value, which the receiver removes. This guarantees edges and makes the exact frame length vary slightly with the data being sent.
Diagram
Fig. 15.5-3 – structure of a standard CAN data frame drawn as a horizontal row of labelled boxes, each box’s width roughly proportional to its bit count: Start of frame (1), Identifier (11), Control field (7), Data field (up to 64), CRC field (16), Acknowledgement (2), End of frame (7), Inter-frame space (3); a bracket beneath the Data field labelled “the only part that carries user data”; a bracket beneath the Identifier labelled “decides priority during arbitration”; total marked as “about 111 bit periods”
\[t_{bit} = \frac{1}{500 \times 10^{3}} \text{ s} = 2\ \mu\text{s}\]
\[t_{frame} = 111 \times 2\ \mu\text{s} = 222\ \mu\text{s}\]
\[t_{total} = 6 \times 222\ \mu\text{s} = 1332\ \mu\text{s} = 1.33 \text{ ms}\]
\[\text{bus load} = \frac{1.33 \text{ ms}}{10 \text{ ms}} = 0.133 = 13.3\%\]
Answer: each frame occupies the bus for 222 µs, and the six controllers together use about 13.3% of its capacity. Check: the magnitude is sensible — 111 bits at 2 µs each must be a fraction of a millisecond. The remaining 87% is not spare capacity to be filled. Bit stuffing lengthens frames by a few per cent, retransmissions after an error consume more, and a bus loaded much beyond about half its capacity begins to delay its lower-priority messages noticeably. Designers commonly plan for a load well under 50%.
Latency behaves well under load. Even when several nodes contend, the highest-priority message is delayed only until the current frame finishes, which is why CAN is trusted for real-time control while a bus with random collision behaviour would not be.
15.5.7 Error Detection and Reliability
This is where CAN separates itself from the other three completely. Its error handling is not an optional bit added to a frame; it is a system, and it runs in hardware without any help from the program.
What is checked
Every frame carries a 15-bit cyclic redundancy check (CRC), a value calculated from the frame’s contents by the transmitter and recalculated by every receiver. A frame whose recalculated value disagrees is known to be corrupt. Unlike a parity bit, a CRC of this length catches burst errors and multiple bit errors, not merely single flips.
Alongside it, several other checks run at once: a transmitting node monitors the bus and detects when the level it reads differs from the level it drove; receivers check that the bit-stuffing rule was obeyed; and every node checks that the fixed-format parts of the frame hold the values they must.
Acknowledgement and retransmission
Every frame contains an acknowledgement slot, which the transmitter sends as recessive. Any node that received the frame correctly drives that slot dominant. If the transmitter reads its own recessive bit back unchanged, no node received the frame, and it retransmits.
When any node detects an error, it signals it on the bus immediately, the frame is aborted everywhere at once, and the transmitter sends it again automatically. Nothing in the application program is involved.
Self-isolation
Each node keeps counters of the errors it has transmitted and received. A node that keeps causing faults becomes error-passive, restricting how it may signal errors, and if the count keeps rising it takes itself off the bus entirely, a state called bus-off.
This matters more than it first appears. A single faulty node with a damaged transceiver could otherwise flood a bus with error signals and prevent every other node communicating. CAN’s answer is that a persistently faulty node removes itself, and the rest of the network keeps running.
The honest limitations
Three should be stated plainly.
The acknowledgement proves that at least one node received the frame correctly. It does not prove that the node which needed the message received it. A message may be perfectly acknowledged by an unrelated node while the intended recipient is disconnected.
Automatic retransmission is a strength that can become a fault. A node whose message is never acknowledged retries, and a badly configured bus can be occupied by a node retransmitting endlessly until its error counters take it off.
And CAN was designed for reliability, not for confidentiality. Every node trusts every message on the bus, because in 1986 the bus was a sealed loom inside one vehicle. Keeping a control network physically isolated from any outward-facing connection is therefore part of designing with it, not an afterthought.
Within its intended setting — a closed network of cooperating nodes in an electrically hostile place — CAN is the most robust of the four by a wide margin, and it is the only one of them that both detects an error and does something about it without being asked.
15.6 Comparing the Four Protocols
Four protocols have now been described one at a time. None of them is better than the others, and a student who leaves this chapter believing that CAN is the good one and SPI the crude one has learned the wrong lesson entirely.
Each was designed for a different problem, and each gave up something to solve it. This section sets the four side by side so that the trade-offs become visible, and then turns them into a way of choosing.
15.6.1 Wiring, Topology and Synchronisation
Start with the physical arrangement, because it is what a student meets first when a robot is built rather than read about.
Read down the wiring row and one pattern stands out. Three of the four protocols use two signal wires however many devices are attached; only SPI grows. Six devices on I2C or CAN still need two wires; six devices on SPI need three shared lines and six select lines, which is nine controller pins.
That single fact decides more designs than speed does. A compact robot with a small controller and eight sensors has effectively already chosen I2C before any other question is asked.
The second pattern is in the synchronisation row. UART and CAN carry no clock wire and therefore need both ends configured to the same rate in advance; I2C and SPI carry a clock and do not. But CAN, unlike UART, keeps realigning itself to the edges inside every frame, which is why it tolerates far longer cables than UART despite sharing the same basic difficulty.
Diagram
Fig. 15.6-1 – four small topology sketches arranged in a row, each labelled; first labelled UART showing two boxes joined by two crossed lines; second labelled I2C showing one master box and four slave boxes all tapped onto two horizontal lines with two pull-up resistors at one end; third labelled SPI showing one master box with three shared lines running to three slave boxes plus three separate select lines drawn as distinct short arrows; fourth labelled CAN showing four boxes tapped onto a twisted pair with a resistor at each end and no master marked; a note under the row reading “device count changes only the SPI wiring”
15.6.2 Speed, Range and Complexity
Now the performance figures. The important thing here is not to memorise the numbers but to see how they are connected to each other.
Set the speed row against the range row and the relationship is unmistakable: the faster protocols reach less far. That is not a coincidence, and three reasons for it have already appeared in this chapter.
The first is the electrical form. SPI drives its lines actively and quickly, which produces sharp edges that reflect and radiate along a long wire. CAN sends a difference between two twisted wires, which cancels interference but costs a transceiver at every node.
The second is checking. SPI’s speed comes partly from checking nothing, which is only defensible over a distance so short that errors are physically improbable. CAN spends about six bit periods in every fourteen on identification, checksums and acknowledgement, and buys reach and trustworthiness with them.
The third is arbitration, which applies to CAN alone. A bit must travel to the far end of the bus and be read back inside one bit period, so raising the rate directly shortens the permitted cable.
Diagram
Fig. 15.6-2 – a chart with a horizontal axis labelled “practical range” marked at 0.1 m, 1 m, 10 m, 100 m and 1 km, and a vertical axis labelled “typical data rate” marked at 10 kbps, 100 kbps, 1 Mbps and 10 Mbps, both axes drawn on a logarithmic scale; four labelled regions plotted as shaded ovals: SPI at high rate and very short range, I2C at moderate rate and short range, UART at low rate and moderate range, CAN at moderate rate extending to long range with the oval drawn sloping downwards to the right; a dashed arrow across the figure labelled “faster protocols reach less far”
15.6.3 Error Detection and Reliability Compared
This is the comparison that matters most on a machine that moves, and it is the one students most often skip.
The four form a ladder, and each rung is paid for.
SPI checks nothing and is the fastest. I2C confirms that a device answered, which catches a disconnected sensor immediately but says nothing about the data, and it pays one bit in nine for that. UART can be told to add a parity bit, which catches a single flipped bit and misses two. CAN checks everything, repairs what it can and removes what it cannot, and spends nearly half of every frame doing so.
The design lesson is the one to carry away from this chapter. A protocol with no error checking is not careless; it is a protocol that assumes a short, quiet wire. The mistake is not using SPI — it is using SPI where that assumption has stopped being true.
15.6.4 Choosing a Protocol for a Robot Subsystem
A protocol is chosen per link, not per robot. One machine will normally use two or three of these four at once, and the choice for each link follows from five questions asked in order.
- How many devices must share this connection? Exactly two allows anything; several favours a bus.
- How far apart are they? Centimetres on one board, tens of centimetres inside one enclosure, or metres across a chassis.
- How much data, and how often? A reading every 100 ms is nothing; a display refresh or a logged block is substantial.
- What is the cost of a wrong byte? A corrupted character on a screen is trivial. A corrupted speed command to a wheel is not.
- What does the hardware actually support? A protocol the controller has no port for, or that needs a transceiver the school does not have, is not available whatever its merits.
Diagram
Fig. 15.6-3 – flow: start block reading “a link is needed between two parts of the robot” → decision block reading “more than two devices on this connection?” → the “no” branch to a decision reading “is it a wireless or long single link?” leading to a box labelled UART → the “yes” branch to a decision reading “distance greater than about a metre, or a noisy environment?” → the “yes” branch to a box labelled CAN → the “no” branch to a decision reading “large blocks of data at speed?” → the “yes” branch to a box labelled SPI → the “no” branch to a box labelled I2C; a final block joined to all four outcome boxes reading “check the controller supports it”
Applying the five questions to a single machine shows how naturally the four separate. Consider a warehouse robot that carries a distance sensor cluster, a display, a data log, a wireless link to a supervisor and four independently driven wheel modules spread across a one-metre chassis.
Notice that the fastest protocol was chosen for the least urgent task and the slowest for the most urgent. Logging is a bulk transfer over a centimetre, so SPI suits it. A wheel command is a few bytes that must not be wrong, sent across a metre of noisy chassis, so CAN suits it. Speed was never the deciding question on either link.
15.7 Making a Communication Link Work
Everything so far has been about choosing the right protocol. This section is about the far commoner situation in a school workshop: the right protocol has been chosen, the wiring looks correct, and nothing arrives.
Almost all such failures come from four causes, and none of them is a fault in the protocol.
15.7.1 The Common Ground Rule
Every protocol in this chapter has quietly required the same third connection, and it is the one most often left out.
A logic level is not an absolute thing. When a board drives a pin to 5 V, it means 5 V above its own 0 V node. The receiving board reads that pin by comparing it with its 0 V node. If nothing joins those two nodes, the two boards have no agreement about where zero is, and the comparison is meaningless.
The symptoms of a missing ground are unhelpfully varied, which is why the fault survives so long. Sometimes nothing at all is received. Sometimes a link works while both boards are powered from the same USB hub — because the hub’s own wiring is quietly providing the ground — and fails the moment the robot runs on its battery. Sometimes data arrives correctly for a while and then becomes intermittent as the two references drift apart. All of this looks like a software fault and is not.
Diagram
Fig. 15.7-1 – two panels; upper panel labelled “Incorrect” showing two boards each with its own battery, joined by a single signal wire from the first board’s TX to the second board’s RX, with each board’s 0 V node marked separately and a large question mark between them labelled “no shared reference”; lower panel labelled “Correct” showing the same two boards and signal wire with an additional thick wire joining the two 0 V nodes, labelled “common ground”, and an arrow along it labelled “return path for the signal current”
There is a second reason for the wire, visible in the lower panel of Fig. 15.7-1. A signal is a current as well as a voltage, and that current must return to its source. Without a deliberate ground conductor it will find some other path — through a USB cable’s shield, through a motor supply’s negative lead, through anything that happens to be connected — and a return current flowing through a path shared with a motor is exactly how motor noise gets into a data line.
The rule to carry away is short. Whenever two devices exchange a signal, join their grounds. Where the two also share a supply, join the grounds at a single point rather than in several places, so that no loop is formed for current to circulate around.
CAN needs the connection too, for the reason given in section 15.5.2: differential signalling rejects noise only while both wires stay within a limited range around the receiver’s own reference, and the ground conductor is what keeps them there.
15.7.2 Matching Logic Levels
A school laboratory holds boards of two families. An Arduino UNO works at 5 V. An ESP32, a NodeMcu board and a Raspberry Pi work at 3.3 V. Wiring one to the other is routine and is also where components get destroyed.
The two directions are not symmetrical, and knowing which is which saves parts.
A 3.3 V output driving a 5 V input usually works. A 5 V microcontroller input typically treats anything above about 60% of its supply — around 3 V — as a logic high, so a 3.3 V signal clears the threshold with a little margin. It is worth checking the datasheet rather than assuming, but this direction is normally safe.
A 5 V output driving a 3.3 V input is not safe. The input is not designed for a voltage above its own supply, and driving one there forces current through the chip’s internal protection diodes. The pin, or the whole device, may be damaged — sometimes immediately, sometimes after weeks of apparently normal operation.
\[3.3 = 5 \times \frac{R_2}{1000 + R_2}\]
\[3.3\ (1000 + R_2) = 5 R_2\]
\[3300 = 1.7 R_2\]
\[R_2 = 1941\ \Omega\]
The nearest standard value is 2 kΩ, which gives
\[V_{out} = 5 \times \frac{2000}{1000 + 2000} = 3.33 \text{ V}\]
\[I = \frac{5 \text{ V}}{3000\ \Omega} = 1.67 \times 10^{-3} \text{ A} = 1.67 \text{ mA}\]
Answer: use \(R_2 = 2\ \text{k}\Omega\) with \(R_1 = 1\ \text{k}\Omega\), giving 3.33 V and drawing 1.67 mA while the line is high. Check: 3.33 V is safely under the 3.6 V that 3.3 V parts typically tolerate and comfortably above their high threshold, and 1.67 mA is well within what any logic pin can supply. The method has two limits worth stating: the divider works in one direction only, so it is useless on a bidirectional line such as SDA; and the resistance together with the cable capacitance slows the edges, which rules it out for a fast SPI clock. For those cases a proper level shifter is the answer.
15.7.3 Cable Length, Noise and Termination
A link that works perfectly on the bench and fails when the robot drives is not haunted. It has met the motors.
A motor is an inductive load switched rapidly by its driver, and a brushed motor additionally makes and breaks contact at its commutator many times a second. Both produce sharp voltage and current changes, and those changes reach a data line by three routes.
Through the supply. A motor starting draws a large current, the battery voltage dips, and every board sharing that supply sees the dip. If it is deep enough, the controller resets or a device on the bus misreads a bit.
Through the air. A changing current in a motor cable produces a changing magnetic field, which induces a voltage in any nearby conductor loop. The larger the area enclosed between a signal wire and its return path, and the closer and more parallel it runs to the motor cable, the more is induced.
Through the ground. If the motor’s return current and a signal’s return current share a length of conductor, the motor current develops a voltage along it, and that voltage adds itself to the signal.
Each route suggests its own remedy, and all of them are available in a school workshop.
- Keep signal cables short, and keep them away from motor leads. Where the two must cross, cross them at a right angle rather than running them side by side, so the coupling is minimised.
- Twist a signal wire together with its ground return. Twisting keeps the enclosed loop area small and makes any induced voltage appear equally in both conductors — the same reasoning that makes CAN’s twisted pair effective.
- Give the motors their own supply, and join that supply’s ground to the logic ground at one single point rather than at several.
- Where a bus must cross a large chassis in a noisy machine, stop trying to harden the wrong protocol. Section 15.6.4 gave the answer: that link wanted CAN.
Diagram
Fig. 15.7-2 – top view of a robot chassis in two panels; left panel labelled “Poor routing” showing a thick motor cable running the length of the chassis with a thin sensor cable taped alongside it for most of that length, and a note reading “long parallel run”; right panel labelled “Better routing” showing the same motor cable, with the sensor cable running along the opposite edge, crossing the motor cable once at a right angle, drawn as a twisted pair with its ground, and a note reading “short, twisted, crossing at 90°”
Termination is for CAN only
Termination resistors belong to CAN and to nothing else in this chapter. A CAN bus takes a 120 Ω resistor at each of its two physical ends, and only there — one at every node overloads the drivers, and none at all lets signals reflect from the open ends.
UART, I2C and SPI are not terminated. Fitting resistors across an I2C bus in the belief that it will help simply loads the pull-ups and stops the bus working.
15.7.4 Finding a Fault in a Link
A dead link is diagnosed the same way every time: from the physical layer upwards, checking the cheapest and most likely things first. Guessing at the protocol before the power and ground have been confirmed wastes hours.
Table 15.15 collects the symptoms that identify a fault quickly.
15.8 Summary
Why a protocol is needed
- A robot is electrically a crowd of devices. A wire carrying one condition, such as dark or light under an infrared sensor, is a signal line and needs no agreement. A connection carrying structured information is a data link, and it works only because both ends follow the same rules.
- A communication protocol is an agreed set of rules that fixes how the wires are used, how the timing is decided, how the data is arranged and how errors are handled. All of it is settled in advance by the standard both manufacturers followed; none of it is discovered at run time.
- Giving every pair of devices its own connection needs \(n(n-1)/2\) links for \(n\) devices, so six devices need fifteen. One shared set of wires — a bus — serves all six, at the cost of rules deciding who may speak and how a device knows which messages are its own.
- In parallel transmission the bits of a byte travel together on separate wires; in serial transmission they travel one after another on one wire. Serial won for three reasons: fewer pins, thinner and more flexible cable, and freedom from skew, the drift that stops parallel bits arriving together as the clock rate rises. UART, I2C, SPI and CAN are all serial.
The terms every protocol is described by
- Topology is the shape of the connection: point-to-point, bus or multi-node bus.
- Synchronisation is how bit timing is agreed. A synchronous link carries a clock line; an asynchronous link carries none and relies on both ends being set to the same rate beforehand.
- Master and slave describe control. A master generates the clock, decides when a transfer happens and chooses the device addressed; a slave only answers.
- Addressing selects one device among many; arbitration decides who wins when two begin at once.
- Duplex is the direction of flow: simplex one way, half-duplex either way but one at a time, full-duplex both ways at once.
- Bit rate is bits placed on the line each second. Overhead is the bits that carry no user data, throughput is what is left, and latency is the delay between sending and receiving. High throughput and poor latency can occur together, and for control messages latency is usually what matters.
- Range is the greatest wiring length over which the link stays reliable.
UART
- A UART is the hardware module that converts parallel data from the processor into serial form for transmission and back on reception, generating and checking the start and stop bits and the optional parity bit.
- It is asynchronous: no clock wire exists, so both ends must be configured to the same baud rate. The line idles high, and every frame opens by pulling it low for one bit period so the receiver knows where to start counting.
- A frame is a start bit, the data bits sent least significant bit first, an optional parity bit and a stop bit. The common 8N1 setting puts 10 bit periods on the wire for 8 bits of data, a fixed overhead of 20%.
- For UART the baud rate equals the bit rate, because each symbol carries exactly one bit. One bit period is \(t_{bit} = 1/\text{baud rate}\), so 9600 baud gives 104 µs per bit and about 1.04 ms per frame.
- A rate mismatch of more than roughly 2% corrupts a frame, because the receiver’s sampling point drifts further from the middle of each successive bit. The symptom is a steady stream of meaningless characters, never silence.
- Wiring is
TXtoRXandRXtoTX, crossed, plus a common ground. The topology is point-to-point and admits exactly two devices; duplex is full. - Its uses in robotics are Bluetooth modules, GPS receivers, serial monitoring and debugging, and links between two microcontrollers.
- Error handling is thin. Parity detects an odd number of flipped bits and cannot correct any; a framing error is raised when the stop bit is not found where expected. There is no acknowledgement and no automatic retransmission, and in the default 8N1 setting there is no parity either, so corrupted data can pass unnoticed.
I2C
- I2C is a two-wire synchronous serial bus.
SCLcarries the clock,SDAcarries the data, and a common ground is required. The master supplies every clock pulse and begins every transfer; slaves only answer. With one data line, the bus is half-duplex. - Its lines are open-drain: a device may pull a line low or release it, never drive it high. A pull-up resistor, typically 4.7 kΩ, returns a released line to the supply. Low always wins, so no two devices can ever oppose each other.
- The pull-up must charge the whole bus capacitance to make a rising edge, which is what limits both the speed and the length of an I2C bus. Duplicate pull-ups from several breakout modules in parallel are a common fault.
- Each slave has an address, usually 7 bits, giving 112 usable addresses once the reserved ones are removed. A transfer runs START, address plus read/write bit, acknowledgement, data bytes each acknowledged, then STOP.
SDAchanges only whileSCLis low, except during START and STOP, which is how those two are recognised. - Defined speeds are 100 kbps standard mode and 400 kbps fast mode, with 1 Mbps and 3.4 Mbps modes on some devices. Each byte occupies 9 bit periods because of its acknowledgement bit.
- Its uses in robotics are sensor clusters such as gyroscopes and accelerometers, magnetometers, barometric pressure and temperature sensors, and peripherals such as small displays, real-time clocks and input-output expanders, on robots where pins are scarce.
- The acknowledgement bit detects a missing, unpowered or wrongly addressed device immediately, which is genuinely useful. It says nothing about whether the eight bits were correct: there is no checksum and no correction. Multi-master arbitration is settled by dominant lows, and clock stretching lets a slow slave delay the master — but a slave that crashes while holding a line low locks the whole bus.
SPI
- SPI is a high-speed synchronous interface using a minimum of four lines:
SCLK, the clock from the master;MOSI, master out, slave in;MISO, master in, slave out; andSS, slave select, with oneSSline per slave. - The master’s shift register and the selected slave’s shift register form one closed ring, so each clock pulse moves a bit each way. Every transfer is therefore simultaneously a send and a receive, and a master wanting only to read clocks out a dummy byte to generate the pulses.
- Outputs are push-pull, actively driven high and low, which gives sharp edges and needs no pull-up resistors. This is safe only because exactly one device drives each line at a time.
- Selection is physical: the master pulls one active-low
SSline down, and unselected slaves ignore the clock and holdMISOin a high-impedance state. There is no addressing and no arbitration, and pin cost grows with every slave added. - SPI fixes no standard rate; the master chooses it and the board sets the ceiling — 8 MHz on an Arduino UNO, being half its 16 MHz system clock, and tens of megahertz on faster hardware. There is no address, acknowledgement or framing bit, so eight clock periods carry eight bits.
- Its uses in robotics are memory cards for data logging, colour and monochrome displays, inertial units and converters sampled rapidly, and peripheral chips such as LED drivers and shift registers.
- It has no error detection of any kind. A corrupted byte is delivered as data, and an absent device returns whatever level the floating
MISOline sits at — a plausible constant rather than a reported fault. Protection must be added above the protocol as a checksum or an echo-back read. TwoSSlines low together make two push-pull outputs oppose each other, which is the characteristic SPI fault.
CAN
- CAN is a multi-master serial bus built for electrically hostile places. Any node may transmit when the bus is free; there is no central controller.
- It is broadcast-based and message-identified rather than addressed. Every node receives every message, and each decides from the message identifier whether to keep or ignore it. Adding a node changes nothing elsewhere.
- The bus is a twisted pair,
CAN_HandCAN_L, with a 120 Ω terminating resistor at each of the two physical ends and a common ground. Every node needs a CAN controller and a transceiver. - Differential signalling carries the data as the difference between the two wires. Interference couples almost equally into both and cancels in the subtraction. The recessive state, logical 1, leaves both wires near 2.5 V; the dominant state, logical 0, drives them to about 3.5 V and 1.5 V.
- Dominant overwrites recessive, and arbitration follows directly. Each node listens while transmitting its identifier; one that sends recessive and reads dominant withdraws. The lower binary identifier wins, the winner’s frame is not delayed at all and the loser’s is not corrupted, which is what non-destructive arbitration means. Choosing identifiers is therefore choosing priorities.
- Speed and distance are traded against each other, because a bit must reach the far end and be read back within one bit period: about 40 m at 1 Mbps, and up to roughly 1 km at low rates. Typical vehicle networks run at 125 kbps to 500 kbps.
- A standard frame carrying 8 data bytes occupies about 111 bit periods, so a little over half the frame is overhead. CAN is optimised for short, critical control messages, not for bulk transfer. Bit stuffing inserts an opposite bit after five identical ones, guaranteeing the edges that keep receivers synchronised.
- Its uses in robotics are distributed control across several intelligent subsystems, large or moving structures where cables run past power conductors, industrial and competition machines, and safety-related messages needing a bounded delay.
- Error handling is a hardware system, not a single bit: a 15-bit cyclic redundancy check on every frame, bus monitoring by the transmitter, stuffing and form checks, a mandatory acknowledgement, automatic retransmission of any aborted frame, and error counters that take a persistently faulty node off the bus so the rest of the network survives. Its limits are that an acknowledgement proves only that some node received the frame, not the intended one, and that every node on the bus is trusted.
What the comparison shows
- Three of the four protocols use two signal wires however many devices are attached; only SPI grows, needing three shared lines plus one select line per slave. On a small controller this often settles the choice before speed is considered.
- The faster protocols reach less far, and for connected reasons: fast push-pull edges reflect and radiate, single-ended levels have no noise cancellation, and a protocol that checks nothing is only safe where errors are physically improbable.
- Reliability is bought with bit periods. SPI spends 8 bit periods per data byte and checks nothing; I2C spends 9 and confirms a device answered; UART spends 10 and can detect a single flipped bit; CAN spends about 14 and detects, retransmits and isolates.
- A protocol is chosen per link, not per robot, by asking how many devices share it, how far apart they are, how much data and how often, what a wrong byte would cost, and what the hardware supports. One machine commonly uses three of the four at once.
Making a link work
- Whenever two devices exchange a signal, join their grounds. A logic level is a voltage measured against a reference, and the signal current needs a defined return path. A missing ground produces intermittent faults that look like software faults.
- A 3.3 V output usually drives a 5 V input correctly, because a 5 V input’s high threshold is around 3 V. A 5 V output must never drive a 3.3 V input directly; use a level shifter, or a resistor divider for a slow one-way signal.
- Motors reach a data line through the shared supply, through magnetic coupling into signal loops and through a shared ground path. Keep signal cables short and away from motor leads, cross them at right angles, twist a signal with its ground return, and join the motor and logic grounds at a single point.
- Termination belongs to CAN alone, one 120 Ω resistor at each of the two ends of the bus and nowhere else.
- Diagnose from the physical layer upwards: supply, then ground, then wiring, then logic levels, then configuration, then a test with the motors off and again with them on. A link that works with the motors stopped and fails with them running has a noise or supply problem, and no change to the program will fix it.
15.9 Key Terms
- 8N1 — the common UART configuration of eight data bits, no parity and one stop bit, which puts ten bit periods on the wire for every eight bits of data.
- ACK and NACK — acknowledgement and non-acknowledgement; a receiver’s reply confirming that a byte or frame was received, or the absence of that reply.
- Acknowledgement — a bit sent by the receiving device to confirm that it received what was sent; used after every byte on I2C and in every frame on CAN.
- Addressing — the means by which a master selects one device among many on a shared connection.
- Arbitration — the rule that decides which device continues when two begin transmitting at the same instant.
- Asynchronous — carrying no clock line, so that both ends must be configured to the same rate in advance and each keeps its own time.
- Baud rate — the number of symbols placed on the line each second; on a UART link, where each symbol carries one bit, it is numerically equal to the bit rate.
- Bit rate — the number of bits placed on the line each second, measured in bits per second (bps) and its multiples kbps and Mbps.
- Bit stuffing — inserting a bit of the opposite value after five identical consecutive bits, so that a CAN receiver always has signal edges to resynchronise on.
- Bus — one shared set of conductors running past several devices, so that each connects to the same lines instead of having its own.
- Bus capacitance — the total capacitance of the wiring and the attached devices, which slows the rise of an I2C line and limits both the bus length and its speed.
- CAN — Controller Area Network; a multi-master differential serial bus built for reliable communication in electrically noisy places.
- CAN FD — an extension of CAN that keeps the same arbitration but raises the rate for the data part of the frame and allows a larger payload.
CAN_HandCAN_L— the two conductors of a CAN twisted pair, whose voltage difference carries the data.- Clock line — a wire carrying a signal that ticks once per bit, generated by one device and followed by the others.
- Clock stretching — an I2C slave holding
SCLlow to make the master wait until it is ready. - Common ground — a conductor joining the 0 V reference nodes of two or more devices, so that a voltage sent by one is measured against the same reference by the other.
- Communication protocol — an agreed set of rules that two or more devices follow so that data sent by one is correctly received and understood by the others.
- CRC — cyclic redundancy check; a value calculated from a frame’s contents and recalculated by the receiver, used by CAN to detect corruption including burst errors.
CTS— Clear To Send; a hardware flow control line found on some serial modules.- Data bits — the bits of the actual data item inside a UART frame, sent least significant bit first.
- Data link — a connection carrying structured information, which works only because both ends follow the same rules; distinct from a signal line, which carries one condition.
- Differential signalling — carrying a signal as the difference in voltage between two wires rather than as the voltage of one wire measured against ground.
- Dominant — the CAN bus state representing logical 0, in which the transceiver drives the two wires apart; a dominant bit overwrites a recessive one.
DTR— Data Terminal Ready; a hardware flow control line found on some serial modules.- Frame — the complete group of bits sent for one item of data, including the bits added by the protocol around the data itself.
- Full-duplex — able to carry data in both directions at the same time, which needs a separate line for each direction.
- Half-duplex — able to carry data in either direction, but only one direction at a time, because the two share a line.
- I2C — Inter-Integrated Circuit; a two-wire synchronous serial bus in which many devices share one clock line and one data line under the control of a master.
- Latency — the delay between a device deciding to send something and the receiver having it.
- Master — the device that generates the clock where there is one, decides when a transfer happens and chooses which device is addressed.
- Message identifier — the value at the start of a CAN message that describes what the message is, decides its priority during arbitration, and is used by each node to filter what it keeps.
MISO— Master In, Slave Out; the SPI line on which the selected slave sends to the master.MOSI— Master Out, Slave In; the SPI line on which the master sends to the slaves.- Node — a device connected to a bus.
- Open-drain — an output that can pull its line low or release it, but can never drive it high, so that several such outputs may share one line safely.
- Overhead — the bits a protocol adds that carry no user data, such as start and stop bits, addresses, acknowledgements and check bits.
- Parallel communication — sending the bits of a data item together, one on each of several wires.
- Parity bit — an optional extra bit in a UART frame, set so that the number of 1 bits is even or odd as agreed; it detects an odd number of flipped bits and corrects nothing.
- Point-to-point — a connection joining exactly two devices.
- Pull-up resistor — a resistor from a line to the positive supply, which returns a released open-drain line to the high level.
- Range — the greatest wiring length over which a link stays reliable.
- Recessive — the CAN bus state representing logical 1, in which neither wire is driven and both sit near 2.5 V.
RX— the receive line of a serial link, which connects to the other device’sTX.SCL— the serial clock line of an I2C bus.SCLK— the SPI clock line, generated by the master.SDA— the serial data line of an I2C bus, used in both directions.- Serial communication — sending the bits of a data item one after another along a single data line, so that the value is spread out in time rather than across several wires.
- Simplex — able to carry data in one direction only.
- Slave — a device that answers a master and never begins a transfer of its own.
- SPI — Serial Peripheral Interface; a high-speed synchronous interface using a clock, two data lines and one slave select line per slave.
SS— Slave Select; the SPI line, normally active-low, by which the master chooses one slave.- Start bit — the single low bit period that opens a UART frame and tells the receiver where to begin counting.
- Stop bit — the high bit period that closes a UART frame and returns the line to its idle state.
- Synchronous — carrying a clock line, so that the receiver is told when each bit is valid instead of counting time for itself.
- Throughput — the amount of actual user data transferred each second, once overhead has been subtracted from the bit rate.
- Topology — the shape of a connection: how many devices it joins and how they are arranged.
- Transceiver — the chip at each CAN node that converts the controller’s logic levels into the differential signals the bus carries, and back again.
TX— the transmit line of a serial link, which connects to the other device’sRX.- UART — Universal Asynchronous Receiver/Transmitter; the hardware module that converts parallel data from the processor into serial form for transmission and back on reception, generating and checking the start, stop and parity bits.
15.10 Objective Questions
- A master is to be connected to three slaves over SPI. Not counting the ground conductor, how many signal wires does the arrangement need?
- 4
- 5
- 6
- 7
Fill in the blank: in the 8N1 configuration, one character occupies ______ bit periods on a UART line.
State whether the following is true or false: a parity bit allows a UART receiver both to detect and to correct a single flipped bit.
Read the assertion and the reason, then choose the correct option. Assertion: an I2C bus will not work unless pull-up resistors are fitted to
SDAandSCL. Reason: an I2C device can pull a bus line low or release it, but cannot drive it high.
- Both the assertion and the reason are true, and the reason is the correct explanation of the assertion.
- Both the assertion and the reason are true, but the reason is not the correct explanation of the assertion.
- The assertion is true but the reason is false.
- The assertion is false but the reason is true.
- Match each protocol in Column A with the feature in Column B that belongs to it.
| Column A | Column B |
|---|---|
| a. UART | i. One select line per slave, and no addressing at all |
| b. I2C | ii. A start bit and a stop bit around every character |
| c. SPI | iii. A differential twisted pair with 120 Ω termination at each end |
| d. CAN | iv. An acknowledgement bit after every byte |
Write the full form of each of the following:
MOSI,SDA,CRC, UART.Two CAN nodes begin transmitting at the same instant, one with the identifier 1A0 and the other with the identifier 0B5, both in hexadecimal. Which node continues, and why?
- The node sending 1A0, because the larger identifier has the higher priority.
- The node sending 0B5, because the smaller identifier has the higher priority.
- Neither; both frames are destroyed and both nodes retransmit.
- Whichever node began transmitting a fraction earlier.
15.11 Check Your Concepts
Define a communication protocol. State what the common ground conductor does in a serial link between two boards.
Differentiate between synchronous and asynchronous serial communication, and name one protocol of each kind from those studied in this chapter.
Explain why the lines of an I2C bus need pull-up resistors. State one consequence of choosing a resistor value that is too large.
SPI transfers data far faster than I2C, yet it is used only over a few centimetres. Give reasons for both parts of this statement.
A robot sends a 15-character status message to a second board over a UART link running at 19200 baud in the 8N1 configuration. Calculate the time taken to transmit one message. The message is to be repeated every 5 ms; state with justification whether the link can keep up, and what the designer should change if it cannot.
Explain how a CAN node detects that a frame has been corrupted, and what the protocol then does about it without any help from the program. Justify why this behaviour makes CAN suitable for a robot whose motor controllers are spread across a large chassis, where a UART link would not be.
15.12 Diagram, Circuit & Output Reading
- A student wires a UART link between two microcontroller boards as follows, and no data is received at either end.
TXof Board A toTXof Board BRXof Board A toRXof Board BGNDof Board A toGNDof Board B- Both boards configured for 9600 baud, 8N1
Identify the single fault in this wiring, state the correct connection, and explain why the fault produces no data rather than corrupted data.
A CAN bus joins five nodes spread along a 1.5 m chassis. During assembly, a 120 Ω resistor has been fitted across
CAN_HandCAN_Lat every one of the five nodes. State what is wrong with this arrangement, describe where the resistors should actually be placed and how many are needed, and explain what each of the two errors — too many terminators and none at all — does to the signal.Two protocols, labelled only as P and Q, are described in the table below.
| Property | Protocol P | Protocol Q |
|---|---|---|
| Signal wires | 2 shared lines plus a ground reference | 4 lines, plus one extra line for each additional device |
| Synchronisation | Clock supplied by the master | Clock supplied by the master |
| Device selection | An address sent on the bus | A dedicated wire per device |
| Bit periods used per data byte | 9 | 8 |
| Detects a missing device? | Yes | No |
Identify P and Q, giving the evidence in the table that decides each. State which of the two you would choose for a cluster of six small sensors mounted beside the controller, and why.
- Three CAN nodes begin transmitting in the same instant. Their 11-bit identifiers, sent most significant bit first, are:
- Node P: 0 0 1 1 0 0 1 0 0 0 0
- Node Q: 0 0 1 0 1 1 0 0 0 0 0
- Node R: 0 0 1 1 0 0 0 0 0 0 0
Recalling that a dominant bit is logical 0 and overwrites a recessive logical 1, work through the identifiers bit by bit. State which node continues transmitting, at which bit position each of the others withdraws, and what happens to the messages of the nodes that withdraw.
15.13 Case-Based Questions
- A school team builds a greenhouse monitoring robot. Its subsystems are listed below.
| Subsystem | Devices | Distance from the controller | Data |
|---|---|---|---|
| Sensor cluster | Temperature, soil moisture and light sensors, and a small display | Within 20 cm, on the same deck | A few bytes from each, once a second |
| Data log | One memory card | On the controller board | Blocks of several hundred bytes |
| Remote link | One Bluetooth module | Adjacent to the controller | Short text commands |
| Pump controller | One separate microcontroller board with its own motor driver | 2.5 m away, its cable running beside the pump motor leads | Short commands whose corruption would start or stop the pump wrongly |
- Name the protocol you would choose for each of the four links, and give the reason for each choice.
- The team first tried to reach the pump controller by extending the sensor cluster’s bus along a 2.5 m ribbon cable. Explain two separate reasons why this link behaved unreliably once the pump ran, and explain why the controller received no warning that anything was wrong.
- The pump controller board is later replaced by one that works at 3.3 V, while the main controller remains a 5 V board. State which direction of the link now needs attention, explain what would happen if it were connected directly, and describe how the problem should be corrected.
- A warehouse robot is built as six independent modules — four wheel drives, a lift mechanism and a sensor head — joined by a CAN bus. The bus runs at 500 kbps. Each module transmits one standard frame of 8 data bytes every 20 ms, and each such frame occupies about 111 bit periods. A separate emergency stop message must also travel on the same bus.
- Calculate the time one frame occupies the bus, and hence the percentage of the bus capacity used by the six modules together. Comment on whether the remaining capacity should be treated as free for other traffic.
- Explain how the message identifiers should be assigned so that the emergency stop message is not delayed by routine traffic, and state precisely what non-destructive arbitration guarantees for both the winning and the losing message.
- The design is extended so that the bus must run the full 60 m length of a larger machine instead of 20 m. State what has to change about the bus, explain the physical reason behind the change, and state what is given up in exchange.