Sub topic 11
Several Peripherals on One Bus
This chapter assumes you can already complete a single SPI exchange with SPI.beginTransaction, SPI.transfer and a chip-select pin. You should also know the four SPI modes and what SPISettings holds. Here the focus is on what changes when a second or third device joins the bus, and what breaks when you do it carelessly.
What is shared and what is not
SPI scales to several peripherals because most of the wiring is common. Only chip select is private to each device.
| Signal | Shared or per device | Notes |
|---|---|---|
| SCLK | Shared | One clock line to every peripheral |
| MOSI | Shared | Every peripheral hears every byte the controller sends |
| MISO | Shared | Only the selected peripheral may drive it |
| Chip select | One per peripheral | Active low on nearly all devices |
Every peripheral sees all clock pulses and all MOSI data. A peripheral ignores them while its own chip select is high. The device pulled low is the only one that listens and the only one that may drive MISO.
The rule: one chip select low at a time
Never pull two chip-select lines low at once. If both devices are selected, both interpret your bytes as commands. Both may also drive MISO, and a driver fighting another driver produces corrupted data and can overload the output stages.
The working discipline has three parts:
- All chip-select pins idle high.
- One chip select goes low for the length of one transaction.
- It returns high before any other device is touched.
Make chip select safe at boot
A chip-select pin configured as an input floats, so the peripheral may see a random level. Even after pinMode(pin, OUTPUT), the pin may briefly drive low on some boards. Set the level before switching the direction. On AVR boards, writing HIGH to an input pin enables the internal pull-up, so the pin goes high as soon as it becomes an output:
digitalWrite(csPin, HIGH); // enables the pull-up while still an input (AVR)
pinMode(csPin, OUTPUT); // pin now drives high with no low glitchInitialize every chip-select pin this way before you call SPI.begin() or talk to any device. A forgotten pin is a common cause of a first device that works alone and fails once a second one is wired in. The unused device's chip select floats low and answers on MISO at the wrong time.
On the Arduino Uno the hardware SS pin (digital 10) must stay an output when the board is the controller. If it becomes an input and goes low, the SPI hardware switches itself into peripheral mode and transfers stop. Treat pin 10 as an output even if you do not use it for chip select.
Different devices need different settings
Devices on one bus often disagree on mode, speed and bit order. A sensor may need mode 3 at 2 MHz, while a flash chip uses mode 0 at 8 MHz. The bus does not care, because the settings apply per transaction. SPI.beginTransaction(settings) reconfigures the hardware, and SPI.endTransaction() releases the bus.
Keep each device's chip-select pin and SPISettings together. A small struct stops you from sending a command with the wrong settings:
#include <SPI.h>
struct SpiDevice {
uint8_t csPin;
SPISettings settings;
};
const SpiDevice sensor = {9, SPISettings(2000000, MSBFIRST, SPI_MODE3)};
const SpiDevice flash = {10, SPISettings(8000000, MSBFIRST, SPI_MODE0)};
void initDevice(const SpiDevice &dev) {
digitalWrite(dev.csPin, HIGH); // set the level first to avoid a low glitch (AVR)
pinMode(dev.csPin, OUTPUT);
}
uint8_t exchange(const SpiDevice &dev, uint8_t command) {
SPI.beginTransaction(dev.settings);
digitalWrite(dev.csPin, LOW);
uint8_t reply = SPI.transfer(command);
digitalWrite(dev.csPin, HIGH);
SPI.endTransaction();
return reply;
}
void setup() {
Serial.begin(115200);
initDevice(sensor); // deselect every device before the bus starts
initDevice(flash);
SPI.begin();
}
void loop() {
uint8_t a = exchange(sensor, 0x01); // command values are placeholders
uint8_t b = exchange(flash, 0x9F);
Serial.print(a, HEX);
Serial.print(' ');
Serial.println(b, HEX);
delay(100);
}Every call to exchange sets the mode and clock for that device. Nothing carries over from the previous call. This is why the library exists in transaction form. Calling SPI.setDataMode() once in setup() would fail as soon as a second device needs a different mode.
Chip select timing around the transaction
Order matters in exchange. Start the transaction first, so the clock idles at the correct level for the device's mode, and only then pull chip select low. Reverse the order on exit. If chip select falls while SCLK sits at the wrong idle level for that device, the peripheral may see a spurious clock edge and shift in a wrong bit. Some datasheets also specify a minimum time between chip select falling and the first clock edge, and between the last edge and chip select rising. At low clock rates the function-call overhead usually covers this. At 8 MHz or more, check the datasheet.
MISO contention
Chip select tells a peripheral to listen, and it should also tell the peripheral to release MISO. A well-behaved device puts its MISO pin into a high-impedance state when deselected. This is called tri-state, and it lets several devices share the line.
Not every device does this. Some, notably certain SD card modules and cheap breakout boards, keep driving MISO after deselection. The symptoms are:
- A sensor reads correctly when it is the only device on the bus and returns garbage once the other device is connected.
- The same wrong value shows up regardless of which device you query.
- Removing a device's MISO wire fixes the other device.
You have three fixes. Put a tri-state buffer such as a 74HC125 on the offending device's MISO, with its output enable tied to that device's chip select. Use a module that has such a buffer built in. Or give that device its own SPI port if the board has a second one.
Interrupts and bus ownership
beginTransaction does more than set the speed. On AVR cores it can block interrupts that are registered through SPI.usingInterrupt(). This matters when an interrupt service routine (ISR) also uses SPI, for example one that reads a data-ready line and fetches a sample. Without protection, the ISR may start a transfer in the middle of the main program's transfer and corrupt both.
Safer designs avoid SPI inside an ISR altogether. Have the ISR set a volatile flag and let the main loop do the transfer. If you must use SPI in an ISR, register the interrupt number with usingInterrupt as your board's SPI library documents, since the support differs between cores.
Scaling beyond a few pins
Each extra peripheral costs one chip-select pin. With many devices, you have these options:
- A 3-to-8 decoder such as the 74HC138 turns three pins into eight active-low chip-selects. Only one output is low at a time, which enforces the one-at-a-time rule in hardware.
- A GPIO expander on I2C can supply chip-select lines, at the cost of slower selection.
- Daisy chaining, covered in a later chapter, lets some devices share one chip select.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Device A works alone, fails with B attached | B's chip select floats low or B drives MISO | Initialize all CS pins high first; add a tri-state buffer |
| Reads return 0xFF or 0x00 for one device only | Wrong mode or speed for that device | Check that its `SPISettings` are passed to `beginTransaction` |
| Data is occasionally corrupted | An ISR transfers during a main-loop transfer | Move SPI out of the ISR or use `usingInterrupt` |
| Transfers stop on an Uno | Pin 10 became an input and went low | Keep pin 10 as an output |
Exercise
You add a second device to a working SPI bus. The first device now returns wrong data, even though your code never talks to the second device. Name two likely hardware causes and one check for each.
Show answer
First, the second device's chip select may be floating or low, so it is selected all the time. Check with a multimeter or logic analyzer that its CS line sits high, and set that pin to a high output before SPI.begin(). Second, the second device may keep driving MISO while deselected. Check by disconnecting its MISO wire. If the first device recovers, add a tri-state buffer enabled by that device's chip select, or use a module that has one.
Exercise
A sensor requires SPIMODE3 at 2 MHz and a flash chip requires SPIMODE0 at 8 MHz. Why is calling SPI.setDataMode(SPI_MODE3) once in setup() a poor design, and what do you do instead?
Show answer
The mode applies to the whole bus, so the flash chip would be clocked in the wrong mode as soon as you talk to it. Instead, build one SPISettings object per device and pass it to SPI.beginTransaction() at the start of every exchange with that device. Each transaction then sets the right mode, clock rate and bit order for the device being used.