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

NoteCuriosity Corner

Q1. Two boards are joined by a single wire. Why must they agree on a speed in advance before even one byte can cross it? Q2. If six sensors are all connected to the same pair of wires, what stops their signals from colliding and turning into nonsense? Q3. Some sensor connections need two extra resistors added to the wires before they will work at all. What are those resistors doing? Q4. One of these four methods is many times faster than the others, yet it is almost never used over more than a few centimetres. Why? Q5. Two boards are joined correctly at every data pin, but nothing is received. What single missing wire is the most likely cause?

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.

Why a shared connection is better than many private ones

The obvious way to join several devices is to give every pair its own wires. This is called a point-to-point connection, and for two devices it is the simplest thing possible.

It stops being simple very quickly. If every one of \(n\) devices must be able to talk to every other, the number of separate links needed is \(n(n-1)/2\). Three devices need 3 links. Six devices need 15. Ten devices need 45, and each of those links occupies pins on both boards it joins.

The alternative is to run one shared set of wires past every device and let all of them connect to it. A shared connection of this kind is called a bus, and each device connected to it is a node. Six devices on a bus need one bus, not fifteen links. Fig. 15.1-2 shows the difference, and it is the difference the engineers at Bosch were chasing.

Diagram

Fig. 15.1-2 – two arrangements side by side; on the left, labelled “Point-to-point”, six circles arranged in a ring, each joined to every other circle by a separate line, giving fifteen crossing lines; on the right, labelled “Bus”, the same six circles arranged along a single horizontal pair of lines, each circle joined to the pair by one short stub; caption labels reading “six devices, fifteen links” and “six devices, one bus”

The saving is not free. On a bus, every node hears everything, so the protocol must now also settle who is allowed to speak, when, and how a node knows which messages are meant for it. Those extra rules are exactly what separates the four protocols in this chapter from one another.

Q. If a bus needs so many extra rules, why not simply give every sensor its own point-to-point link?

A. Because pins run out long before ideas do. An Arduino UNO has 14 digital pins and 6 analogue ones. Two point-to-point links for a display and an accelerometer might use eight of them; four sensors on one shared bus use two. On a compact robot, pin count is usually the binding constraint, not speed.

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.

NoteDefinition

In serial communication, the bits of a data item are sent one after another along a single data line, so that the value is spread out in time rather than across several wires.

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.

Table 15.1 – Parallel and serial transmission compared | Feature | Parallel transmission | Serial transmission | |—|—|—| | Data lines needed | One per bit, typically 8 or 16, plus control lines | One or two, plus a ground reference | | Bits sent at a time | All bits of the item together | One bit after another | | Controller pins used | Many | Few | | Cable | Thick, stiff, costly, poor for flexing joints | Thin, light, easy to route | | Limit on speed | Skew between conductors; bits stop arriving together | Set by the driver and receiver, not by alignment between wires | | Practical distance | Very short | Short to long, depending on the protocol | | Where it is still used | Inside a chip, and between a processor and its memory on a board | Almost every link between separate devices, including all four protocols in this chapter |

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:

  1. 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.
  2. How are the devices arranged? Two devices facing each other, or many devices sharing one bus.
  3. 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.
  4. How is the data packaged? How the receiver recognises where a byte starts, where it ends, and what any extra bits mean.
  5. 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.
  6. Who may transmit, and what happens if two try at once?
  7. 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.

The words master and slave are the traditional terms and are the ones the syllabus uses, so they are used throughout this chapter. Several standards bodies and manufacturers have since renamed the roles — controller and target, or main and secondary — and modern datasheets may use either set. The electrical behaviour is identical whichever names appear on the page.

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.

Table 15.2 – the terms used to describe a communication protocol, and the values each term can take | Term | What it describes | Values it commonly takes | |—|—|—| | Wiring | The number of lines and what each carries | Data lines, clock line, select lines, ground reference | | Topology | The arrangement of devices | Point-to-point, bus, multi-node bus | | Synchronisation | How bit timing is agreed | Synchronous (clock line) or asynchronous (agreed rate) | | Master/slave | Who controls a transfer | No master, single master, multi-master | | Addressing | How one device among many is selected | Address number, dedicated select line, message identifier, none | | Arbitration | Who wins a simultaneous attempt | None needed, or a defined priority rule | | Duplex | Direction of flow | Simplex, half-duplex, full-duplex | | Speed | Bits placed on the line per second | bps, kbps, Mbps | | Range | Reliable wiring length | Centimetres to hundreds of metres | | Error handling | What is detected, and what is done about it | Parity, acknowledgement, checksum, retransmission, none |

