user6249135
user6249135

Reputation:

Python pyserial variable

I am sending one byte ("\x2b") to a device and will be receiving 1 echo byte plus 3 bytes of data("\x2b\x??\x??\x??").I am using .replace("2b","",4) to get rid of the echo byte.I need to change the 3 bytes of hex received to int(16) and name them 3 different variables that I can call separately one at a time in a calculation. Here is what I have so far.

    import serial
    import os

    ser = serial.Serial(port="COM17", baudrate=9600)
    ser.open()
    ser.write("\x2b")
    print int(ser.readline(4).encode("hex").replace("2b", "", 4), 16)
    ser.close()

    os.system("pause")

Upvotes: 0

Views: 656

Answers (2)

umläute
umläute

Reputation: 31294

There is no "natural" conversion to convert a stream of 3 bytes into 3(?) int16 (aka short) numbers.

So you have to be more specific:

  • do you want to convert the bytes to int8 instead? it is of course entirely valid to regard the resulting numbers as int16 (as they will fit in)
  • do you want signed/unsigned output?
  • if you indeed have multibyte numbers (e.g. int16), are you using BIG_ENDIAN or LITTLE_ENDIAN?

in any case, the struct package can do the conversion for you:

import struct

# read 4 bytes, discard the first one, so we get a list of 3 bytes
inputdata = ser.readline(4)[1:]

# the following parses 'inputdata' as 3 `uint8` numbers
a,b,c = struct.unpack('BBB', inputdata)

Upvotes: 0

jsbueno
jsbueno

Reputation: 110440

Use the struct module to retrieve arbitrary binary data from Byte strings:

import serial
import os
import struct

ser = serial.Serial(port="COM17", baudrate=9600)
ser.open()
ser.write("\x2b")
response = ser.readline(4)
echo, a, b, c = struct.unpack("4B", response)
print ("Response numbers: {:02x}, {:02x}, {:02x}".format(a, b, c))
ser.close()

On a side note: avoid using os.system("pause") as part of the program. That is a terrible habit of some so that the Windows DOS prompt stays open when the program is done running, but it is (1) WIndows only, for a program that otherwise would work on Mac OS X and Linux, and (2) involves creating an entire other process for an ordinary operation.

You can add a simple input call in Python, asking the user to press <enter> instead:

(last line):

 input("Press <enter> to close terminal")

Upvotes: 1

Related Questions