ROS:消息发布器和订阅器(c++)

学习资料主要源自http://wiki.ros.org/ROS/Tutorials/WritingPublisherSubscriber%28c%2B%2B%29

$ roscd beginner_tutorials/

$ mkdir -p src

$ cd src

$ gedit talker.cpp

1. 编写发布器节点 talker

#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
int main(int argc, char **argv)
{
  //初始化ROS,名称重映射(唯一),必须为base name,不含/
  ros::init(argc, argv, "talker"); 
  // 为进程的节点创建一个句柄,第一个创建的NodeHandle初始化节点
  ros::NodeHandle n;
  // 告诉主机要在chatter topic上发布一个std_msgs消息
  // 主机会订阅所有chatter topic节点,参数表示发布队列的大小(先进先出)
  ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
  ros::Rate loop_rate(10);  // 自循环频率
  int count = 0;
  while (ros::ok())
  {
    std_msgs::String msg;
    std::stringstream ss;
    ss << "hello world " << count;
    msg.data = ss.str();
    // 输出,用来替代prinf/cout
    ROS_INFO("%s", msg.data.c_str()); 
    chatter_pub.publish(msg);

    ros::spinOnce();
    // 休眠,来使发布频率为10Hz
    loop_rate.sleep();
    ++count;
  }
  return 0;
}

    实现功能:

(1) 初始化ROS系统

(2) 在chatter topic上发布std_msgs/String消息

(3) 以每秒10次频率发布消息

2. 编写订阅器节点

#include "ros/ros.h"
#include "std_msgs/String.h"
// 回调函数
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
  ROS_INFO("I heard: [%s]", msg->data.c_str());
}

int main(int argc, char **argv)
{
 
  ros::init(argc, argv, "listener");
  ros::NodeHandle n;
  // 告诉master需要订阅chatter topic消息
  ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
  ros::spin(); // 自循环
  return 0;
}

    实现功能:

(1) 初始化ROS系统

(2) 订阅chatter topic消息

(3) 进入自循环,等待消息到达

(4) 消息到达,调用chatterCallback()函数

3. src/<package_name> /CMakeLists.txt

cmake_minimum_required(VERSION 2.8.3)
project(beginner_tutorials)

## Find catkin and any catkin packages
find_package(catkin REQUIRED COMPONENTS
  roscpp
  rospy
  std_msgs
  message_generation   
)

## Declare ROS messages and services
add_message_files(
  FILES
  Num.msg
)

add_service_files(
  FILES
  AddTwoInts.srv
)

## Declare a catkin package
catkin_package(
  CATKIN_DEPENDS message_runtime
)

## Build talker and listener
include_directories(include 
  ${catkin_INCLUDE_DIRS}
)

add_executable(talker src/talker.cpp)
target_link_libraries(talker ${catkin_LIBRARIES})
add_dependencies(talker beginner_tutorials_generate_messages_cpp)

add_executable(listener src/listener.cpp)
target_link_libraries(listener ${catkin_LIBRARIES})
add_dependencies(listener beginner_tutorials_generate_messages_cpp)

$ rosrun rqt_graph rqt_graph 或直接rqt_graph

 

注:如果遇到Couldn't find executable named talker below */src/beginner_tutorials

很有可能是工作空间初始化的问题。

参考

http://wiki.ros.org/ROS/Tutorials

转载请注明http://www.cnblogs.com/lizhongpingchn/p/5543013.html

posted on 2016-05-30 16:42  大唐雨夜  阅读(...)  评论(...编辑  收藏

导航