Robot Ignite2: ROS基础--话题(topic)

本文档介绍了ROS中的话题基础,包括创建消息发送者和订阅者。讲解了如何创建自定义消息类型Age.msg,从创建消息文件、修改CMakeLists.txt和package.xml,到编译和使用自定义消息。还给出了一个简单的避障小车的控制策略,展示了如何处理激光雷达数据以避免碰撞。
摘要由CSDN通过智能技术生成

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/)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值