Catto / Topic Map · Digital Electronics IV Year 7
Digital Electronics IV · 120 h · Topic 2 of 6

Serial communication buses

The USART connects two devices. For a microcontroller to talk to twenty ICs on the same board, or to nodes spread around a plant, there are buses: a few shared wires, with clear rules about who talks and when.

I²C SPI RS-485 CAN

Where we start from

Asynchronous serial transmission, the USART, the baud rate and the framing of each character are covered in the serial communication module. Here we add the synchronous and multipoint buses, which are the ones that show up as soon as there are more than two ICs.

01The buses, compared

BusWiresSpeedRangeWhere it is used
I²C2100 k to 1 M< 1 mSensors, memories, clocks and expanders inside a board.
SPI4 (+1 per slave)1 to 50 M< 30 cmMemory cards, displays, fast converters.
1-Wire1 (+ ground)15 ktens of mTemperature sensors and identification keys.
RS-4852 (twisted pair)up to 10 M1,200 mInstruments and drives in a plant. It is the physical medium of Modbus.
CAN2 (twisted pair)up to 1 M40 to 1,000 mAutomotive and machinery: designed for electrically hostile environments.
USB412 M to 5 G5 mConnection to the computer, power supply included.
Ethernet4 or 810 M to 1 G100 mPlant networks and devices with their own web server.
Inside the board or outside the board

I²C and SPI are meant to travel centimeters across a circuit board. Running them over a two-meter cable works some of the time and fails intermittently the rest. As soon as the signal has to leave the enclosure, a differential bus is called for: RS-485 or CAN. This is the most common design mistake and the hardest one to diagnose afterwards.

02I²C: two wires and many ICs

S1001000WAd7d6d5d4d3d2d1d0APSDASCLStart conditionSDA falls while SCL is high. It is the only situation where this happens: it marks the start.7-bit addressThe master names the device. Only the one that matches responds; the others ignore everything that follows.Read/write bitZero to write to the slave, one to read from it.AcknowledgeThe slave pulls SDA low for one clock cycle. If it does not appear, the device is absent or did not understand.Data byteEight bits, most significant first. Data changes while SCL is low and is read while SCL is high.Data acknowledgeThe ACK again. It repeats after every byte transferred.Stop conditionSDA rises while SCL is high: the bus is free for another master.Both lines are open-collector: chips can only pull them low, and the pull-up resistors raise them.
Figure 1. An I²C transaction, animated. The master generates the start condition, sends the address with the read/write bit, and after each byte the receiver replies with an acknowledge. All with two shared wires.
How it works
  • SDA carries the data and SCL the clock. Both are open-collector: the ICs can only pull the line low, and pull-up resistors raise it.
  • Each device has a 7-bit address. The master sends it and only the one that matches responds.
  • After each byte, the receiver pulls the line low for one cycle: that is the ACK. If it does not appear, the device is absent or did not understand.
  • A slow slave can stretch the clock by holding SCL low: clock stretching.
What usually fails
  • The pull-up resistors are missing, or there is one on every module and, in parallel, they end up too low. Typical value: 4.7 kΩ, just one set per bus.
  • Duplicate addresses: two identical sensors without changing their address with jumpers.
  • Long cable: the capacitance rounds off the edges and the bus stops responding.
  • A hung slave leaves SDA low and blocks the entire bus.
Example · Reading a sensor over I²C
/* Reading two bytes from a sensor at address 0x48, register 0x00 */
i2c_start();
i2c_write(0x48 << 1);        /* address + bit 0 = write */
i2c_write(0x00);              /* points to the register to be read */
i2c_start();                  /* repeated start, without releasing the bus */
i2c_write((0x48 << 1) | 1);  /* address + bit 1 = read */
alto = i2c_read(ACK);           /* ACK: I want another byte */
bajo = i2c_read(NACK);          /* NACK: this is the last one */
i2c_stop();

The detail of the repeated start —without releasing the bus between the pointer write and the read— is what keeps another master from barging in between. It is the sequence that appears in almost every datasheet.

03SPI: fast and protocol-free

The four lines
  • SCLK: clock, always generated by the master.
  • MOSI: data from master to slave.
  • MISO: data from slave to master.
  • CS or SS: select, one line per slave. It is the price of speed.

There are no addresses, no acknowledge and no error detection: SPI is a shift register shared between two chips. That is why it is so fast and so simple.

The four modes

They are defined by two bits: CPOL, the idle state of the clock, and CPHA, whether the data is sampled on the first edge or the second.

ModeCPOLCPHA
000
101
210
311

The wrong mode is the number one cause of “I always read zeros” or “the bits come out shifted.” It is in the slave’s datasheet.

04Buses for leaving the enclosure

