Micropython I2C: i2c.writeto_mem(), in my code i get an error

heres my code:


from machine import I2C
import time

print(" +-------------------------------------+")
print(" | XBee MicroPython I2C Scanner Sample |")
print(" +-------------------------------------+
")

# Instantiate an I2C peripheral.
i2c = I2C(1)

# Scan for I2C slaves connected to the interface and print their address.
for address in i2c.scan():
    print("- I2C device found at address: %s" % hex(address))
DEVICE = 0x20  # Device address (A0-A2)
IODIRA = 0x00  # Pin direction register
OLATA = 0x14  # Register for outputs
GPIOA = 0x12  # Register for inputs

# Set all GPA pins as outputs by setting
# all bits of IODIRA register to 0
i2c.writeto_mem(DEVICE, IODIRA, 0x00)

# Set output all 7 output bits to 0
i2c.writeto_mem(DEVICE, OLATA, 0)

for MyData in range(1, 8):
    # Count from 1 to 8 which in binary will count
    # from 001 to 111
    i2c.writeto_mem(DEVICE, OLATA, MyData)
    print(MyData)
    time.sleep(1)

# Set all bits to zero
i2c.writeto_mem(DEVICE, OLATA, 0)

The 3rd parameter in i2c.writeto_mem() tells me it should be a bytearray instead of a byte. what would a byte array look like? How would I pass in a bytearray that just contained sending a bit of value 1.

thanks

I would suggest reading over http://cms.digi.com/resources/documentation/digidocs/90002219/#reference/r_class_i2c.htm?Highlight=I2C

ok well now I have the right type of object passed through… the bytearray.

I have been using bytearray(b’\x00’) and so forth. I dont quite understand the bytearray here. Is that one byte or one bit in the parenthesis. and if its a byte then how do I access its bits?

If you’re getting that error on all writeto_mem() calls, you can do the following to create a valid object. It should work with either a “bytearray” or “bytes” object.


# build a 1-byte bytearray...
buffer = bytearray(1)

# ...and set the byte
buffer[0] = 0x00

# create a bytes object of specific bytes
buffer = bytes([0x00, 0xAA, 0x11])

# convert an integer
buffer = chr(0xAA)

For setting bits, try this instead:


for bit in range(0, 8):
    # Set single bit of MyData
    MyData = chr(1 << bit)
    # or MyData = bytes([1 << bit])
    i2c.writeto_mem(DEVICE, OLATA, MyData)
    print(MyData)
    time.sleep(1)

This should set bit 0, then bit 1, bit 2, etc.

1 Like

b’\x00’ is a 1-byte array with a value of 0x00. If “x = b’\x00’”, you’d need to reference x[0] to get at that first byte, and then “x & 0x01” to check bit 0, “x & 0x80” to check bit 7, etc.