将整数转换为字节(对于 PySerial,使用 Python25)
这看起来应该很简单,但我一直无法弄清楚...
我正在尝试使用 PySerial 与微控制器通信。我想发送一个索引位置,但是当我发送它时,PySerial 会发送该数字的 ASCII(所以当我发送 0 时,它会发送 48)。
我知道对于 Python26 及更高版本,我只需用内置的 bytes 函数将数字括起来,如下所示:
self.index = bytes([index])
但是,Python25 没有该函数。我找不到任何建议等效的文档。有人知道我应该做什么吗?
提前致谢!
编辑:抱歉,这是我的代码的简化版本...
class SecondaryImage():
def __init__(self, index):
self.index = index
def sendIndex(self):
serial.write(self.index)
for i in range(64):
img = SecondaryImage(i)
imgs.append(img)
然后我会单独调用 sendIndex() -
imgs[2].sendIndex()
This seems like it should be simple, but I haven't been able to figure it out...
I'm trying to use PySerial to communicate with a microcontroller. I want to send an index location, but when I send it, it PySerial sends the ASCII of the number (so when I send a 0, it sends 48).
I know for Python26 and up, I would just enclose the number with the built-in bytes function like so:
self.index = bytes([index])
However, Python25 doesn't have that function. I can't find any documentation suggesting an equivalent. Does anybody know what I should do?
Thanks in advance!
EDIT: Sorry, here's a simplified version of my code...
class SecondaryImage():
def __init__(self, index):
self.index = index
def sendIndex(self):
serial.write(self.index)
for i in range(64):
img = SecondaryImage(i)
imgs.append(img)
And then I'd call sendIndex() seperately--
imgs[2].sendIndex()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
chr
是内置的,它将作为您发送的序数的字符。chr
is built-in which will you the character for the ordinal you send.串行以 ascii 进行通信,因此您需要使用
chr
将数字转换为其等效的 ascii 字符。Serial communicates in ascii, so you want to use
chr
to convert numbers to their ascii character equivalents.您尝试过 binascii 模块吗?
http://docs.python.org/release/2.5.4 /lib/module-binascii.html
Have you tried the binascii module?
http://docs.python.org/release/2.5.4/lib/module-binascii.html