A single wire against groundsignal + noisethresholdrecovered bitsthe noise crosses the threshold: false bits appearDifferential pairA and B, both with the same noiseA minus Bthe noise is common to both wires and cancels outThis is why RS-485 and CAN use twisted pair: the noise is induced equally in both wires, and the receiverlooks only at the difference between them. Whatever is common to both disappears.
Figure 2. Why a differential pair resists noise, animated. The noise is induced equally in both wires; the receiver looks at the difference between them and the noise cancels out.
AspectRS-485CAN
Who talksA master asks and the slaves reply in turn. Nobody transmits without being polled.Any node transmits when it wants to; if two collide, the higher-priority message wins without losing anything.
AddressingBy node address, in the protocol layered on top (typically Modbus).By message identifier: you address the content, not the node.
Error detectionProvided by the higher-level protocol, with its redundancy check.Built into the bus itself: CRC, acknowledge and automatic retransmission.
Termination120 Ω at both ends of the pair, and only there.120 Ω at both ends, the same.
TopologyLinear daisy chain. Long stubs cause reflections.Linear daisy chain, with short stubs.
Isolation and grounds

Between two ends of a plant there can be several volts of difference between grounds, and significant currents can flow through the shield. That is why industrial transceivers are usually galvanically isolated, the shield is grounded at one end only, and the bus is run apart from the power cables. Ignoring this produces intermittent faults that show up just when a motor starts.

05How to choose the bus

SituationSuitable bus
Several slow sensors on the same boardI²C: two wires and up to 127 addresses.
Graphic display or memory cardSPI: you need throughput, not addresses.
A thermometer ten meters away1-Wire: a single wire and it tolerates long cables.
Instruments spread around a plantRS-485 with Modbus: 1,200 m and up to 32 nodes per segment.
Vehicle or mobile machineryCAN: priorities, error detection and noise tolerance.
Connection to a PCUSB, or a USB-to-serial converter if that is enough.
A device that must be visible from the networkEthernet, with an embedded web server.

06In the lab

Lab 1 · Exploring the I²C bus

Write a program that scans all 127 addresses and lists the ones that reply with an ACK. Connect several modules and check that they show up. Then remove the pull-up resistors and watch on the oscilloscope how the edges become rounded until the bus stops working.

Lab 2 · SPI with a logic analyzer

Connect a memory or a display over SPI and capture the four lines with a logic analyzer. Decode the frame and compare it with the datasheet. Deliberately change the clock mode and see how the data gets corrupted.

Lab 3 · RS-485 over a distance

Build an RS-485 link between two microcontrollers with transceivers, starting with one meter of cable and working up to the longest distance available at school. Measure the error rate with and without termination resistors, and with the cable running past a motor that is running.

Lab 4 · Modbus

Implement a simple Modbus RTU slave that exposes a sensor reading in a register, and read it from a PC with a master program. It is exactly what an industrial instrument does, and it opens the door to the industrial communications topic.

07Common mistakes

SymptomUsual cause
The I²C bus does not respond to anythingThe pull-up resistors are missing, or a hung slave holds SDA low.
Two identical sensors and only one worksThey share an address: change it with jumpers or use a bus multiplexer.
SPI always returns zeros or shifted dataWrong clock mode, or the select line is not asserted before the transfer.
I²C run over a long cableThe cable capacitance ruins the edges. To leave the enclosure, use RS-485 or CAN.
RS-485 without terminationReflections at the ends and sporadic errors that grow with speed.
Termination at every nodeExcessive loading: the signal ends up too small. Only two go in, one at each end.
Shield grounded at both endsCurrent flows through the shield and noise is injected instead of removed.
Faults that appear when a motor startsGalvanic isolation is missing or the bus runs alongside the power cables.

08Self-assessment

Why does I²C need pull-up resistors?

Because its outputs are open-collector: devices can only pull the line low. The high level is supplied by the resistor. Typical value: 4.7 kΩ, just one per line and per bus.

What is the ACK in I²C and what is it for?

A zero bit that the receiver sends after each byte. It tells you that the device exists and received the data: if it does not appear, the address is wrong or the chip is not connected.

How many wires does SPI use and why does the count grow with the number of slaves?

Four basic ones —clock, two data lines and select—, plus one additional select line for each slave. There are no addresses: the choice is made in hardware.

What do CPOL and CPHA define?

CPOL, the idle state of the clock; CPHA, whether the data is sampled on the first or the second edge. Their combination gives the four SPI modes, and the wrong mode corrupts all the data.

Why does a differential pair resist noise better?

Because the noise is induced practically equally in both wires and the receiver looks only at the difference between them: whatever is common to both cancels out.

Where do the termination resistors go in RS-485?

120 Ω at both ends of the pair, and only there. Putting them on every node loads the bus and shrinks the signal.

What is the essential difference between CAN and RS-485?

CAN is a complete protocol: nodes transmit when they want to, resolve collisions by priority without losing messages, and include CRC and retransmission. RS-485 is only the physical medium; the protocol is added on top.

Which bus is appropriate for a sensor ten meters from the microcontroller?

1-Wire if it is a slow thermometer, or RS-485 if you need speed and robustness. I²C at that distance is not reliable.

Why is the shield grounded at one end only?

So that no current flows through it because of a potential difference between grounds. With both ends connected, the shield injects noise instead of removing it.

What is the most useful tool for diagnosing a serial bus?

The logic analyzer with a protocol decoder: it shows the actual bytes on the wire, which are almost never the ones you think you are sending.

Development of the topic “Communication module” of Digital Electronics IV (Year 7), based on the “Curriculum Proposal – Second Cycle of the Technical-Vocational Track, Secondary Education – Electronics,” Ministry of Education of the Province of Córdoba, DGETyFP. Back to the Topic Map · catto.ar