views:

16

answers:

1

Hi

I'm having some problems making Python talk to a hardware display using pyserial. Some of the display's functions require 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 wierd 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?

+1  A: 

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

S.Lott
Did you read the doc? `pack('>HH', freq, millisecs )` is what you should have done.
S.Lott
pack('>H',freq) + pack('>H',millsecs)...did the job in a similar function!Thanks! :)
Kanonskall
great tips Lott! thanks again! I was a little quick reading it i must admit :)
Kanonskall
@Kanonskall: `pack('>H',freq) + pack('>H',millsecs)` may appear to work, but it's wrong in a serious way. The BigEndian LittleEndian part is wrong when you do this concatenation business.
S.Lott