Everything you need is given here - you just need to know how to put it together:
There are variants of all the major methods that take an extra parameter - that parameter is the first parameter in the parameter list and defines the SS Pin to use for that function. That includes the .transfer()
function.
To use it you have to begin()
all the pins you want to use SPI with. Then you can use .transfer()
with those pins:
void setup() {
SPI.begin(10);
SPI.begin(4);
}
void loop() {
// Receive using pin 10 as SS
byte byteFromTen = SPI.transfer(10, 0x00);
// Transmit 123 using pin 10 as SS
SPI.transfer(10, 123);
// Both directions:
byte otherByteFromTen = SPI.transfer(10, 123);
// Receive using pin 4 as SS
byte byteFromFour = SPI.transfer(4, 0x00);
// Transmit 123 using pin 4 as SS
SPI.transfer(4, 123);
// Both directions:
byte otherByteFromTen = SPI.transfer(4, 123);
}
Doing multi-byte transfers is slightly more complex since you don't have control over the SS pin, so you have to use yet another version of the transfer()
function that tells it to "continue" the transaction:
// Receiving 3 bytes using pin 4:
byte firstByte = SPI.transfer(4, 0x00, SPI_CONTINUE);
byte secondByte = SPI.transfer(4, 0x00, SPI_CONTINUE);
byte thirdByte = SPI.transfer(4, 0x00);
Of course, mixing reading and writing is pretty much the same as usual. For instance, to read the port A values from an MCP23S17 would look like:
SPI.transfer(4, 0x41, SPI_CONTINUE); // Address 0, read bit set
SPI.transfer(4, 0x12, SPI_CONTINUE); // Select register 0x12 (GPIOA)
byte porta = SPI.transfer(4, 0x00);
The SPI_CONTINUE
tells the SPI system to keep the SS pin LOW. It is only then raised once it gets a .transfer()
without the SPI_CONTINUE
. This is the same as the traditional way of using digitalWrite()
to lower SS before the first transfer and raise it after the last transfer.