Velocity Reviews > Re: How can i send 8-bit data or binary data with pyserial?

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

Fredrik Lundh
Guest
Posts: n/a

 12-14-2004
"ouz as" <(E-Mail Removed)> 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

that's nine bits...

> pyserial sent only string data.

in computers, bits are combined into bytes (or longer machine words).
the strings you pass to pyserial are treated as byte sequences.

this might help you figure out how to convert between bit patterns and
byte values:

http://www.math.grin.edu/~rebelsky/C...nt-binary.html

> Can i send this binary data with pyserial or another way with python.

convert the bitpattern to a byte, and send it to pyserial.

01000000 = 0x40 (hex) = 64 (dec)

so

ser.write(chr(64))

or

ser.write(chr(0x40))

or even

ser.write("\x40")

to go from a byte to a bitpattern, use ord(byte):

ord(chr(0x40)) = 0x40

hardware-oriented code often represent bitpatterns as hex constants. by
using constants, it's easy to combine different bits:

FLAG1 = 0x40
FLAG2 = 0x20

ser.write(chr(FLAG1)) # set first flag
ser.write(chr(FLAG1|FLAG2)) # set both flags

flags = getstatus()
ser.write(flags ^ FLAG2) # toggle flag 2

etc.

</F>

Scott David Daniels
Guest
Posts: n/a

 12-15-2004
Fredrik Lundh wrote:
> "ouz as" <(E-Mail Removed)> 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

>
> ... in computers, bits are combined into bytes (or longer machine words).
> the strings you pass to pyserial are treated as byte sequences....

Just one other bit (byte?) of data that wasn't mentioned here:
the array module also provides handy conversions.

array.array('B', [1,2,3,4]).tostring() == '\1\2\3\4'

This may prove useful as you create message packets.

-Scott David Daniels
http://www.velocityreviews.com/forums/(E-Mail Removed)