1

I'm communicating over a serial port, and currently using python2 code which I want to convert to python3. I want to make sure the bytes I send over the wire are the same, but I'm having trouble verifying that that's the case.

In the original code the commands are sent like this:

serial.Serial().write("\xaa\xb4" + chr(2))

If I print "\xaa\xb4" in python2 I get this: ��.
If I print("\xaa\xb4") in python3 I get this: ª´

Encoding and decoding seem opposite too:

Python2: print "\xaa".decode('latin-1') -> ª
Python3: print("\xaa".encode('latin-1')) -> b'\xaa'

To be crude, what do I need to send in serial.write() in python3 to make sure exactly the same sequence of 1s and 0s are sent down the wire?

1 Answer 1

1

Use a bytes sequence.

ser.write(b'\xaa\xb4')
Sign up to request clarification or add additional context in comments.

3 Comments

But if I construct the command like this: a = '\xaa', how would I pass that to write()? print(bytes(a, 'utf8')) -> b'\xc2\xaa'
Normally you wouldn't; you'd use bytes in the first place. If for some reason you have text and you need to convert the first 256 characters to bytes then you can use the latin-1 codec.
Yea thanks. Constructing with b'\xaa' and so on has made everything easier. I've realised my problem is with chr() and ord().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.