[Tutor] Help with building bytearray arrays

Chip Wachob wachobc at gmail.com
Fri Sep 7 15:45:50 EDT 2018


Hello,

I've been struggling with this for the last day or so and I can't seem
to figure out how to make it work.

I'll start out by saying that if there's a better approach, then I'm all ears.

I'm using the Adafruit Breakout board for the FTDI FT232H part.  Along
with this comes the Python libraries and Adafruit libraries which I'm
using.  I don't think that the libraries are the real issue here, but
I thought I should mention it just for the sake of information.

Basically I'm trying to write a block of unsigned bytes to the device
and read back an equal sized block of unsigned bytes.  There's a
function that is provided called transfer(data_to_send, num_of_bytes)
that handles the heavy lifting.  Unfortunately there seems to be a bug
in the part and if I attempt to send the entire block of bytes (64),
the device will lock up.  I've been able to determine that if I send
16 bytes at a time, I'm okay.

So, I take my bytearray(64) and step through it 16 bytes at a time like this:

my function's main pieces are:

def transfer_byte_array():
   MAX_LOOP_COUNT = 64
   slice_size = 16
   read_ary = bytearray(MAX_LOOP_COUNT)
   scratch_ary = bytearray()

   for step in range (0, MAX_LOOP_COUNT, slice_size):
      scratch_ary = transfer(data_to_send, slice_size)

      for bytes in range (0, slice_size):
         read_ary = scratch_ary[bytes]

   return(read_ary)


Ideally, I'd like to take the slice_size chunks that have been read
and concatenate them back togetjer into a long MAX_LOOP_COUNT size
array to pass back to the rest of my code.  Eg:

read_ary = ary_slice[0] + ary_slice[1] + ary_slice[2] + ary_slice[3]

I know that the + version doesn't work (or didn't for me) but it is
just my attempt at illustrating the overall goal.

The problem that I repeatedly run into is with the line:

read_ary = scratch_ary[bytes]  (or variants thereof)

The traceback is this:

Traceback (most recent call last):
  File "SW8T_5.py", line 101, in <module>
    loop_size = RSI_size_the_loop(Print)
  File "/home/temp/Python_Scratch/examples/RSI.py", line 350, in
RSI_size_the_loop
    read_ary.append(scratch_ary[singles])
TypeError: an integer or string of size 1 is required

or, one of the other common ones that I've seen is

TypeError: can't concat bytearray to list

This one is confusing because both of the operands are bytearry
types.. or at least I thought they should be...

when I try to replace the same line with :

read_ary += scratch_ary[bytes]

or

read_ary.append(scratch[bytes])

or

read_ary = read_ary + scratch_ary[bytes]


I'm obviously missing something fundamental here.  Problem is I can't
seem to find any examples of people asking this question before on the
inter-webs..

Thank you in advance to taking time to read.


More information about the Tutor mailing list