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


i'm using pyserial in python 2.7.5 according docs:

read(size=1) parameters: size – number of bytes read. returns:
bytes read port. read size bytes serial port. if timeout set may return less characters requested. no timeout block until requested number of bytes read.

changed in version 2.5: returns instance of bytes when available (python 2.6 , newer) , str otherwise.

mostly want use values hex values , when use them use following code:

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

this works no problem.

but i'm trying read 1 value integer, because it's read in string serial.read, i'm encountering error after error try integer value.

for example:

print ch 

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

print int(ch) 

raises error

valueerror: invalid literal int() base 10: '\x02' 

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

in fact, way have got work converting hex, , integer:

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

this returns expected 2, know doing wrong way. how convert a chr(0x02) value 2 more simply?

believe me, have searched , finding ways in python 3, , work-arounds using imported modules. there native way without resorting importing 1 value?

edit: have tried ord(ch) returning 90 , know value 2, 1) because that's i'm expecting, , 2) because when error, tells me (as above)

here code using generates 90

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

the output count: 90

and cut , pasted code above saw error count != ch!!!!

thanks

use ord function. have in input chr(2) (which, constant, can expressed '\x02').

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

would both store integer 2 in variable i.


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -