2

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.

Sam Chats
  • 2,271
  • 1
  • 12
  • 34
Alan
  • 31
  • 1
  • 4

3 Answers3

0

It can be tempting to use eval() here:

while True:
      vect = eval(ser.read().decode('unicode_escape'))

However, don't use it. It's generally bad to use eval(). I think @PM2Ring's answer is better.

Sam Chats
  • 2,271
  • 1
  • 12
  • 34
  • @PM2Ring What's the problem with that? – Sam Chats Jul 15 '17 at 07:50
  • 1
    `eval` should only be used when you have no other option. Not only is `eval` slow, `eval` and `exec` should generally be avoided because they can be a security risk. Passing arbitrary unsanitised data to `eval` is _extremely_ unsafe. For details, please see [Eval really is dangerous](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) by SO veteran Ned Batchelder. – PM 2Ring Jul 15 '17 at 10:44
  • @PM2Ring Thanks. I'll check out that link. Should I delete this answer then? – Sam Chats Jul 15 '17 at 11:06
  • 1
    Well, that's up to you, but it probably would be a good idea to delete it. OTOH, you can leave it here as a warning, showing how _not_ to do it. ;) – PM 2Ring Jul 15 '17 at 11:28
0

Try to convert the char you receive to int:

vect.extend([ord(ch) for ch in ser.read()])
Depicture
  • 66
  • 3
0

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.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182