Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add bytes to bytearray in Python 3.7?

I am new the Python 3.7 and I am trying to read bytes from a serial port using the following code. I am using pySerial module and the read() function returns bytes.

self.uart = serial.Serial()
self.uart.port = '/dev/tty/USB0'
self.uart.baudrate = 115200
self.uart.open()
# buffer for received bytes
packet_bytes = bytearray()
# read and process data from serial port
while True:
    # read single byte from serial port
    current_bytes = self._uart.read()
    if current_bytes is B'$':
        self.process_packet(packet_bytes)
        packet_bytes = bytearray()
    else:
        packet_bytes.append(current_bytes)        <- Error occurs here

I receive the following error:

TypeError: an integer is required

Some idea how to solve?

like image 434
salocinx Avatar asked May 01 '19 18:05

salocinx


People also ask

How do you append byte?

To concatenate multiple byte arrays, you can use the Bytes. concat() method, which can take any number of arrays.

How do you concatenate bytes in Python 3?

The easiest way to do what you want is a + a[:1] . You could also do a + bytes([a[0]]) . There is no shortcut for creating a single-element bytes object; you have to either use a slice or make a length-one sequence of that byte.

How do you input byte in Python?

We can use the built-in Bytes class in Python to convert a string to bytes: simply pass the string as the first input of the constructor of the Bytes class and then pass the encoding as the second argument. Printing the object shows a user-friendly textual representation, but the data contained in it is​ in bytes.


2 Answers

packet_bytes += bytearray(current_bytes)
like image 139
Olvin Roght Avatar answered Oct 15 '22 03:10

Olvin Roght


I recently had this problem myself and this is what worked for me. Instead of instantiating a bytearray, I just initialized my buffer as a byte object:

buf = b""    #Initialize byte object

  poll = uselect.poll()
  poll.register(uart, uselect.POLLIN)

  while True:
    ch = uart.read(1) if poll.poll() else None

    if ch == b'x':
      buf += ch       #append the byte character to the buffer

    if ch == b'y':
      buf = buf[:-1]  #remove the last byte character from the buffer

    if ch == b'\015': ENTER
      break
like image 33
Biyau Avatar answered Oct 15 '22 02:10

Biyau