Q. Two protocols both claim a speed of 400 kbps. Does data reach the other end equally fast on both?

A. Not necessarily. The 400 kbps is the bit rate, and the two may spend very different fractions of it on overhead. One that sends an address and waits for an acknowledgement after every single byte delivers noticeably less user data per second than one that sends a long run of bytes with no interruption.

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.

NoteDefinition

A UART is a hardware module, built into a microcontroller or supplied as a separate integrated circuit, that converts parallel data from the processor into serial form for transmission and converts received serial data back into parallel form. It also generates and checks the timing, the start and stop bits and the optional parity bit.

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:

  1. A start bit. One bit period at the low level, marking the beginning of the frame.
  2. 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.
  3. A parity bit, optionally. One extra bit used for error checking, described in section 15.2.7.
  4. 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.

NoteDefinition

The baud rate is the number of signal changes, or symbols, placed on the line each second. Because UART uses a simple two-level signal in which each symbol carries exactly one bit, the baud rate of a UART link is numerically equal to its bit rate in bits per second.

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.

setting the baud rate of the board’s UART

Serial.begin(baud_rate);

Parts: baud_rate — an integer giving the bits per second, which must be the same value the device at the other end is using. Common permitted values are 9600, 19200, 38400, 57600 and 115200. Returns / Effect: configures the board’s UART hardware to the stated rate and takes control of the board’s serial pins, after which Serial.print() and Serial.read() may be used. Example:

Serial.begin(9600);
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.

Q1. Two boards are joined by a single wire. Why must they agree on a speed in advance before even one byte can cross it?

A. Because a UART link carries no clock wire. The data line only shows a sequence of high and low levels; nothing on it says where one bit ends and the next begins. The receiver recovers that information by starting a stopwatch at the falling edge of the start bit and then sampling at intervals it counts out itself. Those intervals come from the baud rate it was configured with, so if the two ends were set to different rates, the receiver reads the line at the wrong instants and produces a byte the sender never transmitted.

baud rate mismatch mistaken for a broken board What students do: set Serial.begin(9600) in the sketch, then select 115200 in the Serial Monitor’s rate box, or connect a module whose factory setting is 38400 while the sketch uses 9600. What happens: the connection appears alive but prints a steady stream of meaningless symbols and question marks. Nothing is faulty; the receiver is sampling the correct waveform at the wrong moments. The fix: make the two numbers identical — the value in Serial.begin(), the value in the Serial Monitor, and the module’s own configured rate. A wrong rate produces garbage, never silence, so garbage on the screen is itself the diagnosis.

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.

connecting a module to the pins the USB cable is using What students do: wire a Bluetooth module to pins 0 and 1 on an Arduino UNO, because those are the board’s hardware RX and TX pins, and leave it connected while uploading a sketch. What happens: the upload fails or stalls, and the Serial Monitor shows corrupted output. On an UNO those two pins are shared with the USB-to-serial converter, so the module and the computer are both driving the same lines. The fix: unplug the module’s TX wire while uploading, or move the link to a software serial pair on other pins. A board with more than one hardware UART avoids the clash entirely.

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.

Table 15.3 – key characteristics of UART | Property | UART | |—|—| | Wiring | 2 signal wires, TX and RX, plus a ground reference; module pins may also include VCC, DTR and CTS | | Topology | Point-to-point; exactly 2 devices, directly connected | | Synchronisation | Asynchronous; no clock line, both sides must agree on the timing in advance | | Master/slave | No master and no slave; either device may transmit at any time | | Addressing | None; there is only one possible destination | | Duplex | Full-duplex; both devices can transmit and receive simultaneously | | Typical baud rates | 9600 bps to 115200 bps, extending to about 1 Mbps on many microcontrollers | | Range | Short, typically a few metres or less at logic levels | | Error handling | Optional parity bit; framing error detection; no correction and no retransmission |

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.

Q. If UART cannot address anyone, how does a wireless command reach the correct robot in a workshop where six robots are running?

A. It does not, and the UART is not asked to. The addressing happens in the wireless layer above it — the phone pairs with one particular Bluetooth module. To the controller, the link still looks like a private point-to-point serial connection with exactly one device at the other end.

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.

is 9600 baud fast enough for a distance reading sent every 20 ms?

Given: a robot sends its ultrasonic reading to a second board as six characters followed by a carriage return and a line feed, so 8 characters in total. The link is 8N1 at a baud rate of 9600 baud. A new reading is produced every 20 ms.

Find: the time taken to transmit one reading, and whether the link keeps up.

