Sub topic 4
Chip Select: Starting and Ending an SPI Transfer
Prerequisites
This chapter assumes that you know basic Arduino sketches, pinMode(), digitalWrite(), binary numbers, and the roles of SCLK, MOSI, and MISO. You should also know that SPI can connect several peripherals to one controller.
What chip select does
Chip select (CS), also called slave select (SS), tells one SPI peripheral when it should listen. Each peripheral normally has its own CS wire. CS is usually active low, which means:
HIGH: the peripheral is inactive.LOW: the peripheral is selected.
The controller pulls CS low before sending a command and returns it high when the complete command and data exchange ends. This low period is the transaction frame.
The peripheral often resets its command parser when CS goes high. Raising CS between bytes can therefore cancel a command or make the next byte look like a new command. Keep CS low for every byte that belongs to one device-defined operation.
Selecting and releasing a device
Configure CS as an output and set it high before enabling SPI. This prevents a peripheral from seeing a false selection during startup. The following example reads a register while keeping the entire exchange inside one CS frame.
#include <SPI.h>
const uint8_t CS_PIN = 10;
const uint8_t READ_FLAG = 0x80;
uint8_t readRegister(uint8_t address) {
SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0));
digitalWrite(CS_PIN, LOW);
SPI.transfer(address | READ_FLAG);
uint8_t result = SPI.transfer(0x00);
digitalWrite(CS_PIN, HIGH);
SPI.endTransaction();
return result;
}
void setup() {
Serial.begin(115200);
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH);
SPI.begin();
}
void loop() {
Serial.println(readRegister(0x0F), HEX);
delay(1000);
}The dummy byte 0x00 is not necessarily meaningful to the peripheral. It supplies clock pulses so the peripheral can shift its register value onto MISO.
Common chip-select errors
A floating CS input can randomly select a peripheral. Use a pull-up resistor, or drive the pin high immediately in setup(). Hardware pull-ups are especially useful while the microcontroller is resetting.
Never select two ordinary SPI peripherals at once. They may drive MISO simultaneously, causing conflicting signals and corrupt data. Keep every unused CS pin high.
Some devices require setup or hold time around CS. The datasheet may require a short delay after CS goes low before the first clock, or before CS goes high after the final clock. Follow those timing requirements instead of assuming the GPIO transition and SPI clock happen safely.
Exercise
Exercise
Why should CS remain low while a command byte and its response byte are exchanged?
Show answer
The low interval frames one complete transaction. Raising CS may reset the peripheral's command parser, so the response byte may no longer be associated with the command.