Search code examples
pythonserial-porthexpyserialpython-2to3

pyserial Python2/3 string headache


I'm using pyserial to communicate with some sensors which use the Modbus protocol. In Python 2.7, this works perfectly:

import serial

c = serial.Serial('port/address')  # connect to sensor
msg = "\xFE\x44\x00\x08\x02\x9F\x25"  # 7 hex bytes(?)
c.write(msg)  # send signal
r = c.read(7)  # read 7 hex bytes (?).

In Python 3, this does not work. I know it's something to do with differences in how Python 2/3 handle binary vs. unicode strings. I've found numerous other threads suggesting the solution should be to simply prepend a b on my message (msg=b""\xFE\x44\x00\x08\x02\x9F\x25") to specify it as a binary string but this does not work for my case.

Any insights? What should I be sending in Python 3 so the sensor recieves the same signal? I'm at my wit's end...

I should add that I'm totally new to serial connections (well... 1 week old), and (despite reading around quite a bit) I struggle with understanding different character/string formats... Hence question marks in comments above. Please pitch answers appropriately :).

Thanks in advance!


Solution

  • Solution

    It turned out that specifying the input as a byte string (msg=b""\xFE\x44\x00\x08\x02\x9F\x25") did work. Initial error was from a typo in the msg string...

    Secondary errors arose from how the outputs were handled - in Python 2 ord() had to be applied to the indexed output to return integers, in Python 3 integers can be extracted directly from the output by indexing (i.e. no ord() necessary).

    Hope this might help someone in the future...