I have multiple 32-bit data stored in an array, and I want to sequentially send them by SPI interface. I want to check that my code is correctly sending data by SPI interface, so I upload the code and connect my Linkit7697 to an oscilloscope. The expecting waveform is like this: enter image description here
But it turns out to be like this: enter image description here
It seems that all data are composited together in every 32 bits. What's wrong? Any idea?
Here is my code:
#include <SPI.h>
#define SPI_MOSI (11)
#define SPI_MISO (12)
#define SPI_CS (10)
#define SPI_CLK (13)
uint32_t test[]={
0xF0000000, //11110000000000000000000000000000
0x00F00000, //00000000111100000000000000000000
0x0000F000, //00000000000000001111000000000000
0x0000000F //00000000000000000000000000001111
};
int i = 0;
void setup() {
digitalWrite(SPI_CS,HIGH); //Set slave select to high, linkit7697 is Master
SPI.begin();
SPI.beginTransaction(SPISettings(20000000,MSBFIRST,SPI_MODE0 ));
}
void loop() {
for (i = 0; i < 4; i++){
digitalWrite(SPI_CS,LOW);
SPI.transfer(&test[i],4);
digitalWrite(SPI_CS, HIGH);
}
}
1 Answer 1
SPI.transfer(&test[i],4);
The SPI.transfer()
transmit one byte each time and therefore expecting a pointer to a byte (i.e. uint8_t) while you are passing in an address of an uint32_t
. What you need to do is to cast the address of uint32_t
into a pointer of uint8_t
before passing it into the SPI.transfer
.
uint8_t *ptr = (uint8_t *) &test;
SPI.beginTransaction(SPISettings(20000000,MSBFIRST,SPI_MODE0 ));
digitalWrite(SPI_CS,LOW);
for (i = 0; i < sizeof(test); i++) {
SPI.transfer(*ptr++, 4);
}
digitalWrite(SPI_CS, HIGH);
SPI.endTransaction();
Please also note that Arduino is a little endian machine, so if you have a data as 0x41424344
, the first byte get transmitted will be 0x44
.
One more thing, it is always good to call SPI.endTransaction()
, it free up the SPI bus to allow other SPI devices to use the data bus.
transfer16
andtransfer32
functionsSPI.transfer()
actually will cut off everything after the lowest byte of your data element (because it expects one byte), thus only sending one byte per number. As jsotola wrote, thetransfer32()
function is meant for tranferring 32 bit numbers. You should use itSPI.transfer16()
to do the transfer. I'm sure that the bitwise operator is working (Because I use serial monitor to print the result). But when I connect the Linkit7697 to the oscilloscope, it shows the waveform as I mentioned above.