9

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?

salocinx
  • 3,715
  • 8
  • 61
  • 110
  • Possible duplicate of [What is the difference between Python's list methods append and extend?](https://stackoverflow.com/questions/252703/what-is-the-difference-between-pythons-list-methods-append-and-extend) –  May 01 '19 at 18:14
  • 3
    `is` is the wrong operator in `if current_bytes is B'$'`. You need `==`. You might get away with it for now due to object reuse implementation details, but it's wrong and it will blow up in your face when you make some seemingly-inconsequential change, if it's not going wrong already. – user2357112 May 01 '19 at 18:19
  • @user2357112 Thanks for the additional hint, will change that as well. – salocinx May 01 '19 at 18:42

2 Answers2

18
packet_bytes += bytearray(current_bytes)
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
3

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
Biyau
  • 121
  • 1
  • 12