python - 你如何用python中的字节计算
问题描述
我对python很陌生,主要依赖于我对c++的了解。但是因为树莓派,我进入了 python。我给自己买了一些智能伺服系统(LX-224),但从 RPI 读取角度时遇到问题。我知道这是可能的,但 python 不断抛出一些错误。基本上,RPI 向舵机发送命令,舵机返回 8 个字节的信息。我只需要两个字节,然后我应该用它们来进行“计算”。代码的所有注释都是中文的,所以我只知道谷歌翻译告诉我的。这是代码:
#!/usr/bin/python3
import serial
import time
serialHandle = serial.Serial("/dev/serial0", 115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1)
command = {"MOVE_WRITE":1, "POS_READ":28, "LOAD_UNLOAD_WRITE": 31}
def servoWriteCmd(id, cmd, par1 = None, par2 = None):
buf = bytearray(b'\x55\x55')
try:
len = 3
buf1 = bytearray(b'')
if par1 is not None:
len += 2
par1 = 0xffff & par1
buf1.extend([(0xff & par1), (0xff & (par1 >> 8))])
if par2 is not None:
len += 2
par2 = 0xffff & par2
buf1.extend([(0xff & par2), (0xff & (par2 >> 8))])
buf.extend([(0xff & id), (0xff & len), (0xff & cmd)])
buf.extend(buf1)
sum = 0x00
for b in buf:
sum += b
sum = sum - 0x55 - 0x55
sum = ~sum
buf.append(0xff & sum)
serialHandle.write(buf)
except Exception as e:
print(e)
def readPosition(id):
serialHandle.flushInput()#supposed to flush the buffer
servoWriteCmd(id, command["POS_READ"])#send the read command to the servo
time.sleep(0.005)#give some time to the servo to reply
count = serialHandle.inWaiting()#how many bytes are waiting for me to read
pos = None
if count != 0:
recv_data = serialHandle.read(count)
if count == 8:
if recv_data[0] == b'\x55' and recv_data[1] == b'\x55' and recv_data[4] == b'\x1c' :
#these bytes tell some information about the command recieved I believe, but they come in all right, so this if statement could be ignored I think
pos= b'\xff\xff' & (recv_data[5] | (b'\xff\x00' & (recv_data[6] << 8)))
#this is the problem
return pos
servoWriteCmd(1, command["LOAD_UNLOAD_WRITE"],0)
while True:
try:
pos = readPosition(1)
print(pos)
time.sleep(1)
except Exception as e:
print(e)
break
Python不断告诉我:
<<: 'str' 和 'int' 不支持的操作数类型
所以我想它正在将字节 recv_data[5] 和 [6] 转换为字符串?如果这没有任何意义,我很抱歉,但我在 python 中找不到任何关于“字节计算”的信息。
如果有人有阅读智能伺服系统的经验,任何其他代码片段也很感激!
非常感谢,如果有不清楚的地方,我会尽力澄清。
解决方案
所以显然问题是我使用的是python 2.7.16而不是python 3.7.3。非常感谢@MisterMiyagi 指出这一点。我升级到python 3.7.3,舵机卖家的原始代码开始工作了。很抱歉这个初学者的错误。感谢所有花时间发表评论的人!
推荐阅读
- python - 同时数据库访问问题(Mysql,Sqlite?)
- javascript - 在自动完成搜索中添加链接 url
- python - 破解编码面试,第 6 版,1.7
- r - 如何从宽格式的数据中有效地在 R 中绘制大量图形?
- javascript - 我应该使用 CSS 还是 JS 让我的容器向右滑动 + 同时淡入?
- java - 使用 JNA 从 Java 调用 windows UWP API
- json - 我有一个凌乱的 JSON,我正在尝试使用 jq 进行清理
- android - Firebase 与 appcompat 不兼容
- revel - 在 dep 确保不起作用后去安装 revel cmd
- unity3d - 为什么材质纹理会应用于原生 Unity 游戏对象,而不是我导入的 Blender FBX?