Best practice to handle buffer overwrite on SPI.transfer()?

Hey folks,

as it's documented, the spi->transfer(buffer, size) command will overwrite the buffer variable with the return value of daisy chained shift register response.

I want to avoid that as the "buffer" in my case is also the state, that I want to retain.

I've resorted to this patch before sending, copying all the elements of my buffer state onto another temporary buffer and send that one, but I am wondering if there is a better way to do this.

    // Declare temporary buffer to be used in transfer()
    uint8_t buffer[TOTAL_SIPOS];
   
    // Go through all the Shift Register "Serial Input Parallel Output" (SIPO) chips
    for (uint8_t i = 0; i < TOTAL_SIPOS; i++)
    {
      // "registerStatus" is my global state and buffer - copy it to the local buffer
      buffer[i] = registerStatus[i];
    }

    // At this point the value of "buffer" will be overwritten by the transfer() function
    vspi->transfer(&buffer, TOTAL_SIPOS);

Take the win and be proud.:expressionless:

Or… modify the library. I just had a glance, seems like an alternate transfer() method that had an output buffer as a parameter would be easy to write.

Oh, welcome to the community!

a7

1 Like

On which platform? For example, on Teensy there's an overload of transfer() that takes pointers to separate buffers:

void transfer(const void * buf, void * retbuf, size_t count);

The first is the data sent out MOSI, the second holds the data read from MISO. You can pass nullptr for the latter if you're not interested in reading data from the SPI device.

If you don't need the returned data (write-only shift registers) you can use a loop to send each byte separately and ignore the returned data:

    for (uint8_t i = 0; i < TOTAL_SIPOS; i++)
      vspi->transfer(registerStatus[i]);

If you need the returned data:

    // Declare temporary buffer for received data
    uint8_t buffer[TOTAL_SIPOS];
    for (uint8_t i = 0; i < TOTAL_SIPOS; i++)
      buffer[i] = vspi->transfer(registerStatus[i]);
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.