简体   繁体   English

如何在Python中将Integer转换为Signed Word(用于PySerial)?

[英]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. 我在使Python与使用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). 某些显示器的功能要求在命令后将带符号的单词作为自变量发送(即,显示屏上的X或Y)。

I've been getting by with chr() previously, but that only works with numbers < 255. 我以前一直在使用chr(),但这仅适用于<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 :( 问题是,当我这样做时,这些东西并未放置在x100,y350上,大多数时候显示器会崩溃:(

Any tips on how this can be done properly? 有关如何正确完成此操作的任何提示?

Read about the struct module. 阅读有关struct模块的信息。

http://docs.python.org/library/struct.html http://docs.python.org/library/struct.html

Replace all of the "chr" and stuff with proper struct.pack() calls. 用适当的struct.pack()调用替换所有的“ chr”和东西。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM