how to get the integer value of a single pyserial byte in python

Madivad picture Madivad · Aug 20, 2013 · Viewed 17.1k times · Source

I'm using pyserial in python 2.7.5 which according to the docs:

read(size=1) Parameters: size – Number of bytes to read. Returns:
Bytes read from the port. Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.

Changed in version 2.5: Returns an instance of bytes when available (Python 2.6 and newer) and str otherwise.

Mostly I want to use the values as hex values and so when I use them I use the following code:

ch = ser.read()
print ch.encode('hex')

This works no problem.

But now I'm trying to read just ONE value as an integer, because it's read in as a string from serial.read, I'm encountering error after error as I try to get an integer value.

For example:

print ch

prints nothing because it's an invisible character (in this case chr(0x02)).

print int(ch)

raises an error

ValueError: invalid literal for int() with base 10: '\x02'

trying print int(ch,16), ch.decode(), ch.encode('dec'), ord(ch), unichr(ch) all give errors (or nothing).

In fact, the only way I have got it to work is converting it to hex, and then back to an integer:

print int(ch.encode('hex'),16)

this returns the expected 2, but I know I am doing it the wrong way. How do I convert a a chr(0x02) value to a 2 more simply?

Believe me, I have searched and am finding ways to do this in python 3, and work-arounds using imported modules. Is there a native way to do this without resorting to importing something to get one value?

edit: I have tried ord(ch) but it is returning 90 and I KNOW the value is 2, 1) because that's what I'm expecting, and 2) because when I get an error, it tells me (as above)

Here is the code I am using that generates 90

count = ser.read(1)
print "count:",ord(ch)

the output is count: 90

and as soon as I cut and pasted that code above I saw the error count != ch!!!!

Thanks

Answer

Mario Rossi picture Mario Rossi · Aug 20, 2013

Use the ord function. What you have in your input is a chr(2) (which, as a constant, can also be expressed as '\x02').

i= ord( chr(2) )
i= ord( '\x02' )

would both store the integer 2 in variable i.