Python Forum
UART write binary code - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: UART write binary code (/thread-42045.html)



UART write binary code - trix - Apr-28-2024

hello,

I am trying to send out a binary code with the UART.
with a hexadecimal code it works:
command = b'\x80'
scanner_uart.write(command)
but how can I send out a binary code?
e.g. 00001111
thank you.


RE: UART write binary code - Larz60+ - Apr-28-2024

b'\x80' is just a representation of hexadecimal code and is equivalent to 01000000 binary
so 00001111 would be b'\x0f'

Please show enough code so that condition can be recreated.
Please post all errors


RE: UART write binary code - Gribouillis - Apr-28-2024

You could try this (perhaps not the most efficient)
>>> bytes([int('00001111', 2)])
b'\x0f'
>>> int('00001111', 2).to_bytes(1, 'little')
b'\x0f'



RE: UART write binary code - deanhystad - Apr-28-2024

What do you mean by "send binary code"? Do you want to send a binary string (bytes 30 and 31)? That would be b'00001111' or bytes((30, 30, 30, 30, 31, 31, 31, 31)).

Do you want to send 15? That would be bytes((15)) or b'\08'. There is no escape sequence for binary digits like there is for hexadecimal digits.

Do you have a binary string that you want to convert to bytes? Gribouillis covers that in his post. I would not do this for literals in the program, but if you have entered strings that need to be converted, it will do the trick.