0

I have written a python read script which has the following code`

def read_serial():
    while True:
        # prepare for response
        out = ''
        while ser.inWaiting() > 0:
            out += ser.read(1).decode('unicode_escape')

        if out != '':
            response_header = out.encode('unicode_escape').strip()
            print( "Response recieved " ,response_header)
            print((response_header[0],response_header[1],response_header[2])) //line 2

So the bytes array that I'm sending is:

data[] = {0x9c,0x10,0x01,0x05,0x07,0x08};

and on python side..in line 2 I'm receiving this:

Response recieved  b'\\\x9c\\\x10\\\x01\\\x05\\\x07\\\x08'
(92, 120, 57)

Why 92,120,57 what does this mean because for 9C decimal would be 156?

Any suggestions? Or which encoding technique you suggest for bytes?

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
psk
  • 11
  • 5
  • You are encoding as Unicode escapes, so (92,120,57) are the ASCII codes for backslash, `x` and 9. I assume you are doing that on the sending side also to need the decode. Skip encode/decode and just send bytes. – Mark Tolonen Dec 18 '20 at 07:39
  • When I do it without any encoding technique..For byte above 126 for example 0xab..I receive this error..UnicodeDecodeError: 'utf-8' codec can't decode byte 0xab in position 0: invalid start byte – psk Dec 18 '20 at 08:05
  • If sending data bytes, you don't need encoding at all. `send(bytes([0x9c,0x10,0x01,0x05,0x07,0x08]))`. Actually show your send and recv code if you want more help. – Mark Tolonen Dec 18 '20 at 08:07
  • @Mark I'm sending from arduino – psk Dec 18 '20 at 08:08
  • `out = b''` and `out += ser.read(1)` then. Just receive the byte. No decoding required. – Mark Tolonen Dec 18 '20 at 08:09

1 Answers1

0

Just receive the bytes. Something like this since I can't run your code:

def read_serial():
    while True:
        # prepare for response
        out = b''   # bytes type
        while ser.inWaiting() > 0:
            out += ser.read(1)

        if out != b'':
            print("Response received:",out.hex())
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251