[Tutor] Need help with serial input
alan.gauld at freenet.co.uk
Thu Aug 18 23:47:47 CEST 2005
> i am using the serial module and trying to get some info over an
> RS232 port. Seems to be comming in ok, but when i print it out, its
> in ASCII instead of hex.
Thats because print interprets sequences of bytes as ASCII codes.
The bytes you read from serial are just binary numbers but if you
give them to print it assumes they form a string of ascii codes.
If you want to print the hex representation of those bytes
(the bytes are just a sequence of bits which can be represented
in octal, decimal or hex, the data is the same!) you need to
tell Python that it's numbers you're using.
One way of doing that is to use the ord() function:
result = 
for b in octets:
bytes = ''.join([chr(65),chr(67),chr(69)])
print bytes # data is 65,67,69 but treated as ascii
bytes = getBytes(bytes)
print bytes # data is list of 65, 67, 69
for b in bytes:
print "0x%X" % b # represent number as hex
You can use the struct module too, but it's a wee bit more complicated
to use. An explanation of handling binary data can be found in the
'sidebar' in my File Handling tutorial topic
Author of the Learn to Program web tutor
More information about the Tutor