3

I am having trouble getting SPI.transfer(buffer, size) to work as expected.

Here is the code:

// inslude the SPI library:
#include <SPI.h>
// set pin 10 as the slave select for the digital pot:
const int slaveSelectPin = 10;
uint16_t SPI_message = 0xABCD;
void setup() {
 // set the slaveSelectPin as an output:
 pinMode(slaveSelectPin, OUTPUT);
 // initialize SPI:
 SPI.begin();
}
void loop() {
 SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0));
 SPI.transfer(0xEF);
 SPI.transfer(&SPI_message, 2);
 SPI.endTransaction();
 delayMicroseconds(300);
}

Here is the output of logic analyzer:

enter image description here

As can be seen the call for SPI.Transfer(0xEF) works as expected. However SPI.transfer(&SPI_message,2) sends 0x0000 instead of 0xABCD on the bus.

What am I doing wrong?

asked Sep 27, 2018 at 7:28
6
  • 2
    SPI.transfer(&SPI_message,2) is destructive. The buffer is updated with the received values. Commented Sep 27, 2018 at 7:40
  • I assume this is Arduino? Can you decrease SPI clock - currently you seem to be at the limit of your logic analyser. Does it work if you split the second transfer into two 1B transfers? --- What Mikael said is probably the reason for your issue. Commented Sep 27, 2018 at 7:42
  • @MikaelPatel But still I should be able to see 0xABCD on my MOSI line on the SPI bus? I am not trying here to read data from a variable, but I am observing signals on the line of the SPI. Commented Sep 27, 2018 at 7:45
  • 1
    Only the first time loop is executed, then SPI_message is overwritten and zeroes are sent. Try reinitialising it to 0xabcd in loop. Commented Sep 27, 2018 at 7:49
  • @domen Exactly! this is what I was overseeing! Now it works. Commented Sep 27, 2018 at 7:52

1 Answer 1

4

SPI.transfer(&SPI_message,2) is unfortunately destructive. The buffer is updated with the received values. There is a SPI member function[1] that can be used for 16-bit data; SPI.transfer16(SPI_message).

To correct your sketch either initialize the buffer before each call (as recommended by @domen) or use the 16-bit transfer function.

There are other SPI APIs that included non-destructive transfer function e.g. read/write. Please see [2].

Cheers!

Ref.

  1. https://www.arduino.cc/en/Reference/SPITransfer
  2. https://github.com/mikaelpatel/Arduino-SPI/blob/master/src/SPI.h#L137
answered Sep 27, 2018 at 9:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.