基于ROS的机器人控制报错:RobotControl无turn_right属性
ROS机器人控制报错解决:AttributeError: RobotControl instance has no attribute 'turn_right'
问题分析
你的代码存在两个关键问题:
- 缩进逻辑错误:右转和再次直行的代码被错误缩进在
while循环内部,导致这部分代码只会在a > 1的循环过程中执行,但你的需求是机器人停止后(即a <= 1时)才执行右转操作,这部分代码实际永远不会被触发。 - 方法未定义:
RobotControl类中没有实现turn_right()方法,直接调用会触发AttributeError。
解决方案
1. 修正代码缩进
将右转和直行的代码移出while循环,调整后的代码如下:
from robot_control_class import RobotControl robotcontrol = RobotControl() # 获取前方激光读数 a = robotcontrol.get_laser(360) # 距离墙面大于1米时直行,小于等于1米时停止 while a > 1: robotcontrol.move_straight() a = robotcontrol.get_laser(360) print("Current distance to wall: %f" % a) robotcontrol.stop_robot() # 循环结束后统一停止,避免每次循环频繁启停 # 右转90度并重新直行 robotcontrol.turn_right(90) robotcontrol.move_straight()
2. 实现turn_right()方法
如果RobotControl类没有内置右转方法,你需要在robot_control_class.py中添加该方法。示例实现(基于ROS速度话题发布):
import rospy import math from geometry_msgs.msg import Twist class RobotControl: # 类中已有的其他方法(如move_straight、stop_robot等)... def turn_right(self, angle_deg): # 将角度转换为弧度 angle_rad = math.radians(angle_deg) # 计算旋转时间(假设旋转角速度为1 rad/s,可根据机器人实际参数调整) rotate_time = abs(angle_rad) / 1.0 twist = Twist() twist.angular.z = -1.0 # 负角速度对应右转(需根据机器人坐标系实际方向调整) pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10) rate = rospy.Rate(10) start_time = rospy.Time.now().to_sec() while (rospy.Time.now().to_sec() - start_time) < rotate_time: pub.publish(twist) rate.sleep() # 停止旋转 twist.angular.z = 0.0 pub.publish(twist)
注意:旋转方向(angular.z的正负)和角速度大小需要根据你的机器人实际运动特性调整,确保右转90度的动作符合预期。
内容的提问来源于stack exchange,提问作者NasserCzar
相关产品推荐
相关产品推荐

