Sending Multiple Bytes with SPI.Transfer using Arduino Due

Hi all :slight_smile:

I am a little bit stuck on the need to send out 24 bytes of information over the SPI bus and the best way to do it. I am using the TLC5940 LED driver (datasheet). I know there is a library for it but I really want to try and work it out myself if I can as the data arrays are slightly different.

I have an array with 16 x 12 bit values, 192 bits in total. I need to send out MSB first so it sits as 15MSB .15LSB . 14MSB ...... 0LSB.

I am struggling on how best to convert the array of 16 12 bit values into 24 individual 8 bit values to send over the SPI bus.

As a side note, using the Arduino Dues extended SPI functions, when I setup the following,

void loop(){
  byte response = SPI.transfer(4, 0xFF);
  byte response2 = SPI.transfer(10, 0xFF);
  byte response3 = SPI.transfer(52, 0xFF);
}

Will this execute simultaneously or send/receive the first, then the second then the third?

Thanks in advance

your code example will transmit everything serially. a byte will be sent out and the transfer() function will wait until it receives an a response.

the easiest thing to do is keep using these SPI.transfer() calls and just serialize your 12 bit data to a buffer (a load of bytes). then just transfer all the bytes one by one.

such serialization code will look something like this

uint8_t bytes[24];
uint16_t twelvebit[16];

//..
//... fill twelvebit with meaningful stuff..
//....

int j = 0;
// 16 12-bit words -> 24 bytes
for (int i=0; i<16; i+=2)
{
  bytes[j++] = twelvebit[i] >> 4;
  bytes[j] = (twelvebit[i] & 15)<<4;
  bytes[j++] |= twelvebit[i+1] >> 8;
  bytes[j++] = twelvebit[i+1] & 255;
}

You need to read this:

In particular the use of SPI_CONTINUE

Hi,

Thanks very much for your help. I think I have it sorted as far as converting the 12 bit values to an 8 bit array.

I had seen that page regarding extended usage but I'm not entirely sure on how to go through each of the 8 but values, would I do it with something like this? (Excuse the code, it's very rough idea)

for(i=0; i <=23-1; i++) {
  SPI.transfer(4, bytes[i], SPI_CONTINUE)
}

SPI.transfer(4, bytes[23])

Or would a while loop suit this task better? I'm not overly familiar with while loops.

Thanks again for everyone's help!

the loop you describe should be fine.. omission of the SPI.transfer() 's third parameter is implicitly SPI_LAST. just forget about while loops, for loops can do everything while loops can and more.. and they are typically less programmer error prone.

Thanks again everyone.

I will try it out and let you know how I go :slight_smile: