Search code examples
pythonxbee

How to send and receive a decimal array through serial port?


I'm trying to send an array [0, 100, 150, 175, 255] through serial in python. I convert it to bytearray then send it.

The data I'm receiving looks like

['\x00', 'd', '\x96', '\xaf', '\xff'] and I can't go back to [0, 100, 150, 175, 255].

Is there a better way to send and receive this kind of data? I'm new to python and I'm unfamiliar with some methods.

These are the codes I'm using.

SEND

import serial
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=10)
elements= [0,100,150,175,255]
data2=bytearray(elements)

while True:
      ser.write(data2)

RECEIVE

import serial
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=10)
vect = []

while True:
      vect.extend(ser.read())

Thank you.


Solution

  • Of course you can go back to [0, 100, 150, 175, 255]! You're sending the data from a bytearray, and you should also use a bytearray to receive the data. To convert the received bytes back to integers, you just need to pass the bytearray to list().

    Here's a demo:

    elements = [0, 100, 150, 175, 255]
    
    # Buffer for sending data
    data2 = bytearray(elements)
    
    # Buffer for reading data
    rdata = bytearray()
    
    # Simulate sending data over the serial port
    rdata.extend(data2[0:2])
    rdata.extend(data2[2:5])
    
    vect = list(rdata)
    print(vect)
    

    output

    [0, 100, 150, 175, 255]
    

    This code works correctly on both Python 2 and Python 3.