ROS(melodic):键盘控制小乌龟移动,并转圈圈

一 准备工作

1.创建名为asy_ws工作空间

mkdir -p ~/asy_ws/src

2.初始化工作空间

cd ~/asy_ws/src
catkin_init_workspace

3.创建learning_topic能包

cd ~/asy_ws/src
catkin_create_pkg learning_topic roscpp rospy std_msgs geometry_msgs turtlesim

4.编译工作空间

cd ~/asy_ws
catkin_make

5.设置环境变量并检查是否设置成功

source devel/setup.bash
echo $ROS_PACKAGE_PATH

二 键盘方向键控制小乌龟(一个终端只运行一条命令)

  1. 运行roscore(让节点能相互通信)
roscore
  1. 调出小乌龟(turtlesim_node是小乌龟节点)
rosrun tutlesim turtlesim_node
  1. 控制小乌龟运动(turtle_teleop是另一个节点)
rosrun turtlesim turtle_teleop_key
  1. 调出节点图
rqt_graph

ROS(melodic):键盘控制小乌龟移动,并转圈圈_第1张图片
5. 查看节点,话题,消息

rosnode list
rostopic list
rostopic info /turtel1/cmd_vel

ROS(melodic):键盘控制小乌龟移动,并转圈圈_第2张图片
可以看出来teleop_turtle节点通过turtle1/cmd_vel话题向turtlesim节点发送消息,消息类型为geometry_msgs/Twist

三 控制小乌龟转圈圈

  1. 创建速度发布者
cd ~/asy_ws/src/learning_topic/src
touch velocity_publisher.py
# Python程序

import rospy
from geometry_msgs.msg import Twist

def velocity_publisher():
	# ROS节点初始化
    rospy.init_node('velocity_publisher', anonymous=True)

	# 创建一个Publisher,发布名为/turtle1/cmd_vel的topic,消息类型为geometry_msgs::Twist,队列长度10
    turtle_vel_pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)

	#设置循环的频率
    rate = rospy.Rate(10) 

    while not rospy.is_shutdown():
		# 初始化geometry_msgs::Twist类型的消息
        vel_msg = Twist()
        vel_msg.linear.x = 0.5
        vel_msg.angular.z = 0.2

		# 发布消息
        turtle_vel_pub.publish(vel_msg)
    	rospy.loginfo("Publsh turtle velocity command[%0.2f m/s, %0.2f rad/s]", 
				vel_msg.linear.x, vel_msg.angular.z)

		# 按照循环频率延时
        rate.sleep()

if __name__ == '__main__':
    try:
        velocity_publisher()
    except rospy.ROSInterruptException:
        pass

运行velocity_publisher.py

cd asy_ws/
source devel/setup.bash
rosrun learning_topic velocity_publisher.py

ROS(melodic):键盘控制小乌龟移动,并转圈圈_第3张图片
ROS(melodic):键盘控制小乌龟移动,并转圈圈_第4张图片
2. 创建小乌龟位置订阅者

cd ~/asy_ws/src/learning_topic/src
touch pose_subscriber.py
import rospy
from turtlesim.msg import Pose

def poseCallback(msg):
    rospy.loginfo("Turtle pose: x:%0.6f, y:%0.6f", msg.x, msg.y)

def pose_subscriber():
	# ROS节点初始化
    rospy.init_node('pose_subscriber', anonymous=True)

	# 创建一个Subscriber,订阅名为/turtle1/pose的topic,注册回调函数poseCallback
    rospy.Subscriber("/turtle1/pose", Pose, poseCallback)

	# 循环等待回调函数
    rospy.spin()

if __name__ == '__main__':
    pose_subscriber()

运行pose_subscriber.py

cd asy_ws/
source devel/setup.bash
rosrun learning_topic pose_subscriber.py

ROS(melodic):键盘控制小乌龟移动,并转圈圈_第5张图片

你可能感兴趣的:(ROS笔记)