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:
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?
1 Answer 1
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.
SPI.transfer(&SPI_message,2)
is destructive. The buffer is updated with the received values.loop
is executed, then SPI_message is overwritten and zeroes are sent. Try reinitialising it to 0xabcd inloop
.