0

I'm trying to get 2 devices (camera and sd card)to work on the SPI interface with an Arduino DUE. I'm having trouble finding example code online showing how to communicate with multiple slaves on the DUE as I know it is slightly different than with the UNO.
Questions I have include: How do you indicate you want to talk to a slave on pin 4? Instead of digitalWrite(4,LOW) do you call SPI.begin(4)? etc..

Can someone post some example code?

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.