ros入门历程
需要考虑旋转角度,行走直线
代码
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
from turtlesim.msg import Pose
import math
def pose_callback(data):
# 回调函数获取小乌龟的位置信息,这里我们不需要处理该信息
pass
def draw_star():
rospy.init_node('draw_star', anonymous=True)
turtle_vel_pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
rospy.Subscriber('/turtle1/pose', Pose, pose_callback)
rate = rospy.Rate(1) # 设置ROS节点的更新频率
# 等待TurtleSim启动并获取初始位置
rospy.loginfo("等待TurtleSim启动...")
rate.sleep()
# 控制小乌龟画五角星
for _ in range(5):
move_cmd = Twist()
move_cmd.linear.x = 2.0 # 设置小乌龟前进速度
move_cmd.angular.z = 0 # 设置小乌龟旋转角速度,使其转向形成五角星
turtle_vel_pub.publish(move_cmd)
rate.sleep()
move_cmd.linear.x = 0 # 设置小乌龟前进速度
move_cmd.angular.z = math.pi- math.pi/5 # 设置小乌龟旋转角速度,使其转向形成五角星
turtle_vel_pub.publish(move_cmd)
rate.sleep()
move_cmd.linear.x = 2.0 # 停止小乌龟前进
move_cmd.angular.z = 0 # 停止小乌龟旋转
turtle_vel_pub.publish(move_cmd)
rate.sleep()
move_cmd = Twist()
move_cmd.linear.x = 0 # 设置小乌龟前进速度
move_cmd.angular.z = 0 # 设置小乌龟旋转角速度,使其转向形成五角星
turtle_vel_pub.publish(move_cmd)
rate.sleep()
rospy.loginfo("画五角星完成!")
if __name__ == '__main__':
try:
draw_star()
except rospy.ROSInterruptException:
pass