0

I am trying to send and receive hex commands to and from a device.

The device sends the following hex data: \x02x82x36xFFxFFx01xB5x03

I am using the follow simple code:

import serial

port = serial.Serial('COM1', baudrate=19200, timeout=3.0)

while True:
        rcv = port.readline()
        print (rcv)

The output of rcv is The following python code displays the output as \x028236????01;5\x03'

Help. I am new to python and I am sure i am making a simple mistake but its driving me crazy.

Thanks

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
Jeremy
  • 111
  • 1
  • 5
  • 11
  • Some one mentioned i should look at http://stackoverflow.com/questions/12214801/print-a-string-as-hex-bytes how ever i cannot see how to get this to work with my received data. Please can some one explain further? HELP ! – Jeremy Mar 02 '15 at 17:17

1 Answers1

0

The output you are getting is the printable representation of the bytes received. Each byte is encoding an (extended) ASCII character (printable or not). Printable ones are printed as they are (in your case they are 8236, 01;5). And the others are printed as hex code \x02, \x03 (which are codes 02 and 03 respectively) and so on. If you open some ASCII table you will see that the character 2 is represented as 0x82, and the same about rest of the codes you are getting.

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
  • Thank you. How would I convert the data received back to the data that was sent . I.E data sent is \x02x82x36xFFxFFx01xB5x03 I want print this data? – Jeremy Mar 02 '15 at 17:06
  • See this discussion: http://stackoverflow.com/questions/12214801/print-a-string-as-hex-bytes – Eugene Sh. Mar 02 '15 at 17:07
  • Thanks Eugene. I am struggling to get the solution to work with my received data (rcv) can you explain further? – Jeremy Mar 02 '15 at 17:20
  • rcv = port.readline() 'x'.join(x.encode('hex') for x in rcv) print (rcv) ?? – Jeremy Mar 02 '15 at 17:24