TypeError:&:“float”和“int”的操作数类型不受支持

2024-04-29 03:24:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python2.7中有一个节点。我正在使用此节点旋转电机。在我应用了计算每次旋转编码器脉冲数到每次旋转次数的公式,并应用到代码的其余部分后,我得到如下错误:

Traceback (most recent call last):   
  File "read_write.py", line 167, in <module>
    controller = DynamixelController()
  File "read_write.py", line 34, in __init__
    self.test_motor_client(1)                #here we can put request order as 1 for the using id=14 and position= 1500; or as 2 is id same and position is 2500. The cases could be found in the server.py node  
  File "read_write.py", line 51, in test_motor_client
    self.read_write(response.id, response.position)
  File "read_write.py", line 130, in read_write
    dxl_comm_result, dxl_error = packetHandler.write4ByteTxRx(portHandler, DXL_ID, ADDR_PRO_GOAL_POSITION, dxl_goal_position[index])
  File "/home/kist/catkin_ws/src/DynamixelSDK/ros/src/dynamixel_sdk/protocol2_packet_handler.py", line 671, in write4ByteTxRx
    data_write = [DXL_LOBYTE(DXL_LOWORD(data)),   
  File "/home/kist/catkin_ws/src/DynamixelSDK/ros/src/dynamixel_sdk/robotis_def.py", line 63, in DXL_LOWORD
    return l & 0xFFFF 
TypeError: unsupported operand type(s) for &: 'float' and 'int'

我正在尝试运行和测试的代码:

#!/usr/bin/env python

import os
import rospy
from std_msgs.msg import String
from controller_motor.msg import Motor
from controller_motor.srv import Motor2


if os.name == 'nt':
    import msvcrt
    def getch():
        return msvcrt.getch().decode()
else:
    import sys, tty, termios
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    def getch():
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

from dynamixel_sdk import *                    # Uses Dynamixel SDK library


class DynamixelController(object):
    def __init__(self):
        #print("1")

        self.motor_sub = rospy.Subscriber("/motor_topic", Motor, self.motor_callback)
        self.test_motor_client(1)                #here we can put request order as 1 for the using id=14 and position= 1500; or as 2 is id same and position is 2500. The cases could be found in the server.py node
    
    def motor_callback(self, data):
        _id = data.id
        _position = data.position

        print("_id : {0}, _position : {1}".format(_id, _position))
        self.read_write(_id, _position)

    def test_motor_client(self, request):
        #print("2")
        rospy.wait_for_service('test_motor_service')
        try:
            proxy = rospy.ServiceProxy('test_motor_service', Motor2)
            response = proxy(request)
            print("response is id : {} position : {}".format(response.id, response.position))

            self.read_write(response.id, response.position)

        except rospy.ServiceException as e:
            print("Service call failed: %s"%e)
    
    def read_write(self, _id, _position):
        print("Start the node")
        _degreeposition = (0.088 * (_position))  #Degree per pulse multiple _position
        print(_degreeposition)
        print(type(_degreeposition))

        # Control table address
        ADDR_PRO_TORQUE_ENABLE      = 64               # Control table address is different in Dynamixel model
        ADDR_PRO_GOAL_POSITION      = 116
        ADDR_PRO_PRESENT_POSITION   = 132
        #print(type(ADDR_PRO_GOAL_POSITION))
        # Protocol version
        PROTOCOL_VERSION            = 2.0               # See which protocol version is used in the Dynamixel

        # Default setting
        DXL_ID                      = _id                 # Dynamixel ID : 14
        BAUDRATE                    = 1000000             # Dynamixel default baudrate : 57600
        DEVICENAME                  = '/dev/ttyUSB0'    # Check which port is being used on your controller
                                                        # ex) Windows: "COM1"   Linux: "/dev/ttyUSB0" Mac: "/dev/tty.usbserial-*"

        TORQUE_ENABLE               = 1                 # Value for enabling the torque
        TORQUE_DISABLE              = 0                 # Value for disabling the torque
        DXL_MINIMUM_POSITION_VALUE  = 10.0           # Dynamixel will rotate between this value
        DXL_MAXIMUM_POSITION_VALUE  = _degreeposition            # and this value (note that the Dynamixel would not move when the position value is out of movable range. Check e-manual about the range of the Dynamixel you use.)
        DXL_MOVING_STATUS_THRESHOLD = 20                # Dynamixel moving status threshold

        index = 0
        dxl_goal_position = [DXL_MINIMUM_POSITION_VALUE, DXL_MAXIMUM_POSITION_VALUE]         # Goal position


        # Initialize PortHandler instance
        # Set the port path
        # Get methods and members of PortHandlerLinux or PortHandlerWindows
        portHandler = PortHandler(DEVICENAME)

        # Initialize PacketHandler instance
        # Set the protocol version
        # Get methods and members of Protocol1PacketHandler or Protocol2PacketHandler
        packetHandler = PacketHandler(PROTOCOL_VERSION)

        # Open port
        if portHandler.openPort():
            print("Succeeded to open the port")
        else:
            print("Failed to open the port")
            print("Press any key to terminate...")
            getch()
            quit()


        # Set port baudrate
        if portHandler.setBaudRate(BAUDRATE):
            print("Succeeded to change the baudrate")
        else:
            print("Failed to change the baudrate")
            print("Press any key to terminate...")
            getch()
            quit()

        # Enable Dynamixel Torque
        dxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_ENABLE)
        if dxl_comm_result != COMM_SUCCESS:
            print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
        elif dxl_error != 0:
            print("%s" % packetHandler.getRxPacketError(dxl_error))
        else:
            print("Dynamixel has been successfully connected")

        while 1:
            print("Press any key to continue! (or press ESC to quit!)")
            if getch() == chr(0x1b):
                break

            # Write goal position
            dxl_comm_result, dxl_error = packetHandler.write4ByteTxRx(portHandler, DXL_ID, ADDR_PRO_GOAL_POSITION, dxl_goal_position[index])
            if dxl_comm_result != COMM_SUCCESS:
                print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
            elif dxl_error != 0:
                print("%s" % packetHandler.getRxPacketError(dxl_error))

            while 1:
                # Read present position
                dxl_present_position, dxl_comm_result, dxl_error = packetHandler.read4ByteTxRx(portHandler, DXL_ID, ADDR_PRO_PRESENT_POSITION)
                if dxl_comm_result != COMM_SUCCESS:
                    print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
                elif dxl_error != 0:
                    print("%s" % packetHandler.getRxPacketError(dxl_error))

                print("[ID:%03d] GoalPos:%03d  PresPos:%03d" % (DXL_ID, dxl_goal_position[index], dxl_present_position))

                if not abs(dxl_goal_position[index] - dxl_present_position) > DXL_MOVING_STATUS_THRESHOLD:
                    break

            # Change goal position
            if index == 0:
                index = 1
            else:
                index = 0


        # Disable Dynamixel Torque
        dxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_DISABLE)
        if dxl_comm_result != COMM_SUCCESS:
            print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
        elif dxl_error != 0:
            print("%s" % packetHandler.getRxPacketError(dxl_error))

        # Close port
        portHandler.closePort()