Method: in 8N1 each character occupies 10 bit periods, so the total number of bit periods is 10 times the number of characters. The transmission time is the number of bit periods divided by the baud rate, since one bit period passes per baud on a UART link.

\[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.

Table 15.4 – parity bits for three characters, showing the data bits and the value the parity bit must take | Character | Data bits (b7…b0) | Number of 1 bits | Even parity bit | Odd parity bit | |—|—|—|—|—| | A | 0100 0001 | 2 | 0 | 1 | | C | 0100 0011 | 3 | 1 | 0 | | K | 0100 1011 | 4 | 0 | 1 |

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

I2C is a synchronous serial bus in which many devices share one clock line and one data line, together with a common ground. One device acts as master, generating the clock and beginning every transfer; the others act as slaves and respond only when the master addresses 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.2 The Shared Bus, Open-Drain Lines and Pull-Up Resistors

Hanging eight devices off one wire raises an obvious electrical danger. If one device drives the line to 5 V while another drives it to 0 V, the two outputs are connected directly across the supply. Current is limited only by the transistors themselves, and something gets hot.

I2C removes the danger by removing half of every output. Its lines are open-drain, which means that a device can pull the line down to ground but can never drive it up. When a device is not pulling, it simply releases the line and lets it float.

NoteDefinition

An open-drain output can connect its line to ground or disconnect from it entirely, but it can never source current to drive the line high. Several open-drain outputs may share one line safely, because no two of them can ever oppose each other.

Now the worst that can happen when two devices act at once is that both pull the line low, which is harmless — the line simply goes low. This behaviour is sometimes described as a wired AND: the line is high only when every device has released it.

That leaves the opposite problem. If nobody can drive the line high, a released line sits at no particular voltage at all, floating and picking up noise. Something must hold it high when it is idle, and that something is a pull-up resistor: a resistor from the line to the positive supply, one on SDA and one on SCL, as shown in Fig. 15.3-1.

Diagram

Fig. 15.3-2 – open-drain operation on one line: a rail at the top labelled VDD (5 V or 3.3 V) with a resistor labelled “pull-up resistor” descending to a horizontal line labelled SDA; three devices below the line, each drawn as a box containing a switch to ground labelled “pull low”; the first two switches drawn open and labelled “released”; the third drawn closed and labelled “pulling low”; two annotations, one reading “all released → line pulled high through the resistor”, the other reading “any device pulling → line low”

The resistor must be small enough to pull the line high quickly against the capacitance of the wiring, and large enough that the current drawn when a device pulls low stays modest. Values around 4.7 kΩ are usual for a 5 V bus at 100 kbps, and around 2.2 kΩ where a faster bus or a longer track needs a sharper rise.

Q3. Some sensor connections need two extra resistors added to the wires before they will work at all. What are those resistors doing?

A. They are the pull-up resistors on an I2C bus. Every device on the bus has an open-drain output, which can only pull a line down to ground and can never drive it up. That design is what allows many devices to share two wires without ever damaging one another, but it means no device is able to produce a high level. The two resistors, one on SDA and one on SCL, supply that high level by connecting each line to the positive supply, so a line that nobody is pulling low settles at the high level instead of floating.

too many pull-ups on one bus What students do: connect three ready-made sensor breakout boards to the same bus, each of which already carries its own pair of pull-up resistors on board, and then add another pair on the breadboard. What happens: the four sets of resistors sit in parallel, so the effective pull-up resistance falls to a quarter of the intended value. Devices may fail to pull the line fully low, and the bus becomes unreliable or stops responding. The fix: keep one pair of pull-ups for the whole bus. Check each breakout board’s documentation, and where several boards carry their own, remove or disable all but one set rather than adding more.

Q. What happens to the bus if a slave is powered down while the master keeps running?

A. Ideally nothing, because an unpowered open-drain output simply stops pulling and the pull-ups hold the lines high for everyone else. In practice a device that is unpowered but still wired can leak current through its protection diodes and drag the lines part-way down, which stops the whole bus. Devices sharing a bus should share a supply rail.

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:

  1. The master issues a START condition, which claims the bus.
  2. 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.
  3. Every slave on the bus compares that address with its own. The one that matches pulls SDA low during the ninth clock pulse to acknowledge. Every other slave stays silent for the rest of the transfer.
  4. Data bytes pass in the chosen direction, each one followed by a ninth clock pulse in which the receiver acknowledges it.
  5. 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.

Q2. If six sensors are all connected to the same pair of wires, what stops their signals from colliding and turning into nonsense?

A. Two rules working together. First, only the master may begin a transfer, so no slave ever speaks unless it has been spoken to. Second, every transfer opens with the address of one particular slave, and each slave compares that address with its own; the one that matches replies, and the other five stay off the data line completely. So although all six are electrically connected to the same wires, at most one of them is ever transmitting. The open-drain design in section 15.3.2 provides the safety net: even if two did pull the line at once, nothing would be damaged.

two identical sensors on one bus What students do: buy two of the same temperature sensor breakout and connect both to the same SDA and SCL lines to measure two points on the robot. What happens: both devices carry the same factory address, so both answer every time that address is called and both pull the data line during a read. The readings returned are meaningless, and neither sensor appears faulty when tested alone. The fix: check the datasheet for an address-select pin and tie it high on one board and low on the other, giving the two devices different addresses. Where a device offers no such pin, the second one needs a separate bus.

15.3.4 Key Characteristics

Table 15.5 fills in the same profile used for UART in Table 15.3.

Table 15.5 – key characteristics of I2C | Property | I2C | |—|—| | Wiring | 2 shared bus lines, SDA and SCL, with pull-up resistors, plus a ground reference | | Topology | Multi-device bus; one master with many slaves is typical, multi-master is possible | | Synchronisation | Synchronous; the master provides the clock on SCL | | Master/slave | Single master usual; slaves never begin a transfer | | Addressing | Each slave has an address, and the master selects which slave to talk to | | Duplex | Half-duplex; one device transmits at a time on the single data line | | Typical speeds | 100 kbps standard mode and 400 kbps fast mode; 1 Mbps and 3.4 Mbps modes exist on some devices | | Range | Short, generally under 1–2 m of bus length for reliable operation | | Error handling | Acknowledgement after every byte; arbitration between masters; no checksum and no correction |

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.

Table 15.6 – I2C speed modes and the clock rate each uses | Mode | Clock rate | Where it is met | |—|—|—| | Standard mode | 100 kbps | The default on most microcontroller libraries and most simple sensors | | Fast mode | 400 kbps | Widely supported; used where sensors are read frequently | | Fast mode plus | 1 Mbps | Some newer devices; needs stronger pull-ups and short wiring | | High-speed mode | 3.4 Mbps | Uncommon in robotics; requires careful board design |

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.

how long does one accelerometer reading occupy the bus?

Given: a master reads six data bytes from an accelerometer. The transaction sends the slave address and a register number, then restarts and sends the address again for reading, then receives the six data bytes — nine bytes in total. Each byte occupies 9 clock periods, being 8 data bits plus 1 acknowledgement bit. The bus runs in fast mode at 400 kbps. The robot needs a fresh reading every 5 ms.

Find: the time the transaction occupies the bus, and the fraction of the available interval it uses.

Method: total clock periods equals the number of bytes multiplied by 9. One clock period lasts the reciprocal of the clock rate. The START and STOP conditions add a small amount that is ignored here.

\[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.

NoteDefinition

SPI is a synchronous serial interface in which a master and a selected slave exchange data simultaneously on two separate lines, driven by a clock generated by the master. Every transfer moves a byte in each direction at the same time.

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 marked CS for 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.

leaving a slave select line floating What students do: wire a single SPI device, connect SCLK, MOSI and MISO, and leave the SS pin unconnected, on the reasoning that with only one device there is nothing to choose between. What happens: the floating pin drifts, and the device selects and deselects itself at random as noise moves the pin across the logic threshold. Data arrives corrupted or intermittently, and the fault comes and goes when the board is touched. The fix: always drive SS from a controller pin, and hold it low only for the duration of a transfer. Every unselected device must be held deselected, never left to decide for itself.

Q. A master reads a temperature from an SPI sensor. What is the sensor receiving on MOSI while it sends that value back?

A. Whatever the master happened to load into its shift register — typically a dummy byte of all ones. The exchange is unavoidable, because the ring shifts in both directions with every clock pulse. A well-designed slave simply ignores bytes it did not ask for.

15.4.3 Key Characteristics

Table 15.7 – key characteristics of SPI | Property | SPI | |—|—| | Wiring | 4 primary lines — SCLK, MOSI, MISO and SS — plus one extra SS line per additional slave, and a ground reference | | Topology | Single master with multiple slaves, each having an individual chip select | | Synchronisation | Synchronous; the master clock is carried on SCLK | | Master/slave | One active master; slaves never begin a transfer | | Addressing | None within the protocol; the SS line performs the selection | | Duplex | Full-duplex; data flows on MOSI and MISO simultaneously | | Typical speeds | A few MHz to tens of MHz, giving roughly 1–20 Mbps on many microcontrollers; an Arduino UNO’s SPI clock reaches at most 8 MHz, being half its 16 MHz system clock | | Range | Very short; usually within one board or module, a few tens of centimetres at most without special line drivers | | Error handling | None built in — no parity, no acknowledgement, no checksum |

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.

refreshing a display buffer over SPI and over I2C

Given: a monochrome display of 128 × 64 pixels is refreshed completely. Each pixel is one bit. The SPI link runs at a clock rate of 8 MHz with no per-byte overhead. The I2C alternative runs in fast mode at 400 kbps, where each byte occupies 9 clock periods.

Find: the time taken to send the whole buffer over each interface.

Method: find the size of the buffer in bits and in bytes. For SPI, divide the bit count by the clock rate. For I2C, multiply the byte count by 9 to get clock periods, then divide by the clock rate.

\[\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.

Q4. One of these four methods is many times faster than the others, yet it is almost never used over more than a few centimetres. Why?

A. SPI reaches its speed by stripping out everything that would slow it down. Its outputs actively drive both high and low, so the edges are sharp; there is no address, no acknowledgement and no error check, so nearly every clock pulse carries data. But those same choices leave it defenceless over distance. The signals are ordinary logic levels measured against ground, switching millions of times a second, so a long wire’s capacitance blurs the edges and nearby motor wiring couples noise straight into them. Worse, nothing in the protocol would detect the corruption if it happened. A protocol with no error checking can only be trusted where errors are physically unlikely, and that means a very short, clean connection.

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.

NoteDefinition

CAN is a multi-master serial bus in which every node receives every message. Each message carries an identifier that describes its contents and also fixes its priority, and each node decides from that identifier whether to keep the message or ignore it.

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.

NoteDefinition

Differential signalling carries a signal as the difference in voltage between two wires rather than as the voltage of one wire measured against ground.

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_H up to about 3.5 V and CAN_L down 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.

Q. If differential signalling ignores the ground reference, why do the nodes still need a common ground?

A. Because a transceiver can only reject noise within a limited range of common-mode voltage — a few volts either side of its own supply. If two nodes’ grounds drift far apart, both bus wires appear shifted together, and the difference between them is no longer inside the range the receiver can read. The ground connection keeps the whole bus inside that window.

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.

Table 15.8 – bit-by-bit arbitration between two nodes transmitting identifiers 0C0 and 120 in hexadecimal | Bit position | Node A sends (identifier 0C0) | Node B sends (identifier 120) | Level on the bus | What happens | |—|—|—|—|—| | 1 | 0 (dominant) | 0 (dominant) | 0 | Both agree, both continue | | 2 | 0 (dominant) | 0 (dominant) | 0 | Both agree, both continue | | 3 | 0 (dominant) | 1 (recessive) | 0 | Node B sent recessive but reads dominant, so Node B withdraws | | 4 | 1 | — | 1 | Node A continues alone, its message intact |

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

Table 15.9 – key characteristics of CAN | Property | CAN | |—|—| | Wiring | 2-wire differential bus, CAN_H and CAN_L as a twisted pair, with 120 Ω termination at each end, plus a ground reference | | Topology | Multi-node bus, generally up to about 30–100 nodes, limited by electrical loading; around 112 nodes is a common upper bound | | Synchronisation | No separate clock line; nodes are set to a common bit rate and resynchronise on the signal edges within each frame | | Master/arbitration | Multi-master with collision avoidance by priority arbitration; no single master controller | | Addressing | None; each message carries an identifier that also fixes its priority, and each node filters on it | | Signal levels | Differential — both lines near 2.5 V when recessive, about 3.5 V and 1.5 V when dominant; a CAN transceiver chip is required | | Duplex | Half-duplex, broadcast to every node | | Typical speeds | Up to 1 Mbps for standard CAN; typical vehicle networks run at 125 kbps to 500 kbps, with 1 Mbps reserved for critical real-time parts. CAN FD raises the data phase to several Mbps | | Range | About 40 m at 1 Mbps, several hundred metres at 125 kbps, and up to roughly 1 km at lower rates | | Error handling | 15-bit cyclic redundancy check, mandatory acknowledgement, automatic retransmission, error counters and self-isolation |

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”

how heavily do six motor controllers load a CAN bus?

Given: a robot has six motor controllers, each transmitting one standard CAN frame with 8 data bytes every 10 ms. Each such frame occupies about 111 bit periods. The bus runs at 500 kbps.

Find: the time one frame occupies the bus, and the percentage of the bus’s capacity the six controllers consume.

Method: one bit period is the reciprocal of the bit rate. Frame time is the number of bit periods multiplied by the bit period. Bus load is the total frame time in each 10 ms interval divided by that interval.

\[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.

Table 15.10 – wiring, topology and synchronisation of the four protocols | Feature | UART | I2C | SPI | CAN | |—|—|—|—|—| | Signal wires | 2 (TX, RX) plus ground | 2 (SDA, SCL) plus ground and pull-ups | 4 (SCLK, MOSI, MISO, SS) plus ground, and one more SS per slave | 2 (CAN_H, CAN_L) as a twisted pair, plus ground and 120 Ω termination | | Topology | Point-to-point, exactly 2 devices | Multi-device bus | One master, many slaves | Multi-node bus | | Synchronisation | Asynchronous, agreed rate | Synchronous, clock on SCL | Synchronous, clock on SCLK | No clock line; common bit rate with resynchronisation on signal edges | | Control | Neither device is master | Single master usual, multi-master possible | One master only | Multi-master with arbitration | | Selection of a device | None needed | 7-bit address sent on the bus | A dedicated SS wire per slave | Message identifier, filtered by each node | | Duplex | Full-duplex | Half-duplex | Full-duplex | Half-duplex, broadcast | | Extra hardware needed | None | Two pull-up resistors | None | A CAN controller and a transceiver at every node |

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.

Table 15.11 – speed, reach and cost of the four protocols | Feature | UART | I2C | SPI | CAN | |—|—|—|—|—| | Typical data rate | 9600 bps to 115200 bps, up to about 1 Mbps | 100 kbps standard, 400 kbps fast mode, up to 3.4 Mbps on some devices | Board-dependent; 8 MHz on an Arduino UNO, tens of MHz on faster hardware | Up to 1 Mbps standard, with CAN FD reaching several Mbps in the data phase | | Bit periods used per data byte | 10 in 8N1 | 9, because of the acknowledgement bit | 8, with no additions at all | About 14, averaged over a full 8-byte frame | | Practical range | A few metres | Under 1 m to 2 m of total bus | A few tens of centimetres, usually one board | About 40 m at 1 Mbps, up to roughly 1 km at low rates | | Electrical form | Single-ended logic levels | Single-ended, open-drain with pull-ups | Single-ended, push-pull | Differential pair, twisted and terminated | | Complexity | Low | Medium | Medium | High | | Best suited to | A single link to one module | A cluster of small sensors near the controller | Fast bulk transfer over a very short distance | Distributed subsystems across a large, noisy machine |

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”

Q. CAN is slower than SPI and needs extra chips at every node. Why is it used at all?

A. Because the two are not competing for the same job. SPI moves a large block of data across a few centimetres of clean board. CAN carries small, urgent control messages across metres of cable running beside motor conductors, and guarantees that a corrupted one is detected and sent again. Ask which is faster and SPI wins; ask which will still be working after an hour beside a welding machine and the question answers itself.

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.

Table 15.12 – what each protocol detects, and what it does about it | Question | UART | I2C | SPI | CAN | |—|—|—|—|—| | Is a corrupted bit detected? | Only if parity is enabled, and only an odd number of flipped bits | No | No | Yes, by a 15-bit cyclic redundancy check on every frame | | Is a missing device detected? | No | Yes, by the absence of an acknowledgement | No; a floating line returns a plausible constant | Yes, by the absence of an acknowledgement | | Is bad timing detected? | Yes, as a framing error | Not applicable, the clock is shared | Not applicable, the clock is shared | Yes, through form and stuffing checks | | Is anything retransmitted automatically? | No | No | No | Yes, in hardware | | Is a persistently faulty device isolated? | Not applicable | No | No | Yes, by error counters leading to bus-off | | Where must protection be added? | In the program, as a checksum and an acknowledgement | In the program, as a checksum | In the program, as a checksum or an echo-back read | Nowhere; it is already there |

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.

extending an I2C sensor onto a long cable What students do: mount a temperature or distance sensor at the far end of a robot and run a metre or more of ribbon cable back to the controller, keeping the I2C wiring that worked on the bench. What happens: readings become intermittent, or the bus stops responding altogether once the motors run. The added capacitance slows the pull-up’s rising edges, and I2C has no way to detect a corrupted byte, so wrong values may also pass through silently. The fix: keep the I2C bus short and local. A distant device belongs on a link designed for distance — a UART link with a line driver, or CAN — or the sensor is read by a small local controller that sends the result onward.

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.

  1. How many devices must share this connection? Exactly two allows anything; several favours a bus.
  2. How far apart are they? Centimetres on one board, tens of centimetres inside one enclosure, or metres across a chassis.
  3. How much data, and how often? A reading every 100 ms is nothing; a display refresh or a logged block is substantial.
  4. 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.
  5. 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.

Table 15.13 – protocol chosen for each link of one warehouse robot, with the reason | Link | Devices | Distance | Choice | Reason | |—|—|—|—|—| | Sensor cluster and small display | 5 devices | Within 15 cm of the controller | I2C | Many devices on two wires; the data volume is trivial and the distance is short | | Data logging to a memory card | 1 device | On the controller board | SPI | Blocks of several hundred bytes; speed matters and the run is a few centimetres | | Wireless link to the supervisor | 1 module | Adjacent | UART | A single point-to-point link carrying short text commands, which is exactly what UART is for | | Four wheel modules | 4 controllers | Up to 1 m, beside motor cables | CAN | Distance, electrical noise, and speed commands whose corruption must be detected and repaired |

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.

Read the accelerometer and gyro module over I2C in a loop, using millis() to time one thousand readings, and work out the time for a single reading. Compare it with the value the method of section 15.3.6 predicts, and account for any difference.

15.8 Summary

Why a protocol is needed
  1. 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.
  2. 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.
  3. 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.
  4. 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
  1. Topology is the shape of the connection: point-to-point, bus or multi-node bus.
  2. 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.
  3. Master and slave describe control. A master generates the clock, decides when a transfer happens and chooses the device addressed; a slave only answers.
  4. Addressing selects one device among many; arbitration decides who wins when two begin at once.
  5. Duplex is the direction of flow: simplex one way, half-duplex either way but one at a time, full-duplex both ways at once.
  6. 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.
  7. Range is the greatest wiring length over which the link stays reliable.
UART
  1. 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.
  2. 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.
  3. 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%.
  4. 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.
  5. 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.
  6. Wiring is TX to RX and RX to TX, crossed, plus a common ground. The topology is point-to-point and admits exactly two devices; duplex is full.
  7. Its uses in robotics are Bluetooth modules, GPS receivers, serial monitoring and debugging, and links between two microcontrollers.
  8. 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
  1. I2C is a two-wire synchronous serial bus. SCL carries the clock, SDA carries 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.
  2. 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.
  3. 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.
  4. 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. SDA changes only while SCL is low, except during START and STOP, which is how those two are recognised.
  5. 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.
  6. 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.
  7. 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
  1. 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; and SS, slave select, with one SS line per slave.
  2. 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.
  3. 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.
  4. Selection is physical: the master pulls one active-low SS line down, and unselected slaves ignore the clock and hold MISO in a high-impedance state. There is no addressing and no arbitration, and pin cost grows with every slave added.
  5. 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.
  6. 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.
  7. It has no error detection of any kind. A corrupted byte is delivered as data, and an absent device returns whatever level the floating MISO line 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. Two SS lines low together make two push-pull outputs oppose each other, which is the characteristic SPI fault.
CAN
  1. 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.
  2. 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.
  3. The bus is a twisted pair, CAN_H and CAN_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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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
  1. 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.
  2. 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.
  3. 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.
  4. 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.

15.9 Key Terms

  1. 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.
  2. 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.
  3. 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.
  4. Addressing — the means by which a master selects one device among many on a shared connection.
  5. Arbitration — the rule that decides which device continues when two begin transmitting at the same instant.
  6. Asynchronous — carrying no clock line, so that both ends must be configured to the same rate in advance and each keeps its own time.
  7. 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.
  8. Bit rate — the number of bits placed on the line each second, measured in bits per second (bps) and its multiples kbps and Mbps.
  9. 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.
  10. Bus — one shared set of conductors running past several devices, so that each connects to the same lines instead of having its own.
  11. 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.
  12. CAN — Controller Area Network; a multi-master differential serial bus built for reliable communication in electrically noisy places.
  13. 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.
  14. CAN_H and CAN_L — the two conductors of a CAN twisted pair, whose voltage difference carries the data.
  15. Clock line — a wire carrying a signal that ticks once per bit, generated by one device and followed by the others.
  16. Clock stretching — an I2C slave holding SCL low to make the master wait until it is ready.
  17. 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.
  18. 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.
  19. 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.
  20. CTS — Clear To Send; a hardware flow control line found on some serial modules.
  21. Data bits — the bits of the actual data item inside a UART frame, sent least significant bit first.
  22. 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.
  23. Differential signalling — carrying a signal as the difference in voltage between two wires rather than as the voltage of one wire measured against ground.
  24. Dominant — the CAN bus state representing logical 0, in which the transceiver drives the two wires apart; a dominant bit overwrites a recessive one.
  25. DTR — Data Terminal Ready; a hardware flow control line found on some serial modules.
  26. Frame — the complete group of bits sent for one item of data, including the bits added by the protocol around the data itself.
  27. Full-duplex — able to carry data in both directions at the same time, which needs a separate line for each direction.
  28. Half-duplex — able to carry data in either direction, but only one direction at a time, because the two share a line.
  29. 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.
  30. Latency — the delay between a device deciding to send something and the receiver having it.
  31. Master — the device that generates the clock where there is one, decides when a transfer happens and chooses which device is addressed.
  32. 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.
  33. MISO — Master In, Slave Out; the SPI line on which the selected slave sends to the master.
  34. MOSI — Master Out, Slave In; the SPI line on which the master sends to the slaves.
  35. Node — a device connected to a bus.
  36. 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.
  37. Overhead — the bits a protocol adds that carry no user data, such as start and stop bits, addresses, acknowledgements and check bits.
  38. Parallel communication — sending the bits of a data item together, one on each of several wires.
  39. 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.
  40. Point-to-point — a connection joining exactly two devices.
  41. Pull-up resistor — a resistor from a line to the positive supply, which returns a released open-drain line to the high level.
  42. Range — the greatest wiring length over which a link stays reliable.
  43. Recessive — the CAN bus state representing logical 1, in which neither wire is driven and both sit near 2.5 V.
  44. RX — the receive line of a serial link, which connects to the other device’s TX.
  45. SCL — the serial clock line of an I2C bus.
  46. SCLK — the SPI clock line, generated by the master.
  47. SDA — the serial data line of an I2C bus, used in both directions.
  48. 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.
  49. Simplex — able to carry data in one direction only.
  50. Slave — a device that answers a master and never begins a transfer of its own.
  51. SPI — Serial Peripheral Interface; a high-speed synchronous interface using a clock, two data lines and one slave select line per slave.
  52. SS — Slave Select; the SPI line, normally active-low, by which the master chooses one slave.
  53. Start bit — the single low bit period that opens a UART frame and tells the receiver where to begin counting.
  54. Stop bit — the high bit period that closes a UART frame and returns the line to its idle state.
  55. Synchronous — carrying a clock line, so that the receiver is told when each bit is valid instead of counting time for itself.
  56. Throughput — the amount of actual user data transferred each second, once overhead has been subtracted from the bit rate.
  57. Topology — the shape of a connection: how many devices it joins and how they are arranged.
  58. Transceiver — the chip at each CAN node that converts the controller’s logic levels into the differential signals the bus carries, and back again.
  59. TX — the transmit line of a serial link, which connects to the other device’s RX.
  60. 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

  1. A master is to be connected to three slaves over SPI. Not counting the ground conductor, how many signal wires does the arrangement need?
  1. 4
  2. 5
  3. 6
  4. 7
  1. Fill in the blank: in the 8N1 configuration, one character occupies ______ bit periods on a UART line.

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

  3. 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 SDA and SCL. Reason: an I2C device can pull a bus line low or release it, but cannot drive it high.

  1. Both the assertion and the reason are true, and the reason is the correct explanation of the assertion.
  2. Both the assertion and the reason are true, but the reason is not the correct explanation of the assertion.
  3. The assertion is true but the reason is false.
  4. The assertion is false but the reason is true.
  1. 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
  1. Write the full form of each of the following: MOSI, SDA, CRC, UART.

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

  1. The node sending 1A0, because the larger identifier has the higher priority.
  2. The node sending 0B5, because the smaller identifier has the higher priority.
  3. Neither; both frames are destroyed and both nodes retransmit.
  4. Whichever node began transmitting a fraction earlier.

15.11 Check Your Concepts

  1. Define a communication protocol. State what the common ground conductor does in a serial link between two boards.

  2. Differentiate between synchronous and asynchronous serial communication, and name one protocol of each kind from those studied in this chapter.

  3. Explain why the lines of an I2C bus need pull-up resistors. State one consequence of choosing a resistor value that is too large.

  4. SPI transfers data far faster than I2C, yet it is used only over a few centimetres. Give reasons for both parts of this statement.

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

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

  1. A student wires a UART link between two microcontroller boards as follows, and no data is received at either end.
  • TX of Board A to TX of Board B
  • RX of Board A to RX of Board B
  • GND of Board A to GND of 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.

  1. A CAN bus joins five nodes spread along a 1.5 m chassis. During assembly, a 120 Ω resistor has been fitted across CAN_H and CAN_L at 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.

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

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

  1. 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
  1. Name the protocol you would choose for each of the four links, and give the reason for each choice.
  2. 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.
  3. 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.
  1. 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.
  1. 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.
  2. 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.
  3. 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.