Sub topic 11
Several Peripherals on One SPI Bus
Assume you know the SPI signals, clock modes, and Arduino SPISettings. A shared SPI bus lets several peripherals use the same SCLK, MOSI, and MISO wires. Each peripheral gets its own chip-select (CS) pin.
Shared wires and separate chip selects
Connect the controller's signals to every peripheral:
- SCLK connects to every SCLK input.
- MOSI connects to every MOSI input.
- MISO connects to every MISO output.
- Each peripheral gets a separate CS output from the controller.
- All devices must share a compatible ground.
The controller selects exactly one peripheral by driving its CS pin LOW. The other CS pins stay HIGH. A selected device drives MISO. Unselected devices must release MISO so they do not fight the selected device.
A floating CS pin can accidentally select a device during startup. Configure every CS pin as an output and drive it HIGH before communicating.
Use the correct settings for each device
Peripherals can require different clock rates or SPI modes. Store one SPISettings object for each device, then apply the matching settings inside every transaction.
#include <SPI.h>
const uint8_t CS_SENSOR = 9;
const uint8_t CS_FLASH = 10;
SPISettings sensorSettings(2000000, MSBFIRST, SPI_MODE3);
SPISettings flashSettings(8000000, MSBFIRST, SPI_MODE0);
uint8_t transferOne(uint8_t csPin, const SPISettings &settings,
uint8_t command) {
SPI.beginTransaction(settings);
digitalWrite(csPin, LOW);
uint8_t reply = SPI.transfer(command);
digitalWrite(csPin, HIGH);
SPI.endTransaction();
return reply;
}
void setup() {
Serial.begin(115200);
pinMode(CS_SENSOR, OUTPUT);
pinMode(CS_FLASH, OUTPUT);
digitalWrite(CS_SENSOR, HIGH);
digitalWrite(CS_FLASH, HIGH);
SPI.begin();
}
void loop() {
uint8_t sensorReply = transferOne(CS_SENSOR, sensorSettings, 0x01);
uint8_t flashReply = transferOne(CS_FLASH, flashSettings, 0x02);
Serial.println(sensorReply, HEX);
Serial.println(flashReply, HEX);
delay(1000);
}The command bytes in this example are placeholders. Use the command format from each device's datasheet. Keep CS LOW for the complete command and response sequence unless the datasheet explicitly allows separate frames.
Common errors
- Selecting two peripherals at once can cause both to drive MISO.
- Changing SPI settings while CS is LOW can confuse the selected device.
- Reusing one mode or speed for every device can produce incorrect data.
- Forgetting a common ground causes unreliable logic levels.
- Some boards use additional pins, such as reset, data/command, or busy. Treat those pins according to the device documentation.
Exercise
An SPI sensor requires mode 3 at 1 MHz and a flash chip requires mode 0 at 8 MHz. What must change between their transfers?
Show answer
Select only one CS pin at a time and call beginTransaction with that device's SPISettings before its transfer.