ros topic (part 1)
作业2.1
- src: simple_vel_publisher.py
#! /usr/bin/env python
import rospy
from std_msgs.msg import Int32
from geometry_msgs.msg import Twist
rospy.init_node('topic_publisher')
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=5)
rate = rospy.Rate(10)
count = Twist()
count.linear.x=0
while not rospy.is_shutdown():
pub.publish(count)
count.linear.x+=0.01
rate.sleep()
- launch: simple_vel_publisher_launch.launch
<launch>
<!-- turtlebot_teleop_key already has its own built in velocity smoother -->
<node pkg="my_topic_publisher" type="simple_topic_publisher.py" name="topic_publisher" output="screen">
</node>
</launch>
在Python文件中,创建了一个叫topic_publisher的节点,该节点中有一个消息发布器,发布的消息为/cmd_vel
话题。该消息类型为Twist,隶属于geometry_msgs.msg类。
Twist的数据结构如下,分别是三个线速度,三个角速度。
geometry_msgs/Vector3 linear
float64 x
float64 y
float64 z
geometry_msgs/Vector3 angular
float64 x
float64 y
float64 z
ros topic (part 2)
part 1中讲述如何创建一个消息发送者。 part 2则讲述如何订阅消息,同时创建自己的消息。
例子1
我们创建一个消息订阅器
#! /usr/bin/env python
import rospy
from std_msgs.msg import Int32
def callback(msg):
print msg.data
rospy.init_node('topic_subscriber') #订阅器节点
sub = rospy.Subscriber('counter', Int32, callback)#订阅器生成,参数为1.话题;2.消息数据类型;3.回调函数
#回调函数的作用是将订阅到的消息解析并返回所需要的值
rospy.spin()
但需要注意的是,话题topic必须是已经发布过的,不然订阅不到,会返回如下错误:
WARNING: no messages received and simulated time is active.
Is /clock being published?
在使用指令
rostopic pub <topic_name> <message_type> <value>
#我们这里发布的是
rostopic pub /counter std_msgs/Int32 5
发布话题后,监听/counter
消息可以发现返回了数字5.
user:~$ rostopic echo /counter
data: 5
---
作业1
订阅小车发布的里程计消息.
该消息发布在/odom
话题上。首先看看这个话题中消息类型,可以看出是Odometry
$ rostopic info /odom
Type: nav_msgs/Odometry
Publishers:
* /gazebo (http://ip-172-31-28-139:40165/)