How can i convert Integer to Signed Word in Python (for use with PySerial)?
I'm having some problems making Python talk to a hardware display using pyserial. Some of the display's functions require a signed word to be sent as arguments after commands (ie.开发者_运维知识库 X or Y on display screen).
I've been getting by with chr() previously, but that only works with numbers < 255.
I've tried the following for conversion but it's giving some weird results, placing things way off the set position:
def ByteIt(self,data):
datastring = str()
for each in tuple(str(data)):
datastring = datastring + chr(int(each))
return datastring
I may be way off myself here :)
Example of how i would use it:
x = 100
y = 350
serial.Write('\x01' + ByteIt(x) + ByteIt(y)) # command , xpos , ypos
The thing is, when i do this, the stuff is not placed at x100,y350, most times the display will crash :(
Any tips on how this can be done properly?
Read about the struct
module.
http://docs.python.org/library/struct.html
Replace all of the "chr" and stuff with proper struct.pack()
calls.
Specifically
bytes = struct.pack( 'h', some_data )
Should give you a "signed word".
You may want to revise again the documentation about "pack" and "unpack". Selecting the appropriate upper-case or lower-case allows you to specify the Endianness. So, based on the example above which didn't work perfectly on your device, I presume you need:
x = 100
y = 350
serial.Write('\x01' +
struct.pack('>hh', x) +
struct.pack('>hh', y)) # command , xpos , ypos
精彩评论