Using SPI to send list

Discussion about programs, libraries and tools that work with MicroPython. Mostly these are provided by a third party.
Target audience: All users and developers of MicroPython.
Post Reply
martynwheeler
Posts: 8
Joined: Thu Jan 28, 2021 10:36 pm

Using SPI to send list

Post by martynwheeler » Thu Jan 28, 2021 10:44 pm

Hi,

I am trying to port a function from python into upython. The function uses the spidev library in python which does not exist in upython.

here is the python function:

Code: Select all

    def _spi_write(self, register, payload):
        if type(payload) == int:
            payload = [payload]
        elif type(payload) == bytes:
            payload = [p for p in payload]
        elif type(payload) == str:
            payload = [ord(s) for s in payload]

        self.spi.xfer([register | 0x80] + payload)



xfer is described as

"Performs an SPI transaction. Chip-select should be released and reactivated between blocks. Delay specifies the delay in usec between blocks."

It is sending a list of two bytes in the function. In upython there is an spi.write method which sends a single byte. so can i simply loop over the list and use spi.write?

Thanks in advance,

Martyn

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Using SPI to send list

Post by Roberthh » Fri Jan 29, 2021 7:13 am

The spi.write method of MicroPython sends a buffer with as many bytes as are in the buffer. So you can send either each object independently, or pack them all into a buffer and send that one. For the sake of memory efficiency, I would go for the first option and encode and send the data directly in the if/elif/elif sequence of your same script.
- The int object has to be encoded in a suitable bytes object then be sent, e.g. with formatting: spi.write(b'%d' % payload)
- the byte object can be sent as it is: spi.write(payload)
- the str-object just has to be encoded to bytes and then sent: spi.write(payload.encode())

martynwheeler
Posts: 8
Joined: Thu Jan 28, 2021 10:36 pm

Re: Using SPI to send list

Post by martynwheeler » Fri Jan 29, 2021 7:39 am

Thanks, I will give it a go later.

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Using SPI to send list

Post by pythoncoder » Fri Jan 29, 2021 12:30 pm

If you want exactly two bytes, for the integer I'd use

Code: Select all

self.spi.write(int.to_bytes(payload, 2, 'little'))
The 'little' or 'big' arg determines the order in which the bytes are transmitted.
Peter Hinch
Index to my micropython libraries.

Post Reply