Python spidev xfer2 clarification

48 Views Asked by At

I've not found good answer to the following, and the spidev documentation isn't much help:

Assume I have a SPI device where you send two bytes plus a pad byte before reading back a four byte response. Here's what I want to send, and what I expect to receive:

byte        0       1       2     3     4     5     6
MOSI: txdata0 txdata1 padding dummy dummy dummy dummy
MISO: ignored ignored ignored data0 data1 data2 data3

What is the spidev incantation that results in the MOSI / MISO exchange above? Is it:

  • rxdata = spi.xfer2([txdata0, txdata1], 7) # i.e. expecting 7 bytes back total
  • rxdata = spi.xfer2([txdata0 txdata1, 0], 4) # i.e. expect 4 bytes following txbuf plus pad
  • something else?
1

There are 1 best solutions below

0
On

The solution is simpler than either suggestion in the question. The rule is simple: if you want N bytes in a response to spi.xfer2(), you have to send N bytes. So in order to get:

byte        0       1       2     3     4     5     6
MOSI: txdata0 txdata1 padding dummy dummy dummy dummy
MISO: ignored ignored ignored data0 data1 data2 data3

you do this:

# send two bytes of data, one pad, four more bytes to clock in results
rxbuf = spi.xfer2([txdata0, txdata1]+[0]*5) 
# result data is now in rxbuf[3:]