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?