• ROS教程2 编写简单的消息发布器和订阅器 (C++ catkin)


    创建工作环境

    创建文件夹,创建包

    mkdir -p ~/catkin_arduino_ros/src
    
    catkin_create_pkg test1_pub_sub std_msgs rospy roscpp
    

      

     

    在桌面打开终端,添加工作路径

      

    echo "source /home/dongdong/catkin_arduino_ros/devel/setup.bash" >> ~/.bashrc 
    source ~/.bashrc
    

      

    创建项目文件  

    1创建src/talker.cpp文件

    cd ~/catkin_arduino_ros/src
    gedit talker.cpp
    

     复制代码

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

     保存

    2创建src/listener.cpp文件

    gedit listener.cpp
    

     复制源代码

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

    编译节点

    更改编译文件

    在CMakeLists.txt文件末尾加入几条语句:

    include_directories(include ${catkin_INCLUDE_DIRS})
    
    add_executable(talker src/talker.cpp)
    target_link_libraries(talker ${catkin_LIBRARIES})
    
    add_executable(listener src/listener.cpp)
    target_link_libraries(listener ${catkin_LIBRARIES})
    

      

      

    编译

    cd ~/catkin_arduino_ros/
    catkin_make
    

      

    运行节点

    //分别打开三个窗口
    roscore
    
    rosrun test1_pub_sub talker
    
    rosrun test1_pub_sub listener
    

      

  • 相关阅读:
    frp穿透.md
    6_模板与渲染.md
    4_多数据格式返回请求结果.md
    3_请求参数绑定与多数据格式处理.md
    5_中间件.md
    1_go_gin介绍.md
    2_Gin网络请求与路由处理.md
    14_文件.md
    firefox油猴脚本编写.md
    js 四舍五入
  • 原文地址:https://www.cnblogs.com/kekeoutlook/p/7401159.html
走看看 - 开发者的网上家园