[solved] spi.write() buffer protocol required

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
User avatar
mcauser
Posts: 507
Joined: Mon Jun 15, 2015 8:03 am

[solved] spi.write() buffer protocol required

Post by mcauser » Mon Dec 19, 2016 1:42 pm

I'm rewriting /drivers/nrf24l01/nrf24l01.py to work with the new ESP8266 machine/SPI syntax.

I've hit a snag with spi.write() and buffer protocols.

In some cases the data to spi.write() is an int, a const() or bytes.
So I can't just wrap all values with bytearray([...]), otherwise it throws a TypeError (see below) on bytes.
Is there a way to check if the variable is compatible with spi.write() directly, or needs to be wrapped in a bytearray()?

Code: Select all

>>> buf = 10
>>> spi.write(bytearray([buf]))
works

>>> SOME_CONST = const(0x04)
>>> spi.write(bytearray([SOME_CONST]))
works

>>> buf = b'\x05'
>>> spi.write(bytearray([buf]))
TypeError: can't convert bytes to int

>>> buf = b'\x05'
>>> spi.write(bytearray(buf))
works, without the []

>>> buf = 10
>>> spi.write(bytearray(buf))
works, but sends a 10 byte empty bytearray, not what I want
I tried isinstance():

Code: Select all

>>> buf = bytearray([10])
>>> isinstance(buf, bytearray)
True

>>> buf = b'\x05'
>>> isinstance(buf, bytearray)
False
>>> isinstance(buf, bytes)
True
Seems I should check if the value is bytes and use that to determine whether I should wrap the value with bytearray(...) or bytearray([...]).
Does that sound like the right thing to do?
Last edited by mcauser on Mon Dec 19, 2016 2:30 pm, edited 1 time in total.

User avatar
mcauser
Posts: 507
Joined: Mon Jun 15, 2015 8:03 am

Re: spi.write() buffer protocol required

Post by mcauser » Mon Dec 19, 2016 2:29 pm

It works!
https://github.com/micropython/micropython/pull/2703

Code: Select all

if isinstance(buf, bytes):
    self.spi.write(bytearray(buf))
else:
    self.spi.write(bytearray([buf]))

Post Reply