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

F

Fredrik Lundh

ouz as said:
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>
 
S

Scott David Daniels

Fredrik said:
... 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
(e-mail address removed)
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top