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

Discussion in 'Python' started by Fredrik Lundh, Dec 14, 2004.

  1. "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


    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>
     
    Fredrik Lundh, Dec 14, 2004
    #1
    1. Advertising

  2. Fredrik Lundh wrote:
    > "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

    >
    > ... 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
     
    Scott David Daniels, Dec 15, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Fangs
    Replies:
    3
    Views:
    9,937
    darshana
    Oct 26, 2008
  2. alastair

    pyserial with binary data

    alastair, Nov 26, 2004, in forum: Python
    Replies:
    3
    Views:
    1,497
    Grant Edwards
    Nov 30, 2004
  3. ouz as
    Replies:
    3
    Views:
    694
    Diez B. Roggisch
    Dec 13, 2004
  4. ouz as
    Replies:
    1
    Views:
    961
    Diez B. Roggisch
    Dec 14, 2004
  5. Replies:
    12
    Views:
    607
    Richard Heathfield
    Apr 8, 2007
Loading...

Share This Page