How can i send 8-bit data or binary data with pyserial?

Craig Ringer craig at postnewspapers.com.au
Tue Dec 14 06:10:04 EST 2004


On Tue, 2004-12-14 at 18:31, ouz as wrote:
> i have an electronic module which only understand binary data.
> i use  python pyserial.
> for example the module starts when 001000000 8-bit binary data sent.but 
> pyserial sent only string data.
> Can i send this binary data with pyserial or another way with python.

Strings can be considered binary data, where each character represents
eight bits. Simply build the binary data however you're most comfortable
(a list of bytes; a list of bits; a string representation of a binary
numer, an 8-bit string used as a buffer; whatever) then compose into a
string and send.

>>> bits = '0101101110111101'
>>> bytes = [ mybits[i*8:(i+1)*8] for i in range(len(mybits)/8) ]
>>> bytechars = [ chr(int(x,2)) for x in bytes ]
>>> bytestr = ''.join(bytechars)
>>> bytestr
'[\xbd'

Obviously, you could tidy up that conversion a little. This being
Python, I wouldn't be surprised if there was a built-in function to do
the conversion ;-) .

You can choose to represent your binary data in many ways:

>>> bits = '0101101110111101'
>>> truthlist = [ int(x) and True or False for x in mybits ]
>>> truthlist
[False, True, False, True, True, False, True, True, True, False, True,
True, True, True, False, True]
>>> hexstring = "0x%x" % int(mybits,2)
>>> hexstring
'0x5bbd'
>>> hexstring2 = "\x5b\xbd"
>>> hexstring2
'[\xbd'

and you can convert them all to strings. Just remember that you can work
with a string as a buffer of 8-bit blocks and you'll be fine. In your
specific example:

>>> byte = '001000000'
>>> byte_chr = chr(int(byte,2))
>>> byte_chr
'@'

--
Craig Ringer




More information about the Python-list mailing list