用C++编写一个简单的Publisher和Subscriber

1.创建Publisher Node

  roscd beginner_tutorials

  创建src/talker.cpp文件,内容如下(可从https://raw.github.com/ros/ros_tutorials/kinetic-devel/roscpp_tutorials/talker/talker.cpp获取源码):

  #include "ros/ros.h"
  #include "std_msgs/String.h"

  #include

  int main(int argc, char **argv)
  {
      ros::init(argc, argv,"talker");
      ros::NodeHandle n;
      ros::Publisher chatter_pub =n.advertise("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();
          ROS_INFO("%s",msg.data.c_str());
          chatter_pub.publish(msg);
          ros::spinOnce();
          loop_rate.sleep();
          ++count;
      }
      return 0;
  }

2.创建一个Subscriber Node

  接下来再创建一个订阅者程序src/listener.cpp,源码如下(https://raw.github.com/ros/ros_tutorials/kinetic-devel/roscpp_tutorials/listener/listener.cpp):

  #include "ros/ros.h"
  #include "std_msgs/String.h"

  void chatterCallback(conststd_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;
      ros::Subscriber sub =n.subscribe("chatter", 1000, chatterCallback);
      ros::spin();
      return 0;
  }

  接下来在CMakeLists.txt文件最后添加如下内容:

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

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

3.编译执行

  cd ~/ros/catkin_ws
  catkin_make

  编译完后,使用如下命令执行(分别在两个Terminal):

  rosrun beginner_tutorials talker

  执行后会有如下打印输出:

  [ INFO] [1497787911.592887183]: hello world 0
  [ INFO] [1497787911.692986744]: hello world 1
  [ INFO] [1497787911.792978718]: hello world 2
  [ INFO] [1497787911.892973684]: hello world 3
  [ INFO] [1497787911.992973354]: hello world 4
  [ INFO] [1497787912.092982118]: hello world 5
  [ INFO] [1497787912.192957919]: hello world 6
  [ INFO] [1497787912.292959869]: hello world 7

  而下面命令:

  rosrun beginner_tutorials listener

  执行后有如下输出:

  [ INFO] [1497787976.316714360]: I heard:[hello world 275]
  [ INFO] [1497787976.416562016]: I heard:[hello world 276]
  [ INFO] [1497787976.516452913]: I heard:[hello world 277]
  [ INFO] [1497787976.616635718]: I heard:[hello world 278]
  [ INFO] [1497787976.716403373]: I heard:[hello world 279]
  [ INFO] [1497787976.816449993]: I heard:[hello world 280]
  [ INFO] [1497787976.916431239]: I heard:[hello world 281]

参考网址:http://wiki.ros.org/ROS/Tutorials/WritingPublisherSubscriber%28c%2B%2B%29

你可能感兴趣的:(用C++编写一个简单的Publisher和Subscriber)