I have been trying to figure out how to send a bitstring through python 3 using the serial module. Initially when I tried to serial.write it, it was sending the ascii code for 1 and 0. I'm new to python and didn't find any of the answers to be of much help, despite researching for days now and trying to understand. I'm trying to send bitstrings through the serial port to an arduino, that will interpret them and display them on an LED matrix. Any help would be appreciated, thank you.
1 Answer
Serial only knows about the concept of ,bytes, so you need to convert from bits into bytes before sending.
If you have a bitstring such as "01000001" as a python string, you first need to convert it into an int. You can do this using the int() constructor, specifying base 2:
as_int = int("01000001", 2) # = 65
Then you can put it into an ASCII character to send:
as_character = chr(as_int) # = "A"
You can then send the character down the Serial connection.
If you have a bitstring that is more than a single byte, you will need to break it up into groups of 8 before converting it to an integer. Eg something like:
bitstring = "0101010001101000011010010111001100100000011010010111001100100000011000010010000001101101011001010111001101110011011000010110011101100101"
string_array = [bitstring[i:i+8] for i in range(0, len(bitstring), 8)]
byte_string = bytes([int(s, 2) for s in string_array])
In this case I've assembled it into a bytestring rather than a normal string because in python3, the pyserial module expects a bytestring.
Here's a version with fewer list comprehensions:
bitstring = "0101010001101000011010010111001100100000011010010111001100100000011000010010000001101101011001010111001101110011011000010110011101100101"
string_array = []
normal_string = ""
for offset in range(0, len(bitstring), 8):
string_array.append(bitstring[offset:offset+8])
for string in string_array:
value = int(string, 2)
normal_string += chr(value)
byte_string = normal_string.encode("ASCII")