用python写一个ros18.04小乌龟走矩形
时间: 2024-04-29 20:25:37 浏览: 117
python 文件 在ros下手势控制海龟
以下是Python代码:
```python
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
def move_turtle(lin_vel, ang_vel, distance):
rospy.init_node('move_turtle', anonymous=True)
pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
rate = rospy.Rate(10) # 10hz
twist = Twist()
twist.linear.x = lin_vel
twist.angular.z = ang_vel
time = distance / lin_vel
start_time = rospy.Time.now().to_sec()
while not rospy.is_shutdown():
pub.publish(twist)
elapsed_time = rospy.Time.now().to_sec() - start_time
if elapsed_time > time:
twist.linear.x = 0
twist.angular.z = 0
pub.publish(twist)
break
rate.sleep()
if __name__ == '__main__':
move_turtle(1, 0, 2) # move forward 2m
rospy.sleep(1) # pause for 1 second
move_turtle(0, 1, 2) # turn left
rospy.sleep(1)
move_turtle(1, 0, 2)
rospy.sleep(1)
move_turtle(0, 1, 2)
rospy.sleep(1)
rospy.spin()
```
这个程序会使小乌龟走一个矩形,其中包括向前移动2米、向左转、向前移动2米、向左转、再向前移动2米。您可以根据需要更改移动速度和距离。
阅读全文