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

Fredrik Lundh fredrik at pythonware.com
Tue Dec 14 12:13:15 CET 2004


"ouz as" <oguz_aylanc at hotmail.com> 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/Courses/152/97F/Readings/student-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> 






More information about the Python-list mailing list