SPI read method
Could someone please explain this method. I can't make sense of the documentation.
An example is given...
spi = SPI(0, mode=SPI.MASTER, baudrate=2000000, polarity=0, phase=0, pins=('P19','P20','P21')) spi.write(bytes([0x01, 0x02, 0x03, 0x04, 0x05])) # send 5 bytes on the bus spi.read(5) # receive 5 bytes on the bus
but where are the read bytes?
According to the documentation, the number of bytes read is returned, so where is the actual data?
What do the asterisks indicate in the method description, i.e.
spi.read(nbytes, * , write=0x00)
I only need to send a byte to a register and return the value, which is also a byte.
dan last edited by
robert-hh last edited by
@alidaf Actually spi.read() returns the received bytes. The documentation is wrong about that.
I had to read the micropython site on SPI to get a better understanding. Based on your code I seem to have been doing everything right but I can't seem to get this device to respond via SPI. The PyCom documentation seems to be based on the micropython documentation but with some modifications. spi.read for e.g. in Pycom it returns the number of bytes read but in micropython it returns the actual bytes.
In any case, thanks for the input.
I don't know exactly what do the asterisks indicate, I suppose is a reserved parameter of the method. But if we focus on the use of each method:
spi.read(5) just reads five bytes while sending five 0x00, according to the description in the documentation. If you use spi.read(5, 0x01) then It will read five bytes while sending five 0x01. I know this is used, for example, in some ADC's when you need to bypass the first bytes acquired because are not valid, so you just read while send a constant value but the read data is not going to be used.
If you need to send a single byte and return the value, you can use:
rbuf = bytearray(1) spi.readinto(rbuf, byteToSend)
Read data is stored in rbuf and byteToSend is the byte you need to send.
To send two or more different bytes, I think you can use something like this:
wbuf = [0x02, 0xF0, 0XA1] #Bytes to send rbuf = bytearray(3) spi.write_readinto(bytes(wbuf), rbuf)
It sends wbuf while reads into rbuf, so rbuf will contain the bytes you're reading from the slave device.