0

I need to send binary data via serial port with Python 3.

Example:

command = b'\x02\xF6\x44\x46\x31\x03\x3B\x36'

ser.write(command)

This works.

My problem is that my sequence of bytes is not constant, but need to be built dynamically depending on user inputs and data extracted from a file.

In Python 2 I was used to do:

command_data = [2, 246, 68, 70, 49, 3, 59, 54] #these numbers can be integer variables in my software

command = ""

for i in range (0, len(command_data)):
    command=command + chr(command_data[i]) #converts a sequence of integers in a string
ser.write(command)

Now Python 3 requires a sequence of bytes instead of a string.

I tried:

ser.write(bytes(command, 'utf-8'))

but the actual sequence of bytes transmitted is:

\x02\xc3\xb6\x44\x46\x31\x03\x3b\x36

The integer 246, that is \xf6, is transmitted as the sequence \xc3\xb6

How can I obtain a correct transmission?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Romano
  • 1
  • That is the correct encoding for 0xf6 in utf-8. Which begs the question what you'd consider "correct". – Hans Passant Jun 22 '23 at 10:35
  • Isn't it unnecessary to specify encoding? [How to make a bytes object from a list of integers in Python 3](https://stackoverflow.com/q/30658193/9014308) – kunif Jun 22 '23 at 15:01

0 Answers0