if __name__ == '__main__':
    rospy.init_node('read_write', anonymous=True)
    controller = DynamixelController()
    #controller.read_write(14, 1500)

我的服务器节点:

#!/usr/bin/env python
import rospy
from controller_motor.srv import Motor2, Motor2Response


def motor_info(req):
    print("receive the request : {}".format(req.order))
    if req.order == 1:
        _id = 14
        _position = 2000
        
    elif req.order == 2:
        _id = 14
        _position = 2047.5
       

    print("Response to this request id : {} and postiion : {}".format(_id, _position))
    #print("Response to this request id : {} and _degreepostiion : {}".format(_id, _degreeposition))
    return Motor2Response(_id, _position)
   

    
def motor_info_server():

    rospy.init_node('test_motor_service')
    s = rospy.Service('test_motor_service', Motor2, motor_info)
    print("Ready to response some id and scaled_position")

    # spin() simply keeps python from exiting until this node is stopped
    rospy.spin()

if __name__ == '__main__':
    motor_info_server()

问题是什么?为什么会出现这样的错误


Tags: theidreadifpositionerrorresultdynamixel
1条回答
网友
1楼 · 发布于 2024-04-29 03:24:49

如错误所述,您在&操作中组合了“float”和“int”值,这在python中是不允许的(没有自动类型转换)

似乎有一个源文件执行此操作:

l & 0xFFFF

其中l作为参数传递。从你的代码中我可以看到,这是来自你的目标位置值,两者都是浮动的

dxl_comm_result, dxl_error = packetHandler.write4ByteTxRx(portHandler, DXL_ID, ADDR_PRO_GOAL_POSITION, dxl_goal_position[index])
dxl_goal_position = [DXL_MINIMUM_POSITION_VALUE, DXL_MAXIMUM_POSITION_VALUE]
DXL_MINIMUM_POSITION_VALUE  = 10.0           
DXL_MAXIMUM_POSITION_VALUE  = _degreeposition 
_degreeposition = (0.088 * (_position))

您真的需要它们成为float值吗?你能把这些转换成int吗?对于实验,您只需传递伪int值并检查其是否有效。这将澄清这是否是导致错误的原因。如果解决了这个问题,您需要弄清楚需要传递的正确值是什么(根据您的代码逻辑)

相关问题 更多 >