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
roscore
rosrun tutlesim turtlesim_node
rosrun turtlesim turtle_teleop_key
rqt_graph
rosnode list
rostopic list
rostopic info /turtel1/cmd_vel
可以看出来teleop_turtle节点通过turtle1/cmd_vel话题向turtlesim节点发送消息,消息类型为geometry_msgs/Twist
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
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